switch.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. Platform to control Tuya switches.
  3. Initially based on the Kogan Switch and secondary switch for Purline M100
  4. heater open window detector toggle.
  5. """
  6. from homeassistant.components.switch import SwitchEntity, SwitchDeviceClass
  7. from homeassistant.const import STATE_UNAVAILABLE
  8. from ..device import TuyaLocalDevice
  9. from ..helpers.device_config import TuyaEntityConfig
  10. from ..helpers.mixin import TuyaLocalEntity
  11. class TuyaLocalSwitch(TuyaLocalEntity, SwitchEntity):
  12. """Representation of a Tuya Switch"""
  13. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  14. """
  15. Initialize the switch.
  16. Args:
  17. device (TuyaLocalDevice): The device API instance.
  18. """
  19. dps_map = self._init_begin(device, config)
  20. self._switch_dps = dps_map.pop("switch")
  21. self._power_dps = dps_map.get("current_power_w", None)
  22. self._init_end(dps_map)
  23. @property
  24. def device_class(self):
  25. """Return the class of this device"""
  26. return (
  27. SwitchDeviceClass.OUTLET
  28. if self._config.device_class == "outlet"
  29. else SwitchDeviceClass.SWITCH
  30. )
  31. @property
  32. def is_on(self):
  33. """Return whether the switch is on or not."""
  34. # if there is no switch, it is always on if available.
  35. if self._switch_dps is None:
  36. return self.available
  37. return self._switch_dps.get_value(self._device)
  38. @property
  39. def current_power_w(self):
  40. """Return the current power consumption in Watts."""
  41. if self._power_dps is None:
  42. return None
  43. pwr = self._power_dps.get_value(self._device)
  44. if pwr is None:
  45. return STATE_UNAVAILABLE
  46. return pwr
  47. async def async_turn_on(self, **kwargs):
  48. """Turn the switch on"""
  49. await self._switch_dps.async_set_value(self._device, True)
  50. async def async_turn_off(self, **kwargs):
  51. """Turn the switch off"""
  52. await self._switch_dps.async_set_value(self._device, False)