sensor.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. """Interfaces with the Integration 101 Template api sensors."""
  2. import logging
  3. from homeassistant.components.sensor import (
  4. SensorDeviceClass,
  5. SensorEntity,
  6. SensorStateClass,
  7. )
  8. from homeassistant.const import UnitOfTemperature
  9. from homeassistant.core import HomeAssistant, callback
  10. from homeassistant.helpers.device_registry import DeviceInfo
  11. from homeassistant.helpers.entity_platform import AddEntitiesCallback
  12. from homeassistant.helpers.update_coordinator import CoordinatorEntity
  13. from . import MyConfigEntry
  14. from .api import Device, DeviceType
  15. from .const import DOMAIN
  16. from .coordinator import ExampleCoordinator
  17. _LOGGER = logging.getLogger(__name__)
  18. async def async_setup_entry(
  19. hass: HomeAssistant,
  20. config_entry: MyConfigEntry,
  21. async_add_entities: AddEntitiesCallback,
  22. ):
  23. """Set up the Sensors."""
  24. # This gets the data update coordinator from the config entry runtime data as specified in your __init__.py
  25. coordinator: ExampleCoordinator = config_entry.runtime_data.coordinator
  26. # Enumerate all the sensors in your data value from your DataUpdateCoordinator and add an instance of your sensor class
  27. # to a list for each one.
  28. # This maybe different in your specific case, depending on how your data is structured
  29. sensors = [
  30. ExampleSensor(coordinator, device)
  31. for device in coordinator.data.devices
  32. if device.device_type == DeviceType.TEMP_SENSOR
  33. ]
  34. # Create the sensors.
  35. async_add_entities(sensors)
  36. class ExampleSensor(CoordinatorEntity, SensorEntity):
  37. """Implementation of a sensor."""
  38. def __init__(self, coordinator: ExampleCoordinator, device: Device) -> None:
  39. """Initialise sensor."""
  40. super().__init__(coordinator)
  41. self.device = device
  42. self.device_id = device.device_id
  43. @callback
  44. def _handle_coordinator_update(self) -> None:
  45. """Update sensor with latest data from coordinator."""
  46. # This method is called by your DataUpdateCoordinator when a successful update runs.
  47. self.device = self.coordinator.get_device_by_id(
  48. self.device.device_type, self.device_id
  49. )
  50. _LOGGER.debug("Device: %s", self.device)
  51. self.async_write_ha_state()
  52. @property
  53. def device_class(self) -> str:
  54. """Return device class."""
  55. # https://developers.home-assistant.io/docs/core/entity/sensor/#available-device-classes
  56. return SensorDeviceClass.TEMPERATURE
  57. @property
  58. def device_info(self) -> DeviceInfo:
  59. """Return device information."""
  60. # Identifiers are what group entities into the same device.
  61. # If your device is created elsewhere, you can just specify the indentifiers parameter.
  62. # If your device connects via another device, add via_device parameter with the indentifiers of that device.
  63. return DeviceInfo(
  64. name=f"ExampleDevice{self.device.device_id}",
  65. manufacturer="ACME Manufacturer",
  66. model="Door&Temp v1",
  67. sw_version="1.0",
  68. identifiers={
  69. (
  70. DOMAIN,
  71. f"{self.coordinator.data.controller_name}-{self.device.device_id}",
  72. )
  73. },
  74. )
  75. @property
  76. def name(self) -> str:
  77. """Return the name of the sensor."""
  78. return self.device.name
  79. @property
  80. def native_value(self) -> int | float:
  81. """Return the state of the entity."""
  82. # Using native value and native unit of measurement, allows you to change units
  83. # in Lovelace and HA will automatically calculate the correct value.
  84. return float(self.device.state)
  85. @property
  86. def native_unit_of_measurement(self) -> str | None:
  87. """Return unit of temperature."""
  88. return UnitOfTemperature.CELSIUS
  89. @property
  90. def state_class(self) -> str | None:
  91. """Return state class."""
  92. # https://developers.home-assistant.io/docs/core/entity/sensor/#available-state-classes
  93. return SensorStateClass.MEASUREMENT
  94. @property
  95. def unique_id(self) -> str:
  96. """Return unique id."""
  97. # All entities must have a unique id. Think carefully what you want this to be as
  98. # changing it later will cause HA to create new entities.
  99. return f"{DOMAIN}-{self.device.device_unique_id}"
  100. @property
  101. def extra_state_attributes(self):
  102. """Return the extra state attributes."""
  103. # Add any additional attributes you want on your sensor.
  104. attrs = {}
  105. attrs["extra_info"] = "Extra Info"
  106. return attrs