__init__.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import asyncio
  4. import binascii
  5. import logging
  6. from dataclasses import dataclass
  7. from typing import Any
  8. from uuid import UUID
  9. import bleak
  10. from bleak.backends.device import BLEDevice
  11. from bleak.backends.scanner import AdvertisementData
  12. from bleak_retry_connector import BleakClient, establish_connection
  13. DEFAULT_RETRY_COUNT = 3
  14. DEFAULT_RETRY_TIMEOUT = 1
  15. DEFAULT_SCAN_TIMEOUT = 5
  16. # Keys common to all device types
  17. DEVICE_GET_BASIC_SETTINGS_KEY = "5702"
  18. DEVICE_SET_MODE_KEY = "5703"
  19. DEVICE_SET_EXTENDED_KEY = "570f"
  20. # Bot keys
  21. PRESS_KEY = "570100"
  22. ON_KEY = "570101"
  23. OFF_KEY = "570102"
  24. DOWN_KEY = "570103"
  25. UP_KEY = "570104"
  26. # Curtain keys
  27. OPEN_KEY = "570f450105ff00" # 570F4501010100
  28. CLOSE_KEY = "570f450105ff64" # 570F4501010164
  29. POSITION_KEY = "570F450105ff" # +actual_position ex: 570F450105ff32 for 50%
  30. STOP_KEY = "570F450100ff"
  31. CURTAIN_EXT_SUM_KEY = "570f460401"
  32. CURTAIN_EXT_ADV_KEY = "570f460402"
  33. CURTAIN_EXT_CHAIN_INFO_KEY = "570f468101"
  34. # Base key when encryption is set
  35. KEY_PASSWORD_PREFIX = "571"
  36. _LOGGER = logging.getLogger(__name__)
  37. CONNECT_LOCK = asyncio.Lock()
  38. def _sb_uuid(comms_type: str = "service") -> UUID | str:
  39. """Return Switchbot UUID."""
  40. _uuid = {"tx": "002", "rx": "003", "service": "d00"}
  41. if comms_type in _uuid:
  42. return UUID(f"cba20{_uuid[comms_type]}-224d-11e6-9fb8-0002a5d5c51b")
  43. return "Incorrect type, choose between: tx, rx or service"
  44. def _process_wohand(data: bytes) -> dict[str, bool | int]:
  45. """Process woHand/Bot services data."""
  46. _switch_mode = bool(data[1] & 0b10000000)
  47. _bot_data = {
  48. "switchMode": _switch_mode,
  49. "isOn": not bool(data[1] & 0b01000000) if _switch_mode else False,
  50. "battery": data[2] & 0b01111111,
  51. }
  52. return _bot_data
  53. def _process_wocurtain(data: bytes, reverse: bool = True) -> dict[str, bool | int]:
  54. """Process woCurtain/Curtain services data."""
  55. _position = max(min(data[3] & 0b01111111, 100), 0)
  56. _curtain_data = {
  57. "calibration": bool(data[1] & 0b01000000),
  58. "battery": data[2] & 0b01111111,
  59. "inMotion": bool(data[3] & 0b10000000),
  60. "position": (100 - _position) if reverse else _position,
  61. "lightLevel": (data[4] >> 4) & 0b00001111,
  62. "deviceChain": data[4] & 0b00000111,
  63. }
  64. return _curtain_data
  65. def _process_wosensorth(data: bytes) -> dict[str, object]:
  66. """Process woSensorTH/Temp sensor services data."""
  67. _temp_sign = 1 if data[4] & 0b10000000 else -1
  68. _temp_c = _temp_sign * ((data[4] & 0b01111111) + ((data[3] & 0b00001111) / 10))
  69. _temp_f = (_temp_c * 9 / 5) + 32
  70. _temp_f = (_temp_f * 10) / 10
  71. _wosensorth_data = {
  72. "temp": {"c": _temp_c, "f": _temp_f},
  73. "fahrenheit": bool(data[5] & 0b10000000),
  74. "humidity": data[5] & 0b01111111,
  75. "battery": data[2] & 0b01111111,
  76. }
  77. return _wosensorth_data
  78. def _process_wocontact(data: bytes) -> dict[str, bool | int]:
  79. """Process woContact Sensor services data."""
  80. return {
  81. "tested": bool(data[1] & 0b10000000),
  82. "motion_detected": bool(data[1] & 0b01000000),
  83. "battery": data[2] & 0b01111111,
  84. "contact_open": data[3] & 0b00000010 == 0b00000010,
  85. "contact_timeout": data[3] & 0b00000110 == 0b00000110,
  86. "is_light": bool(data[3] & 0b00000001),
  87. "button_count": (data[7] & 0b11110000) >> 4,
  88. }
  89. @dataclass
  90. class SwitchBotAdvertisement:
  91. """Switchbot advertisement."""
  92. address: str
  93. data: dict[str, Any]
  94. device: BLEDevice
  95. def parse_advertisement_data(
  96. device: BLEDevice, advertisement_data: AdvertisementData
  97. ) -> SwitchBotAdvertisement | None:
  98. """Parse advertisement data."""
  99. _services = list(advertisement_data.service_data.values())
  100. if not _services:
  101. return
  102. _service_data = _services[0]
  103. _model = chr(_service_data[0] & 0b01111111)
  104. supported_types: dict[str, dict[str, Any]] = {
  105. "d": {"modelName": "WoContact", "func": _process_wocontact},
  106. "H": {"modelName": "WoHand", "func": _process_wohand},
  107. "c": {"modelName": "WoCurtain", "func": _process_wocurtain},
  108. "T": {"modelName": "WoSensorTH", "func": _process_wosensorth},
  109. "i": {"modelName": "WoSensorTH", "func": _process_wosensorth},
  110. }
  111. data = {
  112. "address": device.address, # MacOS uses UUIDs
  113. "rawAdvData": list(advertisement_data.service_data.values())[0],
  114. "data": {
  115. "rssi": device.rssi,
  116. },
  117. }
  118. if _model in supported_types:
  119. data.update(
  120. {
  121. "isEncrypted": bool(_service_data[0] & 0b10000000),
  122. "model": _model,
  123. "modelName": supported_types[_model]["modelName"],
  124. "data": supported_types[_model]["func"](_service_data),
  125. }
  126. )
  127. data["data"]["rssi"] = device.rssi
  128. return SwitchBotAdvertisement(device.address, data, device)
  129. class GetSwitchbotDevices:
  130. """Scan for all Switchbot devices and return by type."""
  131. def __init__(self, interface: int = 0) -> None:
  132. """Get switchbot devices class constructor."""
  133. self._interface = f"hci{interface}"
  134. self._adv_data: dict[str, SwitchBotAdvertisement] = {}
  135. def detection_callback(
  136. self,
  137. device: BLEDevice,
  138. advertisement_data: AdvertisementData,
  139. ) -> None:
  140. discovery = parse_advertisement_data(device, advertisement_data)
  141. if discovery:
  142. self._adv_data[discovery.address] = discovery
  143. async def discover(
  144. self, retry: int = DEFAULT_RETRY_COUNT, scan_timeout: int = DEFAULT_SCAN_TIMEOUT
  145. ) -> dict:
  146. """Find switchbot devices and their advertisement data."""
  147. devices = None
  148. devices = bleak.BleakScanner(
  149. # TODO: Find new UUIDs to filter on. For example, see
  150. # https://github.com/OpenWonderLabs/SwitchBotAPI-BLE/blob/4ad138bb09f0fbbfa41b152ca327a78c1d0b6ba9/devicetypes/meter.md
  151. adapter=self._interface,
  152. )
  153. devices.register_detection_callback(self.detection_callback)
  154. async with CONNECT_LOCK:
  155. await devices.start()
  156. await asyncio.sleep(scan_timeout)
  157. await devices.stop()
  158. if devices is None:
  159. if retry < 1:
  160. _LOGGER.error(
  161. "Scanning for Switchbot devices failed. Stop trying", exc_info=True
  162. )
  163. return self._adv_data
  164. _LOGGER.warning(
  165. "Error scanning for Switchbot devices. Retrying (remaining: %d)",
  166. retry,
  167. )
  168. await asyncio.sleep(DEFAULT_RETRY_TIMEOUT)
  169. return await self.discover(retry - 1, scan_timeout)
  170. return self._adv_data
  171. async def _get_devices_by_model(
  172. self,
  173. model: str,
  174. ) -> dict:
  175. """Get switchbot devices by type."""
  176. if not self._adv_data:
  177. await self.discover()
  178. return {
  179. address: adv
  180. for address, adv in self._adv_data.items()
  181. if adv.data.get("model") == model
  182. }
  183. async def get_curtains(self) -> dict[str, SwitchBotAdvertisement]:
  184. """Return all WoCurtain/Curtains devices with services data."""
  185. return await self._get_devices_by_model("c")
  186. async def get_bots(self) -> dict[str, SwitchBotAdvertisement]:
  187. """Return all WoHand/Bot devices with services data."""
  188. return await self._get_devices_by_model("H")
  189. async def get_tempsensors(self) -> dict[str, SwitchBotAdvertisement]:
  190. """Return all WoSensorTH/Temp sensor devices with services data."""
  191. base_meters = await self._get_devices_by_model("T")
  192. plus_meters = await self._get_devices_by_model("i")
  193. return {**base_meters, **plus_meters}
  194. async def get_contactsensors(self) -> dict[str, SwitchBotAdvertisement]:
  195. """Return all WoContact/Contact sensor devices with services data."""
  196. return await self._get_devices_by_model("d")
  197. async def get_device_data(
  198. self, address: str
  199. ) -> dict[str, SwitchBotAdvertisement] | None:
  200. """Return data for specific device."""
  201. if not self._adv_data:
  202. await self.discover()
  203. _switchbot_data = {
  204. device: data
  205. for device, data in self._adv_data.items()
  206. # MacOS uses UUIDs instead of MAC addresses
  207. if data.get("address") == address
  208. }
  209. return _switchbot_data
  210. class SwitchbotDevice:
  211. """Base Representation of a Switchbot Device."""
  212. def __init__(
  213. self,
  214. device: BLEDevice,
  215. password: str | None = None,
  216. interface: int = 0,
  217. **kwargs: Any,
  218. ) -> None:
  219. """Switchbot base class constructor."""
  220. self._interface = f"hci{interface}"
  221. self._device = device
  222. self._sb_adv_data: SwitchBotAdvertisement | None = None
  223. self._scan_timeout: int = kwargs.pop("scan_timeout", DEFAULT_SCAN_TIMEOUT)
  224. self._retry_count: int = kwargs.pop("retry_count", DEFAULT_RETRY_COUNT)
  225. if password is None or password == "":
  226. self._password_encoded = None
  227. else:
  228. self._password_encoded = "%x" % (
  229. binascii.crc32(password.encode("ascii")) & 0xFFFFFFFF
  230. )
  231. def _commandkey(self, key: str) -> str:
  232. """Add password to key if set."""
  233. if self._password_encoded is None:
  234. return key
  235. key_action = key[3]
  236. key_suffix = key[4:]
  237. return KEY_PASSWORD_PREFIX + key_action + self._password_encoded + key_suffix
  238. async def _sendcommand(self, key: str, retry: int) -> bytes:
  239. """Send command to device and read response."""
  240. command = bytearray.fromhex(self._commandkey(key))
  241. _LOGGER.debug("Sending command to switchbot %s", command)
  242. max_attempts = retry + 1
  243. async with CONNECT_LOCK:
  244. for attempt in range(max_attempts):
  245. try:
  246. return await self._send_command_locked(key, command)
  247. except (bleak.BleakError, asyncio.exceptions.TimeoutError):
  248. if attempt == retry:
  249. _LOGGER.error(
  250. "Switchbot communication failed. Stopping trying",
  251. exc_info=True,
  252. )
  253. return b"\x00"
  254. _LOGGER.debug("Switchbot communication failed with:", exc_info=True)
  255. raise RuntimeError("Unreachable")
  256. @property
  257. def name(self) -> str:
  258. """Return device name."""
  259. return f"{self._device.name} ({self._device.address})"
  260. async def _send_command_locked(self, key: str, command: bytes) -> bytes:
  261. """Send command to device and read response."""
  262. client: BleakClient | None = None
  263. try:
  264. _LOGGER.debug("%s: Connnecting to switchbot", self.name)
  265. client = await establish_connection(
  266. BleakClient, self._device, self.name, max_attempts=1
  267. )
  268. _LOGGER.debug(
  269. "%s: Connnected to switchbot: %s", self.name, client.is_connected
  270. )
  271. future: asyncio.Future[bytearray] = asyncio.Future()
  272. def _notification_handler(sender: int, data: bytearray) -> None:
  273. """Handle notification responses."""
  274. if future.done():
  275. _LOGGER.debug("%s: Notification handler already done", self.name)
  276. return
  277. future.set_result(data)
  278. _LOGGER.debug("%s: Subscribe to notifications", self.name)
  279. await client.start_notify(_sb_uuid(comms_type="rx"), _notification_handler)
  280. _LOGGER.debug("%s: Sending command, %s", self.name, key)
  281. await client.write_gatt_char(_sb_uuid(comms_type="tx"), command, False)
  282. notify_msg = await asyncio.wait_for(future, timeout=5)
  283. _LOGGER.info("%s: Notification received: %s", self.name, notify_msg)
  284. _LOGGER.debug("%s: UnSubscribe to notifications", self.name)
  285. await client.stop_notify(_sb_uuid(comms_type="rx"))
  286. finally:
  287. if client:
  288. await client.disconnect()
  289. if notify_msg == b"\x07":
  290. _LOGGER.error("Password required")
  291. elif notify_msg == b"\t":
  292. _LOGGER.error("Password incorrect")
  293. return notify_msg
  294. def get_address(self) -> str:
  295. """Return address of device."""
  296. return self._device.address
  297. def _get_adv_value(self, key: str) -> Any:
  298. """Return value from advertisement data."""
  299. if not self._sb_adv_data:
  300. return None
  301. return self._sb_adv_data.data["data"][key]
  302. def get_battery_percent(self) -> Any:
  303. """Return device battery level in percent."""
  304. return self._get_adv_value("battery")
  305. def update_from_advertisement(self, advertisement: SwitchBotAdvertisement) -> None:
  306. """Update device data from advertisement."""
  307. self._sb_adv_data = advertisement
  308. self._device = advertisement.device
  309. async def get_device_data(
  310. self, retry: int = DEFAULT_RETRY_COUNT, interface: int | None = None
  311. ) -> dict | None:
  312. """Find switchbot devices and their advertisement data."""
  313. if interface:
  314. _interface: int = interface
  315. else:
  316. _interface = int(self._interface.replace("hci", ""))
  317. _data = await GetSwitchbotDevices(interface=_interface).discover(
  318. retry=retry, scan_timeout=self._scan_timeout
  319. )
  320. if self._device.address in _data:
  321. self._sb_adv_data = _data[self._device.address]
  322. return self._sb_adv_data
  323. class Switchbot(SwitchbotDevice):
  324. """Representation of a Switchbot."""
  325. def __init__(self, *args: Any, **kwargs: Any) -> None:
  326. """Switchbot Bot/WoHand constructor."""
  327. super().__init__(*args, **kwargs)
  328. self._inverse: bool = kwargs.pop("inverse_mode", False)
  329. self._settings: dict[str, Any] = {}
  330. async def update(self, interface: int | None = None) -> None:
  331. """Update mode, battery percent and state of device."""
  332. await self.get_device_data(retry=self._retry_count, interface=interface)
  333. async def turn_on(self) -> bool:
  334. """Turn device on."""
  335. result = await self._sendcommand(ON_KEY, self._retry_count)
  336. if result[0] == 1:
  337. return True
  338. if result[0] == 5:
  339. _LOGGER.debug("Bot is in press mode and doesn't have on state")
  340. return True
  341. return False
  342. async def turn_off(self) -> bool:
  343. """Turn device off."""
  344. result = await self._sendcommand(OFF_KEY, self._retry_count)
  345. if result[0] == 1:
  346. return True
  347. if result[0] == 5:
  348. _LOGGER.debug("Bot is in press mode and doesn't have off state")
  349. return True
  350. return False
  351. async def hand_up(self) -> bool:
  352. """Raise device arm."""
  353. result = await self._sendcommand(UP_KEY, self._retry_count)
  354. if result[0] == 1:
  355. return True
  356. if result[0] == 5:
  357. _LOGGER.debug("Bot is in press mode")
  358. return True
  359. return False
  360. async def hand_down(self) -> bool:
  361. """Lower device arm."""
  362. result = await self._sendcommand(DOWN_KEY, self._retry_count)
  363. if result[0] == 1:
  364. return True
  365. if result[0] == 5:
  366. _LOGGER.debug("Bot is in press mode")
  367. return True
  368. return False
  369. async def press(self) -> bool:
  370. """Press command to device."""
  371. result = await self._sendcommand(PRESS_KEY, self._retry_count)
  372. if result[0] == 1:
  373. return True
  374. if result[0] == 5:
  375. _LOGGER.debug("Bot is in switch mode")
  376. return True
  377. return False
  378. async def set_switch_mode(
  379. self, switch_mode: bool = False, strength: int = 100, inverse: bool = False
  380. ) -> bool:
  381. """Change bot mode."""
  382. mode_key = format(switch_mode, "b") + format(inverse, "b")
  383. strength_key = f"{strength:0{2}x}" # to hex with padding to double digit
  384. result = await self._sendcommand(
  385. DEVICE_SET_MODE_KEY + strength_key + mode_key, self._retry_count
  386. )
  387. if result[0] == 1:
  388. return True
  389. return False
  390. async def set_long_press(self, duration: int = 0) -> bool:
  391. """Set bot long press duration."""
  392. duration_key = f"{duration:0{2}x}" # to hex with padding to double digit
  393. result = await self._sendcommand(
  394. DEVICE_SET_EXTENDED_KEY + "08" + duration_key, self._retry_count
  395. )
  396. if result[0] == 1:
  397. return True
  398. return False
  399. async def get_basic_info(self) -> dict[str, Any] | None:
  400. """Get device basic settings."""
  401. _data = await self._sendcommand(
  402. key=DEVICE_GET_BASIC_SETTINGS_KEY, retry=self._retry_count
  403. )
  404. if _data in (b"\x07", b"\x00"):
  405. _LOGGER.error("Unsuccessfull, please try again")
  406. return None
  407. self._settings = {
  408. "battery": _data[1],
  409. "firmware": _data[2] / 10.0,
  410. "strength": _data[3],
  411. "timers": _data[8],
  412. "switchMode": bool(_data[9] & 16),
  413. "inverseDirection": bool(_data[9] & 1),
  414. "holdSeconds": _data[10],
  415. }
  416. return self._settings
  417. def switch_mode(self) -> Any:
  418. """Return true or false from cache."""
  419. # To get actual position call update() first.
  420. return self._get_adv_value("switchMode")
  421. def is_on(self) -> Any:
  422. """Return switch state from cache."""
  423. # To get actual position call update() first.
  424. value = self._get_adv_value("isOn")
  425. if value is None:
  426. return None
  427. if self._inverse:
  428. return not value
  429. return value
  430. class SwitchbotCurtain(SwitchbotDevice):
  431. """Representation of a Switchbot Curtain."""
  432. def __init__(self, *args: Any, **kwargs: Any) -> None:
  433. """Switchbot Curtain/WoCurtain constructor."""
  434. # The position of the curtain is saved returned with 0 = open and 100 = closed.
  435. # This is independent of the calibration of the curtain bot (Open left to right/
  436. # Open right to left/Open from the middle).
  437. # The parameter 'reverse_mode' reverse these values,
  438. # if 'reverse_mode' = True, position = 0 equals close
  439. # and position = 100 equals open. The parameter is default set to True so that
  440. # the definition of position is the same as in Home Assistant.
  441. super().__init__(*args, **kwargs)
  442. self._reverse: bool = kwargs.pop("reverse_mode", True)
  443. self._settings: dict[str, Any] = {}
  444. self.ext_info_sum: dict[str, Any] = {}
  445. self.ext_info_adv: dict[str, Any] = {}
  446. async def open(self) -> bool:
  447. """Send open command."""
  448. result = await self._sendcommand(OPEN_KEY, self._retry_count)
  449. if result[0] == 1:
  450. return True
  451. return False
  452. async def close(self) -> bool:
  453. """Send close command."""
  454. result = await self._sendcommand(CLOSE_KEY, self._retry_count)
  455. if result[0] == 1:
  456. return True
  457. return False
  458. async def stop(self) -> bool:
  459. """Send stop command to device."""
  460. result = await self._sendcommand(STOP_KEY, self._retry_count)
  461. if result[0] == 1:
  462. return True
  463. return False
  464. async def set_position(self, position: int) -> bool:
  465. """Send position command (0-100) to device."""
  466. position = (100 - position) if self._reverse else position
  467. hex_position = "%0.2X" % position
  468. result = await self._sendcommand(POSITION_KEY + hex_position, self._retry_count)
  469. if result[0] == 1:
  470. return True
  471. return False
  472. async def update(self, interface: int | None = None) -> None:
  473. """Update position, battery percent and light level of device."""
  474. await self.get_device_data(retry=self._retry_count, interface=interface)
  475. def get_position(self) -> Any:
  476. """Return cached position (0-100) of Curtain."""
  477. # To get actual position call update() first.
  478. return self._get_adv_value("position")
  479. async def get_basic_info(self) -> dict[str, Any] | None:
  480. """Get device basic settings."""
  481. _data = await self._sendcommand(
  482. key=DEVICE_GET_BASIC_SETTINGS_KEY, retry=self._retry_count
  483. )
  484. if _data in (b"\x07", b"\x00"):
  485. _LOGGER.error("Unsuccessfull, please try again")
  486. return None
  487. _position = max(min(_data[6], 100), 0)
  488. self._settings = {
  489. "battery": _data[1],
  490. "firmware": _data[2] / 10.0,
  491. "chainLength": _data[3],
  492. "openDirection": (
  493. "right_to_left" if _data[4] & 0b10000000 == 128 else "left_to_right"
  494. ),
  495. "touchToOpen": bool(_data[4] & 0b01000000),
  496. "light": bool(_data[4] & 0b00100000),
  497. "fault": bool(_data[4] & 0b00001000),
  498. "solarPanel": bool(_data[5] & 0b00001000),
  499. "calibrated": bool(_data[5] & 0b00000100),
  500. "inMotion": bool(_data[5] & 0b01000011),
  501. "position": (100 - _position) if self._reverse else _position,
  502. "timers": _data[7],
  503. }
  504. return self._settings
  505. async def get_extended_info_summary(self) -> dict[str, Any] | None:
  506. """Get basic info for all devices in chain."""
  507. _data = await self._sendcommand(
  508. key=CURTAIN_EXT_SUM_KEY, retry=self._retry_count
  509. )
  510. if _data in (b"\x07", b"\x00"):
  511. _LOGGER.error("Unsuccessfull, please try again")
  512. return None
  513. self.ext_info_sum["device0"] = {
  514. "openDirectionDefault": not bool(_data[1] & 0b10000000),
  515. "touchToOpen": bool(_data[1] & 0b01000000),
  516. "light": bool(_data[1] & 0b00100000),
  517. "openDirection": (
  518. "left_to_right" if _data[1] & 0b00010000 == 1 else "right_to_left"
  519. ),
  520. }
  521. # if grouped curtain device present.
  522. if _data[2] != 0:
  523. self.ext_info_sum["device1"] = {
  524. "openDirectionDefault": not bool(_data[1] & 0b10000000),
  525. "touchToOpen": bool(_data[1] & 0b01000000),
  526. "light": bool(_data[1] & 0b00100000),
  527. "openDirection": (
  528. "left_to_right" if _data[1] & 0b00010000 else "right_to_left"
  529. ),
  530. }
  531. return self.ext_info_sum
  532. async def get_extended_info_adv(self) -> dict[str, Any] | None:
  533. """Get advance page info for device chain."""
  534. _data = await self._sendcommand(
  535. key=CURTAIN_EXT_ADV_KEY, retry=self._retry_count
  536. )
  537. if _data in (b"\x07", b"\x00"):
  538. _LOGGER.error("Unsuccessfull, please try again")
  539. return None
  540. _state_of_charge = [
  541. "not_charging",
  542. "charging_by_adapter",
  543. "charging_by_solar",
  544. "fully_charged",
  545. "solar_not_charging",
  546. "charging_error",
  547. ]
  548. self.ext_info_adv["device0"] = {
  549. "battery": _data[1],
  550. "firmware": _data[2] / 10.0,
  551. "stateOfCharge": _state_of_charge[_data[3]],
  552. }
  553. # If grouped curtain device present.
  554. if _data[4]:
  555. self.ext_info_adv["device1"] = {
  556. "battery": _data[4],
  557. "firmware": _data[5] / 10.0,
  558. "stateOfCharge": _state_of_charge[_data[6]],
  559. }
  560. return self.ext_info_adv
  561. def get_light_level(self) -> Any:
  562. """Return cached light level."""
  563. # To get actual light level call update() first.
  564. return self._get_adv_value("lightLevel")
  565. def is_reversed(self) -> bool:
  566. """Return True if curtain position is opposite from SB data."""
  567. return self._reverse
  568. def is_calibrated(self) -> Any:
  569. """Return True curtain is calibrated."""
  570. # To get actual light level call update() first.
  571. return self._get_adv_value("calibration")