base_cover.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import logging
  4. from abc import abstractmethod
  5. from typing import Any
  6. from ..models import SwitchBotAdvertisement
  7. from .device import REQ_HEADER, SwitchbotDevice, update_after_operation
  8. # Cover keys
  9. COVER_COMMAND = "4501"
  10. # For second element of open and close arrs we should add two bytes i.e. ff00
  11. # First byte [ff] stands for speed (00 or ff - normal, 01 - slow) *
  12. # * Only for curtains 3. For other models use ff
  13. # Second byte [00] is a command (00 - open, 64 - close)
  14. POSITION_KEYS = [
  15. f"{REQ_HEADER}{COVER_COMMAND}0101",
  16. f"{REQ_HEADER}{COVER_COMMAND}05", # +speed
  17. ] # +actual_position
  18. STOP_KEYS = [f"{REQ_HEADER}{COVER_COMMAND}0001", f"{REQ_HEADER}{COVER_COMMAND}00ff"]
  19. COVER_EXT_SUM_KEY = f"{REQ_HEADER}460401"
  20. COVER_EXT_ADV_KEY = f"{REQ_HEADER}460402"
  21. _LOGGER = logging.getLogger(__name__)
  22. class SwitchbotBaseCover(SwitchbotDevice):
  23. """Representation of a Switchbot Cover devices for both curtains and tilt blinds."""
  24. def __init__(self, reverse: bool, *args: Any, **kwargs: Any) -> None:
  25. """Switchbot Cover device constructor."""
  26. super().__init__(*args, **kwargs)
  27. self._reverse = reverse
  28. self._settings: dict[str, Any] = {}
  29. self.ext_info_sum: dict[str, Any] = {}
  30. self.ext_info_adv: dict[str, Any] = {}
  31. self._is_opening: bool = False
  32. self._is_closing: bool = False
  33. async def _send_multiple_commands(self, keys: list[str]) -> bool:
  34. """Send multiple commands to device.
  35. Since we current have no way to tell which command the device
  36. needs we send both.
  37. """
  38. final_result = False
  39. for key in keys:
  40. result = await self._send_command(key)
  41. final_result |= self._check_command_result(result, 0, {1})
  42. return final_result
  43. @update_after_operation
  44. async def stop(self) -> bool:
  45. """Send stop command to device."""
  46. return await self._send_multiple_commands(STOP_KEYS)
  47. @update_after_operation
  48. async def set_position(self, position: int, speed: int = 255) -> bool:
  49. """Send position command (0-100) to device. Speed 255 - normal, 1 - slow"""
  50. position = (100 - position) if self._reverse else position
  51. return await self._send_multiple_commands(
  52. [
  53. f"{POSITION_KEYS[0]}{position:02X}",
  54. f"{POSITION_KEYS[1]}{speed:02X}{position:02X}",
  55. ]
  56. )
  57. @abstractmethod
  58. def get_position(self) -> Any:
  59. """Return current device position."""
  60. @abstractmethod
  61. async def get_basic_info(self) -> dict[str, Any] | None:
  62. """Get device basic settings."""
  63. @abstractmethod
  64. async def get_extended_info_summary(self) -> dict[str, Any] | None:
  65. """Get extended info for all devices in chain."""
  66. async def get_extended_info_adv(self) -> dict[str, Any] | None:
  67. """Get advance page info for device chain."""
  68. _data = await self._send_command(key=COVER_EXT_ADV_KEY)
  69. if not _data:
  70. _LOGGER.error("%s: Unsuccessful, no result from device", self.name)
  71. return None
  72. if _data in (b"\x07", b"\x00"):
  73. _LOGGER.error("%s: Unsuccessful, please try again", self.name)
  74. return None
  75. _state_of_charge = [
  76. "not_charging",
  77. "charging_by_adapter",
  78. "charging_by_solar",
  79. "fully_charged",
  80. "solar_not_charging",
  81. "charging_error",
  82. ]
  83. self.ext_info_adv["device0"] = {
  84. "battery": _data[1],
  85. "firmware": _data[2] / 10.0,
  86. "stateOfCharge": _state_of_charge[_data[3]],
  87. }
  88. # If grouped curtain device present.
  89. if _data[4]:
  90. self.ext_info_adv["device1"] = {
  91. "battery": _data[4],
  92. "firmware": _data[5] / 10.0,
  93. "stateOfCharge": _state_of_charge[_data[6]],
  94. }
  95. return self.ext_info_adv
  96. def get_light_level(self) -> Any:
  97. """Return cached light level."""
  98. # To get actual light level call update() first.
  99. return self._get_adv_value("lightLevel")
  100. def is_reversed(self) -> bool:
  101. """Return True if curtain position is opposite from SB data."""
  102. return self._reverse
  103. def is_calibrated(self) -> Any:
  104. """Return True curtain is calibrated."""
  105. # To get actual light level call update() first.
  106. return self._get_adv_value("calibration")
  107. def is_opening(self) -> bool:
  108. """Return True if the curtain is opening."""
  109. return self._is_opening
  110. def is_closing(self) -> bool:
  111. """Return True if the curtain is closing."""
  112. return self._is_closing