sensor.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """
  2. Platform to read 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.device_config import TuyaEntityConfig
  12. from ..helpers.mixin import TuyaLocalEntity, unit_from_ascii
  13. _LOGGER = logging.getLogger(__name__)
  14. class TuyaLocalSensor(TuyaLocalEntity, SensorEntity):
  15. """Representation of a Tuya Sensor"""
  16. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  17. """
  18. Initialise the sensor.
  19. Args:
  20. device (TuyaLocalDevice): the device API instance.
  21. config (TuyaEntityConfig): the configuration for this entity
  22. """
  23. dps_map = self._init_begin(device, config)
  24. self._sensor_dps = dps_map.pop("sensor", None)
  25. if self._sensor_dps is None:
  26. raise AttributeError(f"{config.name} is missing a sensor dps")
  27. self._unit_dps = dps_map.pop("unit", None)
  28. self._init_end(dps_map)
  29. @property
  30. def device_class(self):
  31. """Return the class of this device"""
  32. dclass = self._config.device_class
  33. try:
  34. return SensorDeviceClass(dclass)
  35. except ValueError:
  36. if dclass:
  37. _LOGGER.warning(f"Unrecognized sensor device class of {dclass} ignored")
  38. return None
  39. @property
  40. def state_class(self):
  41. """Return the state class of this entity"""
  42. sclass = self._sensor_dps.state_class
  43. if sclass in STATE_CLASSES:
  44. return sclass
  45. else:
  46. return None
  47. @property
  48. def native_value(self):
  49. """Return the value reported by the sensor"""
  50. return self._sensor_dps.get_value(self._device)
  51. @property
  52. def native_unit_of_measurement(self):
  53. """Return the unit for the sensor"""
  54. if self._unit_dps is None:
  55. unit = self._sensor_dps.unit
  56. else:
  57. unit = self._unit_dps.get_value(self._device)
  58. return unit_from_ascii(unit)