sensor.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. Platform to read Tuya sensors.
  3. """
  4. from homeassistant.components.sensor import (
  5. DEVICE_CLASSES,
  6. SensorEntity,
  7. STATE_CLASSES,
  8. )
  9. from ..device import TuyaLocalDevice
  10. from ..helpers.device_config import TuyaEntityConfig
  11. from ..helpers.mixin import TuyaLocalEntity, unit_from_ascii
  12. class TuyaLocalSensor(TuyaLocalEntity, SensorEntity):
  13. """Representation of a Tuya Sensor"""
  14. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  15. """
  16. Initialise the sensor.
  17. Args:
  18. device (TuyaLocalDevice): the device API instance.
  19. config (TuyaEntityConfig): the configuration for this entity
  20. """
  21. dps_map = self._init_begin(device, config)
  22. self._sensor_dps = dps_map.pop("sensor", None)
  23. if self._sensor_dps is None:
  24. raise AttributeError(f"{config.name} is missing a sensor dps")
  25. self._unit_dps = dps_map.pop("unit", None)
  26. self._init_end(dps_map)
  27. @property
  28. def device_class(self):
  29. """Return the class of this device"""
  30. dclass = self._config.device_class
  31. if dclass in DEVICE_CLASSES:
  32. return dclass
  33. else:
  34. return None
  35. @property
  36. def state_class(self):
  37. """Return the state class of this entity"""
  38. sclass = self._sensor_dps.state_class
  39. if sclass in STATE_CLASSES:
  40. return sclass
  41. else:
  42. return None
  43. @property
  44. def native_value(self):
  45. """Return the value reported by the sensor"""
  46. return self._sensor_dps.get_value(self._device)
  47. @property
  48. def native_unit_of_measurement(self):
  49. """Return the unit for the sensor"""
  50. if self._unit_dps is None:
  51. unit = self._sensor_dps.unit
  52. else:
  53. unit = self._unit_dps.get_value(self._device)
  54. return unit_from_ascii(unit)