adv_parser.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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, 741, 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. manufacturer_id: int | None
  34. manufacturer_data_length: int | None
  35. SUPPORTED_TYPES: dict[str, SwitchbotSupportedType] = {
  36. "d": {
  37. "modelName": SwitchbotModel.CONTACT_SENSOR,
  38. "modelFriendlyName": "Contact Sensor",
  39. "func": process_wocontact,
  40. "manufacturer_id": 2409,
  41. "manufacturer_data_length": 13,
  42. },
  43. "H": {
  44. "modelName": SwitchbotModel.BOT,
  45. "modelFriendlyName": "Bot",
  46. "func": process_wohand,
  47. "service_uuids": {"cba20d00-224d-11e6-9fb8-0002a5d5c51b"},
  48. "manufacturer_id": 89,
  49. },
  50. "s": {
  51. "modelName": SwitchbotModel.MOTION_SENSOR,
  52. "modelFriendlyName": "Motion Sensor",
  53. "func": process_wopresence,
  54. "manufacturer_id": 2409,
  55. "manufacturer_data_length": 10,
  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. },
  119. }
  120. _SWITCHBOT_MODEL_TO_CHAR = {
  121. model_data["modelName"]: model_chr
  122. for model_chr, model_data in SUPPORTED_TYPES.items()
  123. }
  124. MODELS_BY_MANUFACTURER_DATA: dict[int, list[tuple[str, SwitchbotSupportedType]]] = {
  125. mfr_id: [] for mfr_id in MFR_DATA_ORDER
  126. }
  127. for model_chr, model in SUPPORTED_TYPES.items():
  128. if "manufacturer_id" in model:
  129. mfr_id = model["manufacturer_id"]
  130. MODELS_BY_MANUFACTURER_DATA[mfr_id].append((model_chr, model))
  131. def parse_advertisement_data(
  132. device: BLEDevice,
  133. advertisement_data: AdvertisementData,
  134. model: SwitchbotModel | None = None,
  135. ) -> SwitchBotAdvertisement | None:
  136. """Parse advertisement data."""
  137. service_data = advertisement_data.service_data
  138. _service_data = None
  139. for uuid in SERVICE_DATA_ORDER:
  140. if uuid in service_data:
  141. _service_data = service_data[uuid]
  142. break
  143. _mfr_data = None
  144. _mfr_id = None
  145. for mfr_id in MFR_DATA_ORDER:
  146. if mfr_id in advertisement_data.manufacturer_data:
  147. _mfr_id = mfr_id
  148. _mfr_data = advertisement_data.manufacturer_data[mfr_id]
  149. break
  150. if _mfr_data is None and _service_data is None:
  151. return None
  152. try:
  153. data = _parse_data(
  154. _service_data,
  155. _mfr_data,
  156. _mfr_id,
  157. model,
  158. )
  159. except Exception as err: # pylint: disable=broad-except
  160. _LOGGER.exception(
  161. "Failed to parse advertisement data: %s: %s", advertisement_data, err
  162. )
  163. return None
  164. if not data:
  165. return None
  166. return SwitchBotAdvertisement(
  167. device.address, data, device, advertisement_data.rssi, bool(_service_data)
  168. )
  169. @lru_cache(maxsize=128)
  170. def _parse_data(
  171. _service_data: bytes | None,
  172. _mfr_data: bytes | None,
  173. _mfr_id: int | None = None,
  174. _switchbot_model: SwitchbotModel | None = None,
  175. ) -> dict[str, Any] | None:
  176. """Parse advertisement data."""
  177. _model = chr(_service_data[0] & 0b01111111) if _service_data else None
  178. if _switchbot_model and _switchbot_model in _SWITCHBOT_MODEL_TO_CHAR:
  179. _model = _SWITCHBOT_MODEL_TO_CHAR[_switchbot_model]
  180. if not _model and _mfr_id and _mfr_id in MODELS_BY_MANUFACTURER_DATA:
  181. for model_chr, model_data in MODELS_BY_MANUFACTURER_DATA[_mfr_id]:
  182. if model_data.get("manufacturer_data_length") == len(_mfr_data):
  183. _model = model_chr
  184. break
  185. if not _model:
  186. return None
  187. _isEncrypted = bool(_service_data[0] & 0b10000000) if _service_data else False
  188. data = {
  189. "rawAdvData": _service_data,
  190. "data": {},
  191. "model": _model,
  192. "isEncrypted": _isEncrypted,
  193. }
  194. type_data = SUPPORTED_TYPES.get(_model)
  195. if type_data:
  196. model_data = type_data["func"](_service_data, _mfr_data)
  197. if model_data:
  198. data.update(
  199. {
  200. "modelFriendlyName": type_data["modelFriendlyName"],
  201. "modelName": type_data["modelName"],
  202. "data": model_data,
  203. }
  204. )
  205. return data