sensor.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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", None)
  20. if self._sensor_dps is None:
  21. raise AttributeError(f"{config.name} is missing a sensor dps")
  22. self._unit_dps = dps_map.pop("unit", None)
  23. self._init_end(dps_map)
  24. @property
  25. def device_class(self):
  26. """Return the class of this device"""
  27. dclass = self._config.device_class
  28. if dclass in DEVICE_CLASSES:
  29. return dclass
  30. else:
  31. return None
  32. @property
  33. def state_class(self):
  34. """Return the state class of this entity"""
  35. sclass = self._sensor_dps.state_class
  36. if sclass in STATE_CLASSES:
  37. return sclass
  38. else:
  39. return None
  40. @property
  41. def native_value(self):
  42. """Return the value reported by the sensor"""
  43. return self._sensor_dps.get_value(self._device)
  44. @property
  45. def native_unit_of_measurement(self):
  46. """Return the unit for the sensor"""
  47. if self._unit_dps is None:
  48. unit = self._sensor_dps.unit
  49. else:
  50. unit = self._unit_dps.get_value(self._device)
  51. # Temperatures use Unicode characters, translate from simpler ASCII
  52. if unit == "C":
  53. unit = TEMP_CELSIUS
  54. elif unit == "F":
  55. unit = TEMP_FAHRENHEIT
  56. return unit