1
0

adv_parser.py 7.2 KB

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