1
0
mirror of https://github.com/home-assistant/core.git synced 2025-12-24 04:50:05 +00:00
Files
core/homeassistant/components/homekit/sensors.py
cdce8p 27b1d448a3 Homekit Update, Support for TempSensor (°F) (#12676)
* Changed version of "HAP-python" to "v1.1.7"

* Updated acc file to simplify init calls

* Code refactored and '°F' temp Sensors added

* Changed call to 'HomeAccessory' and 'HomeBridge'
* Extended function of 'add_preload_service' to add additional characteristics
* Added function to override characteristic property values

* TemperatureSensor
  * Added unit
  * Added calc_temperature

* Updated tests
2018-02-25 19:27:40 -08:00

74 lines
2.4 KiB
Python

"""Class to hold all sensor accessories."""
import logging
from homeassistant.const import (
STATE_UNKNOWN, ATTR_UNIT_OF_MEASUREMENT, TEMP_FAHRENHEIT, TEMP_CELSIUS)
from homeassistant.helpers.event import async_track_state_change
from . import TYPES
from .accessories import (
HomeAccessory, add_preload_service, override_properties)
from .const import (
SERV_TEMPERATURE_SENSOR, CHAR_CURRENT_TEMPERATURE, PROP_CELSIUS)
_LOGGER = logging.getLogger(__name__)
def calc_temperature(state, unit=TEMP_CELSIUS):
"""Calculate temperature from state and unit.
Always return temperature as Celsius value.
Conversion is handled on the device.
"""
if state == STATE_UNKNOWN:
return None
if unit == TEMP_FAHRENHEIT:
value = round((float(state) - 32) / 1.8, 2)
else:
value = float(state)
return value
@TYPES.register('TemperatureSensor')
class TemperatureSensor(HomeAccessory):
"""Generate a TemperatureSensor accessory for a temperature sensor.
Sensor entity must return temperature in °C, °F or STATE_UNKNOWN.
"""
def __init__(self, hass, entity_id, display_name):
"""Initialize a TemperatureSensor accessory object."""
super().__init__(display_name, entity_id, 'SENSOR')
self._hass = hass
self._entity_id = entity_id
self.serv_temp = add_preload_service(self, SERV_TEMPERATURE_SENSOR)
self.char_temp = self.serv_temp. \
get_characteristic(CHAR_CURRENT_TEMPERATURE)
override_properties(self.char_temp, PROP_CELSIUS)
self.unit = None
def run(self):
"""Method called be object after driver is started."""
state = self._hass.states.get(self._entity_id)
self.update_temperature(new_state=state)
async_track_state_change(
self._hass, self._entity_id, self.update_temperature)
def update_temperature(self, entity_id=None, old_state=None,
new_state=None):
"""Update temperature after state changed."""
if new_state is None:
return
unit = new_state.attributes[ATTR_UNIT_OF_MEASUREMENT]
temperature = calc_temperature(new_state.state, unit)
if temperature is not None:
self.char_temp.set_value(temperature)
_LOGGER.debug("%s: Current temperature set to %d°C",
self._entity_id, temperature)