switch.py 2.2 KB

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