mixin.py 2.5 KB

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