__init__.py 23 KB

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