def set_temperature(self, **kwargs): """Set new target temperature.""" if kwargs.get(ATTR_TARGET_TEMP_LOW) is not None and \ kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None: target_temp_high = convert_temperature(kwargs.get( ATTR_TARGET_TEMP_HIGH), self._unit, TEMP_CELSIUS) target_temp_low = convert_temperature(kwargs.get( ATTR_TARGET_TEMP_LOW), self._unit, TEMP_CELSIUS) if self.device.mode == 'range': temp = (target_temp_low, target_temp_high) else: temp = kwargs.get(ATTR_TEMPERATURE) _LOGGER.debug("Nest set_temperature-output-value=%s", temp) self.device.target = temp
def current_temperature(self) -> float | None: """Return the current temperature.""" return convert_temperature( self.coordinator.data.parsed[self.unique_id]["temp"], TEMP_CELSIUS, self.temperature_unit, )
def _get_temperature(self, state: LazyState) -> Optional[float]: """Get temperature value from entity.""" ha_unit = self.hass.config.units.temperature_unit domain = split_entity_id(state.entity_id)[0] if domain == WEATHER_DOMAIN: temperature = state.attributes.get("temperature") entity_unit = ha_unit elif domain in (CLIMATE_DOMAIN, WATER_HEATER_DOMAIN): temperature = state.attributes.get("current_temperature") entity_unit = ha_unit else: temperature = state.state entity_unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) if not self._has_state(temperature): return None try: temperature = convert_temperature(float(temperature), entity_unit, ha_unit) except ValueError as exc: _LOGGER.error('Could not convert value "%s" to float: %s', state, exc) return None return temperature
def display_temp(hass: HomeAssistant, temperature: Optional[float], unit: str, precision: float) -> Optional[float]: """Convert temperature into preferred units/precision for display.""" temperature_unit = unit ha_unit = hass.config.units.temperature_unit if temperature is None: return temperature # If the temperature is not a number this can cause issues # with Polymer components, so bail early there. if not isinstance(temperature, Number): raise TypeError(f"Temperature is not a number: {temperature}") # type ignore: https://github.com/python/mypy/issues/7207 if temperature_unit != ha_unit: # type: ignore temperature = convert_temperature(temperature, temperature_unit, ha_unit) # Round in the units appropriate if precision == PRECISION_HALVES: temperature = round(temperature * 2) / 2.0 elif precision == PRECISION_TENTHS: temperature = round(temperature, 1) # Integer as a fall back (PRECISION_WHOLE) else: temperature = round(temperature) return temperature
def async_temperature_set_service(service): """Set temperature on the target climate devices.""" target_climate = component.async_extract_from_service(service) update_tasks = [] for climate in target_climate: kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, climate.temperature_unit ) else: kwargs[value] = temp yield from climate.async_set_temperature(**kwargs) if not climate.should_poll: continue update_tasks.append(climate.async_update_ha_state(True)) if update_tasks: yield from asyncio.wait(update_tasks, loop=hass.loop)
async def test_temperature_conversion( hass, enable_custom_integrations, unit_system, ): """Test temperature conversion.""" hass.config.units = unit_system native_value = 38 native_unit = TEMP_FAHRENHEIT entity0 = await create_entity( hass, temperature=native_value, temperature_unit=native_unit ) state = hass.states.get(entity0.entity_id) forecast = state.attributes[ATTR_FORECAST][0] expected = convert_temperature( native_value, native_unit, unit_system.temperature_unit ) assert float(state.attributes[ATTR_WEATHER_TEMPERATURE]) == approx( expected, rel=0.1 ) assert float(forecast[ATTR_FORECAST_TEMP]) == approx(expected, rel=0.1) assert float(forecast[ATTR_FORECAST_TEMP_LOW]) == approx(expected, rel=0.1)
def _temperature_index(self) -> Optional[int]: """Transform indoor temperature values to IAQ points.""" entity_id = self._sources.get(CONF_TEMPERATURE) if entity_id is None: return None value = self._get_number_state(entity_id, source_type=CONF_TEMPERATURE) if value is None: return None entity = self.hass.states.get(entity_id) entity_unit = entity.attributes.get(ATTR_UNIT_OF_MEASUREMENT) if entity_unit not in (TEMP_CELSIUS, TEMP_FAHRENHEIT): raise ValueError( UNIT_NOT_RECOGNIZED_TEMPLATE.format(entity_unit, TEMPERATURE) ) if entity_unit != TEMP_CELSIUS: value = convert_temperature(value, entity_unit, TEMP_CELSIUS) index = 1 if 18 <= value <= 21: # °C index = 5 elif 16 < value < 23: # °C index = 4 elif 15 < value < 24: # °C index = 3 elif 14 < value < 25: # °C index = 2 return index
def _temp2c(temperature: float, temperature_unit: str) -> float: """Convert weather temperature to Celsius degree.""" if temperature is not None and temperature_unit != TEMP_CELSIUS: temperature = convert_temperature(temperature, temperature_unit, TEMP_CELSIUS) return temperature
async def async_temperature_set_service(service): """Set temperature on the target climate devices.""" target_climate = component.async_extract_from_service(service) update_tasks = [] for climate in target_climate: kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, climate.temperature_unit ) else: kwargs[value] = temp await climate.async_set_temperature(**kwargs) if not climate.should_poll: continue update_tasks.append(climate.async_update_ha_state(True)) if update_tasks: await asyncio.wait(update_tasks, loop=hass.loop)
def display_temp(hass: HomeAssistant, temperature: float, unit: str, precision: float) -> float: """Convert temperature into preferred units for display purposes.""" temperature_unit = unit ha_unit = hass.config.units.temperature_unit if temperature is None: return temperature # If the temperature is not a number this can cause issues # with Polymer components, so bail early there. if not isinstance(temperature, Number): raise TypeError("Temperature is not a number: {}".format(temperature)) if temperature_unit != ha_unit: temperature = convert_temperature(temperature, temperature_unit, ha_unit) # Round in the units appropriate if precision == 0.5: return round(temperature * 2) / 2.0 elif precision == 0.1: return round(temperature, 1) # Integer as a fall back (PRECISION_WHOLE) return round(temperature)
def state_attributes(self): """Return the state attributes.""" data = { ATTR_WEATHER_TEMPERATURE: convert_temperature(self.temperature, self.temperature_unit, self.hass.config.units.temperature_unit), ATTR_WEATHER_HUMIDITY: self.humidity, } ozone = self.ozone if ozone is not None: data[ATTR_WEATHER_OZONE] = ozone pressure = self.pressure if pressure is not None: data[ATTR_WEATHER_PRESSURE] = pressure wind_bearing = self.wind_bearing if wind_bearing is not None: data[ATTR_WEATHER_WIND_BEARING] = wind_bearing wind_speed = self.wind_speed if wind_speed is not None: data[ATTR_WEATHER_WIND_SPEED] = wind_speed attribution = self.attribution if attribution is not None: data[ATTR_WEATHER_ATTRIBUTION] = attribution return data
def current_temperature(self) -> float | None: """Return the current temperature.""" return convert_temperature( self.device_data.temp, TEMP_CELSIUS, self.temperature_unit, )
def display_temp(hass: HomeAssistant, temperature: float, unit: str, precision: float) -> float: """Convert temperature into preferred units for display purposes.""" temperature_unit = unit ha_unit = hass.config.units.temperature_unit if temperature is None: return temperature # If the temperature is not a number this can cause issues # with Polymer components, so bail early there. if not isinstance(temperature, Number): raise TypeError( "Temperature is not a number: {}".format(temperature)) if temperature_unit != ha_unit: temperature = convert_temperature( temperature, temperature_unit, ha_unit) # Round in the units appropriate if precision == 0.5: return round(temperature * 2) / 2.0 elif precision == 0.1: return round(temperature, 1) # Integer as a fall back (PRECISION_WHOLE) return round(temperature)
def state_attributes(self): """Return the state attributes.""" data = { ATTR_WEATHER_TEMPERATURE: convert_temperature( self.temperature, self.temperature_unit, self.hass.config.units.temperature_unit), ATTR_WEATHER_HUMIDITY: self.humidity, } ozone = self.ozone if ozone is not None: data[ATTR_WEATHER_OZONE] = ozone pressure = self.pressure if pressure is not None: data[ATTR_WEATHER_PRESSURE] = pressure wind_bearing = self.wind_bearing if wind_bearing is not None: data[ATTR_WEATHER_WIND_BEARING] = wind_bearing wind_speed = self.wind_speed if wind_speed is not None: data[ATTR_WEATHER_WIND_SPEED] = wind_speed attribution = self.attribution if attribution is not None: data[ATTR_WEATHER_ATTRIBUTION] = attribution return data
def state(self): """Return the state of the entity.""" if self._state == 'unknown': return 'unknown' celsius = round(float(self._state) / 100, 1) return convert_temperature( celsius, TEMP_CELSIUS, self.unit_of_measurement)
def _temp2c(temperature: Optional[float], temperature_unit: Optional[str]) -> Optional[float]: """Convert weather temperature to Celsius degree.""" if temperature is not None and temperature_unit != TEMP_CELSIUS: temperature = convert_temperature(temperature, temperature_unit, TEMP_CELSIUS) return temperature
def feels_like(self): """Return the calculated Feels Like Temperature""" feels_like = self._sw_currently.data.feels_like_temperature if 'us' in self._dark_sky.units: return round( convert_temperature(feels_like, TEMP_CELSIUS, TEMP_FAHRENHEIT), 2) return feels_like
def dewpoint(self): """Return the dewpoint.""" dewpoint = self._sw_currently.data.dewpoint if 'us' in self._dark_sky.units: return round( convert_temperature(dewpoint, TEMP_CELSIUS, TEMP_FAHRENHEIT), 2) return dewpoint
def temperature(self): """Return the temperature.""" temperature = self._sw_currently.data.temperature if 'us' in self._dark_sky.units: return round( convert_temperature(temperature, TEMP_CELSIUS, TEMP_FAHRENHEIT), 2) return temperature
def current_temperature(self): """Return the current temperature.""" # This field is not affected by temperature_unit. # It is always in C / nativeTemperatureUnit if 'nativeTemperatureUnit' not in self._ac_states: return self._measurements['temperature'] return convert_temperature(self._measurements['temperature'], TEMP_CELSIUS, self.temperature_unit)
def state(self): """Return the state of the entity.""" if self._state == 'unknown': return 'unknown' celsius = round(float(self._state) / 100, 1) return round( convert_temperature(celsius, TEMP_CELSIUS, self.unit_of_measurement), 1)
def set_temperature(self, **kwargs): if kwargs.get(ATTR_TEMPERATURE) is not None: self.rac.set_property( ATTR_TEMPERATURE, convert_temperature(int(kwargs.get(ATTR_TEMPERATURE)), self.temperature_unit, TEMP_CELSIUS)) if kwargs.get(ATTR_TARGET_TEMP_HIGH) is not None: self.rac.set_property( ATTR_TARGET_TEMP_HIGH, convert_temperature(int(kwargs.get(ATTR_TARGET_TEMP_HIGH)), self.temperature_unit, TEMP_CELSIUS)) if kwargs.get(ATTR_TARGET_TEMP_LOW) is not None: self.rac.set_property( ATTR_TARGET_TEMP_LOW, convert_temperature(int(kwargs.get(ATTR_TARGET_TEMP_LOW)), self.temperature_unit, TEMP_CELSIUS)) self.schedule_update_ha_state(True)
def current_temperature(self): """Return the current temperature.""" # This field is not affected by temperatureUnit. # It is always in C return convert_temperature( self._measurements['temperature'], TEMP_CELSIUS, self.temperature_unit)
def state(self): """Return the state of the entity.""" if self._state is None: return None celsius = self._state / 100 return round( convert_temperature(celsius, TEMP_CELSIUS, self.unit_of_measurement), 1)
def temperature(self): """Return the current temperature.""" temp_c = None if self.observation: temp_c = self.observation.get("temperature") if temp_c: return convert_temperature(temp_c, TEMP_CELSIUS, TEMP_FAHRENHEIT) return None
def max_temp(self) -> float: """Return the maximum temperature.""" max_value = self._device.target_temperature_max if max_value is not None: return max_value return convert_temperature(DEFAULT_MAX_TEMP, TEMP_CELSIUS, self.temperature_unit)
def _do_update(self, data) -> None: self._attr_name = data["room"]["name"] self._ac_states = data["acState"] self._attr_extra_state_attributes = { "battery": data["measurements"].get("batteryVoltage") } self._attr_current_temperature = convert_temperature( data["measurements"].get("temperature"), TEMP_CELSIUS, self._attr_temperature_unit, ) self._attr_current_humidity = data["measurements"].get("humidity") self._attr_target_temperature = self._ac_states.get( "targetTemperature") if self._ac_states["on"]: self._attr_hvac_mode = SENSIBO_TO_HA.get(self._ac_states["mode"], "") else: self._attr_hvac_mode = HVAC_MODE_OFF self._attr_fan_mode = self._ac_states.get("fanLevel") self._attr_swing_mode = self._ac_states.get("swing") self._attr_available = data["connectionStatus"].get("isAlive") capabilities = data["remoteCapabilities"] self._attr_hvac_modes = [ SENSIBO_TO_HA[mode] for mode in capabilities["modes"] ] self._attr_hvac_modes.append(HVAC_MODE_OFF) current_capabilities = capabilities["modes"][self._ac_states.get( "mode")] self._attr_fan_modes = current_capabilities.get("fanLevels") self._attr_swing_modes = current_capabilities.get("swing") temperature_unit_key = data.get( "temperatureUnit") or self._ac_states.get("temperatureUnit") if temperature_unit_key: self._temperature_unit = (TEMP_CELSIUS if temperature_unit_key == "C" else TEMP_FAHRENHEIT) self._temperatures_list = ( current_capabilities["temperatures"].get( temperature_unit_key, {}).get("values", [])) else: self._temperature_unit = self._units self._temperatures_list = [] self._attr_min_temp = (self._temperatures_list[0] if self._temperatures_list else super().min_temp) self._attr_max_temp = (self._temperatures_list[-1] if self._temperatures_list else super().max_temp) self._attr_temperature_unit = self._temperature_unit self._attr_supported_features = 0 for key in self._ac_states: if key in FIELD_TO_FLAG: self._attr_supported_features |= FIELD_TO_FLAG[key] self._attr_state = self._external_state or super().state
def convert_hass_to_dev(self, hass_value): v = hass_value """Convert HASS state value to device state.""" if self._min is not None and hass_value < self._min: v = self._min if self._max is not None and hass_value > self._max: v = self._max return convert_temperature(float(v), TEMP_CELSIUS, self._unit)
def current_temperature(self): """Return the current temperature.""" if not self.values.temperature: return None return convert_temperature( self.values.temperature.value, convert_units(self._current_mode_setpoint_values[0].units), self.temperature_unit, )
def state(self): """Return the state of the entity.""" if self._state is None: return None celsius = self._state / 100 return round(convert_temperature(celsius, TEMP_CELSIUS, self.unit_of_measurement), 1)
def current_temperature(self): """Return the current temperature.""" # This field is not affected by temperature_unit. # It is always in C / nativeTemperatureUnit if 'nativeTemperatureUnit' not in self._ac_states: return self._measurements['temperature'] return convert_temperature( self._measurements['temperature'], TEMP_CELSIUS, self.temperature_unit)
def temperature(self): """Return the current temperature.""" temp_c = None if self._observation: temp_c = self._observation.get('temperature', {}).get('value') if temp_c is None and self._metar_obs and self._metar_obs.temp: temp_c = self._metar_obs.temp.value(units='C') if temp_c is not None: return convert_temperature(temp_c, TEMP_CELSIUS, TEMP_FAHRENHEIT) return None
def convert(state): val = 0.0 try: val = float(state.state) except ValueError: return None if state.attributes["unit_of_measurement"] == "%": return val return convert_temperature(val, state.attributes["unit_of_measurement"], TEMP_FAHRENHEIT)
def temperature_from_object(temp_obj, to_unit, interval=False): """Get temperature from Temperature object in requested unit.""" from_unit = TEMP_CELSIUS temp = float(temp_obj['value']) if temp_obj['scale'] == 'FAHRENHEIT': from_unit = TEMP_FAHRENHEIT elif temp_obj['scale'] == 'KELVIN': # convert to Celsius if absolute temperature if not interval: temp -= 273.15 return convert_temperature(temp, from_unit, to_unit, interval)
def temperature_from_object(hass, temp_obj, interval=False): """Get temperature from Temperature object in requested unit.""" to_unit = hass.config.units.temperature_unit from_unit = TEMP_CELSIUS temp = float(temp_obj["value"]) if temp_obj["scale"] == "FAHRENHEIT": from_unit = TEMP_FAHRENHEIT elif temp_obj["scale"] == "KELVIN" and not interval: # convert to Celsius if absolute temperature temp -= 273.15 return convert_temperature(temp, from_unit, to_unit, interval)
async def async_set_temperature(self, **kwargs): """Set new target temperature. Must know if single or double setpoint. """ hvac_mode = kwargs.get(ATTR_HVAC_MODE) if hvac_mode is not None: await self.async_set_hvac_mode(hvac_mode) if len(self._current_mode_setpoint_values) == 1: setpoint = self._current_mode_setpoint_values[0] target_temp = kwargs.get(ATTR_TEMPERATURE) if setpoint is not None and target_temp is not None: target_temp = convert_temperature( target_temp, self.temperature_unit, convert_units(setpoint.units), ) setpoint.send_value(target_temp) elif len(self._current_mode_setpoint_values) == 2: (setpoint_low, setpoint_high) = self._current_mode_setpoint_values target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW) target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) if setpoint_low is not None and target_temp_low is not None: target_temp_low = convert_temperature( target_temp_low, self.temperature_unit, convert_units(setpoint_low.units), ) setpoint_low.send_value(target_temp_low) if setpoint_high is not None and target_temp_high is not None: target_temp_high = convert_temperature( target_temp_high, self.temperature_unit, convert_units(setpoint_high.units), ) setpoint_high.send_value(target_temp_high)
def max_temp(self) -> float: """Return the maximum temperature.""" max_temp = DEFAULT_MAX_TEMP base_unit = TEMP_CELSIUS try: temp = self._setpoint_value(self._current_mode_setpoint_enums[0]) if temp.metadata.max: max_temp = temp.metadata.max base_unit = self.temperature_unit # In case of any error, we fallback to the default except (IndexError, ValueError, TypeError): pass return convert_temperature(max_temp, base_unit, self.temperature_unit)
def _convert_for_display(self, temp): """Convert temperature into preferred units for display purposes.""" if temp is None or not isinstance(temp, Number): return temp value = convert_temperature(temp, self.unit_of_measurement, self.hass.config.units.temperature_unit) if self.hass.config.units.temperature_unit is TEMP_CELSIUS: decimal_count = 1 else: # Users of fahrenheit generally expect integer units. decimal_count = 0 return round(value, decimal_count)
def _convert_for_display(self, temp): """Convert temperature into preferred units for display purposes.""" if temp is None or not isinstance(temp, Number): return temp if self.temperature_unit != self.unit_of_measurement: temp = convert_temperature(temp, self.temperature_unit, self.unit_of_measurement) # Round in the units appropriate if self.precision == PRECISION_HALVES: return round(temp * 2) / 2.0 elif self.precision == PRECISION_TENTHS: return round(temp, 1) else: # PRECISION_WHOLE as a fall back return round(temp)
def _temp_for_display(self, temp): """Convert temperature into preferred units for display purposes.""" unit = self.temperature_unit hass_unit = self.hass.config.units.temperature_unit if (temp is None or not isinstance(temp, Number) or unit == hass_unit): return temp value = convert_temperature(temp, unit, hass_unit) if hass_unit == TEMP_CELSIUS: return round(value, 1) # Users of fahrenheit generally expect integer units. return round(value)
async def async_service_temperature_set(entity, service): """Handle set temperature service.""" hass = entity.hass kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, entity.temperature_unit ) else: kwargs[value] = temp await entity.async_set_temperature(**kwargs)
def temperature_set_service(service): """Set temperature on the target hvacs.""" target_hvacs = component.extract_from_service(service) temperature = util.convert(service.data.get(ATTR_TEMPERATURE), float) if temperature is None: _LOGGER.error("Received call to %s without attribute %s", SERVICE_SET_TEMPERATURE, ATTR_TEMPERATURE) return for hvac in target_hvacs: hvac.set_temperature( convert_temperature(temperature, hass.config.units.temperature_unit, hvac.unit_of_measurement) ) if hvac.should_poll: hvac.update_ha_state(True)
def async_temperature_set_service(service): """Set temperature on the target climate devices.""" target_climate = component.async_extract_from_service(service) for climate in target_climate: kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, climate.temperature_unit ) else: kwargs[value] = temp yield from climate.async_set_temperature(**kwargs) yield from _async_update_climate(target_climate)
def temperature_set_service(service): """Set temperature on the target climate devices.""" target_climate = component.extract_from_service(service) for climate in target_climate: kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, climate.temperature_unit ) else: kwargs[value] = temp climate.set_temperature(**kwargs) if climate.should_poll: climate.update_ha_state(True)
def _convert_for_display(self, temp): """Convert temperature into preferred units for display purposes.""" if temp is None: return temp # if the temperature is not a number this can cause issues # with polymer components, so bail early there. if not isinstance(temp, Number): raise TypeError("Temperature is not a number: %s" % temp) if self.temperature_unit != self.unit_of_measurement: temp = convert_temperature( temp, self.temperature_unit, self.unit_of_measurement) # Round in the units appropriate if self.precision == PRECISION_HALVES: return round(temp * 2) / 2.0 elif self.precision == PRECISION_TENTHS: return round(temp, 1) # PRECISION_WHOLE as a fall back return round(temp)
def max_temp(self): """Return the maximum temperature.""" return convert_temperature(self._max_temp, self._unit, self.hass.config.units.temperature_unit)
def max_temp(self): """Return the maximum temperature.""" return convert_temperature(30, TEMP_CELSIUS, self.unit_of_measurement)
def min_temp(self): """Return the minimum temperature.""" return convert_temperature(19, TEMP_CELSIUS, self.unit_of_measurement)
def max_temp(self): """Return the maximum temperature.""" return convert_temperature(35, TEMP_CELSIUS, self.temperature_unit)
def min_temp(self): """Return the minimum temperature.""" return convert_temperature(7, TEMP_CELSIUS, self.temperature_unit)
def max_temp(self): """Return the maximum temperature.""" return convert_temperature(DEFAULT_MAX_TEMP, TEMP_FAHRENHEIT, self.temperature_unit)