switch.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 ..device import TuyaLocalDevice
  8. from ..helpers.device_config import TuyaEntityConfig
  9. from ..helpers.mixin import TuyaLocalEntity
  10. class TuyaLocalSwitch(TuyaLocalEntity, SwitchEntity):
  11. """Representation of a Tuya Switch"""
  12. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  13. """
  14. Initialize the switch.
  15. Args:
  16. device (TuyaLocalDevice): The device API instance.
  17. """
  18. dps_map = self._init_begin(device, config)
  19. self._switch_dps = dps_map.pop("switch")
  20. self._power_dps = dps_map.get("current_power_w", None)
  21. self._init_end(dps_map)
  22. @property
  23. def device_class(self):
  24. """Return the class of this device"""
  25. return (
  26. SwitchDeviceClass.OUTLET
  27. if self._config.device_class == "outlet"
  28. else SwitchDeviceClass.SWITCH
  29. )
  30. @property
  31. def is_on(self):
  32. """Return whether the switch is on or not."""
  33. # if there is no switch, it is always on if available.
  34. if self._switch_dps is None:
  35. return self.available
  36. return self._switch_dps.get_value(self._device)
  37. @property
  38. def current_power_w(self):
  39. """Return the current power consumption in Watts."""
  40. if self._power_dps is None:
  41. return None
  42. pwr = self._power_dps.get_value(self._device)
  43. return pwr
  44. async def async_turn_on(self, **kwargs):
  45. """Turn the switch on"""
  46. await self._switch_dps.async_set_value(self._device, True)
  47. async def async_turn_off(self, **kwargs):
  48. """Turn the switch off"""
  49. await self._switch_dps.async_set_value(self._device, False)