sensor.py 1.9 KB

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