node-switchbot 4.0.0-beta.8 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (418) hide show
  1. package/BLE.md +215 -838
  2. package/CHANGELOG.md +96 -1371
  3. package/OpenAPI.md +169 -135
  4. package/README.md +1 -1
  5. package/dist/api.d.ts +3 -3
  6. package/dist/api.d.ts.map +1 -1
  7. package/dist/api.js +9 -6
  8. package/dist/api.js.map +1 -1
  9. package/dist/ble.d.ts +33 -1
  10. package/dist/ble.d.ts.map +1 -1
  11. package/dist/ble.js +415 -37
  12. package/dist/ble.js.map +1 -1
  13. package/dist/devices/base.d.ts +100 -1
  14. package/dist/devices/base.d.ts.map +1 -1
  15. package/dist/devices/base.js +248 -11
  16. package/dist/devices/base.js.map +1 -1
  17. package/dist/devices/device-override-state-during-connection.d.ts +27 -0
  18. package/dist/devices/device-override-state-during-connection.d.ts.map +1 -0
  19. package/dist/devices/device-override-state-during-connection.js +45 -0
  20. package/dist/devices/device-override-state-during-connection.js.map +1 -0
  21. package/dist/devices/index.d.ts +36 -0
  22. package/dist/devices/index.d.ts.map +1 -1
  23. package/dist/devices/index.js +36 -0
  24. package/dist/devices/index.js.map +1 -1
  25. package/dist/devices/sequence-device.d.ts +52 -0
  26. package/dist/devices/sequence-device.d.ts.map +1 -0
  27. package/dist/devices/sequence-device.js +91 -0
  28. package/dist/devices/sequence-device.js.map +1 -0
  29. package/dist/devices/wo-ai-hub.d.ts +9 -0
  30. package/dist/devices/wo-ai-hub.d.ts.map +1 -0
  31. package/dist/devices/wo-ai-hub.js +25 -0
  32. package/dist/devices/wo-ai-hub.js.map +1 -0
  33. package/dist/devices/wo-air-purifier-pm25.d.ts +29 -0
  34. package/dist/devices/wo-air-purifier-pm25.d.ts.map +1 -0
  35. package/dist/devices/wo-air-purifier-pm25.js +144 -0
  36. package/dist/devices/wo-air-purifier-pm25.js.map +1 -0
  37. package/dist/devices/wo-air-purifier.d.ts +21 -4
  38. package/dist/devices/wo-air-purifier.d.ts.map +1 -1
  39. package/dist/devices/wo-air-purifier.js +111 -61
  40. package/dist/devices/wo-air-purifier.js.map +1 -1
  41. package/dist/devices/wo-art-frame.d.ts +8 -0
  42. package/dist/devices/wo-art-frame.d.ts.map +1 -0
  43. package/dist/devices/wo-art-frame.js +12 -0
  44. package/dist/devices/wo-art-frame.js.map +1 -0
  45. package/dist/devices/wo-blind-tilt.d.ts +2 -16
  46. package/dist/devices/wo-blind-tilt.d.ts.map +1 -1
  47. package/dist/devices/wo-blind-tilt.js +135 -62
  48. package/dist/devices/wo-blind-tilt.js.map +1 -1
  49. package/dist/devices/wo-bulb.d.ts +37 -1
  50. package/dist/devices/wo-bulb.d.ts.map +1 -1
  51. package/dist/devices/wo-bulb.js +196 -51
  52. package/dist/devices/wo-bulb.js.map +1 -1
  53. package/dist/devices/wo-candle-warmer-lamp.d.ts +25 -0
  54. package/dist/devices/wo-candle-warmer-lamp.d.ts.map +1 -0
  55. package/dist/devices/wo-candle-warmer-lamp.js +81 -0
  56. package/dist/devices/wo-candle-warmer-lamp.js.map +1 -0
  57. package/dist/devices/wo-circulator-fan.d.ts +8 -0
  58. package/dist/devices/wo-circulator-fan.d.ts.map +1 -0
  59. package/dist/devices/wo-circulator-fan.js +12 -0
  60. package/dist/devices/wo-circulator-fan.js.map +1 -0
  61. package/dist/devices/wo-climate-panel.d.ts +8 -0
  62. package/dist/devices/wo-climate-panel.d.ts.map +1 -0
  63. package/dist/devices/wo-climate-panel.js +12 -0
  64. package/dist/devices/wo-climate-panel.js.map +1 -0
  65. package/dist/devices/wo-contact.d.ts +1 -1
  66. package/dist/devices/wo-contact.d.ts.map +1 -1
  67. package/dist/devices/wo-contact.js +19 -35
  68. package/dist/devices/wo-contact.js.map +1 -1
  69. package/dist/devices/wo-curtain.d.ts +20 -4
  70. package/dist/devices/wo-curtain.d.ts.map +1 -1
  71. package/dist/devices/wo-curtain.js +130 -35
  72. package/dist/devices/wo-curtain.js.map +1 -1
  73. package/dist/devices/wo-floor-lamp.d.ts +8 -0
  74. package/dist/devices/wo-floor-lamp.d.ts.map +1 -0
  75. package/dist/devices/wo-floor-lamp.js +12 -0
  76. package/dist/devices/wo-floor-lamp.js.map +1 -0
  77. package/dist/devices/wo-garage-door-opener.d.ts +8 -0
  78. package/dist/devices/wo-garage-door-opener.d.ts.map +1 -0
  79. package/dist/devices/wo-garage-door-opener.js +12 -0
  80. package/dist/devices/wo-garage-door-opener.js.map +1 -0
  81. package/dist/devices/wo-hand.d.ts +22 -6
  82. package/dist/devices/wo-hand.d.ts.map +1 -1
  83. package/dist/devices/wo-hand.js +55 -39
  84. package/dist/devices/wo-hand.js.map +1 -1
  85. package/dist/devices/wo-hub2.d.ts +1 -1
  86. package/dist/devices/wo-hub2.d.ts.map +1 -1
  87. package/dist/devices/wo-hub2.js +17 -33
  88. package/dist/devices/wo-hub2.js.map +1 -1
  89. package/dist/devices/wo-hubmini-matter.d.ts +8 -0
  90. package/dist/devices/wo-hubmini-matter.d.ts.map +1 -0
  91. package/dist/devices/wo-hubmini-matter.js +12 -0
  92. package/dist/devices/wo-hubmini-matter.js.map +1 -0
  93. package/dist/devices/wo-humi.d.ts +18 -2
  94. package/dist/devices/wo-humi.d.ts.map +1 -1
  95. package/dist/devices/wo-humi.js +60 -36
  96. package/dist/devices/wo-humi.js.map +1 -1
  97. package/dist/devices/wo-humi2.d.ts.map +1 -1
  98. package/dist/devices/wo-humi2.js.map +1 -1
  99. package/dist/devices/wo-keypad-vision-pro.d.ts +18 -0
  100. package/dist/devices/wo-keypad-vision-pro.d.ts.map +1 -0
  101. package/dist/devices/wo-keypad-vision-pro.js +15 -0
  102. package/dist/devices/wo-keypad-vision-pro.js.map +1 -0
  103. package/dist/devices/wo-keypad-vision.d.ts +8 -0
  104. package/dist/devices/wo-keypad-vision.d.ts.map +1 -0
  105. package/dist/devices/wo-keypad-vision.js +12 -0
  106. package/dist/devices/wo-keypad-vision.js.map +1 -0
  107. package/dist/devices/wo-keypad.d.ts +1 -1
  108. package/dist/devices/wo-keypad.d.ts.map +1 -1
  109. package/dist/devices/wo-keypad.js +14 -30
  110. package/dist/devices/wo-keypad.js.map +1 -1
  111. package/dist/devices/wo-leak.d.ts +1 -1
  112. package/dist/devices/wo-leak.d.ts.map +1 -1
  113. package/dist/devices/wo-leak.js +15 -31
  114. package/dist/devices/wo-leak.js.map +1 -1
  115. package/dist/devices/wo-lock-lite.d.ts +7 -0
  116. package/dist/devices/wo-lock-lite.d.ts.map +1 -0
  117. package/dist/devices/wo-lock-lite.js +11 -0
  118. package/dist/devices/wo-lock-lite.js.map +1 -0
  119. package/dist/devices/wo-lock-pro-wifi.d.ts +7 -0
  120. package/dist/devices/wo-lock-pro-wifi.d.ts.map +1 -0
  121. package/dist/devices/wo-lock-pro-wifi.js +11 -0
  122. package/dist/devices/wo-lock-pro-wifi.js.map +1 -0
  123. package/dist/devices/wo-lock-pro.d.ts +12 -3
  124. package/dist/devices/wo-lock-pro.d.ts.map +1 -1
  125. package/dist/devices/wo-lock-pro.js +83 -37
  126. package/dist/devices/wo-lock-pro.js.map +1 -1
  127. package/dist/devices/wo-lock-vision-pro.d.ts +7 -0
  128. package/dist/devices/wo-lock-vision-pro.d.ts.map +1 -0
  129. package/dist/devices/wo-lock-vision-pro.js +11 -0
  130. package/dist/devices/wo-lock-vision-pro.js.map +1 -0
  131. package/dist/devices/wo-lock-vision.d.ts +7 -0
  132. package/dist/devices/wo-lock-vision.d.ts.map +1 -0
  133. package/dist/devices/wo-lock-vision.js +11 -0
  134. package/dist/devices/wo-lock-vision.js.map +1 -0
  135. package/dist/devices/wo-lock.d.ts +8 -3
  136. package/dist/devices/wo-lock.d.ts.map +1 -1
  137. package/dist/devices/wo-lock.js +75 -36
  138. package/dist/devices/wo-lock.js.map +1 -1
  139. package/dist/devices/wo-pan-tilt-cam-plus-3k.d.ts +21 -0
  140. package/dist/devices/wo-pan-tilt-cam-plus-3k.d.ts.map +1 -0
  141. package/dist/devices/wo-pan-tilt-cam-plus-3k.js +87 -0
  142. package/dist/devices/wo-pan-tilt-cam-plus-3k.js.map +1 -0
  143. package/dist/devices/wo-plug-mini-us.d.ts +3 -3
  144. package/dist/devices/wo-plug-mini-us.d.ts.map +1 -1
  145. package/dist/devices/wo-plug-mini-us.js +25 -35
  146. package/dist/devices/wo-plug-mini-us.js.map +1 -1
  147. package/dist/devices/wo-presence.d.ts +1 -1
  148. package/dist/devices/wo-presence.d.ts.map +1 -1
  149. package/dist/devices/wo-presence.js +17 -33
  150. package/dist/devices/wo-presence.js.map +1 -1
  151. package/dist/devices/wo-relay-switch-1.d.ts +19 -3
  152. package/dist/devices/wo-relay-switch-1.d.ts.map +1 -1
  153. package/dist/devices/wo-relay-switch-1.js +90 -42
  154. package/dist/devices/wo-relay-switch-1.js.map +1 -1
  155. package/dist/devices/wo-relay-switch-2pm.d.ts +21 -0
  156. package/dist/devices/wo-relay-switch-2pm.d.ts.map +1 -0
  157. package/dist/devices/wo-relay-switch-2pm.js +37 -0
  158. package/dist/devices/wo-relay-switch-2pm.js.map +1 -0
  159. package/dist/devices/wo-remote-with-screen.d.ts +9 -0
  160. package/dist/devices/wo-remote-with-screen.d.ts.map +1 -0
  161. package/dist/devices/wo-remote-with-screen.js +22 -0
  162. package/dist/devices/wo-remote-with-screen.js.map +1 -0
  163. package/dist/devices/wo-remote.d.ts +1 -1
  164. package/dist/devices/wo-remote.d.ts.map +1 -1
  165. package/dist/devices/wo-remote.js +13 -29
  166. package/dist/devices/wo-remote.js.map +1 -1
  167. package/dist/devices/wo-rgbic-bulb.d.ts +29 -0
  168. package/dist/devices/wo-rgbic-bulb.d.ts.map +1 -0
  169. package/dist/devices/wo-rgbic-bulb.js +84 -0
  170. package/dist/devices/wo-rgbic-bulb.js.map +1 -0
  171. package/dist/devices/wo-rgbic-neon-wire-rope-light.d.ts +29 -0
  172. package/dist/devices/wo-rgbic-neon-wire-rope-light.d.ts.map +1 -0
  173. package/dist/devices/wo-rgbic-neon-wire-rope-light.js +113 -0
  174. package/dist/devices/wo-rgbic-neon-wire-rope-light.js.map +1 -0
  175. package/dist/devices/wo-rgbicww-floor-lamp.d.ts +8 -0
  176. package/dist/devices/wo-rgbicww-floor-lamp.d.ts.map +1 -0
  177. package/dist/devices/wo-rgbicww-floor-lamp.js +12 -0
  178. package/dist/devices/wo-rgbicww-floor-lamp.js.map +1 -0
  179. package/dist/devices/wo-rgbicww-strip-light.d.ts +8 -0
  180. package/dist/devices/wo-rgbicww-strip-light.d.ts.map +1 -0
  181. package/dist/devices/wo-rgbicww-strip-light.js +12 -0
  182. package/dist/devices/wo-rgbicww-strip-light.js.map +1 -0
  183. package/dist/devices/wo-roller-shade.d.ts +8 -0
  184. package/dist/devices/wo-roller-shade.d.ts.map +1 -0
  185. package/dist/devices/wo-roller-shade.js +12 -0
  186. package/dist/devices/wo-roller-shade.js.map +1 -0
  187. package/dist/devices/wo-sensor-th.d.ts +1 -1
  188. package/dist/devices/wo-sensor-th.d.ts.map +1 -1
  189. package/dist/devices/wo-sensor-th.js +18 -34
  190. package/dist/devices/wo-sensor-th.js.map +1 -1
  191. package/dist/devices/wo-smart-thermostat-radiator.d.ts +8 -0
  192. package/dist/devices/wo-smart-thermostat-radiator.d.ts.map +1 -0
  193. package/dist/devices/wo-smart-thermostat-radiator.js +12 -0
  194. package/dist/devices/wo-smart-thermostat-radiator.js.map +1 -0
  195. package/dist/devices/wo-strip-light-3.d.ts +8 -0
  196. package/dist/devices/wo-strip-light-3.d.ts.map +1 -0
  197. package/dist/devices/wo-strip-light-3.js +12 -0
  198. package/dist/devices/wo-strip-light-3.js.map +1 -0
  199. package/dist/devices/wo-vacuum-k10-plus.d.ts +7 -0
  200. package/dist/devices/wo-vacuum-k10-plus.d.ts.map +1 -0
  201. package/dist/devices/wo-vacuum-k10-plus.js +11 -0
  202. package/dist/devices/wo-vacuum-k10-plus.js.map +1 -0
  203. package/dist/devices/wo-vacuum-k10-pro-combo.d.ts +7 -0
  204. package/dist/devices/wo-vacuum-k10-pro-combo.d.ts.map +1 -0
  205. package/dist/devices/wo-vacuum-k10-pro-combo.js +11 -0
  206. package/dist/devices/wo-vacuum-k10-pro-combo.js.map +1 -0
  207. package/dist/devices/wo-vacuum-k10-pro.d.ts +7 -0
  208. package/dist/devices/wo-vacuum-k10-pro.d.ts.map +1 -0
  209. package/dist/devices/wo-vacuum-k10-pro.js +11 -0
  210. package/dist/devices/wo-vacuum-k10-pro.js.map +1 -0
  211. package/dist/devices/wo-vacuum-k11-plus.d.ts +7 -0
  212. package/dist/devices/wo-vacuum-k11-plus.d.ts.map +1 -0
  213. package/dist/devices/wo-vacuum-k11-plus.js +11 -0
  214. package/dist/devices/wo-vacuum-k11-plus.js.map +1 -0
  215. package/dist/devices/wo-vacuum-k20.d.ts +7 -0
  216. package/dist/devices/wo-vacuum-k20.d.ts.map +1 -0
  217. package/dist/devices/wo-vacuum-k20.js +11 -0
  218. package/dist/devices/wo-vacuum-k20.js.map +1 -0
  219. package/dist/devices/wo-vacuum-s10.d.ts +7 -0
  220. package/dist/devices/wo-vacuum-s10.d.ts.map +1 -0
  221. package/dist/devices/wo-vacuum-s10.js +11 -0
  222. package/dist/devices/wo-vacuum-s10.js.map +1 -0
  223. package/dist/devices/wo-vacuum-s20.d.ts +7 -0
  224. package/dist/devices/wo-vacuum-s20.d.ts.map +1 -0
  225. package/dist/devices/wo-vacuum-s20.js +11 -0
  226. package/dist/devices/wo-vacuum-s20.js.map +1 -0
  227. package/dist/devices/wo-vacuum.d.ts +44 -0
  228. package/dist/devices/wo-vacuum.d.ts.map +1 -0
  229. package/dist/devices/wo-vacuum.js +143 -0
  230. package/dist/devices/wo-vacuum.js.map +1 -0
  231. package/dist/devices/wo-water-detector.d.ts +9 -0
  232. package/dist/devices/wo-water-detector.d.ts.map +1 -0
  233. package/dist/devices/wo-water-detector.js +20 -0
  234. package/dist/devices/wo-water-detector.js.map +1 -0
  235. package/dist/errors.d.ts +20 -0
  236. package/dist/errors.d.ts.map +1 -1
  237. package/dist/errors.js +31 -1
  238. package/dist/errors.js.map +1 -1
  239. package/dist/index.d.ts +4 -2
  240. package/dist/index.d.ts.map +1 -1
  241. package/dist/index.js +3 -1
  242. package/dist/index.js.map +1 -1
  243. package/dist/settings.d.ts +25 -0
  244. package/dist/settings.d.ts.map +1 -1
  245. package/dist/settings.js +85 -6
  246. package/dist/settings.js.map +1 -1
  247. package/dist/switchbot.d.ts +1 -0
  248. package/dist/switchbot.d.ts.map +1 -1
  249. package/dist/switchbot.js +154 -34
  250. package/dist/switchbot.js.map +1 -1
  251. package/dist/types/ble.d.ts +24 -0
  252. package/dist/types/ble.d.ts.map +1 -1
  253. package/dist/types/ble.js.map +1 -1
  254. package/dist/types/device.d.ts +84 -5
  255. package/dist/types/device.d.ts.map +1 -1
  256. package/dist/types/index.d.ts +26 -0
  257. package/dist/types/index.d.ts.map +1 -1
  258. package/dist/types/index.js.map +1 -1
  259. package/dist/utils/fallback-handler.js +0 -1
  260. package/dist/utils/fallback-handler.js.map +1 -1
  261. package/dist/utils/index.d.ts +21 -1
  262. package/dist/utils/index.d.ts.map +1 -1
  263. package/dist/utils/index.js +49 -0
  264. package/dist/utils/index.js.map +1 -1
  265. package/dist/utils/relay-encryption.d.ts +10 -0
  266. package/dist/utils/relay-encryption.d.ts.map +1 -0
  267. package/dist/utils/relay-encryption.js +23 -0
  268. package/dist/utils/relay-encryption.js.map +1 -0
  269. package/dist/utils/retry.d.ts.map +1 -1
  270. package/dist/utils/retry.js +49 -6
  271. package/dist/utils/retry.js.map +1 -1
  272. package/package.json +30 -14
  273. package/.gitattributes +0 -2
  274. package/.github/copilot-instructions.md +0 -179
  275. package/.github/dependabot.yml +0 -17
  276. package/.github/labeler.yml +0 -38
  277. package/.github/npm-version-script-esm.js +0 -97
  278. package/.github/workflows/beta-release.yml +0 -52
  279. package/.github/workflows/release.yml +0 -71
  280. package/.github/workflows/stale.yml +0 -12
  281. package/PRODUCTION_READY.md +0 -135
  282. package/branding/Node_x_SwitchBot.svg +0 -8
  283. package/branding/icon.png +0 -0
  284. package/branding/switchbot.png +0 -0
  285. package/docs/.nojekyll +0 -1
  286. package/docs/assets/hierarchy.js +0 -1
  287. package/docs/assets/highlight.css +0 -85
  288. package/docs/assets/icons.js +0 -18
  289. package/docs/assets/icons.svg +0 -1
  290. package/docs/assets/main.js +0 -60
  291. package/docs/assets/navigation.js +0 -1
  292. package/docs/assets/search.js +0 -1
  293. package/docs/assets/style.css +0 -1633
  294. package/docs/classes/APIError.html +0 -6
  295. package/docs/classes/APINotAvailableError.html +0 -4
  296. package/docs/classes/BLEConnection.html +0 -17
  297. package/docs/classes/BLENotAvailableError.html +0 -4
  298. package/docs/classes/BLEScanner.html +0 -17
  299. package/docs/classes/CommandFailedError.html +0 -6
  300. package/docs/classes/ConnectionTimeoutError.html +0 -5
  301. package/docs/classes/DeviceManager.html +0 -25
  302. package/docs/classes/DeviceNotFoundError.html +0 -4
  303. package/docs/classes/DiscoveryError.html +0 -5
  304. package/docs/classes/OpenAPIClient.html +0 -66
  305. package/docs/classes/SwitchBot.html +0 -22
  306. package/docs/classes/SwitchBotDevice.html +0 -56
  307. package/docs/classes/SwitchBotError.html +0 -4
  308. package/docs/classes/ValidationError.html +0 -5
  309. package/docs/classes/WoAirPurifier.html +0 -63
  310. package/docs/classes/WoAirPurifierTable.html +0 -64
  311. package/docs/classes/WoBlindTilt.html +0 -67
  312. package/docs/classes/WoBulb.html +0 -65
  313. package/docs/classes/WoCeilingLight.html +0 -66
  314. package/docs/classes/WoContact.html +0 -55
  315. package/docs/classes/WoCurtain.html +0 -63
  316. package/docs/classes/WoHand.html +0 -69
  317. package/docs/classes/WoHub2.html +0 -55
  318. package/docs/classes/WoHub3.html +0 -56
  319. package/docs/classes/WoHumi.html +0 -63
  320. package/docs/classes/WoHumi2.html +0 -64
  321. package/docs/classes/WoIOSensorTH.html +0 -56
  322. package/docs/classes/WoKeypad.html +0 -56
  323. package/docs/classes/WoLeak.html +0 -55
  324. package/docs/classes/WoPlugMiniJP.html +0 -62
  325. package/docs/classes/WoPlugMiniUS.html +0 -61
  326. package/docs/classes/WoPresence.html +0 -55
  327. package/docs/classes/WoRelaySwitch1.html +0 -61
  328. package/docs/classes/WoRelaySwitch1PM.html +0 -62
  329. package/docs/classes/WoRemote.html +0 -56
  330. package/docs/classes/WoSensorTH.html +0 -55
  331. package/docs/classes/WoSensorTHPlus.html +0 -56
  332. package/docs/classes/WoSensorTHPro.html +0 -56
  333. package/docs/classes/WoSensorTHProCO2.html +0 -56
  334. package/docs/classes/WoSmartLock.html +0 -59
  335. package/docs/classes/WoSmartLockPro.html +0 -61
  336. package/docs/classes/WoStrip.html +0 -66
  337. package/docs/enums/LogLevel.html +0 -7
  338. package/docs/enums/SwitchBotBLEModel.html +0 -40
  339. package/docs/enums/SwitchBotBLEModelName.html +0 -40
  340. package/docs/functions/updateBaseURL.html +0 -3
  341. package/docs/hierarchy.html +0 -1
  342. package/docs/index.html +0 -55
  343. package/docs/interfaces/APICommandRequest.html +0 -5
  344. package/docs/interfaces/APICommandResponse.html +0 -5
  345. package/docs/interfaces/APIDevice.html +0 -18
  346. package/docs/interfaces/APIDeviceStatus.html +0 -36
  347. package/docs/interfaces/APIErrorResponse.html +0 -5
  348. package/docs/interfaces/APIResponse.html +0 -5
  349. package/docs/interfaces/AirPurifierCommands.html +0 -5
  350. package/docs/interfaces/AirPurifierServiceData.html +0 -14
  351. package/docs/interfaces/AirPurifierStatus.html +0 -17
  352. package/docs/interfaces/BLEAdvertisement.html +0 -7
  353. package/docs/interfaces/BLEScanOptions.html +0 -10
  354. package/docs/interfaces/BLEServiceData.html +0 -10
  355. package/docs/interfaces/BlindTiltCommands.html +0 -7
  356. package/docs/interfaces/BlindTiltServiceData.html +0 -14
  357. package/docs/interfaces/BlindTiltStatus.html +0 -15
  358. package/docs/interfaces/BotCommands.html +0 -4
  359. package/docs/interfaces/BotServiceData.html +0 -12
  360. package/docs/interfaces/BotStatus.html +0 -14
  361. package/docs/interfaces/BulbCommands.html +0 -6
  362. package/docs/interfaces/BulbServiceData.html +0 -19
  363. package/docs/interfaces/BulbStatus.html +0 -16
  364. package/docs/interfaces/CeilingLightCommands.html +0 -6
  365. package/docs/interfaces/CeilingLightServiceData.html +0 -19
  366. package/docs/interfaces/CeilingLightStatus.html +0 -16
  367. package/docs/interfaces/CommandResult.html +0 -12
  368. package/docs/interfaces/ContactServiceData.html +0 -13
  369. package/docs/interfaces/ContactStatus.html +0 -15
  370. package/docs/interfaces/CurtainCommands.html +0 -5
  371. package/docs/interfaces/CurtainServiceData.html +0 -14
  372. package/docs/interfaces/CurtainStatus.html +0 -17
  373. package/docs/interfaces/DeviceInfo.html +0 -28
  374. package/docs/interfaces/DeviceListResponse.html +0 -4
  375. package/docs/interfaces/DeviceStatus.html +0 -12
  376. package/docs/interfaces/DiscoveryOptions.html +0 -14
  377. package/docs/interfaces/HubServiceData.html +0 -14
  378. package/docs/interfaces/HubStatus.html +0 -15
  379. package/docs/interfaces/HumidifierCommands.html +0 -5
  380. package/docs/interfaces/HumidifierServiceData.html +0 -14
  381. package/docs/interfaces/HumidifierStatus.html +0 -18
  382. package/docs/interfaces/KeypadStatus.html +0 -13
  383. package/docs/interfaces/LeakServiceData.html +0 -11
  384. package/docs/interfaces/LeakStatus.html +0 -13
  385. package/docs/interfaces/LockCommands.html +0 -3
  386. package/docs/interfaces/LockServiceData.html +0 -15
  387. package/docs/interfaces/LockStatus.html +0 -15
  388. package/docs/interfaces/MeterServiceData.html +0 -13
  389. package/docs/interfaces/MeterStatus.html +0 -15
  390. package/docs/interfaces/MotionServiceData.html +0 -13
  391. package/docs/interfaces/MotionStatus.html +0 -14
  392. package/docs/interfaces/PlugCommands.html +0 -4
  393. package/docs/interfaces/PlugServiceData.html +0 -17
  394. package/docs/interfaces/PlugStatus.html +0 -16
  395. package/docs/interfaces/PresenceServiceData.html +0 -12
  396. package/docs/interfaces/PresenceStatus.html +0 -14
  397. package/docs/interfaces/RelaySwitchCommands.html +0 -4
  398. package/docs/interfaces/RelaySwitchServiceData.html +0 -14
  399. package/docs/interfaces/RelaySwitchStatus.html +0 -16
  400. package/docs/interfaces/RemoteStatus.html +0 -12
  401. package/docs/interfaces/SceneListResponse.html +0 -3
  402. package/docs/interfaces/StripCommands.html +0 -6
  403. package/docs/interfaces/StripServiceData.html +0 -19
  404. package/docs/interfaces/StripStatus.html +0 -16
  405. package/docs/interfaces/SwitchBotConfig.html +0 -30
  406. package/docs/interfaces/WebhookConfig.html +0 -4
  407. package/docs/interfaces/WebhookDetails.html +0 -7
  408. package/docs/interfaces/WebhookQueryResponse.html +0 -5
  409. package/docs/interfaces/WebhookSetupResponse.html +0 -5
  410. package/docs/media/BLE.md +0 -1259
  411. package/docs/media/OpenAPI.md +0 -186
  412. package/docs/modules.html +0 -1
  413. package/docs/types/ConnectionType.html +0 -2
  414. package/docs/types/PhysicalDeviceType.html +0 -2
  415. package/docs/types/VirtualDeviceType.html +0 -2
  416. package/docs/variables/urls.html +0 -1
  417. package/tmp-switchbot-scan.mjs +0 -79
  418. package/tsconfig.build.json +0 -17
package/dist/ble.js CHANGED
@@ -2,10 +2,15 @@
2
2
  *
3
3
  * ble.ts: SwitchBot v4.0.0 - BLE Discovery and Communication
4
4
  */
5
+ import { Buffer } from 'node:buffer';
6
+ import { createCipheriv } from 'node:crypto';
5
7
  import { EventEmitter } from 'node:events';
6
- import { BLENotAvailableError, DeviceNotFoundError } from './errors.js';
8
+ import { BLENotAvailableError, CommandFailedError, DeviceNotFoundError } from './errors.js';
7
9
  import { BLE_COMMAND_TIMEOUT, BLE_CONNECT_TIMEOUT, BLE_NOTIFY_CHARACTERISTIC_UUID, BLE_SCAN_TIMEOUT, BLE_SERVICE_UUID, BLE_WRITE_CHARACTERISTIC_UUID, DEVICE_MODEL_MAP } from './settings.js';
8
- import { Logger, macToDeviceId, normalizeMAC, withTimeout, extractMacFromManufacturerData } from './utils/index.js';
10
+ import { extractMacFromManufacturerData, Logger, macToDeviceId, mergeAdvertisement, normalizeMAC, withTimeout } from './utils/index.js';
11
+ // Move RegExp to module scope to avoid re-compilation
12
+ const CHARACTERISTIC_REGEX = /characteristic/i;
13
+ const UUID_DASH_REGEX = /-/g;
9
14
  /**
10
15
  * BLE Scanner for discovering SwitchBot devices
11
16
  */
@@ -14,6 +19,7 @@ export class BLEScanner extends EventEmitter {
14
19
  logger;
15
20
  scanning = false;
16
21
  discoveredDevices = new Map();
22
+ discoveredModelCache = new Map();
17
23
  nobleStateHandler;
18
24
  nobleDiscoverHandler;
19
25
  nobleScanStartHandler;
@@ -157,10 +163,10 @@ export class BLEScanner extends EventEmitter {
157
163
  }
158
164
  // SwitchBot service UUID (current: fd3d, legacy: 000d)
159
165
  const uuid = typeof serviceDataItem.uuid === 'string' ? serviceDataItem.uuid.toLowerCase() : '';
160
- const isSwitchBotUUID = uuid === 'fd3d' ||
161
- uuid === '0000fd3d-0000-1000-8000-00805f9b34fb' ||
162
- uuid === '000d' ||
163
- uuid === '0000000d-0000-1000-8000-00805f9b34fb';
166
+ const isSwitchBotUUID = uuid === 'fd3d'
167
+ || uuid === '0000fd3d-0000-1000-8000-00805f9b34fb'
168
+ || uuid === '000d'
169
+ || uuid === '0000000d-0000-1000-8000-00805f9b34fb';
164
170
  if (!isSwitchBotUUID) {
165
171
  continue;
166
172
  }
@@ -183,15 +189,34 @@ export class BLEScanner extends EventEmitter {
183
189
  this.logger.debug('Skipping BLE discovery with no address and no peripheral id');
184
190
  continue;
185
191
  }
192
+ // Determine if advertisement is encrypted (simple heuristic: check for known encrypted models or data length)
193
+ // This can be refined as needed
194
+ const isEncrypted = !!(serviceData && typeof serviceData.model === 'string' && serviceData.model.startsWith('!'));
195
+ // Try to get a friendly model name (from serviceData or fallback to model code)
196
+ const modelFriendlyName = serviceData?.modelName || serviceData?.model || undefined;
197
+ // Attempt to get the raw advertisement data (from serviceDataItem.data or peripheral.advertisement)
198
+ const rawAdvData = serviceDataItem?.data || peripheral.advertisement?.serviceData?.[0]?.data || undefined;
186
199
  const advertisement = {
187
200
  id: fallbackId,
188
201
  address: normalizedAddress,
189
202
  isAddressable: normalizedAddress !== undefined,
190
203
  rssi,
191
204
  serviceData,
205
+ rawAdvData,
206
+ isEncrypted,
207
+ modelFriendlyName,
192
208
  };
193
209
  const discoveryKey = normalizedAddress ?? `id:${fallbackId}`;
194
- this.discoveredDevices.set(discoveryKey, advertisement);
210
+ // Merge with previous advertisement if present
211
+ const prev = this.discoveredDevices.get(discoveryKey);
212
+ if (prev) {
213
+ const merged = mergeAdvertisement(prev, advertisement);
214
+ this.discoveredDevices.set(discoveryKey, merged);
215
+ }
216
+ else {
217
+ this.discoveredDevices.set(discoveryKey, advertisement);
218
+ }
219
+ this.discoveredModelCache.set(discoveryKey, serviceData.model);
195
220
  this.emit('discover', advertisement);
196
221
  this.logger.debug(`Discovered ${serviceData.modelName} at ${normalizedAddress ?? fallbackId}`);
197
222
  }
@@ -224,6 +249,45 @@ export class BLEScanner extends EventEmitter {
224
249
  if (data.length > 2) {
225
250
  serviceData.battery = data[2] & 0x7F;
226
251
  }
252
+ // Model-specific advertisement parsing for status without active connection
253
+ if (model === 'H' && data.length > 1) {
254
+ // Bot (WoHand): infer mode/state from status bits
255
+ serviceData.mode = (data[1] & 0x80) ? 'switch' : 'press';
256
+ serviceData.state = (data[1] & 0x40) !== 0;
257
+ }
258
+ if ((model === 'c' || model === '{') && data.length > 4) {
259
+ // Curtain/Curtain3
260
+ serviceData.inMotion = (data[1] & 0x40) !== 0;
261
+ serviceData.position = Math.min(100, Math.max(0, data[3] & 0x7F));
262
+ serviceData.lightLevel = data[4] & 0x7F;
263
+ serviceData.calibration = (data[1] & 0x20) !== 0;
264
+ if (data.length > 5) {
265
+ serviceData.deviceChain = data[5] & 0x03;
266
+ }
267
+ }
268
+ if ((model === 'o' || model === '\x11') && data.length > 1) {
269
+ // Lock / Lock Pro
270
+ const lockStatus = data[1] & 0x0F;
271
+ serviceData.status = lockStatus;
272
+ serviceData.doorOpen = (data[1] & 0x10) !== 0;
273
+ serviceData.calibration = (data[1] & 0x80) !== 0;
274
+ serviceData.lockState = lockStatus === 1
275
+ ? 'unlocked'
276
+ : lockStatus === 2
277
+ ? 'jammed'
278
+ : 'locked';
279
+ if (data.length > 3) {
280
+ serviceData.sequenceNumber = data[3];
281
+ }
282
+ }
283
+ if ((model === '\x0D' || model === '\x0E') && data.length > 1) {
284
+ // Relay Switch 1PM / Relay Switch 1
285
+ serviceData.state = (data[1] & 0x01) === 0x01;
286
+ serviceData.channel2State = (data[1] & 0x02) === 0x02;
287
+ if (data.length > 3) {
288
+ serviceData.sequenceNumber = data[3];
289
+ }
290
+ }
227
291
  return serviceData;
228
292
  }
229
293
  catch (error) {
@@ -254,6 +318,7 @@ export class BLEScanner extends EventEmitter {
254
318
  }
255
319
  // Clear previous discoveries if starting fresh
256
320
  this.discoveredDevices.clear();
321
+ this.discoveredModelCache.clear();
257
322
  // Start scanning
258
323
  this.noble.startScanning([], active);
259
324
  // Auto-stop after duration
@@ -280,12 +345,13 @@ export class BLEScanner extends EventEmitter {
280
345
  this.stopScan();
281
346
  this.removeNobleHandlers();
282
347
  this.discoveredDevices.clear();
348
+ this.discoveredModelCache.clear();
283
349
  }
284
350
  /**
285
351
  * Get all discovered devices
286
352
  */
287
353
  getDiscoveredDevices() {
288
- return Array.from(this.discoveredDevices.values());
354
+ return [...this.discoveredDevices.values()];
289
355
  }
290
356
  /**
291
357
  * Get discovered device by MAC or BLE ID
@@ -322,8 +388,8 @@ export class BLEScanner extends EventEmitter {
322
388
  return withTimeout(new Promise((resolve) => {
323
389
  const handler = (advertisement) => {
324
390
  // Match by address (if available) or by ID
325
- const matches = (advertisement.address && normalizeMAC(advertisement.address) === normalizedMac) ||
326
- (bleId && advertisement.id === bleId);
391
+ const matches = (advertisement.address && normalizeMAC(advertisement.address) === normalizedMac)
392
+ || (bleId && advertisement.id === bleId);
327
393
  if (matches) {
328
394
  this.off('discover', handler);
329
395
  resolve(advertisement);
@@ -341,9 +407,24 @@ export class BLEConnection {
341
407
  logger;
342
408
  connections = new Map(); // Map of MAC -> Peripheral
343
409
  characteristics = new Map();
410
+ disconnectTimers = new Map();
411
+ operationLocks = new Map();
412
+ encryptionConfig = new Map();
413
+ notificationHandlers = new Map();
414
+ persistentConnectionMs = 8500;
344
415
  noblePromise = null;
416
+ // Notification handling
417
+ notificationFutures = new Map();
418
+ // Expected disconnect tracking
419
+ expectedDisconnects = new Set();
420
+ /**
421
+ * Mark the next disconnect for this MAC as expected
422
+ */
423
+ markExpectedDisconnect(mac) {
424
+ this.expectedDisconnects.add(normalizeMAC(mac));
425
+ }
345
426
  constructor(options = {}) {
346
- this.logger = new Logger('BLEConnection', options.logLevel);
427
+ this.logger = options.logger ?? new Logger('BLEConnection', options.logLevel);
347
428
  this.noble = options.noble;
348
429
  if (!this.noble) {
349
430
  this.initializeNoble().catch((error) => {
@@ -390,6 +471,216 @@ export class BLEConnection {
390
471
  throw new BLENotAvailableError('BLE not available - noble failed to initialize');
391
472
  }
392
473
  }
474
+ async withMacLock(mac, fn) {
475
+ const normalizedMac = normalizeMAC(mac);
476
+ const previousLock = this.operationLocks.get(normalizedMac) ?? Promise.resolve();
477
+ let releaseCurrent = () => { };
478
+ const currentLock = new Promise((resolve) => {
479
+ releaseCurrent = resolve;
480
+ });
481
+ const chainedLock = previousLock.then(() => currentLock);
482
+ this.operationLocks.set(normalizedMac, chainedLock);
483
+ await previousLock;
484
+ try {
485
+ return await fn();
486
+ }
487
+ finally {
488
+ releaseCurrent();
489
+ if (this.operationLocks.get(normalizedMac) === chainedLock) {
490
+ this.operationLocks.delete(normalizedMac);
491
+ }
492
+ }
493
+ }
494
+ clearDisconnectTimer(mac) {
495
+ const existingTimer = this.disconnectTimers.get(mac);
496
+ if (existingTimer) {
497
+ clearTimeout(existingTimer);
498
+ this.disconnectTimers.delete(mac);
499
+ }
500
+ }
501
+ scheduleDisconnect(mac) {
502
+ this.clearDisconnectTimer(mac);
503
+ const timer = setTimeout(() => {
504
+ this.disconnect(mac).catch((error) => {
505
+ this.logger.debug(`Auto-disconnect failed for ${mac}`, error);
506
+ });
507
+ }, this.persistentConnectionMs);
508
+ this.disconnectTimers.set(mac, timer);
509
+ }
510
+ setPersistentConnectionTimeout(timeoutMs) {
511
+ this.persistentConnectionMs = Math.max(1000, timeoutMs);
512
+ }
513
+ setEncryption(mac, keyHex, ivHex, mode = 'auto') {
514
+ const normalizedMac = normalizeMAC(mac);
515
+ const key = Buffer.from(keyHex, 'hex');
516
+ const iv = Buffer.from(ivHex, 'hex');
517
+ if (key.length !== 16) {
518
+ throw new CommandFailedError('Invalid BLE encryption key length (expected 16 bytes)', 'ble');
519
+ }
520
+ const resolvedMode = mode === 'auto'
521
+ ? (iv.length === 12 ? 'gcm' : 'ctr')
522
+ : mode;
523
+ const expectedIvLength = resolvedMode === 'gcm' ? 12 : 16;
524
+ if (iv.length !== expectedIvLength) {
525
+ throw new CommandFailedError(`Invalid IV length for ${resolvedMode.toUpperCase()} mode`, 'ble');
526
+ }
527
+ this.encryptionConfig.set(normalizedMac, { key, iv: Buffer.from(iv), mode: resolvedMode });
528
+ }
529
+ clearEncryption(mac) {
530
+ this.encryptionConfig.delete(normalizeMAC(mac));
531
+ }
532
+ incrementIv(iv) {
533
+ const nextIv = Buffer.from(iv);
534
+ for (let i = nextIv.length - 1; i >= 0; i--) {
535
+ if ((nextIv[i] ?? 0) === 0xFF) {
536
+ nextIv[i] = 0x00;
537
+ }
538
+ else {
539
+ nextIv[i] = (nextIv[i] ?? 0) + 1;
540
+ break;
541
+ }
542
+ }
543
+ return nextIv;
544
+ }
545
+ encryptIfConfigured(mac, data) {
546
+ const normalizedMac = normalizeMAC(mac);
547
+ const config = this.encryptionConfig.get(normalizedMac);
548
+ if (!config) {
549
+ return data;
550
+ }
551
+ if (config.mode === 'gcm') {
552
+ const cipher = createCipheriv('aes-128-gcm', config.key, config.iv);
553
+ const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
554
+ const tag = cipher.getAuthTag().subarray(0, 2);
555
+ this.encryptionConfig.set(normalizedMac, {
556
+ ...config,
557
+ iv: this.incrementIv(config.iv),
558
+ });
559
+ return Buffer.concat([encrypted, tag]);
560
+ }
561
+ const cipher = createCipheriv('aes-128-ctr', config.key, config.iv);
562
+ return Buffer.concat([cipher.update(data), cipher.final()]);
563
+ }
564
+ validateCommandResult(response, mac) {
565
+ if (!response || response.length === 0) {
566
+ throw new CommandFailedError(`Empty BLE response from ${mac}`, 'ble');
567
+ }
568
+ if (response.includes(0x07)) {
569
+ throw new CommandFailedError(`BLE command rejected by ${mac}: password required`, 'ble');
570
+ }
571
+ if (response.includes(0x09)) {
572
+ throw new CommandFailedError(`BLE command rejected by ${mac}: password incorrect`, 'ble');
573
+ }
574
+ const acknowledged = response.some(byte => byte === 0x01 || byte === 0x05 || byte === 0x06);
575
+ if (!acknowledged) {
576
+ throw new CommandFailedError(`Unexpected BLE response from ${mac}: ${response.toString('hex')}`, 'ble');
577
+ }
578
+ }
579
+ async sendCommand(mac, data, options = {}) {
580
+ const normalizedMac = normalizeMAC(mac);
581
+ const { expectResponse = true, validateResponse = true, responseTimeoutMs = 1200, expectNotification = false, notificationTimeoutMs = 5000, } = options;
582
+ return this.withMacLock(normalizedMac, async () => {
583
+ const payload = this.encryptIfConfigured(normalizedMac, data);
584
+ await this.write(normalizedMac, payload);
585
+ if (expectNotification) {
586
+ // DEBUG: Log future creation
587
+ this.logger.debug(`[DEBUG] Creating notification future for ${normalizedMac}`);
588
+ // Wait for notification (per-command future)
589
+ return await new Promise((resolve, reject) => {
590
+ if (this.notificationFutures.has(normalizedMac)) {
591
+ this.logger.warn(`Notification future already exists for ${normalizedMac}, overwriting`);
592
+ const prev = this.notificationFutures.get(normalizedMac);
593
+ if (prev) {
594
+ clearTimeout(prev.timer);
595
+ }
596
+ }
597
+ const timer = setTimeout(() => {
598
+ this.logger.debug(`[DEBUG] Notification future timed out for ${normalizedMac}`);
599
+ this.notificationFutures.delete(normalizedMac);
600
+ reject(new Error(`Notification timeout (${notificationTimeoutMs}ms) for ${normalizedMac}`));
601
+ }, notificationTimeoutMs);
602
+ this.notificationFutures.set(normalizedMac, { resolve, reject, timer });
603
+ // TEST HOOK: Notify when the notification future is set
604
+ if (typeof this._onNotificationFutureSet === 'function') {
605
+ this._onNotificationFutureSet(normalizedMac);
606
+ }
607
+ this.logger.debug(`[DEBUG] notificationFutures after set: ${[...this.notificationFutures.keys()].join(',')}`);
608
+ });
609
+ }
610
+ if (!expectResponse && !validateResponse) {
611
+ return undefined;
612
+ }
613
+ const response = await withTimeout(this.read(normalizedMac), responseTimeoutMs, `BLE response timeout from ${normalizedMac}`);
614
+ if (validateResponse) {
615
+ this.validateCommandResult(response, normalizedMac);
616
+ }
617
+ return response;
618
+ });
619
+ }
620
+ async subscribeNotifications(mac, handler) {
621
+ const normalizedMac = normalizeMAC(mac);
622
+ if (!this.connections.has(normalizedMac)) {
623
+ await this.connect(normalizedMac);
624
+ }
625
+ const chars = this.characteristics.get(normalizedMac);
626
+ if (!chars?.notify) {
627
+ throw new CommandFailedError(`Notify characteristic not available for ${normalizedMac}`, 'ble');
628
+ }
629
+ if (!this.notificationHandlers.has(normalizedMac)) {
630
+ this.notificationHandlers.set(normalizedMac, new Set());
631
+ if (typeof chars.notify.on === 'function') {
632
+ chars.notify.on('data', (payload) => {
633
+ // DEBUG: Log notification future state
634
+ this.logger.debug(`[DEBUG] notifyChar handler called for ${normalizedMac}`);
635
+ this.logger.debug(`[DEBUG] notificationFutures keys at handler: ${[...this.notificationFutures.keys()].join(',')}`);
636
+ const future = this.notificationFutures.get(normalizedMac);
637
+ if (future) {
638
+ this.logger.debug(`[DEBUG] notificationFutures present, resolving as solicited`);
639
+ clearTimeout(future.timer);
640
+ this.notificationFutures.delete(normalizedMac);
641
+ this.logger.debug(`[DEBUG] notificationFutures after delete: ${[...this.notificationFutures.keys()].join(',')}`);
642
+ future.resolve(payload);
643
+ return;
644
+ }
645
+ this.logger.debug(`[DEBUG] unsolicited notification branch`);
646
+ this.logger.debug(`[DEBUG] about to call logger.info for unsolicited notification`);
647
+ this.logger.info(`Unsolicited notification from ${normalizedMac}: ${payload.toString('hex')}`);
648
+ this.logger.debug(`[DEBUG] after logger.info for unsolicited notification`);
649
+ const handlers = this.notificationHandlers.get(normalizedMac);
650
+ if (!handlers) {
651
+ return;
652
+ }
653
+ for (const listener of handlers) {
654
+ listener(payload);
655
+ }
656
+ });
657
+ }
658
+ }
659
+ this.notificationHandlers.get(normalizedMac).add(handler);
660
+ if (typeof chars.notify.subscribe === 'function') {
661
+ await new Promise((resolve, reject) => {
662
+ chars.notify.subscribe((error) => {
663
+ if (error) {
664
+ reject(error);
665
+ }
666
+ else {
667
+ resolve();
668
+ }
669
+ });
670
+ });
671
+ }
672
+ }
673
+ unsubscribeNotifications(mac, handler) {
674
+ const normalizedMac = normalizeMAC(mac);
675
+ const handlers = this.notificationHandlers.get(normalizedMac);
676
+ if (!handlers) {
677
+ return;
678
+ }
679
+ handlers.delete(handler);
680
+ if (handlers.size === 0) {
681
+ this.notificationHandlers.delete(normalizedMac);
682
+ }
683
+ }
393
684
  /**
394
685
  * Connect to a device
395
686
  */
@@ -398,6 +689,7 @@ export class BLEConnection {
398
689
  const normalizedMac = normalizeMAC(mac);
399
690
  // Already connected?
400
691
  if (this.connections.has(normalizedMac)) {
692
+ this.clearDisconnectTimer(normalizedMac);
401
693
  this.logger.debug(`Already connected to ${mac}`);
402
694
  return;
403
695
  }
@@ -431,6 +723,7 @@ export class BLEConnection {
431
723
  });
432
724
  }), BLE_CONNECT_TIMEOUT, `Connection to ${mac} timed out`);
433
725
  this.connections.set(normalizedMac, peripheral);
726
+ this.clearDisconnectTimer(normalizedMac);
434
727
  this.logger.info(`Connected to ${mac}`);
435
728
  // Discover characteristics (may throw)
436
729
  try {
@@ -461,8 +754,8 @@ export class BLEConnection {
461
754
  }
462
755
  });
463
756
  }), BLE_CONNECT_TIMEOUT, 'Characteristic discovery timed out');
464
- const writeChar = characteristics.find((c) => c.uuid === BLE_WRITE_CHARACTERISTIC_UUID.replace(/-/g, ''));
465
- const notifyChar = characteristics.find((c) => c.uuid === BLE_NOTIFY_CHARACTERISTIC_UUID.replace(/-/g, ''));
757
+ const writeChar = characteristics.find((c) => c.uuid === BLE_WRITE_CHARACTERISTIC_UUID.replace(UUID_DASH_REGEX, ''));
758
+ const notifyChar = characteristics.find((c) => c.uuid === BLE_NOTIFY_CHARACTERISTIC_UUID.replace(UUID_DASH_REGEX, ''));
466
759
  if (!writeChar || !notifyChar) {
467
760
  throw new Error('Required characteristics not found');
468
761
  }
@@ -475,14 +768,33 @@ export class BLEConnection {
475
768
  async disconnect(mac) {
476
769
  const normalizedMac = normalizeMAC(mac);
477
770
  const peripheral = this.connections.get(normalizedMac);
771
+ this.clearDisconnectTimer(normalizedMac);
772
+ // Reset encryption state (IV, cipher, mode) for this device
773
+ this.clearEncryption(normalizedMac);
774
+ this.notificationHandlers.delete(normalizedMac);
775
+ const wasExpected = this.expectedDisconnects.has(normalizedMac);
776
+ if (wasExpected) {
777
+ this.expectedDisconnects.delete(normalizedMac);
778
+ }
478
779
  if (!peripheral) {
780
+ if (!wasExpected) {
781
+ this.logger.warn(`Unexpected disconnect: peripheral not found for ${mac}`);
782
+ }
783
+ else {
784
+ this.logger.info(`Expected disconnect: peripheral not found for ${mac}`);
785
+ }
479
786
  return;
480
787
  }
481
788
  await new Promise((resolve) => {
482
789
  peripheral.disconnect(() => {
483
790
  this.connections.delete(normalizedMac);
484
791
  this.characteristics.delete(normalizedMac);
485
- this.logger.info(`Disconnected from ${mac}`);
792
+ if (wasExpected) {
793
+ this.logger.info(`Expected disconnect from ${mac}`);
794
+ }
795
+ else {
796
+ this.logger.warn(`Unexpected disconnect from ${mac}`);
797
+ }
486
798
  resolve();
487
799
  });
488
800
  });
@@ -496,21 +808,54 @@ export class BLEConnection {
496
808
  if (!this.connections.has(normalizedMac)) {
497
809
  await this.connect(mac);
498
810
  }
499
- const chars = this.characteristics.get(normalizedMac);
811
+ let chars = this.characteristics.get(normalizedMac);
500
812
  if (!chars) {
501
- throw new Error(`Characteristics not available for ${mac}`);
813
+ await this.discoverCharacteristics(normalizedMac, this.connections.get(normalizedMac));
814
+ chars = this.characteristics.get(normalizedMac);
815
+ if (!chars) {
816
+ throw new Error(`Characteristics not available for ${mac}`);
817
+ }
502
818
  }
503
819
  this.logger.debug(`Writing to ${mac}:`, data.toString('hex'));
504
- await withTimeout(new Promise((resolve, reject) => {
505
- chars.write.write(data, false, (error) => {
506
- if (error) {
507
- reject(error);
508
- }
509
- else {
510
- resolve();
820
+ try {
821
+ await withTimeout(new Promise((resolve, reject) => {
822
+ (chars.write).write(data, false, (error) => {
823
+ if (error) {
824
+ reject(error);
825
+ }
826
+ else {
827
+ this.scheduleDisconnect(normalizedMac);
828
+ resolve();
829
+ }
830
+ });
831
+ }), BLE_COMMAND_TIMEOUT, 'Write operation timed out');
832
+ }
833
+ catch (err) {
834
+ // If error is characteristic-related, clear cache and retry once
835
+ if (CHARACTERISTIC_REGEX.test(err?.message || '')) {
836
+ this.characteristics.delete(normalizedMac);
837
+ await this.discoverCharacteristics(normalizedMac, this.connections.get(normalizedMac));
838
+ chars = this.characteristics.get(normalizedMac);
839
+ if (!chars) {
840
+ throw err;
511
841
  }
512
- });
513
- }), BLE_COMMAND_TIMEOUT, 'Write operation timed out');
842
+ // Retry once
843
+ await withTimeout(new Promise((resolve, reject) => {
844
+ (chars.write).write(data, false, (error) => {
845
+ if (error) {
846
+ reject(error);
847
+ }
848
+ else {
849
+ this.scheduleDisconnect(normalizedMac);
850
+ resolve();
851
+ }
852
+ });
853
+ }), BLE_COMMAND_TIMEOUT, 'Write operation timed out');
854
+ }
855
+ else {
856
+ throw err;
857
+ }
858
+ }
514
859
  }
515
860
  /**
516
861
  * Read data from device
@@ -521,21 +866,54 @@ export class BLEConnection {
521
866
  if (!this.connections.has(normalizedMac)) {
522
867
  await this.connect(mac);
523
868
  }
524
- const chars = this.characteristics.get(normalizedMac);
869
+ let chars = this.characteristics.get(normalizedMac);
525
870
  if (!chars) {
526
- throw new Error(`Characteristics not available for ${mac}`);
871
+ await this.discoverCharacteristics(normalizedMac, this.connections.get(normalizedMac));
872
+ chars = this.characteristics.get(normalizedMac);
873
+ if (!chars) {
874
+ throw new Error(`Characteristics not available for ${mac}`);
875
+ }
527
876
  }
528
877
  this.logger.debug(`Reading from ${mac}`);
529
- return withTimeout(new Promise((resolve, reject) => {
530
- chars.notify.read((error, data) => {
531
- if (error) {
532
- reject(error);
533
- }
534
- else {
535
- resolve(data);
878
+ try {
879
+ return await withTimeout(new Promise((resolve, reject) => {
880
+ (chars.notify).read((error, data) => {
881
+ if (error) {
882
+ reject(error);
883
+ }
884
+ else {
885
+ this.scheduleDisconnect(normalizedMac);
886
+ resolve(data);
887
+ }
888
+ });
889
+ }), BLE_COMMAND_TIMEOUT, 'Read operation timed out');
890
+ }
891
+ catch (err) {
892
+ // If error is characteristic-related, clear cache and retry once
893
+ if (CHARACTERISTIC_REGEX.test(err?.message || '')) {
894
+ this.characteristics.delete(normalizedMac);
895
+ await this.discoverCharacteristics(normalizedMac, this.connections.get(normalizedMac));
896
+ chars = this.characteristics.get(normalizedMac);
897
+ if (!chars) {
898
+ throw err;
536
899
  }
537
- });
538
- }), BLE_COMMAND_TIMEOUT, 'Read operation timed out');
900
+ // Retry once
901
+ return await withTimeout(new Promise((resolve, reject) => {
902
+ (chars.notify).read((error, data) => {
903
+ if (error) {
904
+ reject(error);
905
+ }
906
+ else {
907
+ this.scheduleDisconnect(normalizedMac);
908
+ resolve(data);
909
+ }
910
+ });
911
+ }), BLE_COMMAND_TIMEOUT, 'Read operation timed out');
912
+ }
913
+ else {
914
+ throw err;
915
+ }
916
+ }
539
917
  }
540
918
  /**
541
919
  * Check if connected to device
@@ -547,7 +925,7 @@ export class BLEConnection {
547
925
  * Disconnect all devices
548
926
  */
549
927
  async disconnectAll() {
550
- const macs = Array.from(this.connections.keys());
928
+ const macs = [...this.connections.keys()];
551
929
  await Promise.all(macs.map(mac => this.disconnect(mac)));
552
930
  }
553
931
  /**