1
0

adv_parser.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 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. },
  53. "r": {
  54. "modelName": SwitchbotModel.LIGHT_STRIP,
  55. "modelFriendlyName": "Light Strip",
  56. "func": process_wostrip,
  57. },
  58. "c": {
  59. "modelName": SwitchbotModel.CURTAIN,
  60. "modelFriendlyName": "Curtain",
  61. "func": process_wocurtain,
  62. "service_uuids": {
  63. "00001800-0000-1000-8000-00805f9b34fb",
  64. "00001801-0000-1000-8000-00805f9b34fb",
  65. "cba20d00-224d-11e6-9fb8-0002a5d5c51b",
  66. },
  67. "manufacturer_id": 89,
  68. },
  69. "T": {
  70. "modelName": SwitchbotModel.METER,
  71. "modelFriendlyName": "Meter",
  72. "func": process_wosensorth,
  73. },
  74. "i": {
  75. "modelName": SwitchbotModel.METER,
  76. "modelFriendlyName": "Meter Plus",
  77. "func": process_wosensorth,
  78. },
  79. "g": {
  80. "modelName": SwitchbotModel.PLUG_MINI,
  81. "modelFriendlyName": "Plug Mini",
  82. "func": process_woplugmini,
  83. },
  84. "j": {
  85. "modelName": SwitchbotModel.PLUG_MINI,
  86. "modelFriendlyName": "Plug Mini (JP)",
  87. "func": process_woplugmini,
  88. },
  89. "u": {
  90. "modelName": SwitchbotModel.COLOR_BULB,
  91. "modelFriendlyName": "Color Bulb",
  92. "func": process_color_bulb,
  93. },
  94. "q": {
  95. "modelName": SwitchbotModel.CEILING_LIGHT,
  96. "modelFriendlyName": "Ceiling Light",
  97. "func": process_woceiling,
  98. },
  99. "e": {
  100. "modelName": SwitchbotModel.HUMIDIFIER,
  101. "modelFriendlyName": "Humidifier",
  102. "func": process_wohumidifier,
  103. },
  104. "o": {
  105. "modelName": SwitchbotModel.LOCK,
  106. "modelFriendlyName": "Lock",
  107. "func": process_wolock,
  108. },
  109. }
  110. _SWITCHBOT_MODEL_TO_CHAR = {
  111. model_data["modelName"]: model_chr
  112. for model_chr, model_data in SUPPORTED_TYPES.items()
  113. }
  114. MODELS_BY_MANUFACTURER_DATA: dict[int, list[tuple[str, SwitchbotSupportedType]]] = {
  115. mfr_id: [] for mfr_id in MFR_DATA_ORDER
  116. }
  117. for model_chr, model in SUPPORTED_TYPES.items():
  118. if "manufacturer_id" in model:
  119. mfr_id = model["manufacturer_id"]
  120. MODELS_BY_MANUFACTURER_DATA[mfr_id].append((model_chr, model))
  121. def parse_advertisement_data(
  122. device: BLEDevice,
  123. advertisement_data: AdvertisementData,
  124. model: SwitchbotModel | None = None,
  125. ) -> SwitchBotAdvertisement | None:
  126. """Parse advertisement data."""
  127. service_data = advertisement_data.service_data
  128. _service_data = None
  129. for uuid in SERVICE_DATA_ORDER:
  130. if uuid in service_data:
  131. _service_data = service_data[uuid]
  132. break
  133. _mfr_data = None
  134. _mfr_id = None
  135. for mfr_id in MFR_DATA_ORDER:
  136. if mfr_id in advertisement_data.manufacturer_data:
  137. _mfr_id = mfr_id
  138. _mfr_data = advertisement_data.manufacturer_data[mfr_id]
  139. break
  140. if _mfr_data is None and _service_data is None:
  141. return None
  142. try:
  143. data = _parse_data(
  144. "".join(sorted(advertisement_data.service_uuids)),
  145. _service_data,
  146. _mfr_data,
  147. _mfr_id,
  148. model,
  149. )
  150. except Exception as err: # pylint: disable=broad-except
  151. _LOGGER.exception(
  152. "Failed to parse advertisement data: %s: %s", advertisement_data, err
  153. )
  154. return None
  155. if not data:
  156. return None
  157. return SwitchBotAdvertisement(device.address, data, device, advertisement_data.rssi)
  158. @lru_cache(maxsize=128)
  159. def _parse_data(
  160. _service_uuids_str: str,
  161. _service_data: bytes | None,
  162. _mfr_data: bytes | None,
  163. _mfr_id: int | None = None,
  164. _switchbot_model: SwitchbotModel | None = None,
  165. ) -> SwitchBotAdvertisement | None:
  166. """Parse advertisement data."""
  167. _model = chr(_service_data[0] & 0b01111111) if _service_data else None
  168. if not _model and _mfr_id and _mfr_id in MODELS_BY_MANUFACTURER_DATA:
  169. _service_uuids = set(_service_uuids_str.split(","))
  170. for model_chr, model_data in MODELS_BY_MANUFACTURER_DATA[_mfr_id]:
  171. if model_data.get("manufacturer_data_length") == len(_mfr_data):
  172. _model = model_chr
  173. break
  174. if model_data.get("service_uuids", set()).intersection(_service_uuids):
  175. _model = model_chr
  176. break
  177. if not _model and _switchbot_model and _switchbot_model in _SWITCHBOT_MODEL_TO_CHAR:
  178. _model = _SWITCHBOT_MODEL_TO_CHAR[_switchbot_model]
  179. if not _model:
  180. return None
  181. _isEncrypted = bool(_service_data[0] & 0b10000000) if _service_data else False
  182. data = {
  183. "rawAdvData": _service_data,
  184. "data": {},
  185. "model": _model,
  186. "isEncrypted": _isEncrypted,
  187. }
  188. type_data = SUPPORTED_TYPES.get(_model)
  189. if type_data:
  190. model_data = type_data["func"](_service_data, _mfr_data)
  191. if model_data:
  192. data.update(
  193. {
  194. "modelFriendlyName": type_data["modelFriendlyName"],
  195. "modelName": type_data["modelName"],
  196. "data": model_data,
  197. }
  198. )
  199. return data