@switchbot/homebridge-switchbot 5.0.0-beta.12 → 5.0.0-beta.121

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 (588) 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 +187 -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 +276 -0
  25. package/dist/devices/genericDevice.d.ts.map +1 -0
  26. package/dist/devices/genericDevice.js +1320 -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 +203 -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 +59 -0
  51. package/dist/homebridge-ui/public/js/api.d.ts.map +1 -0
  52. package/dist/homebridge-ui/public/js/api.js +219 -0
  53. package/dist/homebridge-ui/public/js/api.js.map +1 -0
  54. package/dist/homebridge-ui/public/js/api.ts +272 -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 +3475 -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 +93 -0
  78. package/dist/homebridge-ui/public/js/devices.js.map +1 -0
  79. package/dist/homebridge-ui/public/js/devices.ts +111 -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 +365 -0
  98. package/dist/homebridge-ui/public/js/modals.js.map +1 -0
  99. package/dist/homebridge-ui/public/js/modals.ts +416 -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 +1553 -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 +1258 -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 +225 -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 +272 -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 +111 -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 +416 -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 +1568 -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/devices-hap/airpurifier.d.ts +0 -54
  284. package/dist/devices-hap/airpurifier.d.ts.map +0 -1
  285. package/dist/devices-hap/airpurifier.js +0 -527
  286. package/dist/devices-hap/airpurifier.js.map +0 -1
  287. package/dist/devices-hap/blindtilt.d.ts +0 -90
  288. package/dist/devices-hap/blindtilt.d.ts.map +0 -1
  289. package/dist/devices-hap/blindtilt.js +0 -974
  290. package/dist/devices-hap/blindtilt.js.map +0 -1
  291. package/dist/devices-hap/bot.d.ts +0 -102
  292. package/dist/devices-hap/bot.d.ts.map +0 -1
  293. package/dist/devices-hap/bot.js +0 -811
  294. package/dist/devices-hap/bot.js.map +0 -1
  295. package/dist/devices-hap/ceilinglight.d.ts +0 -85
  296. package/dist/devices-hap/ceilinglight.d.ts.map +0 -1
  297. package/dist/devices-hap/ceilinglight.js +0 -701
  298. package/dist/devices-hap/ceilinglight.js.map +0 -1
  299. package/dist/devices-hap/colorbulb.d.ts +0 -88
  300. package/dist/devices-hap/colorbulb.d.ts.map +0 -1
  301. package/dist/devices-hap/colorbulb.js +0 -881
  302. package/dist/devices-hap/colorbulb.js.map +0 -1
  303. package/dist/devices-hap/contact.d.ts +0 -44
  304. package/dist/devices-hap/contact.d.ts.map +0 -1
  305. package/dist/devices-hap/contact.js +0 -409
  306. package/dist/devices-hap/contact.js.map +0 -1
  307. package/dist/devices-hap/curtain.d.ts +0 -73
  308. package/dist/devices-hap/curtain.d.ts.map +0 -1
  309. package/dist/devices-hap/curtain.js +0 -869
  310. package/dist/devices-hap/curtain.js.map +0 -1
  311. package/dist/devices-hap/device.d.ts +0 -98
  312. package/dist/devices-hap/device.d.ts.map +0 -1
  313. package/dist/devices-hap/device.js +0 -749
  314. package/dist/devices-hap/device.js.map +0 -1
  315. package/dist/devices-hap/fan.d.ts +0 -69
  316. package/dist/devices-hap/fan.d.ts.map +0 -1
  317. package/dist/devices-hap/fan.js +0 -649
  318. package/dist/devices-hap/fan.js.map +0 -1
  319. package/dist/devices-hap/hub.d.ts +0 -37
  320. package/dist/devices-hap/hub.d.ts.map +0 -1
  321. package/dist/devices-hap/hub.js +0 -392
  322. package/dist/devices-hap/hub.js.map +0 -1
  323. package/dist/devices-hap/humidifier.d.ts +0 -68
  324. package/dist/devices-hap/humidifier.d.ts.map +0 -1
  325. package/dist/devices-hap/humidifier.js +0 -628
  326. package/dist/devices-hap/humidifier.js.map +0 -1
  327. package/dist/devices-hap/iosensor.d.ts +0 -42
  328. package/dist/devices-hap/iosensor.d.ts.map +0 -1
  329. package/dist/devices-hap/iosensor.js +0 -382
  330. package/dist/devices-hap/iosensor.js.map +0 -1
  331. package/dist/devices-hap/lightstrip.d.ts +0 -79
  332. package/dist/devices-hap/lightstrip.d.ts.map +0 -1
  333. package/dist/devices-hap/lightstrip.js +0 -797
  334. package/dist/devices-hap/lightstrip.js.map +0 -1
  335. package/dist/devices-hap/lock.d.ts +0 -53
  336. package/dist/devices-hap/lock.d.ts.map +0 -1
  337. package/dist/devices-hap/lock.js +0 -561
  338. package/dist/devices-hap/lock.js.map +0 -1
  339. package/dist/devices-hap/meter.d.ts +0 -37
  340. package/dist/devices-hap/meter.d.ts.map +0 -1
  341. package/dist/devices-hap/meter.js +0 -379
  342. package/dist/devices-hap/meter.js.map +0 -1
  343. package/dist/devices-hap/meterplus.d.ts +0 -42
  344. package/dist/devices-hap/meterplus.d.ts.map +0 -1
  345. package/dist/devices-hap/meterplus.js +0 -384
  346. package/dist/devices-hap/meterplus.js.map +0 -1
  347. package/dist/devices-hap/meterpro.d.ts +0 -43
  348. package/dist/devices-hap/meterpro.d.ts.map +0 -1
  349. package/dist/devices-hap/meterpro.js +0 -468
  350. package/dist/devices-hap/meterpro.js.map +0 -1
  351. package/dist/devices-hap/motion.d.ts +0 -42
  352. package/dist/devices-hap/motion.d.ts.map +0 -1
  353. package/dist/devices-hap/motion.js +0 -345
  354. package/dist/devices-hap/motion.js.map +0 -1
  355. package/dist/devices-hap/plug.d.ts +0 -49
  356. package/dist/devices-hap/plug.d.ts.map +0 -1
  357. package/dist/devices-hap/plug.js +0 -395
  358. package/dist/devices-hap/plug.js.map +0 -1
  359. package/dist/devices-hap/relayswitch.d.ts +0 -96
  360. package/dist/devices-hap/relayswitch.d.ts.map +0 -1
  361. package/dist/devices-hap/relayswitch.js +0 -642
  362. package/dist/devices-hap/relayswitch.js.map +0 -1
  363. package/dist/devices-hap/robotvacuumcleaner.d.ts +0 -54
  364. package/dist/devices-hap/robotvacuumcleaner.d.ts.map +0 -1
  365. package/dist/devices-hap/robotvacuumcleaner.js +0 -523
  366. package/dist/devices-hap/robotvacuumcleaner.js.map +0 -1
  367. package/dist/devices-hap/waterdetector.d.ts +0 -41
  368. package/dist/devices-hap/waterdetector.d.ts.map +0 -1
  369. package/dist/devices-hap/waterdetector.js +0 -356
  370. package/dist/devices-hap/waterdetector.js.map +0 -1
  371. package/dist/devices-matter/BaseMatterAccessory.d.ts +0 -63
  372. package/dist/devices-matter/BaseMatterAccessory.d.ts.map +0 -1
  373. package/dist/devices-matter/BaseMatterAccessory.js +0 -100
  374. package/dist/devices-matter/BaseMatterAccessory.js.map +0 -1
  375. package/dist/devices-matter/ColorLightAccessory.d.ts +0 -20
  376. package/dist/devices-matter/ColorLightAccessory.d.ts.map +0 -1
  377. package/dist/devices-matter/ColorLightAccessory.js +0 -95
  378. package/dist/devices-matter/ColorLightAccessory.js.map +0 -1
  379. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts +0 -18
  380. package/dist/devices-matter/ColorTemperatureLightAccessory.d.ts.map +0 -1
  381. package/dist/devices-matter/ColorTemperatureLightAccessory.js +0 -78
  382. package/dist/devices-matter/ColorTemperatureLightAccessory.js.map +0 -1
  383. package/dist/devices-matter/ContactSensorAccessory.d.ts +0 -12
  384. package/dist/devices-matter/ContactSensorAccessory.d.ts.map +0 -1
  385. package/dist/devices-matter/ContactSensorAccessory.js +0 -34
  386. package/dist/devices-matter/ContactSensorAccessory.js.map +0 -1
  387. package/dist/devices-matter/DimmableLightAccessory.d.ts +0 -58
  388. package/dist/devices-matter/DimmableLightAccessory.d.ts.map +0 -1
  389. package/dist/devices-matter/DimmableLightAccessory.js +0 -167
  390. package/dist/devices-matter/DimmableLightAccessory.js.map +0 -1
  391. package/dist/devices-matter/DoorLockAccessory.d.ts +0 -14
  392. package/dist/devices-matter/DoorLockAccessory.d.ts.map +0 -1
  393. package/dist/devices-matter/DoorLockAccessory.js +0 -50
  394. package/dist/devices-matter/DoorLockAccessory.js.map +0 -1
  395. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts +0 -21
  396. package/dist/devices-matter/ExtendedColorLightAccessory.d.ts.map +0 -1
  397. package/dist/devices-matter/ExtendedColorLightAccessory.js +0 -107
  398. package/dist/devices-matter/ExtendedColorLightAccessory.js.map +0 -1
  399. package/dist/devices-matter/FanAccessory.d.ts +0 -16
  400. package/dist/devices-matter/FanAccessory.d.ts.map +0 -1
  401. package/dist/devices-matter/FanAccessory.js +0 -81
  402. package/dist/devices-matter/FanAccessory.js.map +0 -1
  403. package/dist/devices-matter/HumiditySensorAccessory.d.ts +0 -12
  404. package/dist/devices-matter/HumiditySensorAccessory.d.ts.map +0 -1
  405. package/dist/devices-matter/HumiditySensorAccessory.js +0 -34
  406. package/dist/devices-matter/HumiditySensorAccessory.js.map +0 -1
  407. package/dist/devices-matter/LeakSensorAccessory.d.ts +0 -12
  408. package/dist/devices-matter/LeakSensorAccessory.d.ts.map +0 -1
  409. package/dist/devices-matter/LeakSensorAccessory.js +0 -33
  410. package/dist/devices-matter/LeakSensorAccessory.js.map +0 -1
  411. package/dist/devices-matter/LightSensorAccessory.d.ts +0 -12
  412. package/dist/devices-matter/LightSensorAccessory.d.ts.map +0 -1
  413. package/dist/devices-matter/LightSensorAccessory.js +0 -34
  414. package/dist/devices-matter/LightSensorAccessory.js.map +0 -1
  415. package/dist/devices-matter/OccupancySensorAccessory.d.ts +0 -12
  416. package/dist/devices-matter/OccupancySensorAccessory.d.ts.map +0 -1
  417. package/dist/devices-matter/OccupancySensorAccessory.js +0 -39
  418. package/dist/devices-matter/OccupancySensorAccessory.js.map +0 -1
  419. package/dist/devices-matter/OnOffLightAccessory.d.ts +0 -38
  420. package/dist/devices-matter/OnOffLightAccessory.d.ts.map +0 -1
  421. package/dist/devices-matter/OnOffLightAccessory.js +0 -118
  422. package/dist/devices-matter/OnOffLightAccessory.js.map +0 -1
  423. package/dist/devices-matter/OnOffOutletAccessory.d.ts +0 -12
  424. package/dist/devices-matter/OnOffOutletAccessory.d.ts.map +0 -1
  425. package/dist/devices-matter/OnOffOutletAccessory.js +0 -40
  426. package/dist/devices-matter/OnOffOutletAccessory.js.map +0 -1
  427. package/dist/devices-matter/OnOffSwitchAccessory.d.ts +0 -14
  428. package/dist/devices-matter/OnOffSwitchAccessory.d.ts.map +0 -1
  429. package/dist/devices-matter/OnOffSwitchAccessory.js +0 -42
  430. package/dist/devices-matter/OnOffSwitchAccessory.js.map +0 -1
  431. package/dist/devices-matter/RoboticVacuumAccessory.d.ts +0 -68
  432. package/dist/devices-matter/RoboticVacuumAccessory.d.ts.map +0 -1
  433. package/dist/devices-matter/RoboticVacuumAccessory.js +0 -334
  434. package/dist/devices-matter/RoboticVacuumAccessory.js.map +0 -1
  435. package/dist/devices-matter/SmokeCOAlarmAccessory.d.ts +0 -11
  436. package/dist/devices-matter/SmokeCOAlarmAccessory.d.ts.map +0 -1
  437. package/dist/devices-matter/SmokeCOAlarmAccessory.js +0 -49
  438. package/dist/devices-matter/SmokeCOAlarmAccessory.js.map +0 -1
  439. package/dist/devices-matter/TemperatureSensorAccessory.d.ts +0 -12
  440. package/dist/devices-matter/TemperatureSensorAccessory.d.ts.map +0 -1
  441. package/dist/devices-matter/TemperatureSensorAccessory.js +0 -36
  442. package/dist/devices-matter/TemperatureSensorAccessory.js.map +0 -1
  443. package/dist/devices-matter/ThermostatAccessory.d.ts +0 -19
  444. package/dist/devices-matter/ThermostatAccessory.d.ts.map +0 -1
  445. package/dist/devices-matter/ThermostatAccessory.js +0 -95
  446. package/dist/devices-matter/ThermostatAccessory.js.map +0 -1
  447. package/dist/devices-matter/VenetianBlindAccessory.d.ts +0 -19
  448. package/dist/devices-matter/VenetianBlindAccessory.d.ts.map +0 -1
  449. package/dist/devices-matter/VenetianBlindAccessory.js +0 -99
  450. package/dist/devices-matter/VenetianBlindAccessory.js.map +0 -1
  451. package/dist/devices-matter/WindowBlindAccessory.d.ts +0 -17
  452. package/dist/devices-matter/WindowBlindAccessory.d.ts.map +0 -1
  453. package/dist/devices-matter/WindowBlindAccessory.js +0 -80
  454. package/dist/devices-matter/WindowBlindAccessory.js.map +0 -1
  455. package/dist/devices-matter/custom/PowerStripAccessory.d.ts +0 -97
  456. package/dist/devices-matter/custom/PowerStripAccessory.d.ts.map +0 -1
  457. package/dist/devices-matter/custom/PowerStripAccessory.js +0 -265
  458. package/dist/devices-matter/custom/PowerStripAccessory.js.map +0 -1
  459. package/dist/devices-matter/custom/index.d.ts +0 -8
  460. package/dist/devices-matter/custom/index.d.ts.map +0 -1
  461. package/dist/devices-matter/custom/index.js +0 -8
  462. package/dist/devices-matter/custom/index.js.map +0 -1
  463. package/dist/devices-matter/index.d.ts +0 -29
  464. package/dist/devices-matter/index.d.ts.map +0 -1
  465. package/dist/devices-matter/index.js +0 -28
  466. package/dist/devices-matter/index.js.map +0 -1
  467. package/dist/index.test.d.ts +0 -2
  468. package/dist/index.test.d.ts.map +0 -1
  469. package/dist/index.test.js +0 -19
  470. package/dist/index.test.js.map +0 -1
  471. package/dist/irdevice/airconditioner.d.ts +0 -61
  472. package/dist/irdevice/airconditioner.d.ts.map +0 -1
  473. package/dist/irdevice/airconditioner.js +0 -472
  474. package/dist/irdevice/airconditioner.js.map +0 -1
  475. package/dist/irdevice/airpurifier.d.ts +0 -50
  476. package/dist/irdevice/airpurifier.d.ts.map +0 -1
  477. package/dist/irdevice/airpurifier.js +0 -213
  478. package/dist/irdevice/airpurifier.js.map +0 -1
  479. package/dist/irdevice/camera.d.ts +0 -32
  480. package/dist/irdevice/camera.d.ts.map +0 -1
  481. package/dist/irdevice/camera.js +0 -107
  482. package/dist/irdevice/camera.js.map +0 -1
  483. package/dist/irdevice/fan.d.ts +0 -36
  484. package/dist/irdevice/fan.d.ts.map +0 -1
  485. package/dist/irdevice/fan.js +0 -200
  486. package/dist/irdevice/fan.js.map +0 -1
  487. package/dist/irdevice/irdevice.d.ts +0 -68
  488. package/dist/irdevice/irdevice.d.ts.map +0 -1
  489. package/dist/irdevice/irdevice.js +0 -298
  490. package/dist/irdevice/irdevice.js.map +0 -1
  491. package/dist/irdevice/light.d.ts +0 -36
  492. package/dist/irdevice/light.d.ts.map +0 -1
  493. package/dist/irdevice/light.js +0 -206
  494. package/dist/irdevice/light.js.map +0 -1
  495. package/dist/irdevice/other.d.ts +0 -57
  496. package/dist/irdevice/other.d.ts.map +0 -1
  497. package/dist/irdevice/other.js +0 -778
  498. package/dist/irdevice/other.js.map +0 -1
  499. package/dist/irdevice/tv.d.ts +0 -45
  500. package/dist/irdevice/tv.d.ts.map +0 -1
  501. package/dist/irdevice/tv.js +0 -327
  502. package/dist/irdevice/tv.js.map +0 -1
  503. package/dist/irdevice/vacuumcleaner.d.ts +0 -28
  504. package/dist/irdevice/vacuumcleaner.d.ts.map +0 -1
  505. package/dist/irdevice/vacuumcleaner.js +0 -104
  506. package/dist/irdevice/vacuumcleaner.js.map +0 -1
  507. package/dist/irdevice/waterheater.d.ts +0 -30
  508. package/dist/irdevice/waterheater.d.ts.map +0 -1
  509. package/dist/irdevice/waterheater.js +0 -105
  510. package/dist/irdevice/waterheater.js.map +0 -1
  511. package/dist/platform-hap.d.ts +0 -149
  512. package/dist/platform-hap.d.ts.map +0 -1
  513. package/dist/platform-hap.js +0 -2861
  514. package/dist/platform-hap.js.map +0 -1
  515. package/dist/platform-matter.d.ts +0 -120
  516. package/dist/platform-matter.d.ts.map +0 -1
  517. package/dist/platform-matter.js +0 -984
  518. package/dist/platform-matter.js.map +0 -1
  519. package/dist/utils.test.d.ts +0 -2
  520. package/dist/utils.test.d.ts.map +0 -1
  521. package/dist/utils.test.js +0 -95
  522. package/dist/utils.test.js.map +0 -1
  523. package/dist/verifyconfig.test.d.ts +0 -2
  524. package/dist/verifyconfig.test.d.ts.map +0 -1
  525. package/dist/verifyconfig.test.js +0 -167
  526. package/dist/verifyconfig.test.js.map +0 -1
  527. package/src/custom.d.ts +0 -7
  528. package/src/devices-hap/airpurifier.ts +0 -563
  529. package/src/devices-hap/blindtilt.ts +0 -1049
  530. package/src/devices-hap/bot.ts +0 -900
  531. package/src/devices-hap/ceilinglight.ts +0 -742
  532. package/src/devices-hap/colorbulb.ts +0 -904
  533. package/src/devices-hap/contact.ts +0 -457
  534. package/src/devices-hap/curtain.ts +0 -944
  535. package/src/devices-hap/device.ts +0 -811
  536. package/src/devices-hap/fan.ts +0 -711
  537. package/src/devices-hap/hub.ts +0 -439
  538. package/src/devices-hap/humidifier.ts +0 -669
  539. package/src/devices-hap/iosensor.ts +0 -427
  540. package/src/devices-hap/lightstrip.ts +0 -836
  541. package/src/devices-hap/lock.ts +0 -620
  542. package/src/devices-hap/meter.ts +0 -426
  543. package/src/devices-hap/meterplus.ts +0 -430
  544. package/src/devices-hap/meterpro.ts +0 -522
  545. package/src/devices-hap/motion.ts +0 -390
  546. package/src/devices-hap/plug.ts +0 -423
  547. package/src/devices-hap/relayswitch.ts +0 -727
  548. package/src/devices-hap/robotvacuumcleaner.ts +0 -568
  549. package/src/devices-hap/waterdetector.ts +0 -400
  550. package/src/devices-matter/BaseMatterAccessory.ts +0 -131
  551. package/src/devices-matter/ColorLightAccessory.ts +0 -110
  552. package/src/devices-matter/ColorTemperatureLightAccessory.ts +0 -92
  553. package/src/devices-matter/ContactSensorAccessory.ts +0 -41
  554. package/src/devices-matter/DimmableLightAccessory.ts +0 -192
  555. package/src/devices-matter/DoorLockAccessory.ts +0 -60
  556. package/src/devices-matter/ExtendedColorLightAccessory.ts +0 -123
  557. package/src/devices-matter/FanAccessory.ts +0 -95
  558. package/src/devices-matter/HumiditySensorAccessory.ts +0 -41
  559. package/src/devices-matter/LeakSensorAccessory.ts +0 -40
  560. package/src/devices-matter/LightSensorAccessory.ts +0 -41
  561. package/src/devices-matter/OccupancySensorAccessory.ts +0 -48
  562. package/src/devices-matter/OnOffLightAccessory.ts +0 -133
  563. package/src/devices-matter/OnOffOutletAccessory.ts +0 -46
  564. package/src/devices-matter/OnOffSwitchAccessory.ts +0 -51
  565. package/src/devices-matter/RoboticVacuumAccessory.ts +0 -407
  566. package/src/devices-matter/SmokeCOAlarmAccessory.ts +0 -59
  567. package/src/devices-matter/TemperatureSensorAccessory.ts +0 -43
  568. package/src/devices-matter/ThermostatAccessory.ts +0 -110
  569. package/src/devices-matter/VenetianBlindAccessory.ts +0 -115
  570. package/src/devices-matter/WindowBlindAccessory.ts +0 -92
  571. package/src/devices-matter/custom/PowerStripAccessory.ts +0 -309
  572. package/src/devices-matter/custom/index.ts +0 -8
  573. package/src/devices-matter/index.ts +0 -29
  574. package/src/index.test.ts +0 -24
  575. package/src/irdevice/airconditioner.ts +0 -533
  576. package/src/irdevice/airpurifier.ts +0 -252
  577. package/src/irdevice/camera.ts +0 -129
  578. package/src/irdevice/fan.ts +0 -226
  579. package/src/irdevice/irdevice.ts +0 -344
  580. package/src/irdevice/light.ts +0 -246
  581. package/src/irdevice/other.ts +0 -790
  582. package/src/irdevice/tv.ts +0 -378
  583. package/src/irdevice/vacuumcleaner.ts +0 -126
  584. package/src/irdevice/waterheater.ts +0 -127
  585. package/src/platform-hap.ts +0 -2997
  586. package/src/platform-matter.ts +0 -1110
  587. package/src/utils.test.ts +0 -96
  588. package/src/verifyconfig.test.ts +0 -197
@@ -0,0 +1,1568 @@
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: 0, // RollerShade (default 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
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1133
+ // Auto-detect Matter from Homebridge API, allow manual override via config
1134
+ const matterAvailable = !!(this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.())
1135
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1136
+ const useMatter = !!(matterEnabled && matterSupported && (!!this.config.preferMatter || matterAvailable))
1137
+
1138
+ try {
1139
+ const created = await createDevice({ id: d.id, type, name: d.name }, this.config, useMatter)
1140
+ this.devices.push(created)
1141
+ // Prefer Matter: try registering to the Matter child bridge first.
1142
+ let matterRegistered = false
1143
+ if (useMatter) {
1144
+ // Only attempt Matter registration if api.matter is truly available
1145
+ const matterApi = (this.api as any)?.matter
1146
+ if (this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.() && matterApi && typeof matterApi.registerPlatformAccessories === 'function') {
1147
+ this.log.info(`Attempting Matter registration for ${d.id} (${type})`)
1148
+ try {
1149
+ const createdDesc = await created.createAccessory(this.api)
1150
+ const uuid = matterApi.uuid.generate(`${d.id}`)
1151
+ const defaultClusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()] || { onOff: { onOff: false } }
1152
+ const clusters = createdDesc.clusters || defaultClusters
1153
+ const deviceType = resolveMatterDeviceType(matterApi, type, createdDesc.deviceType, clusters)
1154
+ const accessory: any = {
1155
+ UUID: uuid,
1156
+ displayName: createdDesc.name || d.name || type,
1157
+ deviceType,
1158
+ manufacturer: createdDesc.manufacturer || 'SwitchBot',
1159
+ model: createdDesc.model || type,
1160
+ serialNumber: createdDesc.serialNumber || d.id,
1161
+ reachable: createdDesc.reachable !== false,
1162
+ firmwareRevision: createdDesc.firmwareRevision || '1.0.0',
1163
+ hardwareRevision: createdDesc.hardwareRevision || '',
1164
+ clusters,
1165
+ handlers: createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined,
1166
+ context: { deviceId: d.id, type, _created: true },
1167
+ }
1168
+ // Log the full accessory descriptor before registration
1169
+ this.log.info(`[MatterDebug] Accessory descriptor for ${d.id}:`, JSON.stringify({
1170
+ UUID: accessory.UUID,
1171
+ displayName: accessory.displayName,
1172
+ deviceType: typeof accessory.deviceType === 'object' && accessory.deviceType?.name ? accessory.deviceType.name : accessory.deviceType,
1173
+ clusters: accessory.clusters,
1174
+ context: accessory.context,
1175
+ }, null, 2))
1176
+ await matterApi.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
1177
+ this.accessories.set(uuid, accessory)
1178
+ matterRegistered = true
1179
+ this.log.info(`[MatterDebug] Registered Matter accessory ${d.id} (${type}) with uuid=${uuid}`)
1180
+ } catch (e: any) {
1181
+ this.log.error(`[MatterDebug] Failed to register Matter accessory for ${d.id} (${type}):`, e && (e.stack || e.message || e))
1182
+ }
1183
+ } else {
1184
+ this.log.info(`Matter API not available for ${d.id} (${type}); skipping Matter registration and falling back to HAP`)
1185
+ }
1186
+ }
1187
+
1188
+ // If Matter wasn't registered (either not supported, API missing, or registration failed), fall back to HAP registration.
1189
+ if (!matterRegistered && this.api && (this.api as any).hap) {
1190
+ // Basic HAP accessory creation using homebridge API when available
1191
+ try {
1192
+ const hap = (this.api as any).hap
1193
+ const uuid = hap.uuid.generate(`${d.id}`)
1194
+ // Reuse cached accessory if available by uuid
1195
+ let accessory: any = this.accessories.get(uuid)
1196
+ // If not found by uuid, attempt to find by stored deviceId in accessory.context
1197
+ if (!accessory) {
1198
+ for (const [, a] of this.accessories.entries()) {
1199
+ try {
1200
+ if (a && a.context && a.context.deviceId === d.id) {
1201
+ accessory = a
1202
+ break
1203
+ }
1204
+ } catch (e) {
1205
+ // ignore
1206
+ }
1207
+ }
1208
+ }
1209
+
1210
+ if (!accessory) {
1211
+ accessory = new (this.api as any).platformAccessory(d.name || type, uuid)
1212
+ // Store device metadata on accessory.context for persistence across restarts
1213
+ try {
1214
+ accessory.context = accessory.context || {}
1215
+ accessory.context.deviceId = d.id
1216
+ accessory.context.type = type
1217
+ } catch (e) {
1218
+ // ignore context failures
1219
+ }
1220
+ // Register new accessory with Homebridge so it's cached
1221
+ try {
1222
+ ;(this.api as any).registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [accessory])
1223
+ } catch (e) {
1224
+ // older API variations may require different registration; ignore if unavailable
1225
+ }
1226
+ this.accessories.set(uuid, accessory)
1227
+ } else {
1228
+ // ensure context includes deviceId (in case restored accessory lacked it)
1229
+ try {
1230
+ accessory.context = accessory.context || {}
1231
+ accessory.context.deviceId = accessory.context.deviceId || d.id
1232
+ accessory.context.type = accessory.context.type || type
1233
+ } catch (e) {
1234
+ // ignore
1235
+ }
1236
+ }
1237
+ // Add basic service descriptor from device
1238
+ const accDesc = await created.createAccessory?.(this.api)
1239
+ if (accDesc && accDesc.services) {
1240
+ for (const s of accDesc.services) {
1241
+ const Service = hap.Service[s.type] || hap.Service[s.type]
1242
+ if (!Service) {
1243
+ continue
1244
+ }
1245
+ const service = accessory.getService(Service) || accessory.addService(Service)
1246
+ for (const [charName, getterSetterRaw] of Object.entries(s.characteristics || {})) {
1247
+ const getterSetter: any = getterSetterRaw
1248
+ const Characteristic = (hap.Characteristic as any)[charName]
1249
+ if (!Characteristic) {
1250
+ continue
1251
+ }
1252
+ // Apply characteristic props if provided (min/max/step)
1253
+ if (getterSetter && getterSetter.props) {
1254
+ try {
1255
+ service.getCharacteristic(Characteristic).setProps(getterSetter.props)
1256
+ } catch (e) {
1257
+ // ignore setProps failures on older HAP implementations
1258
+ }
1259
+ }
1260
+
1261
+ // Wire simple get/set handlers if provided
1262
+ if (getterSetter && typeof getterSetter.get === 'function') {
1263
+ service.getCharacteristic(Characteristic).onGet(getterSetter.get)
1264
+ }
1265
+ if (getterSetter && typeof getterSetter.set === 'function') {
1266
+ service.getCharacteristic(Characteristic).onSet(getterSetter.set)
1267
+ }
1268
+ }
1269
+ }
1270
+ }
1271
+ this.log.info(`Created/updated HAP accessory ${d.id} (${type})`)
1272
+ } catch (e) {
1273
+ this.log.warn('HAP accessory creation failed', e)
1274
+ }
1275
+ } else if (!matterRegistered) {
1276
+ this.log.info(`Created HAP descriptor for ${d.id} (${type}) (API not available to register)`)
1277
+ }
1278
+ } catch (e) {
1279
+ this.log.error(`Failed to create device ${d.id}:`, e as any)
1280
+ }
1281
+ }
1282
+ // Update hash after successfully loading devices
1283
+ this.lastConfigHash = this.getConfigHash()
1284
+ }
1285
+
1286
+ // Example lifecycle method called by Homebridge
1287
+ async configureAccessory(accessory: any) {
1288
+ // Homebridge calls this for restored cached accessories — keep a reference.
1289
+ try {
1290
+ const uuid = accessory.UUID || accessory.UUID
1291
+ this.accessories.set(uuid, accessory)
1292
+ this.log.info(`Restored cached accessory ${accessory.displayName || uuid}`)
1293
+ } catch (e) {
1294
+ this.log.warn('configureAccessory failed to restore accessory', e)
1295
+ }
1296
+ }
1297
+
1298
+ // Called by Homebridge when a cached Matter accessory is restored
1299
+ configureMatterAccessory?(accessory: any) {
1300
+ try {
1301
+ const uuid = accessory.uuid || accessory.UUID || accessory.uuid
1302
+ this.accessories.set(uuid, accessory)
1303
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1304
+ } catch (e) {
1305
+ this.log.warn('configureMatterAccessory failed to restore accessory', e)
1306
+ }
1307
+ }
1308
+ }
1309
+
1310
+ // Matter platform implementation (placeholder)
1311
+ export class SwitchBotMatterPlatform {
1312
+ api: API | undefined
1313
+ log: Logger
1314
+ config: SwitchBotPluginConfig
1315
+ devices: any[] = []
1316
+ accessories: Map<string, any>
1317
+ // Track last loaded config to detect changes
1318
+ private lastConfigHash: string = ''
1319
+ private configReloadInterval: NodeJS.Timeout | null = null
1320
+
1321
+ constructor(log: Logger, config: PlatformConfig, api?: API) {
1322
+ this.log = log
1323
+ this.config = (config as any) ?? {}
1324
+ this.api = api
1325
+ this.accessories = new Map()
1326
+ this.log.info('SwitchBot Matter platform initialized')
1327
+
1328
+ if (this.api && typeof (this.api as any).on === 'function') {
1329
+ ;(this.api as any).on('didFinishLaunching', () => {
1330
+ ;(async () => {
1331
+ // After launch, perform discovery (if any) and register Matter accessories
1332
+ try {
1333
+ await this.loadDevices()
1334
+ if ((this.api as any).isMatterAvailable?.() && (this.api as any).isMatterEnabled?.() && (this.api as any).matter && typeof (this.api as any).matter.registerPlatformAccessories === 'function') {
1335
+ try {
1336
+ await (this as any).registerMatterAccessories?.()
1337
+ } catch (e) {
1338
+ this.log.warn('registerMatterAccessories failed', e)
1339
+ }
1340
+ }
1341
+ } catch (e) {
1342
+ this.log.warn('Error during Matter platform startup', e)
1343
+ }
1344
+ })()
1345
+ // Start periodic config reload to pick up UI changes
1346
+ this.configReloadInterval = setInterval(() => {
1347
+ void this.checkAndReloadDevices()
1348
+ }, 10000) // Check every 10 seconds
1349
+ })
1350
+ } else {
1351
+ void this.loadDevices()
1352
+ // Start periodic config reload to pick up UI changes
1353
+ this.configReloadInterval = setInterval(() => {
1354
+ void this.checkAndReloadDevices()
1355
+ }, 10000) // Check every 10 seconds
1356
+ }
1357
+ // Create/shared SwitchBot client and attach to config so child devices reuse it.
1358
+ try {
1359
+ const client = new SwitchBotClient(this.config)
1360
+ void client.init()
1361
+ ;(this.config as any)._client = client
1362
+ } catch (e) {
1363
+ this.log.debug('Failed to create shared SwitchBot client', e)
1364
+ }
1365
+ }
1366
+
1367
+ async loadDevices() {
1368
+ const devices = (this.config as any)?.devices ?? []
1369
+ for (const raw of devices) {
1370
+ // Normalize config keys produced by the UI schema
1371
+ const d: any = {
1372
+ id: raw.deviceId ?? raw.id,
1373
+ name: raw.configDeviceName ?? raw.name,
1374
+ type: raw.configDeviceType ?? raw.type ?? raw.deviceType ?? 'unknown',
1375
+ _raw: raw,
1376
+ }
1377
+
1378
+ const type: string = normalizeTypeForMatter(d.type)
1379
+
1380
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1381
+ // Auto-detect Matter from Homebridge API, allow manual override via config
1382
+ const matterAvailable = this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.()
1383
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1384
+ const useMatter = matterEnabled && matterSupported
1385
+ try {
1386
+ const created = await createDevice({ id: d.id, type, name: d.name }, this.config, useMatter)
1387
+ this.devices.push(created)
1388
+ if (useMatter) {
1389
+ this.log.info(`Prepared Matter accessory for ${d.id} (${type})${matterAvailable ? ' (auto-detected)' : ' (manually enabled)'}`)
1390
+ } else {
1391
+ if (!matterEnabled) {
1392
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - Matter not available on this bridge`)
1393
+ } else if (!matterSupported) {
1394
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - device type not supported`)
1395
+ } else {
1396
+ this.log.info(`Skipping Matter for ${d.id} (${type}) - not supported`)
1397
+ }
1398
+ }
1399
+ } catch (e) {
1400
+ this.log.error(`Failed to create Matter device ${d.id}:`, e as any)
1401
+ }
1402
+ }
1403
+ // Update hash after successfully loading devices
1404
+ this.lastConfigHash = this.getConfigHash()
1405
+ }
1406
+
1407
+ private getConfigHash(): string {
1408
+ // Create a simple hash of current device config to detect changes
1409
+ const devices = (this.config as any)?.devices ?? []
1410
+ return JSON.stringify(devices.map((d: any) => ({
1411
+ id: d.deviceId ?? d.id,
1412
+ type: d.configDeviceType ?? d.type,
1413
+ name: d.configDeviceName ?? d.name,
1414
+ })))
1415
+ }
1416
+
1417
+ private async checkAndReloadDevices() {
1418
+ const currentHash = this.getConfigHash()
1419
+ if (currentHash !== this.lastConfigHash) {
1420
+ this.log.info('[SwitchBot] Detected config changes, reloading devices...')
1421
+ // Clear existing devices
1422
+ this.devices = []
1423
+ await this.loadDevices()
1424
+ }
1425
+ }
1426
+
1427
+ async configureAccessory(accessory: any) {
1428
+ try {
1429
+ const uuid = accessory.UUID || accessory.UUID
1430
+ this.accessories.set(uuid, accessory)
1431
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1432
+ } catch (e) {
1433
+ this.log.warn('configureAccessory failed to restore Matter accessory', e)
1434
+ }
1435
+ }
1436
+
1437
+ // Homebridge calls this when restoring cached Matter accessories
1438
+ configureMatterAccessory(accessory: any) {
1439
+ try {
1440
+ const uuid = accessory.uuid || accessory.UUID || accessory.uuid
1441
+ this.accessories.set(uuid, accessory)
1442
+ this.log.info(`Restored cached Matter accessory ${accessory.displayName || uuid}`)
1443
+ } catch (e) {
1444
+ this.log.warn('configureMatterAccessory failed to restore Matter accessory', e)
1445
+ }
1446
+ }
1447
+
1448
+ // Register serialized Matter accessories via Homebridge Matter API
1449
+ async registerMatterAccessories() {
1450
+ if (!this.api) {
1451
+ return
1452
+ }
1453
+ const matterApi = (this.api as any).matter
1454
+ if (!matterApi || typeof matterApi.registerPlatformAccessories !== 'function') {
1455
+ this.log.info('Homebridge Matter API not available; skipping Matter accessory registration')
1456
+ return
1457
+ }
1458
+
1459
+ const devices = (this.config as any)?.devices ?? []
1460
+ const accessoriesToRegister: any[] = []
1461
+
1462
+ // Auto-detect Matter from Homebridge API
1463
+ const matterAvailable = this.api?.isMatterAvailable?.() && this.api?.isMatterEnabled?.()
1464
+ const matterEnabled = matterAvailable || !!this.config.enableMatter
1465
+
1466
+ for (const raw of devices) {
1467
+ const d: any = {
1468
+ id: raw.deviceId ?? raw.id,
1469
+ name: raw.configDeviceName ?? raw.name,
1470
+ type: raw.configDeviceType ?? raw.type ?? raw.deviceType ?? 'unknown',
1471
+ }
1472
+
1473
+ if (!d.id) {
1474
+ continue
1475
+ }
1476
+
1477
+ const type: string = normalizeTypeForMatter(d.type)
1478
+
1479
+ const matterSupported = !!DEVICE_MATTER_SUPPORTED[(type || '').toLowerCase()]
1480
+ const useMatter = matterEnabled && matterSupported
1481
+ if (!useMatter) {
1482
+ continue
1483
+ }
1484
+
1485
+ try {
1486
+ const created = await createDevice({ id: d.id, type, name: d.name }, this.config, true)
1487
+ const createdDesc = await created.createAccessory(this.api)
1488
+ const uuid = matterApi.uuid.generate(`${d.id}`)
1489
+ // Try to find existing restored accessory by deviceId
1490
+ let existing: any | undefined
1491
+ for (const [, a] of this.accessories.entries()) {
1492
+ try {
1493
+ if (a && a.context && a.context.deviceId === d.id) {
1494
+ existing = a
1495
+ break
1496
+ }
1497
+ } catch (e) {
1498
+ // ignore
1499
+ }
1500
+ }
1501
+
1502
+ if (existing) {
1503
+ // Ensure context and displayName are up to date
1504
+ // Prioritize device-specific Matter clusters (e.g., RVC for vacuum) over generic HAP-derived clusters
1505
+ let clusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()]
1506
+ if (!clusters) {
1507
+ clusters = existing.clusters || createdDesc.clusters || { onOff: { onOff: false } }
1508
+ }
1509
+ const deviceType = resolveMatterDeviceType(matterApi, type, existing.deviceType || createdDesc.deviceType, clusters)
1510
+ existing.context = existing.context || {}
1511
+ existing.context.deviceId = existing.context.deviceId || d.id
1512
+ existing.context.type = existing.context.type || type
1513
+ existing.deviceType = deviceType
1514
+ existing.manufacturer = existing.manufacturer || createdDesc.manufacturer || 'SwitchBot'
1515
+ existing.model = existing.model || createdDesc.model || type
1516
+ existing.serialNumber = existing.serialNumber || createdDesc.serialNumber || d.id
1517
+ existing.reachable = existing.reachable !== false
1518
+ existing.firmwareRevision = existing.firmwareRevision || createdDesc.firmwareRevision || '1.0.0'
1519
+ existing.hardwareRevision = existing.hardwareRevision || createdDesc.hardwareRevision || ''
1520
+ existing.clusters = clusters
1521
+ existing.handlers = createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined
1522
+ existing.displayName = createdDesc.name || d.name || type
1523
+ existing.UUID = existing.UUID || existing.uuid || uuid
1524
+ accessoriesToRegister.push(existing)
1525
+ this.accessories.set(existing.UUID || uuid, existing)
1526
+ } else {
1527
+ // Prioritize device-specific Matter clusters (e.g., RVC for vacuum) over generic HAP-derived clusters
1528
+ let clusters = DEVICE_MATTER_CLUSTERS[type.toLowerCase()]
1529
+ if (!clusters) {
1530
+ clusters = createdDesc.clusters || { onOff: { onOff: false } }
1531
+ }
1532
+ const deviceType = resolveMatterDeviceType(matterApi, type, createdDesc.deviceType, clusters)
1533
+ const serialized: any = {
1534
+ UUID: uuid,
1535
+ displayName: createdDesc.name || d.name || type,
1536
+ deviceType,
1537
+ manufacturer: createdDesc.manufacturer || 'SwitchBot',
1538
+ model: createdDesc.model || type,
1539
+ serialNumber: createdDesc.serialNumber || d.id,
1540
+ reachable: createdDesc.reachable !== false,
1541
+ firmwareRevision: createdDesc.firmwareRevision || '1.0.0',
1542
+ hardwareRevision: createdDesc.hardwareRevision || '',
1543
+ clusters,
1544
+ handlers: createdDesc.handlers || createMatterHandlers(this.log, d.id, type, (this.config as any)?._client) || undefined,
1545
+ context: { deviceId: d.id, type, created: true },
1546
+ }
1547
+ accessoriesToRegister.push(serialized)
1548
+ this.accessories.set(uuid, serialized)
1549
+ }
1550
+ } catch (e) {
1551
+ this.log.warn(`Failed to prepare Matter accessory for ${d.id} (${type})`, e)
1552
+ }
1553
+ }
1554
+
1555
+ if (accessoriesToRegister.length > 0) {
1556
+ try {
1557
+ await matterApi.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, accessoriesToRegister)
1558
+ this.log.info(`Registered ${accessoriesToRegister.length} Matter accessory(ies) with Homebridge`)
1559
+ } catch (e) {
1560
+ this.log.warn('Failed to register Matter accessories', e)
1561
+ }
1562
+ } else {
1563
+ this.log.info('No Matter accessories to register')
1564
+ }
1565
+ }
1566
+ }
1567
+
1568
+ export default SwitchBotHAPPlatform