4
0

mixin.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """
  2. Mixins to make writing new platforms easier
  3. """
  4. import logging
  5. from homeassistant.const import (
  6. AREA_SQUARE_METERS,
  7. CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
  8. UnitOfTemperature,
  9. )
  10. from homeassistant.helpers.entity import EntityCategory
  11. _LOGGER = logging.getLogger(__name__)
  12. class TuyaLocalEntity:
  13. """Common functions for all entity types."""
  14. def _init_begin(self, device, config):
  15. self._device = device
  16. self._config = config
  17. self._attr_dps = []
  18. return {c.name: c for c in config.dps()}
  19. def _init_end(self, dps):
  20. for d in dps.values():
  21. if not d.hidden:
  22. self._attr_dps.append(d)
  23. @property
  24. def should_poll(self):
  25. return True
  26. @property
  27. def available(self):
  28. return self._device.has_returned_state
  29. @property
  30. def name(self):
  31. """Return the name for the UI."""
  32. return self._config.name()
  33. @property
  34. def has_entity_name(self):
  35. return True
  36. @property
  37. def unique_id(self):
  38. """Return the unique id for this entity."""
  39. return self._config.unique_id(self._device.unique_id)
  40. @property
  41. def device_info(self):
  42. """Return the device's information."""
  43. return self._device.device_info
  44. @property
  45. def entity_category(self):
  46. """Return the entitiy's category."""
  47. return (
  48. None
  49. if self._config.entity_category is None
  50. else EntityCategory(self._config.entity_category)
  51. )
  52. @property
  53. def icon(self):
  54. """Return the icon to use in the frontend for this device."""
  55. icon = self._config.icon(self._device)
  56. if icon:
  57. return icon
  58. else:
  59. return super().icon
  60. @property
  61. def extra_state_attributes(self):
  62. """Get additional attributes that the platform itself does not support."""
  63. attr = {}
  64. for a in self._attr_dps:
  65. value = a.get_value(self._device)
  66. if value is not None or not a.optional:
  67. attr[a.name] = value
  68. return attr
  69. async def async_update(self):
  70. await self._device.async_refresh()
  71. UNIT_ASCII_MAP = {
  72. "C": UnitOfTemperature.CELSIUS,
  73. "F": UnitOfTemperature.FAHRENHEIT,
  74. "ugm3": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
  75. "m2": AREA_SQUARE_METERS,
  76. }
  77. def unit_from_ascii(unit):
  78. if unit in UNIT_ASCII_MAP:
  79. return UNIT_ASCII_MAP[unit]
  80. return unit