@switchbot/homebridge-switchbot 5.0.0-beta.1 → 5.0.0-beta.100

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