mixin.py 2.2 KB

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