1
0

adv_parser.py 7.7 KB

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