__init__.py 26 KB

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