adv_parser.py 7.3 KB

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