bot.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import logging
  4. from typing import Any
  5. from .device import (
  6. DEVICE_SET_EXTENDED_KEY,
  7. DEVICE_SET_MODE_KEY,
  8. SwitchbotDeviceOverrideStateDuringConnection,
  9. )
  10. _LOGGER = logging.getLogger(__name__)
  11. BOT_COMMAND_HEADER = "5701"
  12. # Bot keys
  13. PRESS_KEY = f"{BOT_COMMAND_HEADER}00"
  14. ON_KEY = f"{BOT_COMMAND_HEADER}01"
  15. OFF_KEY = f"{BOT_COMMAND_HEADER}02"
  16. DOWN_KEY = f"{BOT_COMMAND_HEADER}03"
  17. UP_KEY = f"{BOT_COMMAND_HEADER}04"
  18. class Switchbot(SwitchbotDeviceOverrideStateDuringConnection):
  19. """Representation of a Switchbot."""
  20. def __init__(self, *args: Any, **kwargs: Any) -> None:
  21. """Switchbot Bot/WoHand constructor."""
  22. super().__init__(*args, **kwargs)
  23. self._inverse: bool = kwargs.pop("inverse_mode", False)
  24. async def update(self, interface: int | None = None) -> None:
  25. """Update mode, battery percent and state of device."""
  26. await self.get_device_data(retry=self._retry_count, interface=interface)
  27. async def turn_on(self) -> bool:
  28. """Turn device on."""
  29. result = await self._send_command(ON_KEY)
  30. ret = self._check_command_result(result, 0, {1, 5})
  31. self._override_adv_data = {"isOn": True}
  32. _LOGGER.debug(
  33. "%s: Turn on result: %s -> %s",
  34. self.name,
  35. result.hex() if result else None,
  36. self._override_adv_data,
  37. )
  38. self._fire_callbacks()
  39. return ret
  40. async def turn_off(self) -> bool:
  41. """Turn device off."""
  42. result = await self._send_command(OFF_KEY)
  43. ret = self._check_command_result(result, 0, {1, 5})
  44. self._override_adv_data = {"isOn": False}
  45. _LOGGER.debug(
  46. "%s: Turn off result: %s -> %s",
  47. self.name,
  48. result.hex() if result else None,
  49. self._override_adv_data,
  50. )
  51. self._fire_callbacks()
  52. return ret
  53. async def hand_up(self) -> bool:
  54. """Raise device arm."""
  55. result = await self._send_command(UP_KEY)
  56. return self._check_command_result(result, 0, {1, 5})
  57. async def hand_down(self) -> bool:
  58. """Lower device arm."""
  59. result = await self._send_command(DOWN_KEY)
  60. return self._check_command_result(result, 0, {1, 5})
  61. async def press(self) -> bool:
  62. """Press command to device."""
  63. result = await self._send_command(PRESS_KEY)
  64. return self._check_command_result(result, 0, {1, 5})
  65. async def set_switch_mode(
  66. self, switch_mode: bool = False, strength: int = 100, inverse: bool = False
  67. ) -> bool:
  68. """Change bot mode."""
  69. mode_key = format(switch_mode, "b") + format(inverse, "b")
  70. strength_key = f"{strength:0{2}x}" # to hex with padding to double digit
  71. result = await self._send_command(DEVICE_SET_MODE_KEY + strength_key + mode_key)
  72. return self._check_command_result(result, 0, {1})
  73. async def set_long_press(self, duration: int = 0) -> bool:
  74. """Set bot long press duration."""
  75. duration_key = f"{duration:0{2}x}" # to hex with padding to double digit
  76. result = await self._send_command(DEVICE_SET_EXTENDED_KEY + "08" + duration_key)
  77. return self._check_command_result(result, 0, {1})
  78. async def get_basic_info(self) -> dict[str, Any] | None:
  79. """Get device basic settings."""
  80. if not (_data := await self._get_basic_info()):
  81. return None
  82. return {
  83. "battery": _data[1],
  84. "firmware": _data[2] / 10.0,
  85. "strength": _data[3],
  86. "timers": _data[8],
  87. "switchMode": bool(_data[9] & 16),
  88. "inverseDirection": bool(_data[9] & 1),
  89. "holdSeconds": _data[10],
  90. }
  91. def is_on(self) -> bool | None:
  92. """Return switch state from cache."""
  93. # To get actual position call update() first.
  94. value = self._get_adv_value("isOn")
  95. if value is None:
  96. return None
  97. if self._inverse:
  98. return not value
  99. return value