base.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. """Base entity which all other entity platform classes can inherit.
  2. As all entity types have a common set of properties, you can
  3. create a base entity like this and inherit it in all your entity platforms.
  4. This just makes your code more efficient and is totally optional.
  5. See each entity platform (ie sensor.py, switch.py) for how this is inheritted
  6. and what additional properties and methods you need to add for each entity type.
  7. """
  8. import logging
  9. from typing import Any
  10. from homeassistant.core import callback
  11. from homeassistant.helpers.device_registry import DeviceInfo
  12. from homeassistant.helpers.update_coordinator import CoordinatorEntity
  13. from .const import DOMAIN
  14. from .coordinator import ExampleCoordinator
  15. _LOGGER = logging.getLogger(__name__)
  16. class ExampleBaseEntity(CoordinatorEntity):
  17. """Base Entity Class.
  18. This inherits a CoordinatorEntity class to register your entites to be updated
  19. by your DataUpdateCoordinator when async_update_data is called, either on the scheduled
  20. interval or by forcing an update.
  21. """
  22. coordinator: ExampleCoordinator
  23. # ----------------------------------------------------------------------------
  24. # Using attr_has_entity_name = True causes HA to name your entities with the
  25. # device name and entity name. Ie if your name property of your entity is
  26. # Voltage and this entity belongs to a device, Lounge Socket, this will name
  27. # your entity to be sensor.lounge_socket_voltage
  28. #
  29. # It is highly recommended (by me) to use this to give a good name structure
  30. # to your entities. However, totally optional.
  31. # ----------------------------------------------------------------------------
  32. _attr_has_entity_name = True
  33. def __init__(
  34. self, coordinator: ExampleCoordinator, device: dict[str, Any], parameter: str
  35. ) -> None:
  36. """Initialise entity."""
  37. super().__init__(coordinator)
  38. self.device = device
  39. self.device_id = device["device_id"]
  40. self.parameter = parameter
  41. @callback
  42. def _handle_coordinator_update(self) -> None:
  43. """Update sensor with latest data from coordinator."""
  44. # This method is called by your DataUpdateCoordinator when a successful update runs.
  45. self.device = self.coordinator.get_device(self.device_id)
  46. _LOGGER.debug(
  47. "Updating device: %s, %s",
  48. self.device_id,
  49. self.coordinator.get_device_parameter(self.device_id, "device_name"),
  50. )
  51. self.async_write_ha_state()
  52. @property
  53. def device_info(self) -> DeviceInfo:
  54. """Return device information."""
  55. # ----------------------------------------------------------------------------
  56. # Identifiers are what group entities into the same device.
  57. # If your device is created elsewhere, you can just specify the indentifiers
  58. # parameter to link an entity to a device.
  59. # If your device connects via another device, add via_device parameter with
  60. # the indentifiers of that device.
  61. #
  62. # Device identifiers should be unique, so use your integration name (DOMAIN)
  63. # and a device uuid, mac address or some other unique attribute.
  64. # ----------------------------------------------------------------------------
  65. return DeviceInfo(
  66. name=self.coordinator.get_device_parameter(self.device_id, "device_name"),
  67. manufacturer="ACME Manufacturer",
  68. model=str(
  69. self.coordinator.get_device_parameter(self.device_id, "device_type")
  70. )
  71. .replace("_", " ")
  72. .title(),
  73. sw_version=self.coordinator.get_device_parameter(
  74. self.device_id, "software_version"
  75. ),
  76. identifiers={
  77. (
  78. DOMAIN,
  79. self.coordinator.get_device_parameter(self.device_id, "device_uid"),
  80. )
  81. },
  82. )
  83. @property
  84. def name(self) -> str:
  85. """Return the name of the sensor."""
  86. return self.parameter.replace("_", " ").title()
  87. @property
  88. def unique_id(self) -> str:
  89. """Return unique id."""
  90. # ----------------------------------------------------------------------------
  91. # All entities must have a unique id across your whole Home Assistant server -
  92. # and that also goes for anyone using your integration who may have many other
  93. # integrations loaded.
  94. #
  95. # Think carefully what you want this to be as changing it later will cause HA
  96. # to create new entities.
  97. #
  98. # It is recommended to have your integration name (DOMAIN), some unique id
  99. # from your device such as a UUID, MAC address etc (not IP address) and then
  100. # something unique to your entity (like name - as this would be unique on a
  101. # device)
  102. #
  103. # If in your situation you have some hub that connects to devices which then
  104. # you want to create multiple sensors for each device, you would do something
  105. # like.
  106. #
  107. # f"{DOMAIN}-{HUB_MAC_ADDRESS}-{DEVICE_UID}-{ENTITY_NAME}""
  108. #
  109. # This is even more important if your integration supports multiple instances.
  110. # ----------------------------------------------------------------------------
  111. return f"{DOMAIN}-{self.coordinator.get_device_parameter(self.device_id, "device_uid")}-{self.parameter}"