adv_parser.py 7.1 KB

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