__init__.py 23 KB

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