switch.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """
  2. Setup for different kinds of Tuya switch devices
  3. """
  4. from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
  5. from .device import TuyaLocalDevice
  6. from .helpers.config import async_tuya_setup_platform
  7. from .helpers.device_config import TuyaEntityConfig
  8. from .helpers.mixin import TuyaLocalEntity
  9. async def async_setup_entry(hass, config_entry, async_add_entities):
  10. config = {**config_entry.data, **config_entry.options}
  11. await async_tuya_setup_platform(
  12. hass,
  13. async_add_entities,
  14. config,
  15. "switch",
  16. TuyaLocalSwitch,
  17. )
  18. class TuyaLocalSwitch(TuyaLocalEntity, SwitchEntity):
  19. """Representation of a Tuya Switch"""
  20. def __init__(self, device: TuyaLocalDevice, config: TuyaEntityConfig):
  21. """
  22. Initialize the switch.
  23. Args:
  24. device (TuyaLocalDevice): The device API instance.
  25. """
  26. super().__init__()
  27. dps_map = self._init_begin(device, config)
  28. self._switch_dps = dps_map.pop("switch")
  29. self._init_end(dps_map)
  30. @property
  31. def device_class(self):
  32. """Return the class of this device"""
  33. return (
  34. SwitchDeviceClass.OUTLET
  35. if self._config.device_class == "outlet"
  36. else SwitchDeviceClass.SWITCH
  37. )
  38. @property
  39. def is_on(self):
  40. """Return whether the switch is on or not."""
  41. # if there is no switch, it is always on if available.
  42. if self._switch_dps is None:
  43. return self.available
  44. return self._switch_dps.get_value(self._device)
  45. async def async_turn_on(self, **kwargs):
  46. """Turn the switch on"""
  47. await self._switch_dps.async_set_value(self._device, True)
  48. async def async_turn_off(self, **kwargs):
  49. """Turn the switch off"""
  50. await self._switch_dps.async_set_value(self._device, False)