adv_parser.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. "manufacturer_data_length": 10,
  126. },
  127. }
  128. _SWITCHBOT_MODEL_TO_CHAR = {
  129. model_data["modelName"]: model_chr
  130. for model_chr, model_data in SUPPORTED_TYPES.items()
  131. }
  132. MODELS_BY_MANUFACTURER_DATA: dict[int, list[tuple[str, SwitchbotSupportedType]]] = {
  133. mfr_id: [] for mfr_id in MFR_DATA_ORDER
  134. }
  135. for model_chr, model in SUPPORTED_TYPES.items():
  136. if "manufacturer_id" in model:
  137. mfr_id = model["manufacturer_id"]
  138. MODELS_BY_MANUFACTURER_DATA[mfr_id].append((model_chr, model))
  139. def parse_advertisement_data(
  140. device: BLEDevice,
  141. advertisement_data: AdvertisementData,
  142. model: SwitchbotModel | None = None,
  143. ) -> SwitchBotAdvertisement | None:
  144. """Parse advertisement data."""
  145. service_data = advertisement_data.service_data
  146. _service_data = None
  147. for uuid in SERVICE_DATA_ORDER:
  148. if uuid in service_data:
  149. _service_data = service_data[uuid]
  150. break
  151. _mfr_data = None
  152. _mfr_id = None
  153. for mfr_id in MFR_DATA_ORDER:
  154. if mfr_id in advertisement_data.manufacturer_data:
  155. _mfr_id = mfr_id
  156. _mfr_data = advertisement_data.manufacturer_data[mfr_id]
  157. break
  158. if _mfr_data is None and _service_data is None:
  159. return None
  160. try:
  161. data = _parse_data(
  162. _service_data,
  163. _mfr_data,
  164. _mfr_id,
  165. model,
  166. )
  167. except Exception as err: # pylint: disable=broad-except
  168. _LOGGER.exception(
  169. "Failed to parse advertisement data: %s: %s", advertisement_data, err
  170. )
  171. return None
  172. if not data:
  173. return None
  174. return SwitchBotAdvertisement(
  175. device.address, data, device, advertisement_data.rssi, bool(_service_data)
  176. )
  177. @lru_cache(maxsize=128)
  178. def _parse_data(
  179. _service_data: bytes | None,
  180. _mfr_data: bytes | None,
  181. _mfr_id: int | None = None,
  182. _switchbot_model: SwitchbotModel | None = None,
  183. ) -> dict[str, Any] | None:
  184. """Parse advertisement data."""
  185. _model = chr(_service_data[0] & 0b01111111) if _service_data else None
  186. if _switchbot_model and _switchbot_model in _SWITCHBOT_MODEL_TO_CHAR:
  187. _model = _SWITCHBOT_MODEL_TO_CHAR[_switchbot_model]
  188. if not _model and _mfr_id and _mfr_id in MODELS_BY_MANUFACTURER_DATA:
  189. for model_chr, model_data in MODELS_BY_MANUFACTURER_DATA[_mfr_id]:
  190. if model_data.get("manufacturer_data_length") == len(_mfr_data):
  191. _model = model_chr
  192. break
  193. if not _model:
  194. return None
  195. _isEncrypted = bool(_service_data[0] & 0b10000000) if _service_data else False
  196. data = {
  197. "rawAdvData": _service_data,
  198. "data": {},
  199. "model": _model,
  200. "isEncrypted": _isEncrypted,
  201. }
  202. type_data = SUPPORTED_TYPES.get(_model)
  203. if type_data:
  204. model_data = type_data["func"](_service_data, _mfr_data)
  205. if model_data:
  206. data.update(
  207. {
  208. "modelFriendlyName": type_data["modelFriendlyName"],
  209. "modelName": type_data["modelName"],
  210. "data": model_data,
  211. }
  212. )
  213. return data