switch.py 2.1 KB

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