curtain.py 6.6 KB

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