@switchbot/homebridge-switchbot 5.0.0-beta.10 → 5.0.0-beta.101

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