adv_parser.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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
  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. "manufacturer_data_length": 16,
  62. },
  63. "{": {
  64. "modelName": SwitchbotModel.CURTAIN,
  65. "modelFriendlyName": "Curtain 3",
  66. "func": process_wocurtain,
  67. "manufacturer_id": 2409,
  68. },
  69. "c": {
  70. "modelName": SwitchbotModel.CURTAIN,
  71. "modelFriendlyName": "Curtain",
  72. "func": process_wocurtain,
  73. "manufacturer_id": 2409,
  74. },
  75. "w": {
  76. "modelName": SwitchbotModel.IO_METER,
  77. "modelFriendlyName": "Indoor/Outdoor Meter",
  78. "func": process_wosensorth,
  79. "manufacturer_id": 2409,
  80. },
  81. "i": {
  82. "modelName": SwitchbotModel.METER,
  83. "modelFriendlyName": "Meter Plus",
  84. "func": process_wosensorth,
  85. "manufacturer_id": 2409,
  86. },
  87. "T": {
  88. "modelName": SwitchbotModel.METER,
  89. "modelFriendlyName": "Meter",
  90. "func": process_wosensorth,
  91. "manufacturer_id": 2409,
  92. },
  93. "4": {
  94. "modelName": SwitchbotModel.METER_PRO,
  95. "modelFriendlyName": "Meter",
  96. "func": process_wosensorth,
  97. "manufacturer_id": 2409,
  98. },
  99. "v": {
  100. "modelName": SwitchbotModel.HUB2,
  101. "modelFriendlyName": "Hub 2",
  102. "func": process_wohub2,
  103. "manufacturer_id": 2409,
  104. },
  105. "g": {
  106. "modelName": SwitchbotModel.PLUG_MINI,
  107. "modelFriendlyName": "Plug Mini",
  108. "func": process_woplugmini,
  109. "manufacturer_id": 2409,
  110. },
  111. "j": {
  112. "modelName": SwitchbotModel.PLUG_MINI,
  113. "modelFriendlyName": "Plug Mini (JP)",
  114. "func": process_woplugmini,
  115. "manufacturer_id": 2409,
  116. },
  117. "u": {
  118. "modelName": SwitchbotModel.COLOR_BULB,
  119. "modelFriendlyName": "Color Bulb",
  120. "func": process_color_bulb,
  121. "manufacturer_id": 2409,
  122. },
  123. "q": {
  124. "modelName": SwitchbotModel.CEILING_LIGHT,
  125. "modelFriendlyName": "Ceiling Light",
  126. "func": process_woceiling,
  127. "manufacturer_id": 2409,
  128. },
  129. "n": {
  130. "modelName": SwitchbotModel.CEILING_LIGHT,
  131. "modelFriendlyName": "Ceiling Light Pro",
  132. "func": process_woceiling,
  133. "manufacturer_id": 2409,
  134. },
  135. "e": {
  136. "modelName": SwitchbotModel.HUMIDIFIER,
  137. "modelFriendlyName": "Humidifier",
  138. "func": process_wohumidifier,
  139. "manufacturer_id": 741,
  140. "manufacturer_data_length": 6,
  141. },
  142. "o": {
  143. "modelName": SwitchbotModel.LOCK,
  144. "modelFriendlyName": "Lock",
  145. "func": process_wolock,
  146. "manufacturer_id": 2409,
  147. },
  148. "$": {
  149. "modelName": SwitchbotModel.LOCK_PRO,
  150. "modelFriendlyName": "Lock Pro",
  151. "func": process_wolock_pro,
  152. "manufacturer_id": 2409,
  153. },
  154. "x": {
  155. "modelName": SwitchbotModel.BLIND_TILT,
  156. "modelFriendlyName": "Blind Tilt",
  157. "func": process_woblindtilt,
  158. "manufacturer_id": 2409,
  159. },
  160. }
  161. _SWITCHBOT_MODEL_TO_CHAR = {
  162. model_data["modelName"]: model_chr
  163. for model_chr, model_data in SUPPORTED_TYPES.items()
  164. }
  165. MODELS_BY_MANUFACTURER_DATA: dict[int, list[tuple[str, SwitchbotSupportedType]]] = {
  166. mfr_id: [] for mfr_id in MFR_DATA_ORDER
  167. }
  168. for model_chr, model in SUPPORTED_TYPES.items():
  169. if "manufacturer_id" in model:
  170. mfr_id = model["manufacturer_id"]
  171. MODELS_BY_MANUFACTURER_DATA[mfr_id].append((model_chr, model))
  172. def parse_advertisement_data(
  173. device: BLEDevice,
  174. advertisement_data: AdvertisementData,
  175. model: SwitchbotModel | None = None,
  176. ) -> SwitchBotAdvertisement | None:
  177. """Parse advertisement data."""
  178. service_data = advertisement_data.service_data
  179. _service_data = None
  180. for uuid in SERVICE_DATA_ORDER:
  181. if uuid in service_data:
  182. _service_data = service_data[uuid]
  183. break
  184. _mfr_data = None
  185. _mfr_id = None
  186. for mfr_id in MFR_DATA_ORDER:
  187. if mfr_id in advertisement_data.manufacturer_data:
  188. _mfr_id = mfr_id
  189. _mfr_data = advertisement_data.manufacturer_data[mfr_id]
  190. break
  191. if _mfr_data is None and _service_data is None:
  192. return None
  193. try:
  194. data = _parse_data(
  195. _service_data,
  196. _mfr_data,
  197. _mfr_id,
  198. model,
  199. )
  200. except Exception as err: # pylint: disable=broad-except
  201. _LOGGER.exception(
  202. "Failed to parse advertisement data: %s: %s", advertisement_data, err
  203. )
  204. return None
  205. if not data:
  206. return None
  207. return SwitchBotAdvertisement(
  208. device.address, data, device, advertisement_data.rssi, bool(_service_data)
  209. )
  210. @lru_cache(maxsize=128)
  211. def _parse_data(
  212. _service_data: bytes | None,
  213. _mfr_data: bytes | None,
  214. _mfr_id: int | None = None,
  215. _switchbot_model: SwitchbotModel | None = None,
  216. ) -> dict[str, Any] | None:
  217. """Parse advertisement data."""
  218. _model = chr(_service_data[0] & 0b01111111) if _service_data else None
  219. if _switchbot_model and _switchbot_model in _SWITCHBOT_MODEL_TO_CHAR:
  220. _model = _SWITCHBOT_MODEL_TO_CHAR[_switchbot_model]
  221. if not _model and _mfr_id and _mfr_id in MODELS_BY_MANUFACTURER_DATA:
  222. for model_chr, model_data in MODELS_BY_MANUFACTURER_DATA[_mfr_id]:
  223. if model_data.get("manufacturer_data_length") == len(_mfr_data):
  224. _model = model_chr
  225. break
  226. if not _model:
  227. return None
  228. _isEncrypted = bool(_service_data[0] & 0b10000000) if _service_data else False
  229. data = {
  230. "rawAdvData": _service_data,
  231. "data": {},
  232. "model": _model,
  233. "isEncrypted": _isEncrypted,
  234. }
  235. type_data = SUPPORTED_TYPES.get(_model)
  236. if type_data:
  237. model_data = type_data["func"](_service_data, _mfr_data)
  238. if model_data:
  239. data.update(
  240. {
  241. "modelFriendlyName": type_data["modelFriendlyName"],
  242. "modelName": type_data["modelName"],
  243. "data": model_data,
  244. }
  245. )
  246. return data