mixin.py 2.0 KB

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