TR: Thermostat data response.
559046
def _tr_decode(self, msg):
        """"""
        return {'thermostat_index': int(msg[4:6])-1, 'mode': int(msg[6]),
                'hold': msg[7] == '1', 'fan': int(msg[8]),
                'current_temp': int(msg[9:11]), 'heat_setpoint': int(msg[11:13]),
                'cool_setpoint': int(msg[13:15]), 'humidity': int(msg[15:17])}
1225299
def _compute_heating_rates(self):
        ''''''
        self._compute_flux()
        self.heating_rate['Ts'] = -self._flux
        # Modify only the lowest model level
        self.heating_rate['Tatm'][..., -1, np.newaxis] = self._flux
1107973
def temperatures(self, force_refresh=False):
        """"""
        self._populate_full_data(force_refresh)
        for device in self.full_data['devices']:
            set_point = 0
            status = ""
            if 'heatSetpoint' in device['thermostat']['changeableValues']:
                set_point = float(
                    device['thermostat']['changeableValues']["heatSetpoint"]["value"])
                status = device['thermostat']['changeableValues']["heatSetpoint"]["status"]
            else:
                status = device['thermostat']['changeableValues']['status']
            yield {'thermostat': device['thermostatModelType'],
                   'id': device['deviceID'],
                   'name': device['name'],
                   'temp': float(device['thermostat']['indoorTemperature']),
                   'setpoint': set_point,
                   'status': status,
                   'mode': device['thermostat']['changeableValues']['mode']}
1217116
def readTempC(self):
		""""""
		# Read temperature register value.
		t = self._device.readU16BE(MCP9808_REG_AMBIENT_TEMP)
		self._logger.debug('Raw ambient temp register value: 0x{0:04X}'.format(t & 0xFFFF))
		# Scale and convert to signed value.
		temp = (t & 0x0FFF) / 16.0
		if t & 0x1000:
			temp -= 256.0
		return temp
511353
private function _temperature()
    {
        for ($intPosi = 3; $intPosi < 6; $intPosi++) {
            if ($this->_buf_value[$intPosi] == 0) {
                continue;
            }
            preg_match("/([0-9\.])*/", str_replace(",", ".", $this->_buf_value[$intPosi]), $hits);
            $dev = new SensorDevice();
            $dev->setName($this->_buf_label[$intPosi]);
            $dev->setValue($hits[0]);
//            $dev->setMax(70);
            $this->mbinfo->setMbTemp($dev);
        }
    }
883097
def sync_set_heater_temp(self, device_id, set_temp):
        """"""
        loop = asyncio.get_event_loop()
        task = loop.create_task(self.set_heater_temp(device_id, set_temp))
        loop.run_until_complete(task)
985328
private function _temperature()
    {
        foreach ($this->_lines as $line) {
            if (preg_match('/^hw\.sensors\.[0-9]+=[^\s,]+,\s+([^,]+),\s+temp,\s+([0-9\.]+)\s+degC.*$/', $line, $ar_buf)) {
                $dev = new SensorDevice();
                $dev->setName($ar_buf[1]);
                $dev->setValue($ar_buf[2]);
                $this->mbinfo->setMbTemp($dev);
            } elseif (preg_match('/^hw\.sensors\.[0-9]+=[^\s,]+,\s+([^,]+),\s+([0-9\.]+)\s+degC$/', $line, $ar_buf)) {
                $dev = new SensorDevice();
                $dev->setName($ar_buf[1]);
                $dev->setValue($ar_buf[2]);
                $this->mbinfo->setMbTemp($dev);
            } elseif (preg_match('/^hw\.sensors\.[^\.]+\.(.*)=([0-9\.]+)\s+degC\s+\((.*)\)$/', $line, $ar_buf)) {
                $dev = new SensorDevice();
                $dev->setName($ar_buf[3]);
                $dev->setValue($ar_buf[2]);
                $this->mbinfo->setMbTemp($dev);
            } elseif (preg_match('/^hw\.sensors\.[^\.]+\.(.*)=([0-9\.]+)\s+degC$/', $line, $ar_buf)) {
                $dev = new SensorDevice();
                $dev->setName($ar_buf[1]);
                $dev->setValue($ar_buf[2]);
                $this->mbinfo->setMbTemp($dev);
            }
        }
    }
885953
async def set_heater_values(heater_data, heater):
    """"""
    heater.current_temp = heater_data.get('currentTemp')
    heater.device_status = heater_data.get('deviceStatus')
    heater.available = heater.device_status == 0
    heater.name = heater_data.get('deviceName')
    heater.fan_status = heater_data.get('fanStatus')
    heater.is_holiday = heater_data.get('isHoliday')

    # Room assigned devices don't report canChangeTemp
    # in selectDevice response.
    if heater.room is None:
        heater.can_change_temp = heater_data.get('canChangeTemp')

    # Independent devices report their target temperature via
    # holidayTemp value. But isHoliday is still set to 0.
    # Room assigned devices may have set "Control Device individually"
    # which effectively set their isHoliday value to 1.
    # In this mode they behave similar to independent devices
    # reporting their target temperature also via holidayTemp.
    if heater.independent_device or heater.is_holiday == 1:
        heater.set_temp = heater_data.get('holidayTemp')
    elif heater.room is not None:
        if heater.room.current_mode == 1:
            heater.set_temp = heater.room.comfort_temp
        elif heater.room.current_mode == 2:
            heater.set_temp = heater.room.sleep_temp
        elif heater.room.current_mode == 3:
            heater.set_temp = heater.room.away_temp
    heater.power_status = heater_data.get('powerStatus')
    heater.tibber_control = heater_data.get('tibberControl')
    heater.open_window = heater_data.get('open_window',
                                         heater_data.get('open')
                                         )
    heater.is_heating = heater_data.get('heatStatus',
                                        heater_data.get('heaterFlag')
                                        )
    try:
        heater.sub_domain = int(float(heater_data.get('subDomain',
                                                      heater_data.get('subDomainId',
                                                                      heater.sub_domain)
                                                      )))
    except ValueError:
        pass
834906
def get(self, sensor_type='temperature_core'):
        """"""
        self.__update__()
        if sensor_type == 'temperature_core':
            ret = [s for s in self.sensors_list if s['unit'] == SENSOR_TEMP_UNIT]
        elif sensor_type == 'fan_speed':
            ret = [s for s in self.sensors_list if s['unit'] == SENSOR_FAN_UNIT]
        else:
            # Unknown type
            logger.debug("Unknown sensor type %s" % sensor_type)
            ret = []
        return ret
215305
function() {
            return fritz.getDevice(thermostat).then(function(device) {
              console.log("[" + thermostat + "] " + device.name);
            });       
          }
704600
def _compute_heating_rates(self):
        ''''''
        self.LW_to_atm = self._compute_emission()
        self.SW_to_atm = self._compute_reflected_flux()
        self.heating_rate['Ts'] = ( self.LW_from_atm - self.LW_to_atm
                                  + self.SW_from_atm - self.SW_to_atm )
1109478
def device_state_attributes(self):
        """"""
        attr = {}
        attr['active_time'] = self.smartplug.active_time
        attr['voltage'] = self.smartplug.voltage
        attr['active_time'] = self.smartplug.active_time
        attr['weekly_energy_total'] = self.smartplug.weekly_energy_total
        attr['monthly_energy_total'] = self.smartplug.monthly_energy_total
        attr['yearly_energy_total'] = self.smartplug.yearly_energy_total
        return attr
592853
def update(self, first_reading=False):
        """"""
        try:
            if first_reading or not self._ok:
                self._bus.write_byte_data(self._i2c_add, 0xF2,
                                          self.ctrl_hum_reg)
                self._bus.write_byte_data(self._i2c_add, 0xF5, self.config_reg)
                self._bus.write_byte_data(self._i2c_add, 0xF4,
                                          self.ctrl_meas_reg)
                self._populate_calibration_data()

            if self.mode == 2:  # MODE_FORCED
                self._take_forced_measurement()

            data = []
            for i in range(0xF7, 0xF7 + 8):
                data.append(self._bus.read_byte_data(self._i2c_add, i))
        except OSError as exc:
            self.log_error("Bad update: %s", exc)
            self._ok = False
            return

        pres_raw = (data[0] << 12) | (data[1] << 4) | (data[2] >> 4)
        temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)
        hum_raw = (data[6] << 8) | data[7]
        self._ok = False

        temperature = self._compensate_temperature(temp_raw)
        if (temperature >= -20) and (temperature < 80):
            self._temperature = temperature
            self._ok = True
        if self._with_humidity:
            humidity = self._compensate_humidity(hum_raw)
            if (humidity >= 0) and (humidity <= 100):
                self._humidity = humidity
            else:
                self._ok = False
        if self._with_pressure:
            pressure = self._compensate_pressure(pres_raw)
            if pressure > 100:
                self._pressure = pressure
            else:
                self._ok = False
850895
def heating_stats(self):
        """"""
        local_5 = []
        local_10 = []

        for i in range(0, 10):
            level = self.past_heating_level(i)
            if level == 0:
                _LOGGER.debug('Cant calculate stats yet...')
                return
            if i < 5:
                local_5.append(level)
            local_10.append(level)

        _LOGGER.debug('%s Heating History: %s', self.side, local_10)

        try:
            # Average of 5min on the history dict.
            fiveminavg = statistics.mean(local_5)
            tenminavg = statistics.mean(local_10)
            _LOGGER.debug('%s Heating 5 min avg: %s', self.side, fiveminavg)
            _LOGGER.debug('%s Heating 10 min avg: %s', self.side, tenminavg)

            # Standard deviation
            fivestdev = statistics.stdev(local_5)
            tenstdev = statistics.stdev(local_10)
            _LOGGER.debug('%s Heating 5 min stdev: %s', self.side, fivestdev)
            _LOGGER.debug('%s Heating 10 min stdev: %s', self.side, tenstdev)

            # Variance
            fivevar = statistics.variance(local_5)
            tenvar = statistics.variance(local_10)
            _LOGGER.debug('%s Heating 5 min variance: %s', self.side, fivevar)
            _LOGGER.debug('%s Heating 10 min variance: %s', self.side, tenvar)
        except:
            _LOGGER.debug('Cant calculate stats yet...')
1100130
def auto(self, minutes, steps=2000):
        

        def run(T, steps):
            """Anneals a system at constant temperature and returns the state,
            energy, rate of acceptance, and rate of improvement."""
            E = self.energy()
            prevState = self.copy_state(self.state)
            prevEnergy = E
            accepts, improves = 0, 0
            for _ in range(steps):
                self.move()
                E = self.energy()
                dE = E - prevEnergy
                if dE > 0.0 and math.exp(-dE / T) < random.random():
                    self.state = self.copy_state(prevState)
                    E = prevEnergy
                else:
                    accepts += 1
                    if dE < 0.0:
                        improves += 1
                    prevState = self.copy_state(self.state)
                    prevEnergy = E
            return E, float(accepts) / steps, float(improves) / steps

        step = 0
        self.start = time.time()

        # Attempting automatic simulated anneal...
        # Find an initial guess for temperature
        T = 0.0
        E = self.energy()
        self.update(step, T, E, None, None)
        while T == 0.0:
            step += 1
            self.move()
            T = abs(self.energy() - E)

        # Search for Tmax - a temperature that gives 98% acceptance
        E, acceptance, improvement = run(T, steps)

        step += steps
        while acceptance > 0.98:
            T = round_figures(T / 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        while acceptance < 0.98:
            T = round_figures(T * 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        Tmax = T

        # Search for Tmin - a temperature that gives 0% improvement
        while improvement > 0.0:
            T = round_figures(T / 1.5, 2)
            E, acceptance, improvement = run(T, steps)
            step += steps
            self.update(step, T, E, acceptance, improvement)
        Tmin = T

        # Calculate anneal duration
        elapsed = time.time() - self.start
        duration = round_figures(int(60.0 * minutes * step / elapsed), 2)

        # Don't perform anneal, just return params
        return {'tmax': Tmax, 'tmin': Tmin, 'steps': duration, 'updates': self.updates}
1285131
def get_thermostat_meter_data(zone):
    
    meter_uri = zone2meter.get(zone, "None")
    data = []
    def cb(msg):
        for po in msg.payload_objects:
            if po.type_dotted == (2,0,9,1):
                m = msgpack.unpackb(po.content)
                data.append(m['current_demand'])
    handle = c.subscribe(meter_uri+"/signal/meter", cb)

    def stop():
        c.unsubscribe(handle)
        return data
    return stop
14056
def thermostat_state(self):
        
        current_state = self.thermostat_info.active_state
        state = self.get_thermostat_state_by_id(current_state)
        if not state:
            self._logger.debug('Manually set temperature, no Thermostat '
                               'State chosen!')
        return state