sensor.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. Setup for different kinds of Tuya sensors
  3. """
  4. from homeassistant.components.sensor import (
  5. SensorDeviceClass,
  6. SensorEntity,
  7. STATE_CLASSES,
  8. )
  9. import logging
  10. from .device import TuyaLocalDevice
  11. from .helpers.config import async_tuya_setup_platform
  12. from .helpers.device_config import TuyaEntityConfig
  13. from .helpers.mixin import TuyaLocalEntity, unit_from_ascii
  14. _LOGGER = logging.getLogger(__name__)
  15. async def async_setup_entry(hass, config_entry, async_add_entities):
  16. config = {**config_entry.data, **config_entry.options}
  17. await async_tuya_setup_platform(
  18. hass,
  19. async_add_entities,
  20. config,
  21. "sensor",
  22. TuyaLocalSensor,
  23. )
  24. class TuyaLocalSensor(TuyaLocalEntity, SensorEntity):
  25. """Representation of a Tuya Sensor"""
  26. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  27. """
  28. Initialise the sensor.
  29. Args:
  30. device (TuyaLocalDevice): the device API instance.
  31. config (TuyaEntityConfig): the configuration for this entity
  32. """
  33. dps_map = self._init_begin(device, config)
  34. self._sensor_dps = dps_map.pop("sensor", None)
  35. if self._sensor_dps is None:
  36. raise AttributeError(f"{config.name} is missing a sensor dps")
  37. self._unit_dps = dps_map.pop("unit", None)
  38. self._init_end(dps_map)
  39. @property
  40. def device_class(self):
  41. """Return the class of this device"""
  42. dclass = self._config.device_class
  43. try:
  44. return SensorDeviceClass(dclass)
  45. except ValueError:
  46. if dclass:
  47. _LOGGER.warning(f"Unrecognized sensor device class of {dclass} ignored")
  48. return None
  49. @property
  50. def state_class(self):
  51. """Return the state class of this entity"""
  52. sclass = self._sensor_dps.state_class
  53. if sclass in STATE_CLASSES:
  54. return sclass
  55. else:
  56. return None
  57. @property
  58. def native_value(self):
  59. """Return the value reported by the sensor"""
  60. return self._sensor_dps.get_value(self._device)
  61. @property
  62. def native_unit_of_measurement(self):
  63. """Return the unit for the sensor"""
  64. if self._unit_dps is None:
  65. unit = self._sensor_dps.unit
  66. else:
  67. unit = self._unit_dps.get_value(self._device)
  68. return unit_from_ascii(unit)
  69. @property
  70. def native_precision(self):
  71. """Return the precision for the sensor"""
  72. return self._sensor_dps.precision(self._device)
  73. @property
  74. def options(self):
  75. """Return a set of possible options."""
  76. return self._sensor_dps.values(self._device)