adv_parser.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """Library to handle connection with Switchbot."""
  2. from __future__ import annotations
  3. import logging
  4. from collections.abc import Callable
  5. from functools import lru_cache
  6. from typing import Any, TypedDict
  7. from bleak.backends.device import BLEDevice
  8. from bleak.backends.scanner import AdvertisementData
  9. from .adv_parsers.blind_tilt import process_woblindtilt
  10. from .adv_parsers.bot import process_wohand
  11. from .adv_parsers.bulb import process_color_bulb
  12. from .adv_parsers.ceiling_light import process_woceiling
  13. from .adv_parsers.contact import process_wocontact
  14. from .adv_parsers.curtain import process_wocurtain
  15. from .adv_parsers.hub2 import process_wohub2
  16. from .adv_parsers.humidifier import process_wohumidifier
  17. from .adv_parsers.light_strip import process_wostrip
  18. from .adv_parsers.lock import process_wolock, process_wolock_pro
  19. from .adv_parsers.meter import process_wosensorth, process_wosensorth_c
  20. from .adv_parsers.motion import process_wopresence
  21. from .adv_parsers.plug import process_woplugmini
  22. from .const import SwitchbotModel
  23. from .models import SwitchBotAdvertisement
  24. _LOGGER = logging.getLogger(__name__)
  25. SERVICE_DATA_ORDER = (
  26. "0000fd3d-0000-1000-8000-00805f9b34fb",
  27. "00000d00-0000-1000-8000-00805f9b34fb",
  28. )
  29. MFR_DATA_ORDER = (2409, 741, 89)
  30. class SwitchbotSupportedType(TypedDict):
  31. """Supported type of Switchbot."""
  32. modelName: SwitchbotModel
  33. modelFriendlyName: str
  34. func: Callable[[bytes, bytes | None], dict[str, bool | int]]
  35. manufacturer_id: int | None
  36. manufacturer_data_length: int | None
  37. SUPPORTED_TYPES: dict[str, SwitchbotSupportedType] = {
  38. "d": {
  39. "modelName": SwitchbotModel.CONTACT_SENSOR,
  40. "modelFriendlyName": "Contact Sensor",
  41. "func": process_wocontact,
  42. "manufacturer_id": 2409,
  43. },
  44. "H": {
  45. "modelName": SwitchbotModel.BOT,
  46. "modelFriendlyName": "Bot",
  47. "func": process_wohand,
  48. "manufacturer_id": 89,
  49. },
  50. "s": {
  51. "modelName": SwitchbotModel.MOTION_SENSOR,
  52. "modelFriendlyName": "Motion Sensor",
  53. "func": process_wopresence,
  54. "manufacturer_id": 2409,
  55. },
  56. "r": {
  57. "modelName": SwitchbotModel.LIGHT_STRIP,
  58. "modelFriendlyName": "Light Strip",
  59. "func": process_wostrip,
  60. "manufacturer_id": 2409,
  61. },
  62. "{": {
  63. "modelName": SwitchbotModel.CURTAIN,
  64. "modelFriendlyName": "Curtain 3",
  65. "func": process_wocurtain,
  66. "manufacturer_id": 2409,
  67. },
  68. "c": {
  69. "modelName": SwitchbotModel.CURTAIN,
  70. "modelFriendlyName": "Curtain",
  71. "func": process_wocurtain,
  72. "manufacturer_id": 2409,
  73. },
  74. "w": {
  75. "modelName": SwitchbotModel.IO_METER,
  76. "modelFriendlyName": "Indoor/Outdoor Meter",
  77. "func": process_wosensorth,
  78. "manufacturer_id": 2409,
  79. },
  80. "i": {
  81. "modelName": SwitchbotModel.METER,
  82. "modelFriendlyName": "Meter Plus",
  83. "func": process_wosensorth,
  84. "manufacturer_id": 2409,
  85. },
  86. "T": {
  87. "modelName": SwitchbotModel.METER,
  88. "modelFriendlyName": "Meter",
  89. "func": process_wosensorth,
  90. "manufacturer_id": 2409,
  91. },
  92. "4": {
  93. "modelName": SwitchbotModel.METER_PRO,
  94. "modelFriendlyName": "Meter",
  95. "func": process_wosensorth,
  96. "manufacturer_id": 2409,
  97. },
  98. "5": {
  99. "modelName": SwitchbotModel.METER_PRO_C,
  100. "modelFriendlyName": "Meter",
  101. "func": process_wosensorth_c,
  102. "manufacturer_id": 2409,
  103. },
  104. "v": {
  105. "modelName": SwitchbotModel.HUB2,
  106. "modelFriendlyName": "Hub 2",
  107. "func": process_wohub2,
  108. "manufacturer_id": 2409,
  109. },
  110. "g": {
  111. "modelName": SwitchbotModel.PLUG_MINI,
  112. "modelFriendlyName": "Plug Mini",
  113. "func": process_woplugmini,
  114. "manufacturer_id": 2409,
  115. },
  116. "j": {
  117. "modelName": SwitchbotModel.PLUG_MINI,
  118. "modelFriendlyName": "Plug Mini (JP)",
  119. "func": process_woplugmini,
  120. "manufacturer_id": 2409,
  121. },
  122. "u": {
  123. "modelName": SwitchbotModel.COLOR_BULB,
  124. "modelFriendlyName": "Color Bulb",
  125. "func": process_color_bulb,
  126. "manufacturer_id": 2409,
  127. },
  128. "q": {
  129. "modelName": SwitchbotModel.CEILING_LIGHT,
  130. "modelFriendlyName": "Ceiling Light",
  131. "func": process_woceiling,
  132. "manufacturer_id": 2409,
  133. },
  134. "n": {
  135. "modelName": SwitchbotModel.CEILING_LIGHT,
  136. "modelFriendlyName": "Ceiling Light Pro",
  137. "func": process_woceiling,
  138. "manufacturer_id": 2409,
  139. },
  140. "e": {
  141. "modelName": SwitchbotModel.HUMIDIFIER,
  142. "modelFriendlyName": "Humidifier",
  143. "func": process_wohumidifier,
  144. "manufacturer_id": 741,
  145. "manufacturer_data_length": 6,
  146. },
  147. "o": {
  148. "modelName": SwitchbotModel.LOCK,
  149. "modelFriendlyName": "Lock",
  150. "func": process_wolock,
  151. "manufacturer_id": 2409,
  152. },
  153. "$": {
  154. "modelName": SwitchbotModel.LOCK_PRO,
  155. "modelFriendlyName": "Lock Pro",
  156. "func": process_wolock_pro,
  157. "manufacturer_id": 2409,
  158. },
  159. "x": {
  160. "modelName": SwitchbotModel.BLIND_TILT,
  161. "modelFriendlyName": "Blind Tilt",
  162. "func": process_woblindtilt,
  163. "manufacturer_id": 2409,
  164. },
  165. }
  166. _SWITCHBOT_MODEL_TO_CHAR = {
  167. model_data["modelName"]: model_chr
  168. for model_chr, model_data in SUPPORTED_TYPES.items()
  169. }
  170. MODELS_BY_MANUFACTURER_DATA: dict[int, list[tuple[str, SwitchbotSupportedType]]] = {
  171. mfr_id: [] for mfr_id in MFR_DATA_ORDER
  172. }
  173. for model_chr, model in SUPPORTED_TYPES.items():
  174. if "manufacturer_id" in model:
  175. mfr_id = model["manufacturer_id"]
  176. MODELS_BY_MANUFACTURER_DATA[mfr_id].append((model_chr, model))
  177. def parse_advertisement_data(
  178. device: BLEDevice,
  179. advertisement_data: AdvertisementData,
  180. model: SwitchbotModel | None = None,
  181. ) -> SwitchBotAdvertisement | None:
  182. """Parse advertisement data."""
  183. service_data = advertisement_data.service_data
  184. _service_data = None
  185. for uuid in SERVICE_DATA_ORDER:
  186. if uuid in service_data:
  187. _service_data = service_data[uuid]
  188. break
  189. _mfr_data = None
  190. _mfr_id = None
  191. for mfr_id in MFR_DATA_ORDER:
  192. if mfr_id in advertisement_data.manufacturer_data:
  193. _mfr_id = mfr_id
  194. _mfr_data = advertisement_data.manufacturer_data[mfr_id]
  195. break
  196. if _mfr_data is None and _service_data is None:
  197. return None
  198. try:
  199. data = _parse_data(
  200. _service_data,
  201. _mfr_data,
  202. _mfr_id,
  203. model,
  204. )
  205. except Exception as err: # pylint: disable=broad-except
  206. _LOGGER.exception(
  207. "Failed to parse advertisement data: %s: %s", advertisement_data, err
  208. )
  209. return None
  210. if not data:
  211. return None
  212. return SwitchBotAdvertisement(
  213. device.address, data, device, advertisement_data.rssi, bool(_service_data)
  214. )
  215. @lru_cache(maxsize=128)
  216. def _parse_data(
  217. _service_data: bytes | None,
  218. _mfr_data: bytes | None,
  219. _mfr_id: int | None = None,
  220. _switchbot_model: SwitchbotModel | None = None,
  221. ) -> dict[str, Any] | None:
  222. """Parse advertisement data."""
  223. _model = chr(_service_data[0] & 0b01111111) if _service_data else None
  224. if _switchbot_model and _switchbot_model in _SWITCHBOT_MODEL_TO_CHAR:
  225. _model = _SWITCHBOT_MODEL_TO_CHAR[_switchbot_model]
  226. if not _model and _mfr_id and _mfr_id in MODELS_BY_MANUFACTURER_DATA:
  227. for model_chr, model_data in MODELS_BY_MANUFACTURER_DATA[_mfr_id]:
  228. if model_data.get("manufacturer_data_length") == len(_mfr_data):
  229. _model = model_chr
  230. break
  231. if not _model:
  232. return None
  233. _isEncrypted = bool(_service_data[0] & 0b10000000) if _service_data else False
  234. data = {
  235. "rawAdvData": _service_data,
  236. "data": {},
  237. "model": _model,
  238. "isEncrypted": _isEncrypted,
  239. }
  240. type_data = SUPPORTED_TYPES.get(_model)
  241. if type_data:
  242. model_data = type_data["func"](_service_data, _mfr_data)
  243. if model_data:
  244. data.update(
  245. {
  246. "modelFriendlyName": type_data["modelFriendlyName"],
  247. "modelName": type_data["modelName"],
  248. "data": model_data,
  249. }
  250. )
  251. return data