mixin.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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(self._device.name)
  34. @property
  35. def unique_id(self):
  36. """Return the unique id for this entity."""
  37. return self._config.unique_id(self._device.unique_id)
  38. @property
  39. def device_info(self):
  40. """Return the device's information."""
  41. return self._device.device_info
  42. @property
  43. def entity_category(self):
  44. """Return the entitiy's category."""
  45. return (
  46. None
  47. if self._config.entity_category is None
  48. else EntityCategory(self._config.entity_category)
  49. )
  50. @property
  51. def icon(self):
  52. """Return the icon to use in the frontend for this device."""
  53. icon = self._config.icon(self._device)
  54. if icon:
  55. return icon
  56. else:
  57. return super().icon
  58. @property
  59. def extra_state_attributes(self):
  60. """Get additional attributes that the platform itself does not support."""
  61. attr = {}
  62. for a in self._attr_dps:
  63. attr[a.name] = a.get_value(self._device)
  64. return attr
  65. async def async_update(self):
  66. await self._device.async_refresh()
  67. UNIT_ASCII_MAP = {
  68. "C": TEMP_CELSIUS,
  69. "F": TEMP_FAHRENHEIT,
  70. "ugm3": CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
  71. "m2": AREA_SQUARE_METERS,
  72. }
  73. def unit_from_ascii(unit):
  74. if unit in UNIT_ASCII_MAP:
  75. return UNIT_ASCII_MAP[unit]
  76. return unit