bulb.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. from __future__ import annotations
  2. from typing import Any
  3. from .device import SwitchbotDevice
  4. REQ_HEADER = "570f"
  5. BULB_COMMMAND_HEADER = "4701"
  6. BULB_REQUEST = f"{REQ_HEADER}4801"
  7. BULB_COMMAND = f"{REQ_HEADER}{BULB_COMMMAND_HEADER}"
  8. # Bulb keys
  9. BULB_ON_KEY = f"{BULB_COMMAND}01"
  10. BULB_OFF_KEY = f"{BULB_COMMAND}02"
  11. RGB_BRIGHTNESS_KEY = f"{BULB_COMMAND}12"
  12. CW_BRIGHTNESS_KEY = f"{BULB_COMMAND}13"
  13. BRIGHTNESS_KEY = f"{BULB_COMMAND}14"
  14. RGB_KEY = f"{BULB_COMMAND}16"
  15. CW_KEY = f"{BULB_COMMAND}17"
  16. class SwitchbotBulb(SwitchbotDevice):
  17. """Representation of a Switchbot bulb."""
  18. def __init__(self, *args: Any, **kwargs: Any) -> None:
  19. """Switchbot bulb constructor."""
  20. super().__init__(*args, **kwargs)
  21. self._settings: dict[str, Any] = {}
  22. async def update(self, interface: int | None = None) -> None:
  23. """Update state of device."""
  24. result = await self._sendcommand(BULB_REQUEST)
  25. async def turn_on(self) -> bool:
  26. """Turn device on."""
  27. result = await self._sendcommand(BULB_ON_KEY)
  28. return result[1] == 0x80
  29. async def turn_off(self) -> bool:
  30. """Turn device off."""
  31. result = await self._sendcommand(BULB_OFF_KEY)
  32. return result[1] == 0x00
  33. async def set_brightness(self, brightness: int) -> bool:
  34. """Set brightness."""
  35. assert 0 <= brightness <= 100, "Brightness must be between 0 and 100"
  36. result = await self._sendcommand(f"{BRIGHTNESS_KEY}{brightness:02X}")
  37. return result[1] == 0x80
  38. async def set_color_temp(self, brightness: int, color_temp: int) -> bool:
  39. """Set color temp."""
  40. assert 0 <= brightness <= 100, "Brightness must be between 0 and 100"
  41. assert 2700 <= color_temp <= 6500, "Color Temp must be between 0 and 100"
  42. result = await self._sendcommand(
  43. f"{CW_BRIGHTNESS_KEY}{brightness:02X}{color_temp:04X}"
  44. )
  45. return result[1] == 0x80
  46. async def set_rgb(self, brightness: int, r: int, g: int, b: int) -> bool:
  47. """Set rgb."""
  48. assert 0 <= brightness <= 100, "Brightness must be between 0 and 100"
  49. assert 0 <= r <= 255, "r must be between 0 and 255"
  50. assert 0 <= g <= 255, "g must be between 0 and 255"
  51. assert 0 <= b <= 255, "b must be between 0 and 255"
  52. result = await self._sendcommand(
  53. f"{RGB_BRIGHTNESS_KEY}{brightness:02X}{r:02X}{g:02X}{b:02X}"
  54. )
  55. return result[1] == 0x80
  56. async def turn_off(self) -> bool:
  57. """Turn device off."""
  58. result = await self._sendcommand(BULB_OFF_KEY)
  59. return result[1] == 0x00
  60. def is_on(self) -> bool | None:
  61. """Return blub state from cache."""
  62. return self._get_adv_value("isOn")