@switchbot/homebridge-switchbot 5.0.0-beta.13 → 5.0.0-beta.130

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 (593) hide show
  1. package/.github/ISSUE_TEMPLATE/e2e-verification.md +36 -0
  2. package/.github/copilot-instructions.md +39 -0
  3. package/.github/workflows/ci.yml +32 -0
  4. package/.github/workflows/manual-e2e.yml +115 -0
  5. package/.github/workflows/release.yml +0 -4
  6. package/CHANGELOG.md +35 -0
  7. package/E2E-VERIFICATION.md +121 -0
  8. package/MIGRATION.md +54 -0
  9. package/README.md +99 -3
  10. package/TODO.md +263 -0
  11. package/config.schema.json +198 -14787
  12. package/dist/device-types.d.ts +31 -0
  13. package/dist/device-types.d.ts.map +1 -0
  14. package/dist/device-types.js +246 -0
  15. package/dist/device-types.js.map +1 -0
  16. package/dist/deviceFactory.d.ts +13 -0
  17. package/dist/deviceFactory.d.ts.map +1 -0
  18. package/dist/deviceFactory.js +146 -0
  19. package/dist/deviceFactory.js.map +1 -0
  20. package/dist/devices/deviceBase.d.ts +50 -0
  21. package/dist/devices/deviceBase.d.ts.map +1 -0
  22. package/dist/devices/deviceBase.js +119 -0
  23. package/dist/devices/deviceBase.js.map +1 -0
  24. package/dist/devices/genericDevice.d.ts +277 -0
  25. package/dist/devices/genericDevice.d.ts.map +1 -0
  26. package/dist/devices/genericDevice.js +1383 -0
  27. package/dist/devices/genericDevice.js.map +1 -0
  28. package/dist/errors.d.ts +5 -0
  29. package/dist/errors.d.ts.map +1 -0
  30. package/dist/errors.js +51 -0
  31. package/dist/errors.js.map +1 -0
  32. package/dist/homebridge-ui/endpoints/config.d.ts +3 -0
  33. package/dist/homebridge-ui/endpoints/config.d.ts.map +1 -0
  34. package/dist/homebridge-ui/endpoints/config.js +107 -0
  35. package/dist/homebridge-ui/endpoints/config.js.map +1 -0
  36. package/dist/homebridge-ui/endpoints/credentials.d.ts +6 -0
  37. package/dist/homebridge-ui/endpoints/credentials.d.ts.map +1 -0
  38. package/dist/homebridge-ui/endpoints/credentials.js +65 -0
  39. package/dist/homebridge-ui/endpoints/credentials.js.map +1 -0
  40. package/dist/homebridge-ui/endpoints/devices.d.ts +6 -0
  41. package/dist/homebridge-ui/endpoints/devices.d.ts.map +1 -0
  42. package/dist/homebridge-ui/endpoints/devices.js +430 -0
  43. package/dist/homebridge-ui/endpoints/devices.js.map +1 -0
  44. package/dist/homebridge-ui/endpoints/discovery.d.ts +7 -0
  45. package/dist/homebridge-ui/endpoints/discovery.d.ts.map +1 -0
  46. package/dist/homebridge-ui/endpoints/discovery.js +212 -0
  47. package/dist/homebridge-ui/endpoints/discovery.js.map +1 -0
  48. package/dist/homebridge-ui/public/css/styles.css +447 -0
  49. package/dist/homebridge-ui/public/index.html +144 -248
  50. package/dist/homebridge-ui/public/js/api.d.ts +62 -0
  51. package/dist/homebridge-ui/public/js/api.d.ts.map +1 -0
  52. package/dist/homebridge-ui/public/js/api.js +225 -0
  53. package/dist/homebridge-ui/public/js/api.js.map +1 -0
  54. package/dist/homebridge-ui/public/js/api.ts +279 -0
  55. package/dist/homebridge-ui/public/js/app.d.ts +2 -0
  56. package/dist/homebridge-ui/public/js/app.d.ts.map +1 -0
  57. package/dist/homebridge-ui/public/js/app.js +3600 -0
  58. package/dist/homebridge-ui/public/js/app.js.map +7 -0
  59. package/dist/homebridge-ui/public/js/app.ts +23 -0
  60. package/dist/homebridge-ui/public/js/constants.d.ts +2 -0
  61. package/dist/homebridge-ui/public/js/constants.d.ts.map +1 -0
  62. package/dist/homebridge-ui/public/js/constants.js +2 -0
  63. package/dist/homebridge-ui/public/js/constants.js.map +1 -0
  64. package/dist/homebridge-ui/public/js/constants.ts +1 -0
  65. package/dist/homebridge-ui/public/js/credentials.d.ts +3 -0
  66. package/dist/homebridge-ui/public/js/credentials.d.ts.map +1 -0
  67. package/dist/homebridge-ui/public/js/credentials.js +96 -0
  68. package/dist/homebridge-ui/public/js/credentials.js.map +1 -0
  69. package/dist/homebridge-ui/public/js/credentials.ts +100 -0
  70. package/dist/homebridge-ui/public/js/devices-delete.d.ts +3 -0
  71. package/dist/homebridge-ui/public/js/devices-delete.d.ts.map +1 -0
  72. package/dist/homebridge-ui/public/js/devices-delete.js +206 -0
  73. package/dist/homebridge-ui/public/js/devices-delete.js.map +1 -0
  74. package/dist/homebridge-ui/public/js/devices-delete.ts +236 -0
  75. package/dist/homebridge-ui/public/js/devices.d.ts +9 -0
  76. package/dist/homebridge-ui/public/js/devices.d.ts.map +1 -0
  77. package/dist/homebridge-ui/public/js/devices.js +94 -0
  78. package/dist/homebridge-ui/public/js/devices.js.map +1 -0
  79. package/dist/homebridge-ui/public/js/devices.ts +114 -0
  80. package/dist/homebridge-ui/public/js/discovery.d.ts +4 -0
  81. package/dist/homebridge-ui/public/js/discovery.d.ts.map +1 -0
  82. package/dist/homebridge-ui/public/js/discovery.js +1364 -0
  83. package/dist/homebridge-ui/public/js/discovery.js.map +1 -0
  84. package/dist/homebridge-ui/public/js/discovery.ts +1492 -0
  85. package/dist/homebridge-ui/public/js/logger.d.ts +6 -0
  86. package/dist/homebridge-ui/public/js/logger.d.ts.map +1 -0
  87. package/dist/homebridge-ui/public/js/logger.js +12 -0
  88. package/dist/homebridge-ui/public/js/logger.js.map +1 -0
  89. package/dist/homebridge-ui/public/js/logger.ts +11 -0
  90. package/dist/homebridge-ui/public/js/modal.d.ts +5 -0
  91. package/dist/homebridge-ui/public/js/modal.d.ts.map +1 -0
  92. package/dist/homebridge-ui/public/js/modal.js +26 -0
  93. package/dist/homebridge-ui/public/js/modal.js.map +1 -0
  94. package/dist/homebridge-ui/public/js/modal.ts +28 -0
  95. package/dist/homebridge-ui/public/js/modals.d.ts +7 -0
  96. package/dist/homebridge-ui/public/js/modals.d.ts.map +1 -0
  97. package/dist/homebridge-ui/public/js/modals.js +494 -0
  98. package/dist/homebridge-ui/public/js/modals.js.map +1 -0
  99. package/dist/homebridge-ui/public/js/modals.ts +546 -0
  100. package/dist/homebridge-ui/public/js/render.d.ts +68 -0
  101. package/dist/homebridge-ui/public/js/render.d.ts.map +1 -0
  102. package/dist/homebridge-ui/public/js/render.js +914 -0
  103. package/dist/homebridge-ui/public/js/render.js.map +1 -0
  104. package/dist/homebridge-ui/public/js/render.ts +1026 -0
  105. package/dist/homebridge-ui/public/js/toast.d.ts +6 -0
  106. package/dist/homebridge-ui/public/js/toast.d.ts.map +1 -0
  107. package/dist/homebridge-ui/public/js/toast.js +29 -0
  108. package/dist/homebridge-ui/public/js/toast.js.map +1 -0
  109. package/dist/homebridge-ui/public/js/toast.ts +37 -0
  110. package/dist/homebridge-ui/public/js/types.d.ts +23 -0
  111. package/dist/homebridge-ui/public/js/types.d.ts.map +1 -0
  112. package/dist/homebridge-ui/public/js/types.js +2 -0
  113. package/dist/homebridge-ui/public/js/types.js.map +1 -0
  114. package/dist/homebridge-ui/public/js/types.ts +26 -0
  115. package/dist/homebridge-ui/server.js +11 -41
  116. package/dist/homebridge-ui/server.js.map +1 -1
  117. package/dist/homebridge-ui/utils/config-parser.d.ts +35 -0
  118. package/dist/homebridge-ui/utils/config-parser.d.ts.map +1 -0
  119. package/dist/homebridge-ui/utils/config-parser.js +87 -0
  120. package/dist/homebridge-ui/utils/config-parser.js.map +1 -0
  121. package/dist/homebridge-ui/utils/device-migration.d.ts +35 -0
  122. package/dist/homebridge-ui/utils/device-migration.d.ts.map +1 -0
  123. package/dist/homebridge-ui/utils/device-migration.js +111 -0
  124. package/dist/homebridge-ui/utils/device-migration.js.map +1 -0
  125. package/dist/homebridge-ui/utils/logger.d.ts +7 -0
  126. package/dist/homebridge-ui/utils/logger.d.ts.map +1 -0
  127. package/dist/homebridge-ui/utils/logger.js +17 -0
  128. package/dist/homebridge-ui/utils/logger.js.map +1 -0
  129. package/dist/index.d.ts.map +1 -1
  130. package/dist/index.js +1 -3
  131. package/dist/index.js.map +1 -1
  132. package/dist/platform.d.ts +39 -0
  133. package/dist/platform.d.ts.map +1 -0
  134. package/dist/platform.js +1570 -0
  135. package/dist/platform.js.map +1 -0
  136. package/dist/settings.d.ts +10 -249
  137. package/dist/settings.d.ts.map +1 -1
  138. package/dist/settings.js +5 -30
  139. package/dist/settings.js.map +1 -1
  140. package/dist/switchbotClient.d.ts +32 -0
  141. package/dist/switchbotClient.d.ts.map +1 -0
  142. package/dist/switchbotClient.js +253 -0
  143. package/dist/switchbotClient.js.map +1 -0
  144. package/dist/utils.d.ts +36 -82
  145. package/dist/utils.d.ts.map +1 -1
  146. package/dist/utils.js +40 -786
  147. package/dist/utils.js.map +1 -1
  148. package/docs/assets/highlight.css +21 -0
  149. package/docs/assets/icons.js +1 -1
  150. package/docs/assets/icons.svg +1 -1
  151. package/docs/assets/main.js +2 -2
  152. package/docs/assets/style.css +3 -3
  153. package/docs/index.html +103 -13
  154. package/docs/variables/default.html +1 -1
  155. package/eslint.config.js +7 -8
  156. package/nodemon.json +2 -2
  157. package/package.json +36 -32
  158. package/scripts/build-ui.js +36 -0
  159. package/scripts/e2e/README.md +25 -0
  160. package/scripts/e2e/curtain-e2e.sh +70 -0
  161. package/scripts/e2e/fan-e2e.sh +75 -0
  162. package/scripts/e2e/light-advanced-e2e.sh +97 -0
  163. package/scripts/e2e/light-e2e.sh +75 -0
  164. package/scripts/e2e/list-accessories.sh +19 -0
  165. package/scripts/e2e/lock-e2e.sh +65 -0
  166. package/scripts/free-dev-ports.mjs +105 -0
  167. package/scripts/generate-matter-maps.js +60 -0
  168. package/scripts/run-e2e-local.sh +14 -0
  169. package/scripts/sync-device-types.mjs +28 -0
  170. package/src/device-types.ts +261 -0
  171. package/src/deviceFactory.ts +190 -0
  172. package/src/devices/deviceBase.ts +141 -0
  173. package/src/devices/genericDevice.ts +1333 -0
  174. package/src/errors.ts +43 -0
  175. package/src/homebridge-ui/endpoints/config.ts +126 -0
  176. package/src/homebridge-ui/endpoints/credentials.ts +74 -0
  177. package/src/homebridge-ui/endpoints/devices.ts +464 -0
  178. package/src/homebridge-ui/endpoints/discovery.ts +233 -0
  179. package/src/homebridge-ui/public/css/styles.css +447 -0
  180. package/src/homebridge-ui/public/index.html +144 -248
  181. package/src/homebridge-ui/public/js/api.ts +279 -0
  182. package/src/homebridge-ui/public/js/app.ts +23 -0
  183. package/src/homebridge-ui/public/js/constants.ts +1 -0
  184. package/src/homebridge-ui/public/js/credentials.ts +100 -0
  185. package/src/homebridge-ui/public/js/devices-delete.ts +236 -0
  186. package/src/homebridge-ui/public/js/devices.ts +114 -0
  187. package/src/homebridge-ui/public/js/discovery.ts +1492 -0
  188. package/src/homebridge-ui/public/js/logger.ts +11 -0
  189. package/src/homebridge-ui/public/js/modal.ts +28 -0
  190. package/src/homebridge-ui/public/js/modals.ts +546 -0
  191. package/src/homebridge-ui/public/js/render.ts +1026 -0
  192. package/src/homebridge-ui/public/js/toast.ts +37 -0
  193. package/src/homebridge-ui/public/js/types.ts +26 -0
  194. package/src/homebridge-ui/server.ts +11 -43
  195. package/src/homebridge-ui/utils/config-parser.ts +108 -0
  196. package/src/homebridge-ui/utils/device-migration.ts +144 -0
  197. package/src/homebridge-ui/utils/logger.ts +17 -0
  198. package/src/index.ts +1 -3
  199. package/src/platform.ts +1585 -0
  200. package/src/settings.ts +12 -277
  201. package/src/switchbotClient.ts +251 -0
  202. package/src/utils.ts +48 -812
  203. package/test/accessory-restore.spec.ts +73 -0
  204. package/test/device-mapping.spec.ts +37 -0
  205. package/test/deviceFactory.spec.ts +18 -0
  206. package/test/e2e/run-e2e.spec.ts +52 -0
  207. package/test/fan-swing.spec.ts +29 -0
  208. package/test/helpers/matter-harness.ts +53 -0
  209. package/test/lock-users.spec.ts +44 -0
  210. package/test/matter-childbridge.spec.ts +59 -0
  211. package/test/matter-descriptors.spec.ts +97 -0
  212. package/test/matter-device-state.spec.ts +101 -0
  213. package/test/matter-integration.spec.ts +136 -0
  214. package/test/platform.integration.spec.ts +55 -0
  215. package/test/switchbot-client-debounce.spec.ts +131 -0
  216. package/test/switchbot-client-openapi.spec.ts +56 -0
  217. package/test/switchbotClient.spec.ts +10 -0
  218. package/test/utils.spec.ts +36 -0
  219. package/todo/COMPLETED.md +542 -0
  220. package/todo/README.md +59 -0
  221. package/todo/TODO.md +190 -0
  222. package/todo/mockups/filtering-sorting.svg +112 -0
  223. package/todo/mockups/modal-switchbot-theme.svg +66 -0
  224. package/todo/mockups/signal-strength-visualization.svg +94 -0
  225. package/vitest.config.ts +7 -0
  226. package/coverage/base.css +0 -224
  227. package/coverage/block-navigation.js +0 -87
  228. package/coverage/clover.xml +0 -15847
  229. package/coverage/coverage-final.json +0 -42
  230. package/coverage/docs/assets/dmt/dmt-component-data.js.html +0 -85
  231. package/coverage/docs/assets/dmt/dmt-components.js.html +0 -286
  232. package/coverage/docs/assets/dmt/index.html +0 -131
  233. package/coverage/docs/assets/hierarchy.js.html +0 -85
  234. package/coverage/docs/assets/icons.js.html +0 -136
  235. package/coverage/docs/assets/index.html +0 -146
  236. package/coverage/docs/assets/main.js.html +0 -265
  237. package/coverage/favicon.png +0 -0
  238. package/coverage/index.html +0 -191
  239. package/coverage/prettify.css +0 -1
  240. package/coverage/prettify.js +0 -2
  241. package/coverage/sort-arrow-sprite.png +0 -0
  242. package/coverage/sorter.js +0 -196
  243. package/coverage/src/device/blindtilt.ts.html +0 -3238
  244. package/coverage/src/device/bot.ts.html +0 -2803
  245. package/coverage/src/device/ceilinglight.ts.html +0 -2338
  246. package/coverage/src/device/colorbulb.ts.html +0 -2824
  247. package/coverage/src/device/contact.ts.html +0 -1465
  248. package/coverage/src/device/curtain.ts.html +0 -2869
  249. package/coverage/src/device/device.ts.html +0 -2500
  250. package/coverage/src/device/fan.ts.html +0 -2242
  251. package/coverage/src/device/hub.ts.html +0 -1408
  252. package/coverage/src/device/humidifier.ts.html +0 -2116
  253. package/coverage/src/device/index.html +0 -416
  254. package/coverage/src/device/iosensor.ts.html +0 -1375
  255. package/coverage/src/device/lightstrip.ts.html +0 -2617
  256. package/coverage/src/device/lock.ts.html +0 -1963
  257. package/coverage/src/device/meter.ts.html +0 -1372
  258. package/coverage/src/device/meterplus.ts.html +0 -1384
  259. package/coverage/src/device/meterpro.ts.html +0 -1618
  260. package/coverage/src/device/motion.ts.html +0 -1264
  261. package/coverage/src/device/plug.ts.html +0 -1372
  262. package/coverage/src/device/relayswitch.ts.html +0 -2284
  263. package/coverage/src/device/robotvacuumcleaner.ts.html +0 -1810
  264. package/coverage/src/device/waterdetector.ts.html +0 -1294
  265. package/coverage/src/homebridge-ui/index.html +0 -116
  266. package/coverage/src/homebridge-ui/server.ts.html +0 -229
  267. package/coverage/src/index.html +0 -161
  268. package/coverage/src/index.ts.html +0 -124
  269. package/coverage/src/irdevice/airconditioner.ts.html +0 -1687
  270. package/coverage/src/irdevice/airpurifier.ts.html +0 -844
  271. package/coverage/src/irdevice/camera.ts.html +0 -475
  272. package/coverage/src/irdevice/fan.ts.html +0 -766
  273. package/coverage/src/irdevice/index.html +0 -251
  274. package/coverage/src/irdevice/irdevice.ts.html +0 -1117
  275. package/coverage/src/irdevice/light.ts.html +0 -826
  276. package/coverage/src/irdevice/other.ts.html +0 -2458
  277. package/coverage/src/irdevice/tv.ts.html +0 -1222
  278. package/coverage/src/irdevice/vacuumcleaner.ts.html +0 -466
  279. package/coverage/src/irdevice/waterheater.ts.html +0 -469
  280. package/coverage/src/platform.ts.html +0 -8776
  281. package/coverage/src/settings.ts.html +0 -934
  282. package/coverage/src/utils.ts.html +0 -2092
  283. package/dist/baseMatterAccessory.test.d.ts +0 -2
  284. package/dist/baseMatterAccessory.test.d.ts.map +0 -1
  285. package/dist/baseMatterAccessory.test.js +0 -71
  286. package/dist/baseMatterAccessory.test.js.map +0 -1
  287. package/dist/devices-hap/airpurifier.d.ts +0 -54
  288. package/dist/devices-hap/airpurifier.d.ts.map +0 -1
  289. package/dist/devices-hap/airpurifier.js +0 -527
  290. package/dist/devices-hap/airpurifier.js.map +0 -1
  291. package/dist/devices-hap/blindtilt.d.ts +0 -90
  292. package/dist/devices-hap/blindtilt.d.ts.map +0 -1
  293. package/dist/devices-hap/blindtilt.js +0 -974
  294. package/dist/devices-hap/blindtilt.js.map +0 -1
  295. package/dist/devices-hap/bot.d.ts +0 -102
  296. package/dist/devices-hap/bot.d.ts.map +0 -1
  297. package/dist/devices-hap/bot.js +0 -811
  298. package/dist/devices-hap/bot.js.map +0 -1
  299. package/dist/devices-hap/ceilinglight.d.ts +0 -85
  300. package/dist/devices-hap/ceilinglight.d.ts.map +0 -1
  301. package/dist/devices-hap/ceilinglight.js +0 -701
  302. package/dist/devices-hap/ceilinglight.js.map +0 -1
  303. package/dist/devices-hap/colorbulb.d.ts +0 -88
  304. package/dist/devices-hap/colorbulb.d.ts.map +0 -1
  305. package/dist/devices-hap/colorbulb.js +0 -881
  306. package/dist/devices-hap/colorbulb.js.map +0 -1
  307. package/dist/devices-hap/contact.d.ts +0 -44
  308. package/dist/devices-hap/contact.d.ts.map +0 -1
  309. package/dist/devices-hap/contact.js +0 -409
  310. package/dist/devices-hap/contact.js.map +0 -1
  311. package/dist/devices-hap/curtain.d.ts +0 -73
  312. package/dist/devices-hap/curtain.d.ts.map +0 -1
  313. package/dist/devices-hap/curtain.js +0 -869
  314. package/dist/devices-hap/curtain.js.map +0 -1
  315. package/dist/devices-hap/device.d.ts +0 -98
  316. package/dist/devices-hap/device.d.ts.map +0 -1
  317. package/dist/devices-hap/device.js +0 -749
  318. package/dist/devices-hap/device.js.map +0 -1
  319. package/dist/devices-hap/fan.d.ts +0 -69
  320. package/dist/devices-hap/fan.d.ts.map +0 -1
  321. package/dist/devices-hap/fan.js +0 -649
  322. package/dist/devices-hap/fan.js.map +0 -1
  323. package/dist/devices-hap/hub.d.ts +0 -37
  324. package/dist/devices-hap/hub.d.ts.map +0 -1
  325. package/dist/devices-hap/hub.js +0 -392
  326. package/dist/devices-hap/hub.js.map +0 -1
  327. package/dist/devices-hap/humidifier.d.ts +0 -68
  328. package/dist/devices-hap/humidifier.d.ts.map +0 -1
  329. package/dist/devices-hap/humidifier.js +0 -628
  330. package/dist/devices-hap/humidifier.js.map +0 -1
  331. package/dist/devices-hap/iosensor.d.ts +0 -42
  332. package/dist/devices-hap/iosensor.d.ts.map +0 -1
  333. package/dist/devices-hap/iosensor.js +0 -382
  334. package/dist/devices-hap/iosensor.js.map +0 -1
  335. package/dist/devices-hap/lightstrip.d.ts +0 -79
  336. package/dist/devices-hap/lightstrip.d.ts.map +0 -1
  337. package/dist/devices-hap/lightstrip.js +0 -797
  338. package/dist/devices-hap/lightstrip.js.map +0 -1
  339. package/dist/devices-hap/lock.d.ts +0 -53
  340. package/dist/devices-hap/lock.d.ts.map +0 -1
  341. package/dist/devices-hap/lock.js +0 -561
  342. package/dist/devices-hap/lock.js.map +0 -1
  343. package/dist/devices-hap/meter.d.ts +0 -37
  344. package/dist/devices-hap/meter.d.ts.map +0 -1
  345. package/dist/devices-hap/meter.js +0 -379
  346. package/dist/devices-hap/meter.js.map +0 -1
  347. package/dist/devices-hap/meterplus.d.ts +0 -42
  348. package/dist/devices-hap/meterplus.d.ts.map +0 -1
  349. package/dist/devices-hap/meterplus.js +0 -384
  350. package/dist/devices-hap/meterplus.js.map +0 -1
  351. package/dist/devices-hap/meterpro.d.ts +0 -43
  352. package/dist/devices-hap/meterpro.d.ts.map +0 -1
  353. package/dist/devices-hap/meterpro.js +0 -468
  354. package/dist/devices-hap/meterpro.js.map +0 -1
  355. package/dist/devices-hap/motion.d.ts +0 -42
  356. package/dist/devices-hap/motion.d.ts.map +0 -1
  357. package/dist/devices-hap/motion.js +0 -345
  358. package/dist/devices-hap/motion.js.map +0 -1
  359. package/dist/devices-hap/plug.d.ts +0 -49
  360. package/dist/devices-hap/plug.d.ts.map +0 -1
  361. package/dist/devices-hap/plug.js +0 -395
  362. package/dist/devices-hap/plug.js.map +0 -1
  363. package/dist/devices-hap/relayswitch.d.ts +0 -96
  364. package/dist/devices-hap/relayswitch.d.ts.map +0 -1
  365. package/dist/devices-hap/relayswitch.js +0 -642
  366. package/dist/devices-hap/relayswitch.js.map +0 -1
  367. package/dist/devices-hap/robotvacuumcleaner.d.ts +0 -54
  368. package/dist/devices-hap/robotvacuumcleaner.d.ts.map +0 -1
  369. package/dist/devices-hap/robotvacuumcleaner.js +0 -523
  370. package/dist/devices-hap/robotvacuumcleaner.js.map +0 -1
  371. package/dist/devices-hap/waterdetector.d.ts +0 -41
  372. package/dist/devices-hap/waterdetector.d.ts.map +0 -1
  373. package/dist/devices-hap/waterdetector.js +0 -356
  374. package/dist/devices-hap/waterdetector.js.map +0 -1
  375. package/dist/devices-matter/BaseMatterAccessory.d.ts +0 -78
  376. package/dist/devices-matter/BaseMatterAccessory.d.ts.map +0 -1
  377. package/dist/devices-matter/BaseMatterAccessory.js +0 -220
  378. package/dist/devices-matter/BaseMatterAccessory.js.map +0 -1
  379. package/dist/devices-matter/ColorLightAccessory.d.ts +0 -20
  380. package/dist/devices-matter/ColorLightAccessory.d.ts.map +0 -1
  381. package/dist/devices-matter/ColorLightAccessory.js +0 -95
  382. package/dist/devices-matter/ColorLightAccessory.js.map +0 -1
  383. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts +0 -18
  384. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts.map +0 -1
  385. package/dist/devices-matter/ColorTemperatureLightAccessory.js +0 -76
  386. package/dist/devices-matter/ColorTemperatureLightAccessory.js.map +0 -1
  387. package/dist/devices-matter/ContactSensorAccessory.d.ts +0 -12
  388. package/dist/devices-matter/ContactSensorAccessory.d.ts.map +0 -1
  389. package/dist/devices-matter/ContactSensorAccessory.js +0 -34
  390. package/dist/devices-matter/ContactSensorAccessory.js.map +0 -1
  391. package/dist/devices-matter/DimmableLightAccessory.d.ts +0 -58
  392. package/dist/devices-matter/DimmableLightAccessory.d.ts.map +0 -1
  393. package/dist/devices-matter/DimmableLightAccessory.js +0 -167
  394. package/dist/devices-matter/DimmableLightAccessory.js.map +0 -1
  395. package/dist/devices-matter/DoorLockAccessory.d.ts +0 -14
  396. package/dist/devices-matter/DoorLockAccessory.d.ts.map +0 -1
  397. package/dist/devices-matter/DoorLockAccessory.js +0 -50
  398. package/dist/devices-matter/DoorLockAccessory.js.map +0 -1
  399. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts +0 -21
  400. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts.map +0 -1
  401. package/dist/devices-matter/ExtendedColorLightAccessory.js +0 -106
  402. package/dist/devices-matter/ExtendedColorLightAccessory.js.map +0 -1
  403. package/dist/devices-matter/FanAccessory.d.ts +0 -16
  404. package/dist/devices-matter/FanAccessory.d.ts.map +0 -1
  405. package/dist/devices-matter/FanAccessory.js +0 -81
  406. package/dist/devices-matter/FanAccessory.js.map +0 -1
  407. package/dist/devices-matter/HumiditySensorAccessory.d.ts +0 -12
  408. package/dist/devices-matter/HumiditySensorAccessory.d.ts.map +0 -1
  409. package/dist/devices-matter/HumiditySensorAccessory.js +0 -34
  410. package/dist/devices-matter/HumiditySensorAccessory.js.map +0 -1
  411. package/dist/devices-matter/LeakSensorAccessory.d.ts +0 -12
  412. package/dist/devices-matter/LeakSensorAccessory.d.ts.map +0 -1
  413. package/dist/devices-matter/LeakSensorAccessory.js +0 -33
  414. package/dist/devices-matter/LeakSensorAccessory.js.map +0 -1
  415. package/dist/devices-matter/LightSensorAccessory.d.ts +0 -12
  416. package/dist/devices-matter/LightSensorAccessory.d.ts.map +0 -1
  417. package/dist/devices-matter/LightSensorAccessory.js +0 -34
  418. package/dist/devices-matter/LightSensorAccessory.js.map +0 -1
  419. package/dist/devices-matter/OccupancySensorAccessory.d.ts +0 -12
  420. package/dist/devices-matter/OccupancySensorAccessory.d.ts.map +0 -1
  421. package/dist/devices-matter/OccupancySensorAccessory.js +0 -39
  422. package/dist/devices-matter/OccupancySensorAccessory.js.map +0 -1
  423. package/dist/devices-matter/OnOffLightAccessory.d.ts +0 -38
  424. package/dist/devices-matter/OnOffLightAccessory.d.ts.map +0 -1
  425. package/dist/devices-matter/OnOffLightAccessory.js +0 -110
  426. package/dist/devices-matter/OnOffLightAccessory.js.map +0 -1
  427. package/dist/devices-matter/OnOffOutletAccessory.d.ts +0 -14
  428. package/dist/devices-matter/OnOffOutletAccessory.d.ts.map +0 -1
  429. package/dist/devices-matter/OnOffOutletAccessory.js +0 -43
  430. package/dist/devices-matter/OnOffOutletAccessory.js.map +0 -1
  431. package/dist/devices-matter/OnOffSwitchAccessory.d.ts +0 -14
  432. package/dist/devices-matter/OnOffSwitchAccessory.d.ts.map +0 -1
  433. package/dist/devices-matter/OnOffSwitchAccessory.js +0 -42
  434. package/dist/devices-matter/OnOffSwitchAccessory.js.map +0 -1
  435. package/dist/devices-matter/RoboticVacuumAccessory.d.ts +0 -68
  436. package/dist/devices-matter/RoboticVacuumAccessory.d.ts.map +0 -1
  437. package/dist/devices-matter/RoboticVacuumAccessory.js +0 -334
  438. package/dist/devices-matter/RoboticVacuumAccessory.js.map +0 -1
  439. package/dist/devices-matter/SmokeCOAlarmAccessory.d.ts +0 -11
  440. package/dist/devices-matter/SmokeCOAlarmAccessory.d.ts.map +0 -1
  441. package/dist/devices-matter/SmokeCOAlarmAccessory.js +0 -49
  442. package/dist/devices-matter/SmokeCOAlarmAccessory.js.map +0 -1
  443. package/dist/devices-matter/TemperatureSensorAccessory.d.ts +0 -12
  444. package/dist/devices-matter/TemperatureSensorAccessory.d.ts.map +0 -1
  445. package/dist/devices-matter/TemperatureSensorAccessory.js +0 -36
  446. package/dist/devices-matter/TemperatureSensorAccessory.js.map +0 -1
  447. package/dist/devices-matter/ThermostatAccessory.d.ts +0 -19
  448. package/dist/devices-matter/ThermostatAccessory.d.ts.map +0 -1
  449. package/dist/devices-matter/ThermostatAccessory.js +0 -95
  450. package/dist/devices-matter/ThermostatAccessory.js.map +0 -1
  451. package/dist/devices-matter/VenetianBlindAccessory.d.ts +0 -19
  452. package/dist/devices-matter/VenetianBlindAccessory.d.ts.map +0 -1
  453. package/dist/devices-matter/VenetianBlindAccessory.js +0 -99
  454. package/dist/devices-matter/VenetianBlindAccessory.js.map +0 -1
  455. package/dist/devices-matter/WindowBlindAccessory.d.ts +0 -17
  456. package/dist/devices-matter/WindowBlindAccessory.d.ts.map +0 -1
  457. package/dist/devices-matter/WindowBlindAccessory.js +0 -80
  458. package/dist/devices-matter/WindowBlindAccessory.js.map +0 -1
  459. package/dist/devices-matter/custom/PowerStripAccessory.d.ts +0 -97
  460. package/dist/devices-matter/custom/PowerStripAccessory.d.ts.map +0 -1
  461. package/dist/devices-matter/custom/PowerStripAccessory.js +0 -265
  462. package/dist/devices-matter/custom/PowerStripAccessory.js.map +0 -1
  463. package/dist/devices-matter/custom/index.d.ts +0 -8
  464. package/dist/devices-matter/custom/index.d.ts.map +0 -1
  465. package/dist/devices-matter/custom/index.js +0 -8
  466. package/dist/devices-matter/custom/index.js.map +0 -1
  467. package/dist/devices-matter/index.d.ts +0 -29
  468. package/dist/devices-matter/index.d.ts.map +0 -1
  469. package/dist/devices-matter/index.js +0 -28
  470. package/dist/devices-matter/index.js.map +0 -1
  471. package/dist/index.test.d.ts +0 -2
  472. package/dist/index.test.d.ts.map +0 -1
  473. package/dist/index.test.js +0 -19
  474. package/dist/index.test.js.map +0 -1
  475. package/dist/irdevice/airconditioner.d.ts +0 -61
  476. package/dist/irdevice/airconditioner.d.ts.map +0 -1
  477. package/dist/irdevice/airconditioner.js +0 -472
  478. package/dist/irdevice/airconditioner.js.map +0 -1
  479. package/dist/irdevice/airpurifier.d.ts +0 -50
  480. package/dist/irdevice/airpurifier.d.ts.map +0 -1
  481. package/dist/irdevice/airpurifier.js +0 -213
  482. package/dist/irdevice/airpurifier.js.map +0 -1
  483. package/dist/irdevice/camera.d.ts +0 -32
  484. package/dist/irdevice/camera.d.ts.map +0 -1
  485. package/dist/irdevice/camera.js +0 -107
  486. package/dist/irdevice/camera.js.map +0 -1
  487. package/dist/irdevice/fan.d.ts +0 -36
  488. package/dist/irdevice/fan.d.ts.map +0 -1
  489. package/dist/irdevice/fan.js +0 -200
  490. package/dist/irdevice/fan.js.map +0 -1
  491. package/dist/irdevice/irdevice.d.ts +0 -68
  492. package/dist/irdevice/irdevice.d.ts.map +0 -1
  493. package/dist/irdevice/irdevice.js +0 -298
  494. package/dist/irdevice/irdevice.js.map +0 -1
  495. package/dist/irdevice/light.d.ts +0 -36
  496. package/dist/irdevice/light.d.ts.map +0 -1
  497. package/dist/irdevice/light.js +0 -206
  498. package/dist/irdevice/light.js.map +0 -1
  499. package/dist/irdevice/other.d.ts +0 -57
  500. package/dist/irdevice/other.d.ts.map +0 -1
  501. package/dist/irdevice/other.js +0 -778
  502. package/dist/irdevice/other.js.map +0 -1
  503. package/dist/irdevice/tv.d.ts +0 -45
  504. package/dist/irdevice/tv.d.ts.map +0 -1
  505. package/dist/irdevice/tv.js +0 -327
  506. package/dist/irdevice/tv.js.map +0 -1
  507. package/dist/irdevice/vacuumcleaner.d.ts +0 -28
  508. package/dist/irdevice/vacuumcleaner.d.ts.map +0 -1
  509. package/dist/irdevice/vacuumcleaner.js +0 -104
  510. package/dist/irdevice/vacuumcleaner.js.map +0 -1
  511. package/dist/irdevice/waterheater.d.ts +0 -30
  512. package/dist/irdevice/waterheater.d.ts.map +0 -1
  513. package/dist/irdevice/waterheater.js +0 -105
  514. package/dist/irdevice/waterheater.js.map +0 -1
  515. package/dist/platform-hap.d.ts +0 -149
  516. package/dist/platform-hap.d.ts.map +0 -1
  517. package/dist/platform-hap.js +0 -2861
  518. package/dist/platform-hap.js.map +0 -1
  519. package/dist/platform-matter.d.ts +0 -120
  520. package/dist/platform-matter.d.ts.map +0 -1
  521. package/dist/platform-matter.js +0 -999
  522. package/dist/platform-matter.js.map +0 -1
  523. package/dist/utils.test.d.ts +0 -2
  524. package/dist/utils.test.d.ts.map +0 -1
  525. package/dist/utils.test.js +0 -95
  526. package/dist/utils.test.js.map +0 -1
  527. package/dist/verifyconfig.test.d.ts +0 -2
  528. package/dist/verifyconfig.test.d.ts.map +0 -1
  529. package/dist/verifyconfig.test.js +0 -167
  530. package/dist/verifyconfig.test.js.map +0 -1
  531. package/src/baseMatterAccessory.test.ts +0 -88
  532. package/src/custom.d.ts +0 -7
  533. package/src/devices-hap/airpurifier.ts +0 -563
  534. package/src/devices-hap/blindtilt.ts +0 -1049
  535. package/src/devices-hap/bot.ts +0 -900
  536. package/src/devices-hap/ceilinglight.ts +0 -742
  537. package/src/devices-hap/colorbulb.ts +0 -904
  538. package/src/devices-hap/contact.ts +0 -457
  539. package/src/devices-hap/curtain.ts +0 -944
  540. package/src/devices-hap/device.ts +0 -811
  541. package/src/devices-hap/fan.ts +0 -711
  542. package/src/devices-hap/hub.ts +0 -439
  543. package/src/devices-hap/humidifier.ts +0 -669
  544. package/src/devices-hap/iosensor.ts +0 -427
  545. package/src/devices-hap/lightstrip.ts +0 -836
  546. package/src/devices-hap/lock.ts +0 -620
  547. package/src/devices-hap/meter.ts +0 -426
  548. package/src/devices-hap/meterplus.ts +0 -430
  549. package/src/devices-hap/meterpro.ts +0 -522
  550. package/src/devices-hap/motion.ts +0 -390
  551. package/src/devices-hap/plug.ts +0 -423
  552. package/src/devices-hap/relayswitch.ts +0 -727
  553. package/src/devices-hap/robotvacuumcleaner.ts +0 -568
  554. package/src/devices-hap/waterdetector.ts +0 -400
  555. package/src/devices-matter/BaseMatterAccessory.ts +0 -249
  556. package/src/devices-matter/ColorLightAccessory.ts +0 -110
  557. package/src/devices-matter/ColorTemperatureLightAccessory.ts +0 -90
  558. package/src/devices-matter/ContactSensorAccessory.ts +0 -41
  559. package/src/devices-matter/DimmableLightAccessory.ts +0 -192
  560. package/src/devices-matter/DoorLockAccessory.ts +0 -60
  561. package/src/devices-matter/ExtendedColorLightAccessory.ts +0 -122
  562. package/src/devices-matter/FanAccessory.ts +0 -95
  563. package/src/devices-matter/HumiditySensorAccessory.ts +0 -41
  564. package/src/devices-matter/LeakSensorAccessory.ts +0 -40
  565. package/src/devices-matter/LightSensorAccessory.ts +0 -41
  566. package/src/devices-matter/OccupancySensorAccessory.ts +0 -48
  567. package/src/devices-matter/OnOffLightAccessory.ts +0 -125
  568. package/src/devices-matter/OnOffOutletAccessory.ts +0 -51
  569. package/src/devices-matter/OnOffSwitchAccessory.ts +0 -51
  570. package/src/devices-matter/RoboticVacuumAccessory.ts +0 -407
  571. package/src/devices-matter/SmokeCOAlarmAccessory.ts +0 -59
  572. package/src/devices-matter/TemperatureSensorAccessory.ts +0 -43
  573. package/src/devices-matter/ThermostatAccessory.ts +0 -110
  574. package/src/devices-matter/VenetianBlindAccessory.ts +0 -115
  575. package/src/devices-matter/WindowBlindAccessory.ts +0 -92
  576. package/src/devices-matter/custom/PowerStripAccessory.ts +0 -309
  577. package/src/devices-matter/custom/index.ts +0 -8
  578. package/src/devices-matter/index.ts +0 -29
  579. package/src/index.test.ts +0 -24
  580. package/src/irdevice/airconditioner.ts +0 -533
  581. package/src/irdevice/airpurifier.ts +0 -252
  582. package/src/irdevice/camera.ts +0 -129
  583. package/src/irdevice/fan.ts +0 -226
  584. package/src/irdevice/irdevice.ts +0 -344
  585. package/src/irdevice/light.ts +0 -246
  586. package/src/irdevice/other.ts +0 -790
  587. package/src/irdevice/tv.ts +0 -378
  588. package/src/irdevice/vacuumcleaner.ts +0 -126
  589. package/src/irdevice/waterheater.ts +0 -127
  590. package/src/platform-hap.ts +0 -2997
  591. package/src/platform-matter.ts +0 -1124
  592. package/src/utils.test.ts +0 -96
  593. package/src/verifyconfig.test.ts +0 -197
@@ -0,0 +1,1585 @@
1
+ import type { SwitchBotPluginConfig } from './settings.js'
2
+ import type { API, Logger, PlatformConfig } from 'homebridge'
3
+
4
+ import { createDevice } from './deviceFactory.js'
5
+ import { PLATFORM_NAME, PLUGIN_NAME } from './settings.js'
6
+ import { SwitchBotClient } from './switchbotClient.js'
7
+
8
+ // Which device types should prefer Matter if available
9
+ // Based on HAP service mappings: device implementations use specific HomeKit services
10
+ // that map to corresponding Matter clusters when Matter is enabled
11
+ const DEVICE_MATTER_SUPPORTED: Record<string, boolean> = {
12
+ // Core devices
13
+ 'bot': true, // Switch → OnOff
14
+ 'curtain': true, // WindowCovering → WindowCovering
15
+ 'fan': true, // Fan → FanControl
16
+ 'light': true, // Lightbulb → OnOff + LevelControl
17
+ 'lightstrip': true, // Lightbulb (color) → OnOff + LevelControl + ColorControl
18
+ 'motion': true, // MotionSensor → OccupancySensing
19
+ 'contact': true, // ContactSensor → BooleanState
20
+ 'vacuum': true, // Switch → RobotVacuumCleaner
21
+ 'lock': true, // LockMechanism → DoorLock
22
+ 'humidifier': true, // Fan + Humidity → OnOff + FanControl + RelativeHumidityMeasurement
23
+ 'temperature': true, // TemperatureSensor → TemperatureMeasurement
24
+
25
+ // Switch devices
26
+ 'relay': true, // Switch → OnOff
27
+ 'relay switch 1': true, // Switch → OnOff
28
+ 'relay switch 1pm': true, // Switch → OnOff
29
+ 'plug': true, // Outlet → OnOff
30
+ 'plug mini (jp)': true, // Outlet → OnOff
31
+ 'plug mini (us)': true, // Outlet → OnOff
32
+
33
+ // Window covering variants
34
+ 'blindtilt': true, // WindowCovering → WindowCovering
35
+ 'blind tilt': true, // WindowCovering → WindowCovering
36
+ 'curtain3': true, // WindowCovering → WindowCovering
37
+ 'rollershade': true, // WindowCovering → WindowCovering
38
+ 'roller shade': true, // WindowCovering → WindowCovering
39
+ 'worollershade': true, // WindowCovering → WindowCovering
40
+ 'wo rollershade': true, // WindowCovering → WindowCovering
41
+
42
+ // Vacuum variants (normalized to 'vacuum' before lookup)
43
+ 'wosweeper': true, // VacuumDevice → RobotVacuumCleaner
44
+ 'wosweepermini': true, // VacuumDevice → RobotVacuumCleaner
45
+ 'wosweeperminipro': true, // VacuumDevice → RobotVacuumCleaner
46
+ 'k10+': true, // VacuumDevice → RobotVacuumCleaner
47
+ 'k10+ pro': true, // VacuumDevice → RobotVacuumCleaner
48
+
49
+ // Sensors
50
+ 'meter': true, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
51
+ 'meterplus': true, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
52
+ 'meter plus (jp)': true, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
53
+ 'meterpro': true, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
54
+ 'meterpro(co2)': true, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
55
+ 'waterdetector': true, // LeakSensor → BooleanState
56
+ 'water detector': true, // LeakSensor → BooleanState
57
+
58
+ // Other devices
59
+ 'smart fan': true, // Fan → FanControl
60
+ 'strip light': true, // Lightbulb (color) → OnOff + LevelControl + ColorControl
61
+ 'hub 2': false, // Hub device - not exposed as accessory
62
+ 'walletfinder': false, // Button device - Matter support TBD
63
+ }
64
+
65
+ // Default Matter cluster configurations by device type
66
+ // Maps device types to their Matter cluster states (used when device doesn't provide clusters)
67
+ // Note: wosweeper/curtain/plug variants are normalized before cluster lookup (see loadDevices)
68
+ export const DEVICE_MATTER_CLUSTERS: Record<string, any> = {
69
+ // Core devices - aligned with HAP service implementations
70
+ bot: { onOff: { onOff: false } }, // Switch → OnOff
71
+ vacuum: {
72
+ rvcRunMode: {
73
+ supportedModes: [
74
+ { label: 'Idle', mode: 0, modeTags: [{ value: 16384 }] },
75
+ { label: 'Cleaning', mode: 1, modeTags: [{ value: 16385 }] },
76
+ ],
77
+ currentMode: 0,
78
+ },
79
+ rvcCleanMode: {
80
+ supportedModes: [
81
+ { label: 'Vacuum', mode: 0, modeTags: [{ value: 16385 }] },
82
+ ],
83
+ currentMode: 0,
84
+ },
85
+ rvcOperationalState: {
86
+ operationalStateList: [
87
+ { operationalStateId: 0 }, // Stopped
88
+ { operationalStateId: 1 }, // Running
89
+ { operationalStateId: 2 }, // Paused
90
+ { operationalStateId: 3 }, // Error (required)
91
+ { operationalStateId: 64 }, // Seeking charger
92
+ { operationalStateId: 65 }, // Charging
93
+ { operationalStateId: 66 }, // Docked
94
+ ],
95
+ operationalState: 66,
96
+ },
97
+ }, // Switch in HAP, RobotVacuumCleaner in Matter
98
+ curtain: {
99
+ windowCovering: {
100
+ type: 4, // Curtain (correct for standard lift-only curtains)
101
+ },
102
+ }, // WindowCovering → WindowCovering (includes curtain3, rollershade variants via normalization)
103
+ blindtilt: {
104
+ windowCovering: {
105
+ type: 8, // TiltBlindLiftAndTilt - supports tilt feature
106
+ },
107
+ }, // WindowCovering with tilt → WindowCovering
108
+ fan: {
109
+ onOff: { onOff: false },
110
+ fanControl: {
111
+ fanMode: 0,
112
+ percentCurrent: 0,
113
+ percentSetting: 0,
114
+ speedCurrent: 0,
115
+ speedMax: 100,
116
+ },
117
+ }, // Fan → OnOff + FanControl
118
+ light: {
119
+ onOff: { onOff: false },
120
+ levelControl: {
121
+ currentLevel: 0,
122
+ minLevel: 0,
123
+ maxLevel: 254,
124
+ },
125
+ }, // Lightbulb → OnOff + LevelControl
126
+ lightstrip: {
127
+ onOff: { onOff: false },
128
+ levelControl: {
129
+ currentLevel: 0,
130
+ minLevel: 0,
131
+ maxLevel: 254,
132
+ },
133
+ colorControl: {
134
+ colorMode: 0,
135
+ },
136
+ }, // Lightbulb with color → OnOff + LevelControl + ColorControl
137
+ lock: {
138
+ doorLock: {
139
+ lockState: 0,
140
+ lockType: 0,
141
+ actuatorEnabled: true,
142
+ operatingMode: 0,
143
+ },
144
+ }, // LockMechanism → DoorLock
145
+ motion: {
146
+ occupancySensing: {
147
+ occupancy: 0,
148
+ occupancySensorType: 0,
149
+ },
150
+ }, // MotionSensor → OccupancySensing
151
+ contact: {
152
+ booleanState: {
153
+ stateValue: false,
154
+ },
155
+ }, // ContactSensor → BooleanState
156
+ humidifier: {
157
+ onOff: { onOff: false },
158
+ fanControl: {
159
+ fanMode: 0,
160
+ percentCurrent: 0,
161
+ },
162
+ relativeHumidityMeasurement: {
163
+ measuredValue: 0,
164
+ minMeasuredValue: 0,
165
+ maxMeasuredValue: 100,
166
+ },
167
+ }, // HumidifierDehumidifier → OnOff + FanControl + RelativeHumidityMeasurement
168
+ temperature: {
169
+ temperatureMeasurement: {
170
+ measuredValue: 0,
171
+ minMeasuredValue: -27315,
172
+ maxMeasuredValue: 32767,
173
+ },
174
+ }, // TemperatureSensor → TemperatureMeasurement
175
+
176
+ // Switch/Outlet devices
177
+ relay: { onOff: { onOff: false } }, // Switch → OnOff
178
+ plug: {
179
+ onOff: { onOff: false },
180
+ electricalMeasurement: {
181
+ activePower: 0,
182
+ rmsCurrent: 0,
183
+ rmsVoltage: 0,
184
+ },
185
+ }, // Outlet → OnOff + ElectricalMeasurement (for PM models)
186
+
187
+ // Sensors
188
+ meter: {
189
+ temperatureMeasurement: {
190
+ measuredValue: 0,
191
+ minMeasuredValue: -27315,
192
+ maxMeasuredValue: 32767,
193
+ },
194
+ relativeHumidityMeasurement: {
195
+ measuredValue: 0,
196
+ minMeasuredValue: 0,
197
+ maxMeasuredValue: 100,
198
+ },
199
+ }, // TemperatureSensor + HumiditySensor → TemperatureMeasurement + RelativeHumidityMeasurement
200
+ waterdetector: {
201
+ booleanState: {
202
+ stateValue: false,
203
+ },
204
+ }, // LeakSensor → BooleanState
205
+ }
206
+
207
+ const DEVICE_MATTER_DEVICE_TYPE_KEYS: Record<string, string> = {
208
+ bot: 'OnOffSwitch',
209
+ vacuum: 'RoboticVacuumCleaner',
210
+ curtain: 'WindowCovering',
211
+ blindtilt: 'WindowCovering',
212
+ fan: 'Fan',
213
+ light: 'DimmableLight',
214
+ lightstrip: 'ExtendedColorLight',
215
+ lock: 'DoorLock',
216
+ motion: 'MotionSensor',
217
+ contact: 'ContactSensor',
218
+ humidifier: 'Fan',
219
+ temperature: 'TemperatureSensor',
220
+ relay: 'OnOffSwitch',
221
+ plug: 'OnOffOutlet',
222
+ meter: 'TemperatureSensor',
223
+ waterdetector: 'LeakSensor',
224
+ }
225
+
226
+ function normalizeTypeForMatter(typeValue: string | undefined | null): string {
227
+ const raw = String(typeValue || '').trim().toLowerCase()
228
+ if (!raw) {
229
+ return 'unknown'
230
+ }
231
+
232
+ // Vacuum variants
233
+ if (['wosweeper', 'wosweepermini', 'wosweeperminipro', 'k10+', 'k10+ pro'].includes(raw)) {
234
+ return 'vacuum'
235
+ }
236
+
237
+ // Window covering variants
238
+ if (['blindtilt', 'blind tilt', 'curtain3', 'rollershade', 'roller shade', 'worollershade', 'wo rollershade'].includes(raw)) {
239
+ return 'curtain'
240
+ }
241
+
242
+ // Plug variants
243
+ if (['plug mini (jp)', 'plug mini (us)', 'plug mini (eu)'].includes(raw)) {
244
+ return 'plug'
245
+ }
246
+
247
+ // Meter variants
248
+ if (['meterplus', 'meter plus', 'meter plus (jp)', 'meterpro', 'meter pro', 'meterpro(co2)', 'meter pro (co2)'].includes(raw)) {
249
+ return 'meter'
250
+ }
251
+
252
+ // Relay switch variants
253
+ if (['relay switch 1', 'relay switch 1pm'].includes(raw)) {
254
+ return 'relay'
255
+ }
256
+
257
+ // Water detector variants
258
+ if (['water detector', 'waterdetector'].includes(raw)) {
259
+ return 'waterdetector'
260
+ }
261
+
262
+ // Fan variants
263
+ if (['smart fan', 'circulator fan', 'battery circulator fan', 'standing circulator fan'].includes(raw)) {
264
+ return 'fan'
265
+ }
266
+
267
+ // Light variants
268
+ if (['strip light', 'strip light 3', 'rgbic neon rope light', 'rgbic neon wire rope light', 'rgbicww floor lamp', 'rgbicww strip light'].includes(raw)) {
269
+ return 'lightstrip'
270
+ }
271
+ if (['color bulb', 'ceiling light', 'ceiling light pro', 'candle warmer lamp', 'floor lamp'].includes(raw)) {
272
+ return 'light'
273
+ }
274
+
275
+ // Sensor variants
276
+ if (raw === 'motion sensor') {
277
+ return 'motion'
278
+ }
279
+ if (['contact sensor', 'presence sensor'].includes(raw)) {
280
+ return 'contact'
281
+ }
282
+
283
+ // Lock variants
284
+ if (['smart lock', 'smart lock pro', 'smart lock ultra', 'lock lite', 'keypad', 'keypad touch', 'keypad vision', 'keypad vision pro', 'lock vision pro'].includes(raw)) {
285
+ return 'lock'
286
+ }
287
+
288
+ // Climate variant
289
+ if (raw === 'humidifier2') {
290
+ return 'humidifier'
291
+ }
292
+
293
+ return raw
294
+ }
295
+
296
+ // Factory function to create Matter handlers with Homebridge logger integration
297
+ function createMatterHandlers(log: Logger, deviceId: string, type: string, client: any): any {
298
+ const lowerType = type.toLowerCase()
299
+
300
+ switch (lowerType) {
301
+ case 'vacuum':
302
+ return {
303
+ rvcRunMode: {
304
+ changeToMode: async (request: any) => {
305
+ const modeNames = ['Idle', 'Cleaning', 'Mapping']
306
+ const modeName = modeNames[request?.newMode] || `Unknown (${request?.newMode})`
307
+ log.info(`[${deviceId}] RVC run mode change requested: ${modeName}`)
308
+ if (!client) {
309
+ log.warn(`[${deviceId}] No SwitchBot client available`)
310
+ return { success: false }
311
+ }
312
+ try {
313
+ // For K10+ family: use 'start' to begin cleaning (mode 1 = Cleaning)
314
+ // For older K10+: only supports start/stop/dock
315
+ // For newer K20+/S10/S20: supports startClean with more parameters
316
+ // Map Matter mode to SwitchBot command
317
+ const switchBotCommand = request?.newMode === 1 ? 'start' : 'stop'
318
+ const body = {
319
+ command: switchBotCommand,
320
+ parameter: 'default',
321
+ commandType: 'command',
322
+ }
323
+ log.debug(`[${deviceId}] Sending RVC mode change request:`, JSON.stringify(body))
324
+ const result = await client.setDeviceState(deviceId, body)
325
+ log.debug(`[${deviceId}] RVC mode change API response:`, JSON.stringify(result))
326
+ log.info(`[${deviceId}] RVC mode changed successfully to ${switchBotCommand}`)
327
+ return { success: true, result }
328
+ } catch (e) {
329
+ log.error(`[${deviceId}] Failed to change RVC mode:`, e)
330
+ return { success: false, error: e }
331
+ }
332
+ },
333
+ },
334
+ rvcCleanMode: {
335
+ changeToMode: async (request: any) => {
336
+ const modeName = request?.newMode !== undefined ? `Mode ${request.newMode}` : 'Unknown'
337
+ log.info(`[${deviceId}] RVC clean mode change requested: ${modeName}`)
338
+ if (!client) {
339
+ log.warn(`[${deviceId}] No SwitchBot client available`)
340
+ return { success: false }
341
+ }
342
+ try {
343
+ // Clean mode (vacuum/mop/etc) not directly supported via Matter for K10+
344
+ // K20+ Pro and newer models support via startClean action parameter
345
+ log.info(`[${deviceId}] Clean mode change requires startClean command (not yet implemented for Matter)`)
346
+ return { success: true }
347
+ } catch (e) {
348
+ log.error(`[${deviceId}] Failed to change RVC clean mode:`, e)
349
+ return { success: false, error: e }
350
+ }
351
+ },
352
+ },
353
+ rvcOperationalState: {
354
+ pause: async () => {
355
+ log.info(`[${deviceId}] RVC pause command received`)
356
+ if (!client) {
357
+ log.warn(`[${deviceId}] No SwitchBot client available`)
358
+ return { success: false }
359
+ }
360
+ try {
361
+ const body = {
362
+ command: 'stop',
363
+ parameter: 'default',
364
+ commandType: 'command',
365
+ }
366
+ log.debug(`[${deviceId}] Sending RVC pause request:`, JSON.stringify(body))
367
+ const result = await client.setDeviceState(deviceId, body)
368
+ log.debug(`[${deviceId}] RVC pause API response:`, JSON.stringify(result))
369
+ log.info(`[${deviceId}] RVC paused successfully`)
370
+ return { success: true, result }
371
+ } catch (e) {
372
+ log.error(`[${deviceId}] Failed to pause RVC:`, e)
373
+ return { success: false, error: e }
374
+ }
375
+ },
376
+ resume: async () => {
377
+ log.info(`[${deviceId}] RVC resume command received`)
378
+ if (!client) {
379
+ log.warn(`[${deviceId}] No SwitchBot client available`)
380
+ return { success: false }
381
+ }
382
+ try {
383
+ const body = {
384
+ command: 'start',
385
+ parameter: 'default',
386
+ commandType: 'command',
387
+ }
388
+ log.debug(`[${deviceId}] Sending RVC resume request:`, JSON.stringify(body))
389
+ const result = await client.setDeviceState(deviceId, body)
390
+ log.debug(`[${deviceId}] RVC resume API response:`, JSON.stringify(result))
391
+ log.info(`[${deviceId}] RVC resumed successfully`)
392
+ return { success: true, result }
393
+ } catch (e) {
394
+ log.error(`[${deviceId}] Failed to resume RVC:`, e)
395
+ return { success: false, error: e }
396
+ }
397
+ },
398
+ goHome: async () => {
399
+ log.info(`[${deviceId}] RVC goHome command received`)
400
+ if (!client) {
401
+ log.warn(`[${deviceId}] No SwitchBot client available`)
402
+ return { success: false }
403
+ }
404
+ try {
405
+ const body = {
406
+ command: 'dock',
407
+ parameter: 'default',
408
+ commandType: 'command',
409
+ }
410
+ log.debug(`[${deviceId}] Sending RVC goHome request:`, JSON.stringify(body))
411
+ const result = await client.setDeviceState(deviceId, body)
412
+ log.debug(`[${deviceId}] RVC goHome API response:`, JSON.stringify(result))
413
+ log.info(`[${deviceId}] RVC sent to dock successfully`)
414
+ return { success: true, result }
415
+ } catch (e) {
416
+ log.error(`[${deviceId}] Failed to send goHome command:`, e)
417
+ return { success: false, error: e }
418
+ }
419
+ },
420
+ },
421
+ }
422
+
423
+ case 'bot':
424
+ return {
425
+ onOff: {
426
+ on: async () => {
427
+ log.info(`[${deviceId}] Bot ON command received`)
428
+ if (!client) {
429
+ log.warn(`[${deviceId}] No SwitchBot client available`)
430
+ return { success: false }
431
+ }
432
+ try {
433
+ const result = await client.setDeviceState(deviceId, {
434
+ command: 'turnOn',
435
+ parameter: 'default',
436
+ commandType: 'command',
437
+ })
438
+ log.info(`[${deviceId}] Bot turned on successfully`)
439
+ return { success: true, result }
440
+ } catch (e) {
441
+ log.error(`[${deviceId}] Failed to turn on Bot:`, e)
442
+ return { success: false, error: e }
443
+ }
444
+ },
445
+ off: async () => {
446
+ log.info(`[${deviceId}] Bot OFF command received`)
447
+ if (!client) {
448
+ log.warn(`[${deviceId}] No SwitchBot client available`)
449
+ return { success: false }
450
+ }
451
+ try {
452
+ const result = await client.setDeviceState(deviceId, {
453
+ command: 'turnOff',
454
+ parameter: 'default',
455
+ commandType: 'command',
456
+ })
457
+ log.info(`[${deviceId}] Bot turned off successfully`)
458
+ return { success: true, result }
459
+ } catch (e) {
460
+ log.error(`[${deviceId}] Failed to turn off Bot:`, e)
461
+ return { success: false, error: e }
462
+ }
463
+ },
464
+ },
465
+ }
466
+
467
+ case 'curtain':
468
+ case 'blindtilt':
469
+ return {
470
+ windowCovering: {
471
+ goToLiftPercentage: async (request: any) => {
472
+ const percentage = request?.liftPercent100thsValue
473
+ log.info(`[${deviceId}] Curtain position change requested: ${percentage}`)
474
+ if (!client) {
475
+ log.warn(`[${deviceId}] No SwitchBot client available`)
476
+ return { success: false }
477
+ }
478
+ try {
479
+ // Convert Matter percentage (0-10000) to SwitchBot (0-100)
480
+ const position = Math.max(0, Math.min(100, Math.round((percentage || 0) / 100)))
481
+ const result = await client.setDeviceState(deviceId, {
482
+ command: 'setPosition',
483
+ parameter: String(position),
484
+ commandType: 'command',
485
+ })
486
+ log.info(`[${deviceId}] Curtain position set to ${position}% successfully`)
487
+ return { success: true, result }
488
+ } catch (e) {
489
+ log.error(`[${deviceId}] Failed to set curtain position:`, e)
490
+ return { success: false, error: e }
491
+ }
492
+ },
493
+ upOrOpen: async () => {
494
+ log.info(`[${deviceId}] Curtain open command received`)
495
+ if (!client) {
496
+ log.warn(`[${deviceId}] No SwitchBot client available`)
497
+ return { success: false }
498
+ }
499
+ try {
500
+ const result = await client.setDeviceState(deviceId, {
501
+ command: 'open',
502
+ parameter: 'default',
503
+ commandType: 'command',
504
+ })
505
+ log.info(`[${deviceId}] Curtain opened successfully`)
506
+ return { success: true, result }
507
+ } catch (e) {
508
+ log.error(`[${deviceId}] Failed to open curtain:`, e)
509
+ return { success: false, error: e }
510
+ }
511
+ },
512
+ downOrClose: async () => {
513
+ log.info(`[${deviceId}] Curtain close command received`)
514
+ if (!client) {
515
+ log.warn(`[${deviceId}] No SwitchBot client available`)
516
+ return { success: false }
517
+ }
518
+ try {
519
+ const result = await client.setDeviceState(deviceId, {
520
+ command: 'close',
521
+ parameter: 'default',
522
+ commandType: 'command',
523
+ })
524
+ log.info(`[${deviceId}] Curtain closed successfully`)
525
+ return { success: true, result }
526
+ } catch (e) {
527
+ log.error(`[${deviceId}] Failed to close curtain:`, e)
528
+ return { success: false, error: e }
529
+ }
530
+ },
531
+ stopMotion: async () => {
532
+ log.info(`[${deviceId}] Curtain stop command received`)
533
+ if (!client) {
534
+ log.warn(`[${deviceId}] No SwitchBot client available`)
535
+ return { success: false }
536
+ }
537
+ try {
538
+ const result = await client.setDeviceState(deviceId, {
539
+ command: 'pause',
540
+ parameter: 'default',
541
+ commandType: 'command',
542
+ })
543
+ log.info(`[${deviceId}] Curtain motion stopped successfully`)
544
+ return { success: true, result }
545
+ } catch (e) {
546
+ log.error(`[${deviceId}] Failed to stop curtain:`, e)
547
+ return { success: false, error: e }
548
+ }
549
+ },
550
+ },
551
+ }
552
+
553
+ case 'plug':
554
+ return {
555
+ onOff: {
556
+ on: async () => {
557
+ log.info(`[${deviceId}] Plug ON command received`)
558
+ if (!client) {
559
+ log.warn(`[${deviceId}] No SwitchBot client available`)
560
+ return { success: false }
561
+ }
562
+ try {
563
+ const result = await client.setDeviceState(deviceId, {
564
+ command: 'turnOn',
565
+ parameter: 'default',
566
+ commandType: 'command',
567
+ })
568
+ log.info(`[${deviceId}] Plug turned on successfully`)
569
+ return { success: true, result }
570
+ } catch (e) {
571
+ log.error(`[${deviceId}] Failed to turn on plug:`, e)
572
+ return { success: false, error: e }
573
+ }
574
+ },
575
+ off: async () => {
576
+ log.info(`[${deviceId}] Plug OFF command received`)
577
+ if (!client) {
578
+ log.warn(`[${deviceId}] No SwitchBot client available`)
579
+ return { success: false }
580
+ }
581
+ try {
582
+ const result = await client.setDeviceState(deviceId, {
583
+ command: 'turnOff',
584
+ parameter: 'default',
585
+ commandType: 'command',
586
+ })
587
+ log.info(`[${deviceId}] Plug turned off successfully`)
588
+ return { success: true, result }
589
+ } catch (e) {
590
+ log.error(`[${deviceId}] Failed to turn off plug:`, e)
591
+ return { success: false, error: e }
592
+ }
593
+ },
594
+ },
595
+ }
596
+
597
+ case 'lock':
598
+ return {
599
+ doorLock: {
600
+ setLockState: async (request: any) => {
601
+ const state = request?.lockState === 1 ? 'LOCKED' : 'UNLOCKED'
602
+ log.info(`[${deviceId}] Lock state change requested: ${state}`)
603
+ if (!client) {
604
+ log.warn(`[${deviceId}] No SwitchBot client available`)
605
+ return { success: false }
606
+ }
607
+ try {
608
+ const command = request?.lockState === 1 ? 'lock' : 'unlock'
609
+ const result = await client.setDeviceState(deviceId, {
610
+ command,
611
+ parameter: 'default',
612
+ commandType: 'command',
613
+ })
614
+ log.info(`[${deviceId}] Lock ${state} successfully`)
615
+ return { success: true, result }
616
+ } catch (e) {
617
+ log.error(`[${deviceId}] Failed to change lock state:`, e)
618
+ return { success: false, error: e }
619
+ }
620
+ },
621
+ },
622
+ }
623
+
624
+ case 'fan':
625
+ return {
626
+ onOff: {
627
+ on: async () => {
628
+ log.info(`[${deviceId}] Fan ON command received`)
629
+ if (!client) {
630
+ log.warn(`[${deviceId}] No SwitchBot client available`)
631
+ return { success: false }
632
+ }
633
+ try {
634
+ const result = await client.setDeviceState(deviceId, {
635
+ command: 'turnOn',
636
+ parameter: 'default',
637
+ commandType: 'command',
638
+ })
639
+ log.info(`[${deviceId}] Fan turned on successfully`)
640
+ return { success: true, result }
641
+ } catch (e) {
642
+ log.error(`[${deviceId}] Failed to turn on fan:`, e)
643
+ return { success: false, error: e }
644
+ }
645
+ },
646
+ off: async () => {
647
+ log.info(`[${deviceId}] Fan OFF command received`)
648
+ if (!client) {
649
+ log.warn(`[${deviceId}] No SwitchBot client available`)
650
+ return { success: false }
651
+ }
652
+ try {
653
+ const result = await client.setDeviceState(deviceId, {
654
+ command: 'turnOff',
655
+ parameter: 'default',
656
+ commandType: 'command',
657
+ })
658
+ log.info(`[${deviceId}] Fan turned off successfully`)
659
+ return { success: true, result }
660
+ } catch (e) {
661
+ log.error(`[${deviceId}] Failed to turn off fan:`, e)
662
+ return { success: false, error: e }
663
+ }
664
+ },
665
+ },
666
+ fanControl: {
667
+ setFanSpeed: async (request: any) => {
668
+ const speed = request?.percentSetting || 0
669
+ log.info(`[${deviceId}] Fan speed change requested: ${speed}%`)
670
+ if (!client) {
671
+ log.warn(`[${deviceId}] No SwitchBot client available`)
672
+ return { success: false }
673
+ }
674
+ try {
675
+ // Convert percentage to SwitchBot fan speed parameter
676
+ const speedParam = Math.max(1, Math.min(100, speed))
677
+ const result = await client.setDeviceState(deviceId, {
678
+ command: 'setFanSpeed',
679
+ parameter: String(speedParam),
680
+ commandType: 'command',
681
+ })
682
+ log.info(`[${deviceId}] Fan speed set to ${speedParam}% successfully`)
683
+ return { success: true, result }
684
+ } catch (e) {
685
+ log.error(`[${deviceId}] Failed to set fan speed:`, e)
686
+ return { success: false, error: e }
687
+ }
688
+ },
689
+ },
690
+ }
691
+
692
+ case 'light':
693
+ return {
694
+ onOff: {
695
+ on: async () => {
696
+ log.info(`[${deviceId}] Light ON command received`)
697
+ if (!client) {
698
+ log.warn(`[${deviceId}] No SwitchBot client available`)
699
+ return { success: false }
700
+ }
701
+ try {
702
+ const result = await client.setDeviceState(deviceId, {
703
+ command: 'turnOn',
704
+ parameter: 'default',
705
+ commandType: 'command',
706
+ })
707
+ log.info(`[${deviceId}] Light turned on successfully`)
708
+ return { success: true, result }
709
+ } catch (e) {
710
+ log.error(`[${deviceId}] Failed to turn on light:`, e)
711
+ return { success: false, error: e }
712
+ }
713
+ },
714
+ off: async () => {
715
+ log.info(`[${deviceId}] Light OFF command received`)
716
+ if (!client) {
717
+ log.warn(`[${deviceId}] No SwitchBot client available`)
718
+ return { success: false }
719
+ }
720
+ try {
721
+ const result = await client.setDeviceState(deviceId, {
722
+ command: 'turnOff',
723
+ parameter: 'default',
724
+ commandType: 'command',
725
+ })
726
+ log.info(`[${deviceId}] Light turned off successfully`)
727
+ return { success: true, result }
728
+ } catch (e) {
729
+ log.error(`[${deviceId}] Failed to turn off light:`, e)
730
+ return { success: false, error: e }
731
+ }
732
+ },
733
+ },
734
+ levelControl: {
735
+ moveToLevel: async (request: any) => {
736
+ const level = request?.level || 0
737
+ // Convert from 0-254 to 0-100
738
+ const brightness = Math.round((level / 254) * 100)
739
+ log.info(`[${deviceId}] Light brightness change requested: ${brightness}%`)
740
+ if (!client) {
741
+ log.warn(`[${deviceId}] No SwitchBot client available`)
742
+ return { success: false }
743
+ }
744
+ try {
745
+ const param = Math.max(0, Math.min(100, brightness))
746
+ const result = await client.setDeviceState(deviceId, {
747
+ command: 'setBrightness',
748
+ parameter: String(param),
749
+ commandType: 'command',
750
+ })
751
+ log.info(`[${deviceId}] Light brightness set to ${param}% successfully`)
752
+ return { success: true, result }
753
+ } catch (e) {
754
+ log.error(`[${deviceId}] Failed to set light brightness:`, e)
755
+ return { success: false, error: e }
756
+ }
757
+ },
758
+ },
759
+ }
760
+
761
+ case 'lightstrip':
762
+ return {
763
+ onOff: {
764
+ on: async () => {
765
+ log.info(`[${deviceId}] Lightstrip ON command received`)
766
+ if (!client) {
767
+ log.warn(`[${deviceId}] No SwitchBot client available`)
768
+ return { success: false }
769
+ }
770
+ try {
771
+ const result = await client.setDeviceState(deviceId, {
772
+ command: 'turnOn',
773
+ parameter: 'default',
774
+ commandType: 'command',
775
+ })
776
+ log.info(`[${deviceId}] Lightstrip turned on successfully`)
777
+ return { success: true, result }
778
+ } catch (e) {
779
+ log.error(`[${deviceId}] Failed to turn on lightstrip:`, e)
780
+ return { success: false, error: e }
781
+ }
782
+ },
783
+ off: async () => {
784
+ log.info(`[${deviceId}] Lightstrip OFF command received`)
785
+ if (!client) {
786
+ log.warn(`[${deviceId}] No SwitchBot client available`)
787
+ return { success: false }
788
+ }
789
+ try {
790
+ const result = await client.setDeviceState(deviceId, {
791
+ command: 'turnOff',
792
+ parameter: 'default',
793
+ commandType: 'command',
794
+ })
795
+ log.info(`[${deviceId}] Lightstrip turned off successfully`)
796
+ return { success: true, result }
797
+ } catch (e) {
798
+ log.error(`[${deviceId}] Failed to turn off lightstrip:`, e)
799
+ return { success: false, error: e }
800
+ }
801
+ },
802
+ },
803
+ levelControl: {
804
+ moveToLevel: async (request: any) => {
805
+ const level = request?.level || 0
806
+ // Convert from 0-254 to 0-100
807
+ const brightness = Math.round((level / 254) * 100)
808
+ log.info(`[${deviceId}] Lightstrip brightness change requested: ${brightness}%`)
809
+ if (!client) {
810
+ log.warn(`[${deviceId}] No SwitchBot client available`)
811
+ return { success: false }
812
+ }
813
+ try {
814
+ const param = Math.max(0, Math.min(100, brightness))
815
+ const result = await client.setDeviceState(deviceId, {
816
+ command: 'setBrightness',
817
+ parameter: String(param),
818
+ commandType: 'command',
819
+ })
820
+ log.info(`[${deviceId}] Lightstrip brightness set to ${param}% successfully`)
821
+ return { success: true, result }
822
+ } catch (e) {
823
+ log.error(`[${deviceId}] Failed to set lightstrip brightness:`, e)
824
+ return { success: false, error: e }
825
+ }
826
+ },
827
+ },
828
+ colorControl: {
829
+ moveToHueAndSaturation: async (request: any) => {
830
+ const hue = request?.hue || 0
831
+ const saturation = request?.saturation || 0
832
+ log.info(`[${deviceId}] Lightstrip color change requested: hue=${hue}, sat=${saturation}`)
833
+ if (!client) {
834
+ log.warn(`[${deviceId}] No SwitchBot client available`)
835
+ return { success: false }
836
+ }
837
+ try {
838
+ // Convert hue (0-254) and saturation (0-254) to combined color parameter
839
+ // SwitchBot typically expects RGB or HSV format as parameter
840
+ const colorParam = `${Math.round(hue)},${Math.round(saturation)}`
841
+ const result = await client.setDeviceState(deviceId, {
842
+ command: 'setColor',
843
+ parameter: colorParam,
844
+ commandType: 'command',
845
+ })
846
+ log.info(`[${deviceId}] Lightstrip color set successfully`)
847
+ return { success: true, result }
848
+ } catch (e) {
849
+ log.error(`[${deviceId}] Failed to set lightstrip color:`, e)
850
+ return { success: false, error: e }
851
+ }
852
+ },
853
+ moveToColorTemperature: async (request: any) => {
854
+ const mireds = request?.colorTemperatureMireds || 400
855
+ // Convert mireds (158-500 typical range) to Kelvin: K = 1000000 / mireds
856
+ const kelvin = Math.round(1000000 / mireds)
857
+ log.info(`[${deviceId}] Lightstrip color temperature change requested: ${mireds} mireds (${kelvin}K)`)
858
+ if (!client) {
859
+ log.warn(`[${deviceId}] No SwitchBot client available`)
860
+ return { success: false }
861
+ }
862
+ try {
863
+ // Map Kelvin to SwitchBot color temperature parameter (typically 0-100 or specific values)
864
+ // Normalize to 0-100 scale where 0=warm (2700K) and 100=cool (6500K)
865
+ const colorTempParam = Math.max(0, Math.min(100, Math.round(((kelvin - 2700) / 3800) * 100)))
866
+ const result = await client.setDeviceState(deviceId, {
867
+ command: 'setColorTemperature',
868
+ parameter: String(colorTempParam),
869
+ commandType: 'command',
870
+ })
871
+ log.info(`[${deviceId}] Lightstrip color temperature set to ${kelvin}K successfully`)
872
+ return { success: true, result }
873
+ } catch (e) {
874
+ log.error(`[${deviceId}] Failed to set lightstrip color temperature:`, e)
875
+ return { success: false, error: e }
876
+ }
877
+ },
878
+ },
879
+ }
880
+
881
+ case 'humidifier':
882
+ return {
883
+ onOff: {
884
+ on: async () => {
885
+ log.info(`[${deviceId}] Humidifier ON command received`)
886
+ if (!client) {
887
+ log.warn(`[${deviceId}] No SwitchBot client available`)
888
+ return { success: false }
889
+ }
890
+ try {
891
+ const result = await client.setDeviceState(deviceId, {
892
+ command: 'turnOn',
893
+ parameter: 'default',
894
+ commandType: 'command',
895
+ })
896
+ log.info(`[${deviceId}] Humidifier turned on successfully`)
897
+ return { success: true, result }
898
+ } catch (e) {
899
+ log.error(`[${deviceId}] Failed to turn on humidifier:`, e)
900
+ return { success: false, error: e }
901
+ }
902
+ },
903
+ off: async () => {
904
+ log.info(`[${deviceId}] Humidifier OFF command received`)
905
+ if (!client) {
906
+ log.warn(`[${deviceId}] No SwitchBot client available`)
907
+ return { success: false }
908
+ }
909
+ try {
910
+ const result = await client.setDeviceState(deviceId, {
911
+ command: 'turnOff',
912
+ parameter: 'default',
913
+ commandType: 'command',
914
+ })
915
+ log.info(`[${deviceId}] Humidifier turned off successfully`)
916
+ return { success: true, result }
917
+ } catch (e) {
918
+ log.error(`[${deviceId}] Failed to turn off humidifier:`, e)
919
+ return { success: false, error: e }
920
+ }
921
+ },
922
+ },
923
+ fanControl: {
924
+ setFanSpeed: async (request: any) => {
925
+ const speed = request?.percentSetting || 0
926
+ log.info(`[${deviceId}] Humidifier speed change requested: ${speed}%`)
927
+ if (!client) {
928
+ log.warn(`[${deviceId}] No SwitchBot client available`)
929
+ return { success: false }
930
+ }
931
+ try {
932
+ // Convert percentage to SwitchBot humidifier speed parameter
933
+ const speedParam = Math.max(1, Math.min(100, speed))
934
+ const result = await client.setDeviceState(deviceId, {
935
+ command: 'setFanSpeed',
936
+ parameter: String(speedParam),
937
+ commandType: 'command',
938
+ })
939
+ log.info(`[${deviceId}] Humidifier speed set to ${speedParam}% successfully`)
940
+ return { success: true, result }
941
+ } catch (e) {
942
+ log.error(`[${deviceId}] Failed to set humidifier speed:`, e)
943
+ return { success: false, error: e }
944
+ }
945
+ },
946
+ },
947
+ }
948
+
949
+ case 'relay':
950
+ return {
951
+ onOff: {
952
+ on: async () => {
953
+ log.info(`[${deviceId}] Relay ON command received`)
954
+ if (!client) {
955
+ log.warn(`[${deviceId}] No SwitchBot client available`)
956
+ return { success: false }
957
+ }
958
+ try {
959
+ const result = await client.setDeviceState(deviceId, {
960
+ command: 'turnOn',
961
+ parameter: 'default',
962
+ commandType: 'command',
963
+ })
964
+ log.info(`[${deviceId}] Relay turned on successfully`)
965
+ return { success: true, result }
966
+ } catch (e) {
967
+ log.error(`[${deviceId}] Failed to turn on relay:`, e)
968
+ return { success: false, error: e }
969
+ }
970
+ },
971
+ off: async () => {
972
+ log.info(`[${deviceId}] Relay OFF command received`)
973
+ if (!client) {
974
+ log.warn(`[${deviceId}] No SwitchBot client available`)
975
+ return { success: false }
976
+ }
977
+ try {
978
+ const result = await client.setDeviceState(deviceId, {
979
+ command: 'turnOff',
980
+ parameter: 'default',
981
+ commandType: 'command',
982
+ })
983
+ log.info(`[${deviceId}] Relay turned off successfully`)
984
+ return { success: true, result }
985
+ } catch (e) {
986
+ log.error(`[${deviceId}] Failed to turn off relay:`, e)
987
+ return { success: false, error: e }
988
+ }
989
+ },
990
+ },
991
+ }
992
+
993
+ default:
994
+ return undefined
995
+ }
996
+ }
997
+
998
+ function resolveMatterDeviceType(matterApi: any, type: string, createdDeviceType?: any, clusters?: any): any {
999
+ if (createdDeviceType && typeof createdDeviceType === 'object' && typeof createdDeviceType.with === 'function') {
1000
+ return createdDeviceType
1001
+ }
1002
+
1003
+ const lowerType = (typeof createdDeviceType === 'string' && createdDeviceType) ? createdDeviceType.toLowerCase() : (type || '').toLowerCase()
1004
+
1005
+ // Cluster-based upgrade for color lights if descriptor omitted device type.
1006
+ const hasColorControl = !!clusters?.colorControl
1007
+ const inferredType = hasColorControl && lowerType === 'light'
1008
+ ? 'lightstrip'
1009
+ : lowerType
1010
+
1011
+ const mappedKey = DEVICE_MATTER_DEVICE_TYPE_KEYS[inferredType] || 'OnOffSwitch'
1012
+ return matterApi?.deviceTypes?.[mappedKey] || matterApi?.deviceTypes?.OnOffSwitch
1013
+ }
1014
+
1015
+ export class SwitchBotHAPPlatform {
1016
+ api: API | undefined
1017
+ log: Logger
1018
+ config: SwitchBotPluginConfig
1019
+ devices: any[] = []
1020
+ // cached accessories restored by Homebridge
1021
+ accessories: Map<string, any>
1022
+ // Track last loaded config to detect changes
1023
+ private lastConfigHash: string = ''
1024
+ private configReloadInterval: NodeJS.Timeout | null = null
1025
+
1026
+ constructor(log: Logger, config: PlatformConfig, api?: API) {
1027
+ this.log = log
1028
+ this.config = (config as any) ?? {}
1029
+ this.api = api
1030
+ this.accessories = new Map()
1031
+ this.log.info('SwitchBot HAP platform initialized')
1032
+
1033
+ // Create/shared SwitchBot client and attach to config so child devices reuse it.
1034
+ try {
1035
+ const client = new SwitchBotClient(this.config)
1036
+ void client.init()
1037
+ ;(this.config as any)._client = client
1038
+ } catch (e) {
1039
+ this.log.debug('Failed to create shared SwitchBot client', e)
1040
+ }
1041
+
1042
+ // Create/shared SwitchBot client and attach to config so child devices reuse it.
1043
+ try {
1044
+ const client = new SwitchBotClient(this.config)
1045
+ void client.init()
1046
+ ;(this.config as any)._client = client
1047
+ } catch (e) {
1048
+ this.log.debug('Failed to create shared SwitchBot client', e)
1049
+ }
1050
+
1051
+ // Wait for Homebridge to finish launching to create/register accessories
1052
+ if (this.api && typeof (this.api as any).on === 'function') {
1053
+ (this.api as any).on('didFinishLaunching', async () => {
1054
+ await this.loadDevicesWithMatterInit()
1055
+ // Start periodic config reload to pick up UI changes
1056
+ this.configReloadInterval = setInterval(() => {
1057
+ void this.loadDevicesWithMatterInit()
1058
+ }, 10000) // Check every 10 seconds
1059
+ })
1060
+ } else {
1061
+ void this.loadDevicesWithMatterInit()
1062
+ // Start periodic config reload to pick up UI changes
1063
+ this.configReloadInterval = setInterval(() => {
1064
+ void this.loadDevicesWithMatterInit()
1065
+ }, 10000) // Check every 10 seconds
1066
+ }
1067
+ }
1068
+
1069
+ /**
1070
+ * Ensures Matter API is loaded before loading devices.
1071
+ */
1072
+ private async loadDevicesWithMatterInit() {
1073
+ // Wait for Matter API to be loaded and available before loading devices
1074
+ const maxAttempts = 20 // Wait up to 10 seconds (20 x 500ms)
1075
+ let attempt = 0
1076
+ let matterLoaded = false
1077
+ if (
1078
+ this.api
1079
+ && typeof (this.api as any).isMatterAvailable === 'function'
1080
+ && typeof (this.api as any).isMatterEnabled === 'function'
1081
+ && typeof (this.api as any).loadMatterAPI === 'function'
1082
+ ) {
1083
+ if ((this.api as any).isMatterAvailable() && (this.api as any).isMatterEnabled()) {
1084
+ try {
1085
+ await (this.api as any).loadMatterAPI()
1086
+ this.log.info('Homebridge Matter API loaded successfully')
1087
+ } catch (e) {
1088
+ this.log.warn('Failed to load Homebridge Matter API', e)
1089
+ }
1090
+ // Wait for api.matter to be available
1091
+ while (attempt < maxAttempts) {
1092
+ if ((this.api as any).matter) {
1093
+ matterLoaded = true
1094
+ break
1095
+ }
1096
+ await new Promise(res => setTimeout(res, 500))
1097
+ attempt++
1098
+ }
1099
+ if (!matterLoaded) {
1100
+ this.log.warn('Matter API did not become available after loadMatterAPI()')
1101
+ }
1102
+ }
1103
+ }
1104
+ await this.loadDevices()
1105
+ }
1106
+
1107
+ private getConfigHash(): string {
1108
+ // Create a simple hash of current device config to detect changes
1109
+ const devices = (this.config as any)?.devices ?? []
1110
+ return JSON.stringify(devices.map((d: any) => ({
1111
+ id: d.deviceId ?? d.id,
1112
+ type: d.configDeviceType ?? d.type,
1113
+ name: d.configDeviceName ?? d.name,
1114
+ })))
1115
+ }
1116
+
1117
+ async loadDevices() {
1118
+ const devices = (this.config as any)?.devices ?? []
1119
+ for (const raw of devices) {
1120
+ // Normalize config keys from UI schema to internal shape
1121
+ const d: any = {
1122
+ id: raw.deviceId ?? raw.id,
1123
+ name: raw.configDeviceName ?? raw.name,
1124
+ type: raw.configDeviceType ?? raw.type ?? raw.deviceType ?? 'unknown',
1125
+ encryptionKey: raw.encryptionKey,
1126
+ keyId: raw.keyId,
1127
+ _raw: raw,
1128
+ }
1129
+
1130
+ const type: string = normalizeTypeForMatter(d.type)
1131
+
1132
+ // Pass matterType for window covering types
1133
+ const windowCoveringTypes = ['curtain', 'curtain3', 'rollershade', 'roller shade', 'blindtilt', 'blind tilt']
1134
+ const deviceOpts: any = { id: d.id, type, name: d.name, encryptionKey: d.encryptionKey, keyId: d.keyId }
1135
+ if (windowCoveringTypes.includes(type.toLowerCase()) && typeof raw.matterType === 'number') {
1136
+ deviceOpts.matterType = raw.matterType
1137
+ }
1138
+
1139
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1140
+ // Auto-detect Matter from Homebridge API, allow manual override via config
1141
+ const matterAvailable = !!(this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.())
1142
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1143
+ const useMatter = !!(matterEnabled && matterSupported && (!!this.config.preferMatter || matterAvailable))
1144
+
1145
+ try {
1146
+ const created = await createDevice(deviceOpts, this.config, useMatter)
1147
+ this.devices.push(created)
1148
+ // Prefer Matter: try registering to the Matter child bridge first.
1149
+ let matterRegistered = false
1150
+ if (useMatter) {
1151
+ const matterApi = (this.api as any)?.matter
1152
+ if (this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.() && matterApi && typeof matterApi.registerPlatformAccessories === 'function') {
1153
+ try {
1154
+ const createdDesc = await created.createAccessory(this.api)
1155
+ const uuid = matterApi.uuid.generate(`${d.id}`)
1156
+ const defaultClusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()] || { onOff: { onOff: false } }
1157
+ const clusters = createdDesc.clusters || defaultClusters
1158
+ const deviceType = resolveMatterDeviceType(matterApi, type, createdDesc.deviceType, clusters)
1159
+ const accessory: any = {
1160
+ UUID: uuid,
1161
+ displayName: createdDesc.name || d.name || type,
1162
+ deviceType,
1163
+ manufacturer: createdDesc.manufacturer || 'SwitchBot',
1164
+ model: createdDesc.model || type,
1165
+ serialNumber: createdDesc.serialNumber || d.id,
1166
+ reachable: createdDesc.reachable !== false,
1167
+ firmwareRevision: createdDesc.firmwareRevision || '1.0.0',
1168
+ hardwareRevision: createdDesc.hardwareRevision || '',
1169
+ clusters,
1170
+ handlers: createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined,
1171
+ context: { deviceId: d.id, type, _created: true },
1172
+ }
1173
+ this.log.info(`[MatterDebug] Accessory descriptor for ${d.id}:`, JSON.stringify({
1174
+ UUID: accessory.UUID,
1175
+ displayName: accessory.displayName,
1176
+ deviceType: typeof accessory.deviceType === 'object' && accessory.deviceType?.name ? accessory.deviceType.name : accessory.deviceType,
1177
+ clusters: accessory.clusters,
1178
+ context: accessory.context,
1179
+ }, null, 2))
1180
+ await matterApi.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
1181
+ this.accessories.set(uuid, accessory)
1182
+ matterRegistered = true
1183
+ this.log.info(`[MatterDebug] Registered Matter accessory ${d.id} (${type}) with uuid=${uuid}`)
1184
+ } catch (e: any) {
1185
+ this.log.error(`[MatterDebug] Failed to register Matter accessory for ${d.id} (${type}):`, e && (e.stack || e.message || e))
1186
+ if (e && (e.message?.includes('Conformance') || e.message?.includes('enum value Rollershade') || e.message?.includes('Behaviors have errors'))) {
1187
+ try {
1188
+ const uuid = matterApi.uuid.generate(`${d.id}`)
1189
+ const cached = this.accessories.get(uuid)
1190
+ if (cached && typeof this.api?.unregisterPlatformAccessories === 'function') {
1191
+ this.log.warn(`[MatterDebug] Removing cached accessory for ${d.id} due to registration error`)
1192
+ this.api.unregisterPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [cached])
1193
+ this.accessories.delete(uuid)
1194
+ }
1195
+ } catch (cleanupErr) {
1196
+ this.log.warn(`[MatterDebug] Failed to cleanup cached accessory for ${d.id}:`, cleanupErr)
1197
+ }
1198
+ }
1199
+ }
1200
+ } else {
1201
+ this.log.info(`Matter API not available for ${d.id} (${type}); skipping Matter registration and falling back to HAP`)
1202
+ }
1203
+ }
1204
+
1205
+ // If Matter wasn't registered (either not supported, API missing, or registration failed), fall back to HAP registration.
1206
+ if (!matterRegistered && this.api && (this.api as any).hap) {
1207
+ // Basic HAP accessory creation using homebridge API when available
1208
+ try {
1209
+ const hap = (this.api as any).hap
1210
+ const uuid = hap.uuid.generate(`${d.id}`)
1211
+ // Reuse cached accessory if available by uuid
1212
+ let accessory: any = this.accessories.get(uuid)
1213
+ // If not found by uuid, attempt to find by stored deviceId in accessory.context
1214
+ if (!accessory) {
1215
+ for (const [, a] of this.accessories.entries()) {
1216
+ try {
1217
+ if (a && a.context && a.context.deviceId === d.id) {
1218
+ accessory = a
1219
+ break
1220
+ }
1221
+ } catch (e) {
1222
+ // ignore
1223
+ }
1224
+ }
1225
+ }
1226
+
1227
+ if (!accessory) {
1228
+ accessory = new (this.api as any).platformAccessory(d.name || type, uuid)
1229
+ // Store device metadata on accessory.context for persistence across restarts
1230
+ try {
1231
+ accessory.context = accessory.context || {}
1232
+ accessory.context.deviceId = d.id
1233
+ accessory.context.type = type
1234
+ } catch (e) {
1235
+ // ignore context failures
1236
+ }
1237
+ // Register new accessory with Homebridge so it's cached
1238
+ try {
1239
+ ;(this.api as any).registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
1240
+ } catch (e) {
1241
+ // older API variations may require different registration; ignore if unavailable
1242
+ }
1243
+ this.accessories.set(uuid, accessory)
1244
+ } else {
1245
+ // ensure context includes deviceId (in case restored accessory lacked it)
1246
+ try {
1247
+ accessory.context = accessory.context || {}
1248
+ accessory.context.deviceId = accessory.context.deviceId || d.id
1249
+ accessory.context.type = accessory.context.type || type
1250
+ } catch (e) {
1251
+ // ignore
1252
+ }
1253
+ }
1254
+ // Add basic service descriptor from device
1255
+ const accDesc = await created.createAccessory?.(this.api)
1256
+ if (accDesc && accDesc.services) {
1257
+ for (const s of accDesc.services) {
1258
+ const Service = hap.Service[s.type] || hap.Service[s.type]
1259
+ if (!Service) {
1260
+ continue
1261
+ }
1262
+ const service = accessory.getService(Service) || accessory.addService(Service)
1263
+ for (const [charName, getterSetterRaw] of Object.entries(s.characteristics || {})) {
1264
+ const getterSetter: any = getterSetterRaw
1265
+ const Characteristic = (hap.Characteristic as any)[charName]
1266
+ if (!Characteristic) {
1267
+ continue
1268
+ }
1269
+ // Apply characteristic props if provided (min/max/step)
1270
+ if (getterSetter && getterSetter.props) {
1271
+ try {
1272
+ service.getCharacteristic(Characteristic).setProps(getterSetter.props)
1273
+ } catch (e) {
1274
+ // ignore setProps failures on older HAP implementations
1275
+ }
1276
+ }
1277
+
1278
+ // Wire simple get/set handlers if provided
1279
+ if (getterSetter && typeof getterSetter.get === 'function') {
1280
+ service.getCharacteristic(Characteristic).onGet(getterSetter.get)
1281
+ }
1282
+ if (getterSetter && typeof getterSetter.set === 'function') {
1283
+ service.getCharacteristic(Characteristic).onSet(getterSetter.set)
1284
+ }
1285
+ }
1286
+ }
1287
+ }
1288
+ this.log.info(`Created/updated HAP accessory ${d.id} (${type})`)
1289
+ } catch (e) {
1290
+ this.log.warn('HAP accessory creation failed', e)
1291
+ }
1292
+ } else if (!matterRegistered) {
1293
+ this.log.info(`Created HAP descriptor for ${d.id} (${type}) (API not available to register)`)
1294
+ }
1295
+ } catch (e) {
1296
+ this.log.error(`Failed to create device ${d.id}:`, e as any)
1297
+ }
1298
+ }
1299
+ // Update hash after successfully loading devices
1300
+ this.lastConfigHash = this.getConfigHash()
1301
+ }
1302
+
1303
+ // Example lifecycle method called by Homebridge
1304
+ async configureAccessory(accessory: any) {
1305
+ // Homebridge calls this for restored cached accessories — keep a reference.
1306
+ try {
1307
+ const uuid = accessory.UUID || accessory.UUID
1308
+ this.accessories.set(uuid, accessory)
1309
+ this.log.info(`Restored cached accessory ${accessory.displayName || uuid}`)
1310
+ } catch (e) {
1311
+ this.log.warn('configureAccessory failed to restore accessory', e)
1312
+ }
1313
+ }
1314
+
1315
+ // Called by Homebridge when a cached Matter accessory is restored
1316
+ configureMatterAccessory?(accessory: any) {
1317
+ try {
1318
+ const uuid = accessory.uuid || accessory.UUID || accessory.uuid
1319
+ this.accessories.set(uuid, accessory)
1320
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1321
+ } catch (e) {
1322
+ this.log.warn('configureMatterAccessory failed to restore accessory', e)
1323
+ }
1324
+ }
1325
+ }
1326
+
1327
+ // Matter platform implementation (placeholder)
1328
+ export class SwitchBotMatterPlatform {
1329
+ api: API | undefined
1330
+ log: Logger
1331
+ config: SwitchBotPluginConfig
1332
+ devices: any[] = []
1333
+ accessories: Map<string, any>
1334
+ // Track last loaded config to detect changes
1335
+ private lastConfigHash: string = ''
1336
+ private configReloadInterval: NodeJS.Timeout | null = null
1337
+
1338
+ constructor(log: Logger, config: PlatformConfig, api?: API) {
1339
+ this.log = log
1340
+ this.config = (config as any) ?? {}
1341
+ this.api = api
1342
+ this.accessories = new Map()
1343
+ this.log.info('SwitchBot Matter platform initialized')
1344
+
1345
+ if (this.api && typeof (this.api as any).on === 'function') {
1346
+ ;(this.api as any).on('didFinishLaunching', () => {
1347
+ ;(async () => {
1348
+ // After launch, perform discovery (if any) and register Matter accessories
1349
+ try {
1350
+ await this.loadDevices()
1351
+ if ((this.api as any).isMatterAvailable?.() && (this.api as any).isMatterEnabled?.() && (this.api as any).matter && typeof (this.api as any).matter.registerPlatformAccessories === 'function') {
1352
+ try {
1353
+ await (this as any).registerMatterAccessories?.()
1354
+ } catch (e) {
1355
+ this.log.warn('registerMatterAccessories failed', e)
1356
+ }
1357
+ }
1358
+ } catch (e) {
1359
+ this.log.warn('Error during Matter platform startup', e)
1360
+ }
1361
+ })()
1362
+ // Start periodic config reload to pick up UI changes
1363
+ this.configReloadInterval = setInterval(() => {
1364
+ void this.checkAndReloadDevices()
1365
+ }, 10000) // Check every 10 seconds
1366
+ })
1367
+ } else {
1368
+ void this.loadDevices()
1369
+ // Start periodic config reload to pick up UI changes
1370
+ this.configReloadInterval = setInterval(() => {
1371
+ void this.checkAndReloadDevices()
1372
+ }, 10000) // Check every 10 seconds
1373
+ }
1374
+ // Create/shared SwitchBot client and attach to config so child devices reuse it.
1375
+ try {
1376
+ const client = new SwitchBotClient(this.config)
1377
+ void client.init()
1378
+ ;(this.config as any)._client = client
1379
+ } catch (e) {
1380
+ this.log.debug('Failed to create shared SwitchBot client', e)
1381
+ }
1382
+ }
1383
+
1384
+ async loadDevices() {
1385
+ const devices = (this.config as any)?.devices ?? []
1386
+ for (const raw of devices) {
1387
+ // Normalize config keys produced by the UI schema
1388
+ const d: any = {
1389
+ id: raw.deviceId ?? raw.id,
1390
+ name: raw.configDeviceName ?? raw.name,
1391
+ type: raw.configDeviceType ?? raw.type ?? raw.deviceType ?? 'unknown',
1392
+ _raw: raw,
1393
+ }
1394
+
1395
+ const type: string = normalizeTypeForMatter(d.type)
1396
+
1397
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1398
+ // Auto-detect Matter from Homebridge API, allow manual override via config
1399
+ const matterAvailable = this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.()
1400
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1401
+ const useMatter = matterEnabled && matterSupported
1402
+ try {
1403
+ const created = await createDevice({ id: d.id, type, name: d.name }, this.config, useMatter)
1404
+ this.devices.push(created)
1405
+ if (useMatter) {
1406
+ this.log.info(`Prepared Matter accessory for ${d.id} (${type})${matterAvailable ? ' (auto-detected)' : ' (manually enabled)'}`)
1407
+ } else {
1408
+ if (!matterEnabled) {
1409
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - Matter not available on this bridge`)
1410
+ } else if (!matterSupported) {
1411
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - device type not supported`)
1412
+ } else {
1413
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - not supported`)
1414
+ }
1415
+ }
1416
+ } catch (e) {
1417
+ this.log.error(`Failed to create Matter device ${d.id}:`, e as any)
1418
+ }
1419
+ }
1420
+ // Update hash after successfully loading devices
1421
+ this.lastConfigHash = this.getConfigHash()
1422
+ }
1423
+
1424
+ private getConfigHash(): string {
1425
+ // Create a simple hash of current device config to detect changes
1426
+ const devices = (this.config as any)?.devices ?? []
1427
+ return JSON.stringify(devices.map((d: any) => ({
1428
+ id: d.deviceId ?? d.id,
1429
+ type: d.configDeviceType ?? d.type,
1430
+ name: d.configDeviceName ?? d.name,
1431
+ })))
1432
+ }
1433
+
1434
+ private async checkAndReloadDevices() {
1435
+ const currentHash = this.getConfigHash()
1436
+ if (currentHash !== this.lastConfigHash) {
1437
+ this.log.info('[SwitchBot] Detected config changes, reloading devices...')
1438
+ // Clear existing devices
1439
+ this.devices = []
1440
+ await this.loadDevices()
1441
+ }
1442
+ }
1443
+
1444
+ async configureAccessory(accessory: any) {
1445
+ try {
1446
+ const uuid = accessory.UUID || accessory.UUID
1447
+ this.accessories.set(uuid, accessory)
1448
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1449
+ } catch (e) {
1450
+ this.log.warn('configureAccessory failed to restore Matter accessory', e)
1451
+ }
1452
+ }
1453
+
1454
+ // Homebridge calls this when restoring cached Matter accessories
1455
+ configureMatterAccessory(accessory: any) {
1456
+ try {
1457
+ const uuid = accessory.uuid || accessory.UUID || accessory.uuid
1458
+ this.accessories.set(uuid, accessory)
1459
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1460
+ } catch (e) {
1461
+ this.log.warn('configureMatterAccessory failed to restore Matter accessory', e)
1462
+ }
1463
+ }
1464
+
1465
+ // Register serialized Matter accessories via Homebridge Matter API
1466
+ async registerMatterAccessories() {
1467
+ if (!this.api) {
1468
+ return
1469
+ }
1470
+ const matterApi = (this.api as any).matter
1471
+ if (!matterApi || typeof matterApi.registerPlatformAccessories !== 'function') {
1472
+ this.log.info('Homebridge Matter API not available; skipping Matter accessory registration')
1473
+ return
1474
+ }
1475
+
1476
+ const devices = (this.config as any)?.devices ?? []
1477
+ const accessoriesToRegister: any[] = []
1478
+
1479
+ // Auto-detect Matter from Homebridge API
1480
+ const matterAvailable = this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.()
1481
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1482
+
1483
+ for (const raw of devices) {
1484
+ const d: any = {
1485
+ id: raw.deviceId ?? raw.id,
1486
+ name: raw.configDeviceName ?? raw.name,
1487
+ type: raw.configDeviceType ?? raw.type ?? raw.deviceType ?? 'unknown',
1488
+ }
1489
+
1490
+ if (!d.id) {
1491
+ continue
1492
+ }
1493
+
1494
+ const type: string = normalizeTypeForMatter(d.type)
1495
+
1496
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1497
+ const useMatter = matterEnabled && matterSupported
1498
+ if (!useMatter) {
1499
+ continue
1500
+ }
1501
+
1502
+ try {
1503
+ const created = await createDevice({ id: d.id, type, name: d.name }, this.config, true)
1504
+ const createdDesc = await created.createAccessory(this.api)
1505
+ const uuid = matterApi.uuid.generate(`${d.id}`)
1506
+ // Try to find existing restored accessory by deviceId
1507
+ let existing: any | undefined
1508
+ for (const [, a] of this.accessories.entries()) {
1509
+ try {
1510
+ if (a && a.context && a.context.deviceId === d.id) {
1511
+ existing = a
1512
+ break
1513
+ }
1514
+ } catch (e) {
1515
+ // ignore
1516
+ }
1517
+ }
1518
+
1519
+ if (existing) {
1520
+ // Ensure context and displayName are up to date
1521
+ // Prioritize device-specific Matter clusters (e.g., RVC for vacuum) over generic HAP-derived clusters
1522
+ let clusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()]
1523
+ if (!clusters) {
1524
+ clusters = existing.clusters || createdDesc.clusters || { onOff: { onOff: false } }
1525
+ }
1526
+ const deviceType = resolveMatterDeviceType(matterApi, type, existing.deviceType || createdDesc.deviceType, clusters)
1527
+ existing.context = existing.context || {}
1528
+ existing.context.deviceId = existing.context.deviceId || d.id
1529
+ existing.context.type = existing.context.type || type
1530
+ existing.deviceType = deviceType
1531
+ existing.manufacturer = existing.manufacturer || createdDesc.manufacturer || 'SwitchBot'
1532
+ existing.model = existing.model || createdDesc.model || type
1533
+ existing.serialNumber = existing.serialNumber || createdDesc.serialNumber || d.id
1534
+ existing.reachable = existing.reachable !== false
1535
+ existing.firmwareRevision = existing.firmwareRevision || createdDesc.firmwareRevision || '1.0.0'
1536
+ existing.hardwareRevision = existing.hardwareRevision || createdDesc.hardwareRevision || ''
1537
+ existing.clusters = clusters
1538
+ existing.handlers = createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined
1539
+ existing.displayName = createdDesc.name || d.name || type
1540
+ existing.UUID = existing.UUID || existing.uuid || uuid
1541
+ accessoriesToRegister.push(existing)
1542
+ this.accessories.set(existing.UUID || uuid, existing)
1543
+ } else {
1544
+ // Prioritize device-specific Matter clusters (e.g., RVC for vacuum) over generic HAP-derived clusters
1545
+ let clusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()]
1546
+ if (!clusters) {
1547
+ clusters = createdDesc.clusters || { onOff: { onOff: false } }
1548
+ }
1549
+ const deviceType = resolveMatterDeviceType(matterApi, type, createdDesc.deviceType, clusters)
1550
+ const serialized: any = {
1551
+ UUID: uuid,
1552
+ displayName: createdDesc.name || d.name || type,
1553
+ deviceType,
1554
+ manufacturer: createdDesc.manufacturer || 'SwitchBot',
1555
+ model: createdDesc.model || type,
1556
+ serialNumber: createdDesc.serialNumber || d.id,
1557
+ reachable: createdDesc.reachable !== false,
1558
+ firmwareRevision: createdDesc.firmwareRevision || '1.0.0',
1559
+ hardwareRevision: createdDesc.hardwareRevision || '',
1560
+ clusters,
1561
+ handlers: createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined,
1562
+ context: { deviceId: d.id, type, created: true },
1563
+ }
1564
+ accessoriesToRegister.push(serialized)
1565
+ this.accessories.set(uuid, serialized)
1566
+ }
1567
+ } catch (e) {
1568
+ this.log.warn(`Failed to prepare Matter accessory for ${d.id} (${type})`, e)
1569
+ }
1570
+ }
1571
+
1572
+ if (accessoriesToRegister.length > 0) {
1573
+ try {
1574
+ await matterApi.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessoriesToRegister)
1575
+ this.log.info(`Registered ${accessoriesToRegister.length} Matter accessory(ies) with Homebridge`)
1576
+ } catch (e) {
1577
+ this.log.warn('Failed to register Matter accessories', e)
1578
+ }
1579
+ } else {
1580
+ this.log.info('No Matter accessories to register')
1581
+ }
1582
+ }
1583
+ }
1584
+
1585
+ export default SwitchBotHAPPlatform