curtain.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import logging
  4. from typing import Any
  5. from .device import REQ_HEADER, SwitchbotDevice
  6. # Curtain keys
  7. CURTAIN_COMMAND = "4501"
  8. OPEN_KEY = f"{REQ_HEADER}{CURTAIN_COMMAND}010100"
  9. CLOSE_KEY = f"{REQ_HEADER}{CURTAIN_COMMAND}010164"
  10. POSITION_KEY = f"{REQ_HEADER}{CURTAIN_COMMAND}0101" # +actual_position
  11. STOP_KEY = f"{REQ_HEADER}{CURTAIN_COMMAND}0001"
  12. CURTAIN_EXT_SUM_KEY = f"{REQ_HEADER}460401"
  13. CURTAIN_EXT_ADV_KEY = f"{REQ_HEADER}460402"
  14. CURTAIN_EXT_CHAIN_INFO_KEY = f"{REQ_HEADER}468101"
  15. _LOGGER = logging.getLogger(__name__)
  16. class SwitchbotCurtain(SwitchbotDevice):
  17. """Representation of a Switchbot Curtain."""
  18. def __init__(self, *args: Any, **kwargs: Any) -> None:
  19. """Switchbot Curtain/WoCurtain constructor."""
  20. # The position of the curtain is saved returned with 0 = open and 100 = closed.
  21. # This is independent of the calibration of the curtain bot (Open left to right/
  22. # Open right to left/Open from the middle).
  23. # The parameter 'reverse_mode' reverse these values,
  24. # if 'reverse_mode' = True, position = 0 equals close
  25. # and position = 100 equals open. The parameter is default set to True so that
  26. # the definition of position is the same as in Home Assistant.
  27. super().__init__(*args, **kwargs)
  28. self._reverse: bool = kwargs.pop("reverse_mode", True)
  29. self._settings: dict[str, Any] = {}
  30. self.ext_info_sum: dict[str, Any] = {}
  31. self.ext_info_adv: dict[str, Any] = {}
  32. async def open(self) -> bool:
  33. """Send open command."""
  34. result = await self._send_command(OPEN_KEY)
  35. return self._check_command_result(result, 0, {1})
  36. async def close(self) -> bool:
  37. """Send close command."""
  38. result = await self._send_command(CLOSE_KEY)
  39. return self._check_command_result(result, 0, {1})
  40. async def stop(self) -> bool:
  41. """Send stop command to device."""
  42. result = await self._send_command(STOP_KEY)
  43. return self._check_command_result(result, 0, {1})
  44. async def set_position(self, position: int) -> bool:
  45. """Send position command (0-100) to device."""
  46. position = (100 - position) if self._reverse else position
  47. hex_position = "%0.2X" % position
  48. result = await self._send_command(POSITION_KEY + hex_position)
  49. return self._check_command_result(result, 0, {1})
  50. async def update(self, interface: int | None = None) -> None:
  51. """Update position, battery percent and light level of device."""
  52. await self.get_device_data(retry=self._retry_count, interface=interface)
  53. def get_position(self) -> Any:
  54. """Return cached position (0-100) of Curtain."""
  55. # To get actual position call update() first.
  56. return self._get_adv_value("position")
  57. async def get_basic_info(self) -> dict[str, Any] | None:
  58. """Get device basic settings."""
  59. if not (_data := await self._get_basic_info()):
  60. return None
  61. _position = max(min(_data[6], 100), 0)
  62. return {
  63. "battery": _data[1],
  64. "firmware": _data[2] / 10.0,
  65. "chainLength": _data[3],
  66. "openDirection": (
  67. "right_to_left" if _data[4] & 0b10000000 == 128 else "left_to_right"
  68. ),
  69. "touchToOpen": bool(_data[4] & 0b01000000),
  70. "light": bool(_data[4] & 0b00100000),
  71. "fault": bool(_data[4] & 0b00001000),
  72. "solarPanel": bool(_data[5] & 0b00001000),
  73. "calibrated": bool(_data[5] & 0b00000100),
  74. "inMotion": bool(_data[5] & 0b01000011),
  75. "position": (100 - _position) if self._reverse else _position,
  76. "timers": _data[7],
  77. }
  78. async def get_extended_info_summary(self) -> dict[str, Any] | None:
  79. """Get basic info for all devices in chain."""
  80. _data = await self._send_command(key=CURTAIN_EXT_SUM_KEY)
  81. if not _data:
  82. _LOGGER.error("%s: Unsuccessful, no result from device", self.name)
  83. return None
  84. if _data in (b"\x07", b"\x00"):
  85. _LOGGER.error("%s: Unsuccessful, please try again", self.name)
  86. return None
  87. self.ext_info_sum["device0"] = {
  88. "openDirectionDefault": not bool(_data[1] & 0b10000000),
  89. "touchToOpen": bool(_data[1] & 0b01000000),
  90. "light": bool(_data[1] & 0b00100000),
  91. "openDirection": (
  92. "left_to_right" if _data[1] & 0b00010000 == 1 else "right_to_left"
  93. ),
  94. }
  95. # if grouped curtain device present.
  96. if _data[2] != 0:
  97. self.ext_info_sum["device1"] = {
  98. "openDirectionDefault": not bool(_data[1] & 0b10000000),
  99. "touchToOpen": bool(_data[1] & 0b01000000),
  100. "light": bool(_data[1] & 0b00100000),
  101. "openDirection": (
  102. "left_to_right" if _data[1] & 0b00010000 else "right_to_left"
  103. ),
  104. }
  105. return self.ext_info_sum
  106. async def get_extended_info_adv(self) -> dict[str, Any] | None:
  107. """Get advance page info for device chain."""
  108. _data = await self._send_command(key=CURTAIN_EXT_ADV_KEY)
  109. if not _data:
  110. _LOGGER.error("%s: Unsuccessful, no result from device", self.name)
  111. return None
  112. if _data in (b"\x07", b"\x00"):
  113. _LOGGER.error("%s: Unsuccessful, please try again", self.name)
  114. return None
  115. _state_of_charge = [
  116. "not_charging",
  117. "charging_by_adapter",
  118. "charging_by_solar",
  119. "fully_charged",
  120. "solar_not_charging",
  121. "charging_error",
  122. ]
  123. self.ext_info_adv["device0"] = {
  124. "battery": _data[1],
  125. "firmware": _data[2] / 10.0,
  126. "stateOfCharge": _state_of_charge[_data[3]],
  127. }
  128. # If grouped curtain device present.
  129. if _data[4]:
  130. self.ext_info_adv["device1"] = {
  131. "battery": _data[4],
  132. "firmware": _data[5] / 10.0,
  133. "stateOfCharge": _state_of_charge[_data[6]],
  134. }
  135. return self.ext_info_adv
  136. def get_light_level(self) -> Any:
  137. """Return cached light level."""
  138. # To get actual light level call update() first.
  139. return self._get_adv_value("lightLevel")
  140. def is_reversed(self) -> bool:
  141. """Return True if curtain position is opposite from SB data."""
  142. return self._reverse
  143. def is_calibrated(self) -> Any:
  144. """Return True curtain is calibrated."""
  145. # To get actual light level call update() first.
  146. return self._get_adv_value("calibration")