matter-all-in-one-addon 2.1.2 → 2.3.1

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 (413) hide show
  1. package/README.md +71 -274
  2. package/dist/camera/ai/camera-ai-detector.d.ts +6 -4
  3. package/dist/camera/ai/camera-ai-detector.js +62 -36
  4. package/dist/camera/ai/camera-ai-detector.js.map +1 -1
  5. package/dist/camera/ai/camera-diagnostics.d.ts +48 -0
  6. package/dist/camera/ai/camera-diagnostics.js +41 -0
  7. package/dist/camera/ai/camera-diagnostics.js.map +1 -0
  8. package/dist/camera/ai/diagnostics-auth.d.ts +2 -0
  9. package/dist/camera/ai/diagnostics-auth.js +13 -0
  10. package/dist/camera/ai/diagnostics-auth.js.map +1 -0
  11. package/dist/camera/camera-capabilities.js +7 -6
  12. package/dist/camera/camera-capabilities.js.map +1 -1
  13. package/dist/camera/camera-entity-control.d.ts +12 -0
  14. package/dist/camera/camera-entity-control.js +24 -0
  15. package/dist/camera/camera-entity-control.js.map +1 -0
  16. package/dist/camera/camera-source-resolver.d.ts +16 -0
  17. package/dist/camera/camera-source-resolver.js +123 -0
  18. package/dist/camera/camera-source-resolver.js.map +1 -1
  19. package/dist/camera/camera-types.d.ts +2 -0
  20. package/dist/camera/cameraui/cameraui-homekit-bridge.js +26 -6
  21. package/dist/camera/cameraui/cameraui-homekit-bridge.js.map +1 -1
  22. package/dist/camera/homekit/ffmpeg-helper.d.ts +1 -4
  23. package/dist/camera/homekit/ffmpeg-helper.js +65 -27
  24. package/dist/camera/homekit/ffmpeg-helper.js.map +1 -1
  25. package/dist/camera/homekit/hevc/bootstrap.d.ts +9 -0
  26. package/dist/camera/homekit/hevc/bootstrap.js +47 -0
  27. package/dist/camera/homekit/hevc/bootstrap.js.map +1 -0
  28. package/dist/camera/homekit/hevc/hevc-recording.d.ts +2 -0
  29. package/dist/camera/homekit/hevc/hevc-recording.js +70 -33
  30. package/dist/camera/homekit/hevc/hevc-recording.js.map +1 -1
  31. package/dist/camera/homekit/hevc/multi-tier-rtp.d.ts +15 -1
  32. package/dist/camera/homekit/hevc/multi-tier-rtp.js +229 -64
  33. package/dist/camera/homekit/hevc/multi-tier-rtp.js.map +1 -1
  34. package/dist/camera/homekit/hevc/recording-output.d.ts +2 -0
  35. package/dist/camera/homekit/hevc/recording-output.js +33 -0
  36. package/dist/camera/homekit/hevc/recording-output.js.map +1 -0
  37. package/dist/camera/homekit/hevc/sframe-rtp.d.ts +2 -0
  38. package/dist/camera/homekit/hevc/sframe-rtp.js +38 -4
  39. package/dist/camera/homekit/hevc/sframe-rtp.js.map +1 -1
  40. package/dist/camera/homekit/hevc/sframe.d.ts +11 -1
  41. package/dist/camera/homekit/hevc/sframe.js +195 -23
  42. package/dist/camera/homekit/hevc/sframe.js.map +1 -1
  43. package/dist/camera/homekit/hevc/webrtc-session.d.ts +17 -3
  44. package/dist/camera/homekit/hevc/webrtc-session.js +262 -63
  45. package/dist/camera/homekit/hevc/webrtc-session.js.map +1 -1
  46. package/dist/camera/homekit/homekit-camera-recording.delegate.d.ts +5 -0
  47. package/dist/camera/homekit/homekit-camera-recording.delegate.js +89 -111
  48. package/dist/camera/homekit/homekit-camera-recording.delegate.js.map +1 -1
  49. package/dist/camera/homekit/homekit-camera-stream.delegate.d.ts +10 -2
  50. package/dist/camera/homekit/homekit-camera-stream.delegate.js +339 -310
  51. package/dist/camera/homekit/homekit-camera-stream.delegate.js.map +1 -1
  52. package/dist/camera/homekit/homekit-camera.accessory.d.ts +42 -2
  53. package/dist/camera/homekit/homekit-camera.accessory.js +255 -162
  54. package/dist/camera/homekit/homekit-camera.accessory.js.map +1 -1
  55. package/dist/camera/homekit/live-view-telemetry.d.ts +4 -0
  56. package/dist/camera/homekit/live-view-telemetry.js.map +1 -1
  57. package/dist/camera/homekit/media-policy.d.ts +25 -0
  58. package/dist/camera/homekit/media-policy.js +102 -0
  59. package/dist/camera/homekit/media-policy.js.map +1 -0
  60. package/dist/camera/homekit/route-address.d.ts +2 -0
  61. package/dist/camera/homekit/route-address.js +27 -0
  62. package/dist/camera/homekit/route-address.js.map +1 -0
  63. package/dist/camera/homekit/rtp-relay.d.ts +21 -0
  64. package/dist/camera/homekit/rtp-relay.js +112 -0
  65. package/dist/camera/homekit/rtp-relay.js.map +1 -0
  66. package/dist/camera/homekit/startup-timing.d.ts +8 -0
  67. package/dist/camera/homekit/startup-timing.js +14 -0
  68. package/dist/camera/homekit/startup-timing.js.map +1 -0
  69. package/dist/camera/motion/ffmpeg-motion-detector.d.ts +10 -0
  70. package/dist/camera/motion/ffmpeg-motion-detector.js +126 -77
  71. package/dist/camera/motion/ffmpeg-motion-detector.js.map +1 -1
  72. package/dist/camera/scrypted/scrypted-stream-validator.d.ts +1 -1
  73. package/dist/camera/scrypted/scrypted-stream-validator.js +8 -3
  74. package/dist/camera/scrypted/scrypted-stream-validator.js.map +1 -1
  75. package/dist/camera/source-adapter.d.ts +132 -0
  76. package/dist/camera/source-adapter.js +282 -0
  77. package/dist/camera/source-adapter.js.map +1 -0
  78. package/dist/converters/vacuum.converter.d.ts +3 -2
  79. package/dist/converters/vacuum.converter.js +29 -4
  80. package/dist/converters/vacuum.converter.js.map +1 -1
  81. package/dist/device-profiles.d.ts +3 -3
  82. package/dist/device-profiles.js +26 -6
  83. package/dist/device-profiles.js.map +1 -1
  84. package/dist/device-registry.d.ts +1 -0
  85. package/dist/device-registry.js +11 -3
  86. package/dist/device-registry.js.map +1 -1
  87. package/dist/entities/base.entity.js +3 -1
  88. package/dist/entities/base.entity.js.map +1 -1
  89. package/dist/entities/camera.entity.d.ts +2 -0
  90. package/dist/entities/camera.entity.js +40 -1
  91. package/dist/entities/camera.entity.js.map +1 -1
  92. package/dist/entities/composite-device.entity.js +2 -1
  93. package/dist/entities/composite-device.entity.js.map +1 -1
  94. package/dist/entities/energy_tariff.entity.js +21 -8
  95. package/dist/entities/energy_tariff.entity.js.map +1 -1
  96. package/dist/entities/vacuum.entity.d.ts +8 -0
  97. package/dist/entities/vacuum.entity.js +300 -36
  98. package/dist/entities/vacuum.entity.js.map +1 -1
  99. package/dist/frontend/assets/index-Bka3TVAQ.js +21 -0
  100. package/dist/frontend/assets/{index-CJdlkpIy.css → index-NrzHqycm.css} +1 -1
  101. package/dist/frontend/index.html +2 -2
  102. package/dist/hap/hap-generic-accessory.d.ts +3 -1
  103. package/dist/hap/hap-generic-accessory.js +50 -0
  104. package/dist/hap/hap-generic-accessory.js.map +1 -1
  105. package/dist/homeAssistant.d.ts +13 -0
  106. package/dist/homeAssistant.js +54 -13
  107. package/dist/homeAssistant.js.map +1 -1
  108. package/dist/homekit.compat.d.ts +2 -1
  109. package/dist/homekit.compat.js +4 -1
  110. package/dist/homekit.compat.js.map +1 -1
  111. package/dist/platform.d.ts +19 -7
  112. package/dist/platform.js +865 -587
  113. package/dist/platform.js.map +1 -1
  114. package/dist/proxy.js +1 -11
  115. package/dist/proxy.js.map +1 -1
  116. package/dist/utils/atomic-json-store.d.ts +5 -0
  117. package/dist/utils/atomic-json-store.js +31 -0
  118. package/dist/utils/atomic-json-store.js.map +1 -0
  119. package/dist/utils/ha-entity-names.d.ts +21 -0
  120. package/dist/utils/ha-entity-names.js +26 -0
  121. package/dist/utils/ha-entity-names.js.map +1 -0
  122. package/package.json +22 -19
  123. package/vendor/hap-nodejs/LICENSE +176 -0
  124. package/vendor/hap-nodejs/MIAO.md +5 -0
  125. package/vendor/hap-nodejs/PATCH.md +37 -0
  126. package/vendor/hap-nodejs/README.md +86 -0
  127. package/vendor/hap-nodejs/dist/accessories/AirConditioner_accessory.d.ts +2 -0
  128. package/vendor/hap-nodejs/dist/accessories/AirConditioner_accessory.d.ts.map +1 -0
  129. package/vendor/hap-nodejs/dist/accessories/AirConditioner_accessory.js +128 -0
  130. package/vendor/hap-nodejs/dist/accessories/AirConditioner_accessory.js.map +1 -0
  131. package/vendor/hap-nodejs/dist/accessories/AppleTVRemote_accessory.d.ts +2 -0
  132. package/vendor/hap-nodejs/dist/accessories/AppleTVRemote_accessory.d.ts.map +1 -0
  133. package/vendor/hap-nodejs/dist/accessories/AppleTVRemote_accessory.js +159 -0
  134. package/vendor/hap-nodejs/dist/accessories/AppleTVRemote_accessory.js.map +1 -0
  135. package/vendor/hap-nodejs/dist/accessories/Camera_accessory.d.ts +2 -0
  136. package/vendor/hap-nodejs/dist/accessories/Camera_accessory.d.ts.map +1 -0
  137. package/vendor/hap-nodejs/dist/accessories/Camera_accessory.js +545 -0
  138. package/vendor/hap-nodejs/dist/accessories/Camera_accessory.js.map +1 -0
  139. package/vendor/hap-nodejs/dist/accessories/Fan_accessory.d.ts +2 -0
  140. package/vendor/hap-nodejs/dist/accessories/Fan_accessory.d.ts.map +1 -0
  141. package/vendor/hap-nodejs/dist/accessories/Fan_accessory.js +74 -0
  142. package/vendor/hap-nodejs/dist/accessories/Fan_accessory.js.map +1 -0
  143. package/vendor/hap-nodejs/dist/accessories/GarageDoorOpener_accessory.d.ts +2 -0
  144. package/vendor/hap-nodejs/dist/accessories/GarageDoorOpener_accessory.d.ts.map +1 -0
  145. package/vendor/hap-nodejs/dist/accessories/GarageDoorOpener_accessory.js +78 -0
  146. package/vendor/hap-nodejs/dist/accessories/GarageDoorOpener_accessory.js.map +1 -0
  147. package/vendor/hap-nodejs/dist/accessories/Light-AdaptiveLighting_accessory.d.ts +2 -0
  148. package/vendor/hap-nodejs/dist/accessories/Light-AdaptiveLighting_accessory.d.ts.map +1 -0
  149. package/vendor/hap-nodejs/dist/accessories/Light-AdaptiveLighting_accessory.js +106 -0
  150. package/vendor/hap-nodejs/dist/accessories/Light-AdaptiveLighting_accessory.js.map +1 -0
  151. package/vendor/hap-nodejs/dist/accessories/Light_accessory.d.ts +2 -0
  152. package/vendor/hap-nodejs/dist/accessories/Light_accessory.d.ts.map +1 -0
  153. package/vendor/hap-nodejs/dist/accessories/Light_accessory.js +145 -0
  154. package/vendor/hap-nodejs/dist/accessories/Light_accessory.js.map +1 -0
  155. package/vendor/hap-nodejs/dist/accessories/Lock_accessory.d.ts +2 -0
  156. package/vendor/hap-nodejs/dist/accessories/Lock_accessory.d.ts.map +1 -0
  157. package/vendor/hap-nodejs/dist/accessories/Lock_accessory.js +76 -0
  158. package/vendor/hap-nodejs/dist/accessories/Lock_accessory.js.map +1 -0
  159. package/vendor/hap-nodejs/dist/accessories/MotionSensor_accessory.d.ts +2 -0
  160. package/vendor/hap-nodejs/dist/accessories/MotionSensor_accessory.d.ts.map +1 -0
  161. package/vendor/hap-nodejs/dist/accessories/MotionSensor_accessory.js +45 -0
  162. package/vendor/hap-nodejs/dist/accessories/MotionSensor_accessory.js.map +1 -0
  163. package/vendor/hap-nodejs/dist/accessories/Outlet_accessory.d.ts +2 -0
  164. package/vendor/hap-nodejs/dist/accessories/Outlet_accessory.d.ts.map +1 -0
  165. package/vendor/hap-nodejs/dist/accessories/Outlet_accessory.js +79 -0
  166. package/vendor/hap-nodejs/dist/accessories/Outlet_accessory.js.map +1 -0
  167. package/vendor/hap-nodejs/dist/accessories/SmartSpeaker_accessory.d.ts +2 -0
  168. package/vendor/hap-nodejs/dist/accessories/SmartSpeaker_accessory.d.ts.map +1 -0
  169. package/vendor/hap-nodejs/dist/accessories/SmartSpeaker_accessory.js +44 -0
  170. package/vendor/hap-nodejs/dist/accessories/SmartSpeaker_accessory.js.map +1 -0
  171. package/vendor/hap-nodejs/dist/accessories/Sprinkler_accessory.d.ts +2 -0
  172. package/vendor/hap-nodejs/dist/accessories/Sprinkler_accessory.d.ts.map +1 -0
  173. package/vendor/hap-nodejs/dist/accessories/Sprinkler_accessory.js +128 -0
  174. package/vendor/hap-nodejs/dist/accessories/Sprinkler_accessory.js.map +1 -0
  175. package/vendor/hap-nodejs/dist/accessories/TV_accessory.d.ts +2 -0
  176. package/vendor/hap-nodejs/dist/accessories/TV_accessory.d.ts.map +1 -0
  177. package/vendor/hap-nodejs/dist/accessories/TV_accessory.js +101 -0
  178. package/vendor/hap-nodejs/dist/accessories/TV_accessory.js.map +1 -0
  179. package/vendor/hap-nodejs/dist/accessories/TemperatureSensor_accessory.d.ts +2 -0
  180. package/vendor/hap-nodejs/dist/accessories/TemperatureSensor_accessory.d.ts.map +1 -0
  181. package/vendor/hap-nodejs/dist/accessories/TemperatureSensor_accessory.js +44 -0
  182. package/vendor/hap-nodejs/dist/accessories/TemperatureSensor_accessory.js.map +1 -0
  183. package/vendor/hap-nodejs/dist/accessories/Wi-FiRouter_accessory.d.ts +3 -0
  184. package/vendor/hap-nodejs/dist/accessories/Wi-FiRouter_accessory.d.ts.map +1 -0
  185. package/vendor/hap-nodejs/dist/accessories/Wi-FiRouter_accessory.js +17 -0
  186. package/vendor/hap-nodejs/dist/accessories/Wi-FiRouter_accessory.js.map +1 -0
  187. package/vendor/hap-nodejs/dist/accessories/Wi-FiSatellite_accessory.d.ts +3 -0
  188. package/vendor/hap-nodejs/dist/accessories/Wi-FiSatellite_accessory.d.ts.map +1 -0
  189. package/vendor/hap-nodejs/dist/accessories/Wi-FiSatellite_accessory.js +19 -0
  190. package/vendor/hap-nodejs/dist/accessories/Wi-FiSatellite_accessory.js.map +1 -0
  191. package/vendor/hap-nodejs/dist/accessories/gstreamer-audioProducer.d.ts +25 -0
  192. package/vendor/hap-nodejs/dist/accessories/gstreamer-audioProducer.d.ts.map +1 -0
  193. package/vendor/hap-nodejs/dist/accessories/gstreamer-audioProducer.js +145 -0
  194. package/vendor/hap-nodejs/dist/accessories/gstreamer-audioProducer.js.map +1 -0
  195. package/vendor/hap-nodejs/dist/accessories/types.d.ts +78 -0
  196. package/vendor/hap-nodejs/dist/accessories/types.d.ts.map +1 -0
  197. package/vendor/hap-nodejs/dist/accessories/types.js +88 -0
  198. package/vendor/hap-nodejs/dist/accessories/types.js.map +1 -0
  199. package/vendor/hap-nodejs/dist/index.d.ts +50 -0
  200. package/vendor/hap-nodejs/dist/index.d.ts.map +1 -0
  201. package/vendor/hap-nodejs/dist/index.js +54 -0
  202. package/vendor/hap-nodejs/dist/index.js.map +1 -0
  203. package/vendor/hap-nodejs/dist/internal-types.d.ts +76 -0
  204. package/vendor/hap-nodejs/dist/internal-types.d.ts.map +1 -0
  205. package/vendor/hap-nodejs/dist/internal-types.js +80 -0
  206. package/vendor/hap-nodejs/dist/internal-types.js.map +1 -0
  207. package/vendor/hap-nodejs/dist/lib/Accessory.d.ts +521 -0
  208. package/vendor/hap-nodejs/dist/lib/Accessory.d.ts.map +1 -0
  209. package/vendor/hap-nodejs/dist/lib/Accessory.js +1762 -0
  210. package/vendor/hap-nodejs/dist/lib/Accessory.js.map +1 -0
  211. package/vendor/hap-nodejs/dist/lib/Advertiser.d.ts +190 -0
  212. package/vendor/hap-nodejs/dist/lib/Advertiser.d.ts.map +1 -0
  213. package/vendor/hap-nodejs/dist/lib/Advertiser.js +592 -0
  214. package/vendor/hap-nodejs/dist/lib/Advertiser.js.map +1 -0
  215. package/vendor/hap-nodejs/dist/lib/Bridge.d.ts +12 -0
  216. package/vendor/hap-nodejs/dist/lib/Bridge.d.ts.map +1 -0
  217. package/vendor/hap-nodejs/dist/lib/Bridge.js +19 -0
  218. package/vendor/hap-nodejs/dist/lib/Bridge.js.map +1 -0
  219. package/vendor/hap-nodejs/dist/lib/Characteristic.d.ts +1768 -0
  220. package/vendor/hap-nodejs/dist/lib/Characteristic.d.ts.map +1 -0
  221. package/vendor/hap-nodejs/dist/lib/Characteristic.js +2532 -0
  222. package/vendor/hap-nodejs/dist/lib/Characteristic.js.map +1 -0
  223. package/vendor/hap-nodejs/dist/lib/HAPServer.d.ts +299 -0
  224. package/vendor/hap-nodejs/dist/lib/HAPServer.d.ts.map +1 -0
  225. package/vendor/hap-nodejs/dist/lib/HAPServer.js +968 -0
  226. package/vendor/hap-nodejs/dist/lib/HAPServer.js.map +1 -0
  227. package/vendor/hap-nodejs/dist/lib/Service.d.ts +598 -0
  228. package/vendor/hap-nodejs/dist/lib/Service.d.ts.map +1 -0
  229. package/vendor/hap-nodejs/dist/lib/Service.js +797 -0
  230. package/vendor/hap-nodejs/dist/lib/Service.js.map +1 -0
  231. package/vendor/hap-nodejs/dist/lib/camera/CMAFIngest.d.ts +102 -0
  232. package/vendor/hap-nodejs/dist/lib/camera/CMAFIngest.d.ts.map +1 -0
  233. package/vendor/hap-nodejs/dist/lib/camera/CMAFIngest.js +317 -0
  234. package/vendor/hap-nodejs/dist/lib/camera/CMAFIngest.js.map +1 -0
  235. package/vendor/hap-nodejs/dist/lib/camera/HDSSnapshotTransport.d.ts +38 -0
  236. package/vendor/hap-nodejs/dist/lib/camera/HDSSnapshotTransport.d.ts.map +1 -0
  237. package/vendor/hap-nodejs/dist/lib/camera/HDSSnapshotTransport.js +174 -0
  238. package/vendor/hap-nodejs/dist/lib/camera/HDSSnapshotTransport.js.map +1 -0
  239. package/vendor/hap-nodejs/dist/lib/camera/RTPProxy.d.ts +59 -0
  240. package/vendor/hap-nodejs/dist/lib/camera/RTPProxy.d.ts.map +1 -0
  241. package/vendor/hap-nodejs/dist/lib/camera/RTPProxy.js +267 -0
  242. package/vendor/hap-nodejs/dist/lib/camera/RTPProxy.js.map +1 -0
  243. package/vendor/hap-nodejs/dist/lib/camera/RTPStreamManagement.d.ts +379 -0
  244. package/vendor/hap-nodejs/dist/lib/camera/RTPStreamManagement.d.ts.map +1 -0
  245. package/vendor/hap-nodejs/dist/lib/camera/RTPStreamManagement.js +1021 -0
  246. package/vendor/hap-nodejs/dist/lib/camera/RTPStreamManagement.js.map +1 -0
  247. package/vendor/hap-nodejs/dist/lib/camera/RecordingManagement.d.ts +325 -0
  248. package/vendor/hap-nodejs/dist/lib/camera/RecordingManagement.d.ts.map +1 -0
  249. package/vendor/hap-nodejs/dist/lib/camera/RecordingManagement.js +800 -0
  250. package/vendor/hap-nodejs/dist/lib/camera/RecordingManagement.js.map +1 -0
  251. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoCredentials.d.ts +20 -0
  252. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoCredentials.d.ts.map +1 -0
  253. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoCredentials.js +48 -0
  254. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoCredentials.js.map +1 -0
  255. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoTypes.d.ts +618 -0
  256. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoTypes.d.ts.map +1 -0
  257. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoTypes.js +911 -0
  258. package/vendor/hap-nodejs/dist/lib/camera/SecureVideoTypes.js.map +1 -0
  259. package/vendor/hap-nodejs/dist/lib/camera/index.d.ts +8 -0
  260. package/vendor/hap-nodejs/dist/lib/camera/index.d.ts.map +1 -0
  261. package/vendor/hap-nodejs/dist/lib/camera/index.js +11 -0
  262. package/vendor/hap-nodejs/dist/lib/camera/index.js.map +1 -0
  263. package/vendor/hap-nodejs/dist/lib/controller/AdaptiveLightingController.d.ts +452 -0
  264. package/vendor/hap-nodejs/dist/lib/controller/AdaptiveLightingController.d.ts.map +1 -0
  265. package/vendor/hap-nodejs/dist/lib/controller/AdaptiveLightingController.js +868 -0
  266. package/vendor/hap-nodejs/dist/lib/controller/AdaptiveLightingController.js.map +1 -0
  267. package/vendor/hap-nodejs/dist/lib/controller/CameraController.d.ts +410 -0
  268. package/vendor/hap-nodejs/dist/lib/controller/CameraController.d.ts.map +1 -0
  269. package/vendor/hap-nodejs/dist/lib/controller/CameraController.js +658 -0
  270. package/vendor/hap-nodejs/dist/lib/controller/CameraController.js.map +1 -0
  271. package/vendor/hap-nodejs/dist/lib/controller/Controller.d.ts +197 -0
  272. package/vendor/hap-nodejs/dist/lib/controller/Controller.d.ts.map +1 -0
  273. package/vendor/hap-nodejs/dist/lib/controller/Controller.js +32 -0
  274. package/vendor/hap-nodejs/dist/lib/controller/Controller.js.map +1 -0
  275. package/vendor/hap-nodejs/dist/lib/controller/DoorbellController.d.ts +59 -0
  276. package/vendor/hap-nodejs/dist/lib/controller/DoorbellController.d.ts.map +1 -0
  277. package/vendor/hap-nodejs/dist/lib/controller/DoorbellController.js +102 -0
  278. package/vendor/hap-nodejs/dist/lib/controller/DoorbellController.js.map +1 -0
  279. package/vendor/hap-nodejs/dist/lib/controller/RemoteController.d.ts +434 -0
  280. package/vendor/hap-nodejs/dist/lib/controller/RemoteController.d.ts.map +1 -0
  281. package/vendor/hap-nodejs/dist/lib/controller/RemoteController.js +1178 -0
  282. package/vendor/hap-nodejs/dist/lib/controller/RemoteController.js.map +1 -0
  283. package/vendor/hap-nodejs/dist/lib/controller/SecureVideoController.d.ts +380 -0
  284. package/vendor/hap-nodejs/dist/lib/controller/SecureVideoController.d.ts.map +1 -0
  285. package/vendor/hap-nodejs/dist/lib/controller/SecureVideoController.js +947 -0
  286. package/vendor/hap-nodejs/dist/lib/controller/SecureVideoController.js.map +1 -0
  287. package/vendor/hap-nodejs/dist/lib/controller/index.d.ts +7 -0
  288. package/vendor/hap-nodejs/dist/lib/controller/index.d.ts.map +1 -0
  289. package/vendor/hap-nodejs/dist/lib/controller/index.js +10 -0
  290. package/vendor/hap-nodejs/dist/lib/controller/index.js.map +1 -0
  291. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamManagement.d.ts +73 -0
  292. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamManagement.d.ts.map +1 -0
  293. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamManagement.js +205 -0
  294. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamManagement.js.map +1 -0
  295. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamParser.d.ts +186 -0
  296. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamParser.d.ts.map +1 -0
  297. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamParser.js +880 -0
  298. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamParser.js.map +1 -0
  299. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamServer.d.ts +351 -0
  300. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamServer.d.ts.map +1 -0
  301. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamServer.js +878 -0
  302. package/vendor/hap-nodejs/dist/lib/datastream/DataStreamServer.js.map +1 -0
  303. package/vendor/hap-nodejs/dist/lib/datastream/index.d.ts +4 -0
  304. package/vendor/hap-nodejs/dist/lib/datastream/index.d.ts.map +1 -0
  305. package/vendor/hap-nodejs/dist/lib/datastream/index.js +7 -0
  306. package/vendor/hap-nodejs/dist/lib/datastream/index.js.map +1 -0
  307. package/vendor/hap-nodejs/dist/lib/definitions/CharacteristicDefinitions.d.ts +2245 -0
  308. package/vendor/hap-nodejs/dist/lib/definitions/CharacteristicDefinitions.d.ts.map +1 -0
  309. package/vendor/hap-nodejs/dist/lib/definitions/CharacteristicDefinitions.js +4957 -0
  310. package/vendor/hap-nodejs/dist/lib/definitions/CharacteristicDefinitions.js.map +1 -0
  311. package/vendor/hap-nodejs/dist/lib/definitions/ServiceDefinitions.d.ts +584 -0
  312. package/vendor/hap-nodejs/dist/lib/definitions/ServiceDefinitions.d.ts.map +1 -0
  313. package/vendor/hap-nodejs/dist/lib/definitions/ServiceDefinitions.js +1518 -0
  314. package/vendor/hap-nodejs/dist/lib/definitions/ServiceDefinitions.js.map +1 -0
  315. package/vendor/hap-nodejs/dist/lib/definitions/generate-definitions.d.ts +34 -0
  316. package/vendor/hap-nodejs/dist/lib/definitions/generate-definitions.d.ts.map +1 -0
  317. package/vendor/hap-nodejs/dist/lib/definitions/generate-definitions.js +624 -0
  318. package/vendor/hap-nodejs/dist/lib/definitions/generate-definitions.js.map +1 -0
  319. package/vendor/hap-nodejs/dist/lib/definitions/generator-configuration.d.ts +22 -0
  320. package/vendor/hap-nodejs/dist/lib/definitions/generator-configuration.d.ts.map +1 -0
  321. package/vendor/hap-nodejs/dist/lib/definitions/generator-configuration.js +734 -0
  322. package/vendor/hap-nodejs/dist/lib/definitions/generator-configuration.js.map +1 -0
  323. package/vendor/hap-nodejs/dist/lib/definitions/index.d.ts +3 -0
  324. package/vendor/hap-nodejs/dist/lib/definitions/index.d.ts.map +1 -0
  325. package/vendor/hap-nodejs/dist/lib/definitions/index.js +6 -0
  326. package/vendor/hap-nodejs/dist/lib/definitions/index.js.map +1 -0
  327. package/vendor/hap-nodejs/dist/lib/gen/HomeKit.d.ts +8 -0
  328. package/vendor/hap-nodejs/dist/lib/gen/HomeKit.d.ts.map +1 -0
  329. package/vendor/hap-nodejs/dist/lib/gen/HomeKit.js +9 -0
  330. package/vendor/hap-nodejs/dist/lib/gen/HomeKit.js.map +1 -0
  331. package/vendor/hap-nodejs/dist/lib/model/AccessoryInfo.d.ts +91 -0
  332. package/vendor/hap-nodejs/dist/lib/model/AccessoryInfo.d.ts.map +1 -0
  333. package/vendor/hap-nodejs/dist/lib/model/AccessoryInfo.js +311 -0
  334. package/vendor/hap-nodejs/dist/lib/model/AccessoryInfo.js.map +1 -0
  335. package/vendor/hap-nodejs/dist/lib/model/ControllerStorage.d.ts +46 -0
  336. package/vendor/hap-nodejs/dist/lib/model/ControllerStorage.d.ts.map +1 -0
  337. package/vendor/hap-nodejs/dist/lib/model/ControllerStorage.js +277 -0
  338. package/vendor/hap-nodejs/dist/lib/model/ControllerStorage.js.map +1 -0
  339. package/vendor/hap-nodejs/dist/lib/model/HAPFileStorage.d.ts +75 -0
  340. package/vendor/hap-nodejs/dist/lib/model/HAPFileStorage.d.ts.map +1 -0
  341. package/vendor/hap-nodejs/dist/lib/model/HAPFileStorage.js +190 -0
  342. package/vendor/hap-nodejs/dist/lib/model/HAPFileStorage.js.map +1 -0
  343. package/vendor/hap-nodejs/dist/lib/model/HAPStorage.d.ts +26 -0
  344. package/vendor/hap-nodejs/dist/lib/model/HAPStorage.d.ts.map +1 -0
  345. package/vendor/hap-nodejs/dist/lib/model/HAPStorage.js +79 -0
  346. package/vendor/hap-nodejs/dist/lib/model/HAPStorage.js.map +1 -0
  347. package/vendor/hap-nodejs/dist/lib/model/IdentifierCache.d.ts +33 -0
  348. package/vendor/hap-nodejs/dist/lib/model/IdentifierCache.d.ts.map +1 -0
  349. package/vendor/hap-nodejs/dist/lib/model/IdentifierCache.js +114 -0
  350. package/vendor/hap-nodejs/dist/lib/model/IdentifierCache.js.map +1 -0
  351. package/vendor/hap-nodejs/dist/lib/tv/AccessControlManagement.d.ts +83 -0
  352. package/vendor/hap-nodejs/dist/lib/tv/AccessControlManagement.d.ts.map +1 -0
  353. package/vendor/hap-nodejs/dist/lib/tv/AccessControlManagement.js +127 -0
  354. package/vendor/hap-nodejs/dist/lib/tv/AccessControlManagement.js.map +1 -0
  355. package/vendor/hap-nodejs/dist/lib/util/checkName.d.ts +8 -0
  356. package/vendor/hap-nodejs/dist/lib/util/checkName.d.ts.map +1 -0
  357. package/vendor/hap-nodejs/dist/lib/util/checkName.js +28 -0
  358. package/vendor/hap-nodejs/dist/lib/util/checkName.js.map +1 -0
  359. package/vendor/hap-nodejs/dist/lib/util/clone.d.ts +7 -0
  360. package/vendor/hap-nodejs/dist/lib/util/clone.d.ts.map +1 -0
  361. package/vendor/hap-nodejs/dist/lib/util/clone.js +22 -0
  362. package/vendor/hap-nodejs/dist/lib/util/clone.js.map +1 -0
  363. package/vendor/hap-nodejs/dist/lib/util/color-utils.d.ts +18 -0
  364. package/vendor/hap-nodejs/dist/lib/util/color-utils.d.ts.map +1 -0
  365. package/vendor/hap-nodejs/dist/lib/util/color-utils.js +442 -0
  366. package/vendor/hap-nodejs/dist/lib/util/color-utils.js.map +1 -0
  367. package/vendor/hap-nodejs/dist/lib/util/eventedhttp.d.ts +251 -0
  368. package/vendor/hap-nodejs/dist/lib/util/eventedhttp.d.ts.map +1 -0
  369. package/vendor/hap-nodejs/dist/lib/util/eventedhttp.js +714 -0
  370. package/vendor/hap-nodejs/dist/lib/util/eventedhttp.js.map +1 -0
  371. package/vendor/hap-nodejs/dist/lib/util/hapCrypto.d.ts +50 -0
  372. package/vendor/hap-nodejs/dist/lib/util/hapCrypto.d.ts.map +1 -0
  373. package/vendor/hap-nodejs/dist/lib/util/hapCrypto.js +185 -0
  374. package/vendor/hap-nodejs/dist/lib/util/hapCrypto.js.map +1 -0
  375. package/vendor/hap-nodejs/dist/lib/util/hapStatusError.d.ts +16 -0
  376. package/vendor/hap-nodejs/dist/lib/util/hapStatusError.d.ts.map +1 -0
  377. package/vendor/hap-nodejs/dist/lib/util/hapStatusError.js +29 -0
  378. package/vendor/hap-nodejs/dist/lib/util/hapStatusError.js.map +1 -0
  379. package/vendor/hap-nodejs/dist/lib/util/net-utils.d.ts +21 -0
  380. package/vendor/hap-nodejs/dist/lib/util/net-utils.d.ts.map +1 -0
  381. package/vendor/hap-nodejs/dist/lib/util/net-utils.js +79 -0
  382. package/vendor/hap-nodejs/dist/lib/util/net-utils.js.map +1 -0
  383. package/vendor/hap-nodejs/dist/lib/util/once.d.ts +7 -0
  384. package/vendor/hap-nodejs/dist/lib/util/once.d.ts.map +1 -0
  385. package/vendor/hap-nodejs/dist/lib/util/once.js +22 -0
  386. package/vendor/hap-nodejs/dist/lib/util/once.js.map +1 -0
  387. package/vendor/hap-nodejs/dist/lib/util/promise-utils.d.ts +14 -0
  388. package/vendor/hap-nodejs/dist/lib/util/promise-utils.d.ts.map +1 -0
  389. package/vendor/hap-nodejs/dist/lib/util/promise-utils.js +29 -0
  390. package/vendor/hap-nodejs/dist/lib/util/promise-utils.js.map +1 -0
  391. package/vendor/hap-nodejs/dist/lib/util/request-util.d.ts +36 -0
  392. package/vendor/hap-nodejs/dist/lib/util/request-util.d.ts.map +1 -0
  393. package/vendor/hap-nodejs/dist/lib/util/request-util.js +108 -0
  394. package/vendor/hap-nodejs/dist/lib/util/request-util.js.map +1 -0
  395. package/vendor/hap-nodejs/dist/lib/util/time.d.ts +9 -0
  396. package/vendor/hap-nodejs/dist/lib/util/time.d.ts.map +1 -0
  397. package/vendor/hap-nodejs/dist/lib/util/time.js +23 -0
  398. package/vendor/hap-nodejs/dist/lib/util/time.js.map +1 -0
  399. package/vendor/hap-nodejs/dist/lib/util/tlv.d.ts +90 -0
  400. package/vendor/hap-nodejs/dist/lib/util/tlv.d.ts.map +1 -0
  401. package/vendor/hap-nodejs/dist/lib/util/tlv.js +318 -0
  402. package/vendor/hap-nodejs/dist/lib/util/tlv.js.map +1 -0
  403. package/vendor/hap-nodejs/dist/lib/util/uuid.d.ts +23 -0
  404. package/vendor/hap-nodejs/dist/lib/util/uuid.d.ts.map +1 -0
  405. package/vendor/hap-nodejs/dist/lib/util/uuid.js +78 -0
  406. package/vendor/hap-nodejs/dist/lib/util/uuid.js.map +1 -0
  407. package/vendor/hap-nodejs/dist/types.d.ts +276 -0
  408. package/vendor/hap-nodejs/dist/types.d.ts.map +1 -0
  409. package/vendor/hap-nodejs/dist/types.js +11 -0
  410. package/vendor/hap-nodejs/dist/types.js.map +1 -0
  411. package/vendor/hap-nodejs/package.json +53 -0
  412. package/vendor/hap-nodejs/src/lib/util/hapCrypto.ts +208 -0
  413. package/dist/frontend/assets/index-8tQZaFmi.js +0 -28
package/dist/platform.js CHANGED
@@ -1,9 +1,11 @@
1
+ import { controlCameraEntity } from "./camera/camera-entity-control.js";
1
2
  /**
2
3
  * Core platform class for matter-all-in-one-chrisalvir.
3
4
  */
4
5
  import "./utils/log-buffer.js";
5
6
  import { getLogs, clearLogs } from "./utils/log-buffer.js";
6
7
  import { NodeIdentityStore } from "./utils/node-identity.js";
8
+ import { AtomicJsonStore } from "./utils/atomic-json-store.js";
7
9
  import { MatterbridgeDynamicPlatform, } from "matterbridge";
8
10
  import { CYAN, idn, nf, rs } from "matterbridge/logger";
9
11
  import http from "http";
@@ -24,6 +26,9 @@ import crypto from "crypto";
24
26
  import { uuid, HAPStorage } from "@homebridge/hap-nodejs";
25
27
  import { resolveFfmpegPath, getFfmpegVersion, } from "./camera/homekit/ffmpeg-helper.js";
26
28
  import { CameraEntity } from "./entities/camera.entity.js";
29
+ import { getHaEntitySearchText } from "./utils/ha-entity-names.js";
30
+ import { buildCameraAiDiagnostics } from "./camera/ai/camera-diagnostics.js";
31
+ import { isCameraDiagnosticsAuthorized } from "./camera/ai/diagnostics-auth.js";
27
32
  import { SoilSensorEntity } from "./entities/soil_sensor.entity.js";
28
33
  import { EnergyTariffEntity } from "./entities/energy_tariff.entity.js";
29
34
  import { VacuumEntity } from "./entities/vacuum.entity.js";
@@ -133,6 +138,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
133
138
  ].filter(Boolean));
134
139
  /** Exported keys whose HA entities were absent at restore time (late integrations). */
135
140
  pendingRestore = new Set();
141
+ atomicJsonStore = new AtomicJsonStore();
142
+ /** Entity IDs already evaluated by refreshDiscoveryCatalog to prevent O(N) scans on every UI poll. */
143
+ catalogedHaEntityIds = new Set();
144
+ inventoryMembers;
145
+ inventoryRegistry;
136
146
  /**
137
147
  * HA can emit several state_changed events for the same entity in a single
138
148
  * tick. Coalescing those events keeps Matter attribute transactions from
@@ -151,6 +161,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
151
161
  haDisconnectGraceTimer;
152
162
  /** Serialize destructive/transport operations for the same Matter node. */
153
163
  matterAccessoryOperations = new Map();
164
+ unregisterInFlight = new Map();
165
+ unregisterTimedOut = new Set();
154
166
  stateUpdateFlushScheduled = false;
155
167
  stateUpdateFlushInFlight;
156
168
  syncInFlight;
@@ -165,7 +177,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
165
177
  async saveHomeKitCameraRecords() {
166
178
  try {
167
179
  const list = Array.from(this.homekitCameraRecords.values());
168
- await fs.writeFile("/data/homekit-cameras.json", JSON.stringify(list, null, 2), "utf8");
180
+ await this.atomicJsonStore.write("/data/homekit-cameras.json", list);
169
181
  }
170
182
  catch (err) {
171
183
  this.log.debug(`Failed to save homekit-cameras.json: ${err}`);
@@ -252,10 +264,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
252
264
  }
253
265
  }
254
266
  async saveHapAccessoryRecords() {
255
- this.hapAccessorySaveQueue = this.hapAccessorySaveQueue.then(async () => {
267
+ this.hapAccessorySaveQueue = this.hapAccessorySaveQueue
268
+ .then(async () => {
256
269
  const list = Array.from(this.hapAccessoryRecords.values());
257
270
  await writeHapAccessoryRecords("/data/homekit-accessories.json", list);
258
- }).catch((err) => {
271
+ })
272
+ .catch((err) => {
259
273
  this.log.debug(`Failed to save homekit-accessories.json: ${err instanceof Error ? err.name : "unknown error"}`);
260
274
  });
261
275
  await this.hapAccessorySaveQueue;
@@ -333,7 +347,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
333
347
  record.model !== identity.model ||
334
348
  record.serialNumber !== identity.serialNumber;
335
349
  if (changed) {
336
- Object.assign(record, identity, { lastUpdated: new Date().toISOString() });
350
+ Object.assign(record, identity, {
351
+ lastUpdated: new Date().toISOString(),
352
+ });
337
353
  }
338
354
  return changed;
339
355
  }
@@ -351,7 +367,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
351
367
  record.lastUpdated = new Date().toISOString();
352
368
  this.hapAccessories.set(entityId, acc);
353
369
  await this.saveHapAccessoryRecords();
354
- this.log.notice(`Exported HAP generic accessory for ${idn}${entityId}${rs} as "${HAP_PROFILE_LABELS[hapProfile]}" (port ${record.port}, PIN: ${record.pincode})`);
370
+ this.log.notice(`Exported HAP generic accessory for ${idn}${entityId}${rs} as "${HAP_PROFILE_LABELS[hapProfile]}" (port ${record.port})`);
355
371
  }
356
372
  /**
357
373
  * Restore all previously published HAP generic accessories on startup.
@@ -453,14 +469,23 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
453
469
  async setHapAlarmCode(entityId, alarmCode) {
454
470
  const record = this.hapAccessoryRecords.get(entityId);
455
471
  if (!record || record.hapProfile !== "security_system") {
456
- return { success: false, error: "This HAP accessory is not an alarm panel." };
472
+ return {
473
+ success: false,
474
+ error: "This HAP accessory is not an alarm panel.",
475
+ };
457
476
  }
458
477
  if (typeof alarmCode !== "string" || alarmCode.length > 64) {
459
- return { success: false, error: "Alarm PIN must be a text value of at most 64 characters." };
478
+ return {
479
+ success: false,
480
+ error: "Alarm PIN must be a text value of at most 64 characters.",
481
+ };
460
482
  }
461
483
  const normalized = alarmCode.trim();
462
484
  if (normalized && /[\u0000-\u001f\u007f]/.test(normalized)) {
463
- return { success: false, error: "Alarm PIN cannot contain control characters." };
485
+ return {
486
+ success: false,
487
+ error: "Alarm PIN cannot contain control characters.",
488
+ };
464
489
  }
465
490
  if (normalized)
466
491
  record.alarmCode = normalized;
@@ -586,7 +611,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
586
611
  continue;
587
612
  const previousSource = previousSources.get(camera.id);
588
613
  const accessory = await CameraUiHomeKitBridge.mountCamera(this, camera, {
589
- forceRemount: previousSources.has(camera.id) && previousSource !== camera.rtspUrl,
614
+ forceRemount: previousSources.has(camera.id) &&
615
+ previousSource !== camera.rtspUrl,
590
616
  });
591
617
  if (accessory)
592
618
  mountedCount++;
@@ -1035,7 +1061,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1035
1061
  this.log.info(`[MatterCommandTrace][${entityId}] start command=${command}`);
1036
1062
  },
1037
1063
  onCommandOutcome: (command, durationMs, outcome, late) => {
1038
- const stage = late ? "ha_operation_finished_after_handler_return" : "handler_returned";
1064
+ const stage = late
1065
+ ? "ha_operation_finished_after_handler_return"
1066
+ : "handler_returned";
1039
1067
  this.log.info(`[MatterCommandTrace][${entityId}] ${stage} command=${command} elapsed_ms=${durationMs} outcome=${outcome}`);
1040
1068
  },
1041
1069
  onFailure: async (command, error, late) => {
@@ -1380,32 +1408,61 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1380
1408
  }
1381
1409
  }
1382
1410
  }
1411
+ /** Build a short-lived index for synchronous inventory operations. */
1412
+ buildInventoryIndex() {
1413
+ this.inventoryMembers = new Map();
1414
+ this.inventoryRegistry = new Map();
1415
+ for (const [id, entry] of this.ha?.hassEntities ?? []) {
1416
+ if (!entry.device_id)
1417
+ continue;
1418
+ const ids = this.inventoryRegistry.get(entry.device_id) ?? [];
1419
+ ids.push(id);
1420
+ this.inventoryRegistry.set(entry.device_id, ids);
1421
+ }
1422
+ for (const entity of this.entities.values()) {
1423
+ const deviceId = this.ha?.hassEntities?.get(entity.entityId)?.device_id;
1424
+ if (!deviceId)
1425
+ continue;
1426
+ const members = this.inventoryMembers.get(deviceId) ?? [];
1427
+ members.push(entity);
1428
+ this.inventoryMembers.set(deviceId, members);
1429
+ }
1430
+ }
1383
1431
  /** Poll live server state even when the custom UI is closed. */
1384
1432
  monitorMatterConnections() {
1385
- for (const [entityId] of this.entities) {
1386
- if (!this.isEntityExported(entityId))
1387
- continue;
1388
- try {
1389
- const compositeDeviceId = this.compositeMembership.get(entityId) ??
1390
- this.getCompositeCandidate(entityId)?.deviceId;
1391
- const endpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
1392
- const current = this.getMatterConnectionInfo(endpoint);
1393
- const previous = this.matterConnectionStates.get(entityId);
1394
- this.observeMatterConnection(entityId, current);
1395
- if (!previous ||
1396
- previous.fabricCount !== current.fabricCount ||
1397
- previous.pairingCode !== current.pairingCode ||
1398
- previous.manualPairingCode !== current.manualPairingCode) {
1399
- this.pushEntityUpdate(entityId);
1433
+ this.buildInventoryIndex();
1434
+ try {
1435
+ for (const [entityId] of this.entities) {
1436
+ if (!this.isEntityExported(entityId))
1437
+ continue;
1438
+ try {
1439
+ const compositeDeviceId = this.compositeMembership.get(entityId) ??
1440
+ this.getCompositeCandidate(entityId)?.deviceId;
1441
+ const endpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
1442
+ const current = this.getMatterConnectionInfo(endpoint);
1443
+ const previous = this.matterConnectionStates.get(entityId);
1444
+ this.observeMatterConnection(entityId, current);
1445
+ if (!previous ||
1446
+ previous.fabricCount !== current.fabricCount ||
1447
+ previous.pairingCode !== current.pairingCode ||
1448
+ previous.manualPairingCode !== current.manualPairingCode) {
1449
+ this.pushEntityUpdate(entityId);
1450
+ }
1451
+ }
1452
+ catch (error) {
1453
+ this.log.debug(`[Matter] Unable to inspect pairing state for ${entityId}: ${String(error)}`);
1400
1454
  }
1401
- }
1402
- catch (error) {
1403
- this.log.debug(`[Matter] Unable to inspect pairing state for ${entityId}: ${String(error)}`);
1404
1455
  }
1405
1456
  }
1457
+ finally {
1458
+ this.inventoryMembers = undefined;
1459
+ this.inventoryRegistry = undefined;
1460
+ }
1406
1461
  }
1407
1462
  async runMatterAccessoryOperation(entityId, operation) {
1408
- const key = this.compositeMembership.get(entityId) ?? entityId;
1463
+ const key = this.compositeMembership.get(entityId) ??
1464
+ this.ha?.hassEntities?.get(entityId)?.device_id ??
1465
+ entityId;
1409
1466
  const previous = this.matterAccessoryOperations.get(key) ?? Promise.resolve();
1410
1467
  const current = previous.catch(() => undefined).then(operation);
1411
1468
  this.matterAccessoryOperations.set(key, current);
@@ -1450,6 +1507,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1450
1507
  }, 4_000);
1451
1508
  }
1452
1509
  cameraUiHealthMonitor = null;
1510
+ cameraUiHealthStartupTimer;
1453
1511
  startCameraUiHealthMonitor() {
1454
1512
  if (this.cameraUiHealthMonitor)
1455
1513
  return;
@@ -1476,7 +1534,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1476
1534
  }
1477
1535
  catch { }
1478
1536
  };
1479
- setTimeout(() => void checkLiveness(), 4000);
1537
+ this.cameraUiHealthStartupTimer = setTimeout(() => {
1538
+ this.cameraUiHealthStartupTimer = undefined;
1539
+ void checkLiveness();
1540
+ }, 4000);
1480
1541
  this.cameraUiHealthMonitor = setInterval(() => void checkLiveness(), 30_000);
1481
1542
  }
1482
1543
  cameraUiMotionPoller = null;
@@ -1491,7 +1552,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1491
1552
  startCameraUiMotionPoller() {
1492
1553
  if (this.cameraUiMotionPoller)
1493
1554
  return;
1555
+ let pollInFlight = false;
1494
1556
  const pollNotifications = async () => {
1557
+ if (pollInFlight)
1558
+ return;
1559
+ pollInFlight = true;
1495
1560
  try {
1496
1561
  const store = await CameraUiStorage.load();
1497
1562
  // Return only if Camera.UI is not configured at all (no serverUrl)
@@ -1641,24 +1706,33 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1641
1706
  .toLowerCase();
1642
1707
  const isVehicle = /vehicle|vehiculo|vehículo|car|auto|camion|camión|truck|bus|motorcycle|moto/i.test(allText);
1643
1708
  const isPerson = /person|persona|humano|human|face|cara/i.test(allText);
1644
- const isPet = /dog|perro|cat|gato|pet|animal|mascota|bird|ave/i.test(allText);
1709
+ const isDog = /dog|perro/i.test(allText);
1710
+ const isCat = /cat|gato/i.test(allText);
1711
+ const isBird = /bird|ave|pajaro|pájaro/i.test(allText);
1645
1712
  const targets = [];
1646
1713
  if (isVehicle)
1647
1714
  targets.push("vehicle");
1648
1715
  if (isPerson)
1649
1716
  targets.push("person");
1650
- if (isPet)
1717
+ if (isDog)
1651
1718
  targets.push("dog");
1652
- if (targets.length === 0)
1653
- targets.push("person");
1654
- this.cameraAiDetector.dispatchDetection(this, matchedCuiId, {
1655
- cameraId: matchedCuiId,
1656
- timestamp: Date.now(),
1657
- targets,
1658
- labels: [String(triggerInfo)],
1659
- confidence: 0.95,
1660
- rawDetails: `Camera.UI OpenCV: ${triggerInfo}`,
1661
- });
1719
+ if (isCat)
1720
+ targets.push("cat");
1721
+ if (isBird)
1722
+ targets.push("bird");
1723
+ // A generic motion webhook is not evidence of a person. Keep
1724
+ // motion reporting above, but only publish object detections
1725
+ // when the source explicitly identifies a supported class.
1726
+ if (targets.length > 0) {
1727
+ this.cameraAiDetector.dispatchDetection(this, matchedCuiId, {
1728
+ cameraId: matchedCuiId,
1729
+ timestamp: Date.now(),
1730
+ targets,
1731
+ labels: [String(triggerInfo)],
1732
+ confidence: 0.95,
1733
+ rawDetails: `Camera.UI event: ${triggerInfo}`,
1734
+ });
1735
+ }
1662
1736
  }
1663
1737
  const existingTimer = this.cameraUiActiveMotionTimers.get(matchedCuiId);
1664
1738
  if (existingTimer)
@@ -1683,6 +1757,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1683
1757
  // Reset client on error so next poll re-authenticates
1684
1758
  this.cameraUiPollerClient = null;
1685
1759
  }
1760
+ finally {
1761
+ pollInFlight = false;
1762
+ }
1686
1763
  };
1687
1764
  this.cameraUiMotionPoller = setInterval(() => void pollNotifications(), 1500);
1688
1765
  }
@@ -1724,7 +1801,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1724
1801
  this.entities.get(entityId)?.state?.attributes?.friendly_name;
1725
1802
  if (nodeName && typeof this.getDeviceByName === "function") {
1726
1803
  const byName = this.getDeviceByName(nodeName);
1727
- if (byName?.serverNode) {
1804
+ if (byName?.serverNode && byName.uniqueId === compKey) {
1728
1805
  this.matterbridgeDevices.set(this.compositeStorageKey(compositeDeviceId), byName);
1729
1806
  return byName;
1730
1807
  }
@@ -1742,7 +1819,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1742
1819
  const friendlyName = this.entities.get(entityId)?.state?.attributes?.friendly_name;
1743
1820
  if (friendlyName && typeof this.getDeviceByName === "function") {
1744
1821
  const byName = this.getDeviceByName(friendlyName);
1745
- if (byName?.serverNode) {
1822
+ if (byName?.serverNode && byName.uniqueId === uniqueId) {
1746
1823
  this.matterbridgeDevices.set(entityId, byName);
1747
1824
  return byName;
1748
1825
  }
@@ -1844,11 +1921,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1844
1921
  async refreshDiscoveryCatalog() {
1845
1922
  if (!this.ha?.hassStates)
1846
1923
  return;
1847
- if (this.entities.size === this.ha.hassStates.size)
1848
- return;
1849
1924
  for (const state of this.ha.hassStates.values()) {
1850
- if (!this.entities.has(state.entity_id)) {
1851
- await this.registerHAEntity(state);
1925
+ if (!this.catalogedHaEntityIds.has(state.entity_id)) {
1926
+ if (!this.entities.has(state.entity_id)) {
1927
+ await this.registerHAEntity(state);
1928
+ }
1929
+ this.catalogedHaEntityIds.add(state.entity_id);
1852
1930
  }
1853
1931
  }
1854
1932
  }
@@ -1861,10 +1939,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1861
1939
  isMultiSwitchDevice(deviceId) {
1862
1940
  if (!deviceId)
1863
1941
  return false;
1864
- const allMembers = Array.from(this.entities.values()).filter((entity) => {
1865
- const hassEntry = this.ha.hassEntities?.get(entity.entityId);
1866
- return hassEntry?.device_id === deviceId;
1867
- });
1942
+ const allMembers = this.inventoryMembers?.get(deviceId) ??
1943
+ Array.from(this.entities.values()).filter((entity) => {
1944
+ const hassEntry = this.ha.hassEntities?.get(entity.entityId);
1945
+ return hassEntry?.device_id === deviceId;
1946
+ });
1868
1947
  const isNonGeneric = (e) => !this.isDpsGenericEntity(e.entityId) &&
1869
1948
  !this.isAuxiliaryEntity(e.entityId);
1870
1949
  const switches = allMembers.filter((e) => e.entityId.startsWith("switch.") && isNonGeneric(e));
@@ -1898,8 +1977,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1898
1977
  // If device has 2+ real switches, 2+ real lights, 2+ switch/light buttons, or matches controller/switch keywords with 2+ channels:
1899
1978
  if (switches.length >= 2 ||
1900
1979
  lights.length >= 2 ||
1901
- (switches.length + lights.length >= 2 && (!isLightingDevice || isSwitchOrPlugDevice)) ||
1902
- (isSwitchOrPlugDevice && switches.length + lights.length + fans.length >= 2)) {
1980
+ (switches.length + lights.length >= 2 &&
1981
+ (!isLightingDevice || isSwitchOrPlugDevice)) ||
1982
+ (isSwitchOrPlugDevice &&
1983
+ switches.length + lights.length + fans.length >= 2)) {
1903
1984
  return true;
1904
1985
  }
1905
1986
  // 1. Any device with 2 or more fan entities (e.g. 2-gang fan controller)
@@ -1931,7 +2012,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1931
2012
  return undefined;
1932
2013
  }
1933
2014
  const config = this.getCompositeConfigForEntity(entityId, deviceId);
1934
- if (config?.group_by_device_id === false) {
2015
+ const existingComposite = this.exportedDevices.has(this.compositeStorageKey(deviceId)) ||
2016
+ this.compositeDevices.has(deviceId);
2017
+ if (config?.group_by_device_id === false && !existingComposite) {
1935
2018
  this.log.debug(`[Composite] ${entityId}: grouping explicitly disabled for device ${deviceId}`);
1936
2019
  return undefined;
1937
2020
  }
@@ -1943,11 +2026,13 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1943
2026
  // sibling entities are loaded) and pinned. Recomputing it at every boot
1944
2027
  // flips identities when a slow integration only exposes part of a device.
1945
2028
  const pinnedMode = this.nodeIdentities.get(`mode:${deviceId}`);
1946
- const multi = pinnedMode === "multi"
1947
- ? true
1948
- : pinnedMode === "composite"
1949
- ? false
1950
- : this.isMultiSwitchDevice(deviceId);
2029
+ const multi = existingComposite
2030
+ ? false
2031
+ : pinnedMode === "multi"
2032
+ ? true
2033
+ : pinnedMode === "composite"
2034
+ ? false
2035
+ : this.isMultiSwitchDevice(deviceId);
1951
2036
  if (multi) {
1952
2037
  this.log.debug(`[Composite] ${entityId}: multi-switch device ${deviceId} — composite grouping bypassed, each entity gets its own QR`);
1953
2038
  return undefined;
@@ -1965,7 +2050,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1965
2050
  "binary_sensor",
1966
2051
  "humidifier",
1967
2052
  ]);
1968
- let members = Array.from(this.entities.values()).filter((entity) => {
2053
+ const sourceMembers = explicitlyIncluded?.length
2054
+ ? Array.from(this.entities.values())
2055
+ : (this.inventoryMembers?.get(compositeDeviceId) ??
2056
+ Array.from(this.entities.values()));
2057
+ let members = sourceMembers.filter((entity) => {
1969
2058
  const [domain] = entity.entityId.split(".");
1970
2059
  if (!supported.has(domain))
1971
2060
  return false;
@@ -1981,9 +2070,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
1981
2070
  hassEntry?.entity_category === "diagnostic") {
1982
2071
  return false;
1983
2072
  }
1984
- // Exclude unnamed generic Tuya DPS entities
2073
+ // Exclude unnamed generic Tuya DPS entities and auxiliary companion entities (e.g. vacuum sensors)
1985
2074
  if (this.isDpsGenericEntity(entity.entityId))
1986
2075
  return false;
2076
+ if (this.isAuxiliaryEntity(entity.entityId))
2077
+ return false;
1987
2078
  return true;
1988
2079
  });
1989
2080
  if (config?.primary_entity &&
@@ -2042,7 +2133,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2042
2133
  member.entityId.startsWith("humidifier."));
2043
2134
  const isAllSensors = members.every((member) => member.entityId.startsWith("sensor.") ||
2044
2135
  member.entityId.startsWith("binary_sensor."));
2045
- if (!hasPrimaryControllable && !isAllSensors) {
2136
+ if (!hasPrimaryControllable && !isAllSensors && !existingComposite) {
2046
2137
  this.log.debug(`[Composite] ${entityId}: neither a primary controllable (fan/lock) nor a pure sensor group — not a composite candidate`);
2047
2138
  return undefined;
2048
2139
  }
@@ -2190,7 +2281,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2190
2281
  };
2191
2282
  }
2192
2283
  getPrimaryEntityId(entityId) {
2193
- const deviceId = this.ha.hassEntities.get(entityId)?.device_id;
2284
+ const deviceId = this.ha?.hassEntities?.get(entityId)?.device_id;
2194
2285
  if (!deviceId)
2195
2286
  return undefined;
2196
2287
  const priority = [
@@ -2205,11 +2296,49 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2205
2296
  "switch",
2206
2297
  "fan",
2207
2298
  ];
2208
- const candidates = Array.from(this.entities.values())
2209
- .filter((entity) => this.ha.hassEntities.get(entity.entityId)?.device_id === deviceId)
2299
+ const candidates = (this.inventoryMembers?.get(deviceId) ??
2300
+ Array.from(this.entities.values()).filter((entity) => this.ha?.hassEntities?.get(entity.entityId)?.device_id === deviceId))
2301
+ .slice()
2210
2302
  .sort((left, right) => priority.indexOf(left.entityId.split(".")[0]) -
2211
2303
  priority.indexOf(right.entityId.split(".")[0]));
2212
- return candidates.find((entity) => priority.includes(entity.entityId.split(".")[0]))?.entityId;
2304
+ const foundInEntities = candidates.find((entity) => priority.includes(entity.entityId.split(".")[0]))?.entityId;
2305
+ if (foundInEntities)
2306
+ return foundInEntities;
2307
+ // Fallback to hassEntities if primary entity hasn't been registered yet during initial pass
2308
+ for (const domain of priority) {
2309
+ if (this.inventoryRegistry) {
2310
+ const id = this.inventoryRegistry
2311
+ .get(deviceId)
2312
+ ?.find((id) => id.startsWith(`${domain}.`));
2313
+ if (id)
2314
+ return id;
2315
+ }
2316
+ else {
2317
+ for (const [id, reg] of this.ha?.hassEntities?.entries() ?? []) {
2318
+ if (reg.device_id === deviceId && id.startsWith(`${domain}.`))
2319
+ return id;
2320
+ }
2321
+ }
2322
+ }
2323
+ return undefined;
2324
+ }
2325
+ /** Returns true when this entity belongs to the same physical HA device as a `vacuum.*` entity. */
2326
+ isVacuumCompanionEntity(entityId) {
2327
+ if (entityId.startsWith("vacuum."))
2328
+ return false;
2329
+ const deviceId = this.ha?.hassEntities?.get(entityId)?.device_id;
2330
+ if (!deviceId)
2331
+ return false;
2332
+ if (this.inventoryRegistry)
2333
+ return (this.inventoryRegistry
2334
+ .get(deviceId)
2335
+ ?.some((id) => id.startsWith("vacuum.")) ?? false);
2336
+ for (const [id, reg] of this.ha?.hassEntities?.entries() ?? []) {
2337
+ if (reg.device_id === deviceId && id.startsWith("vacuum.")) {
2338
+ return true;
2339
+ }
2340
+ }
2341
+ return false;
2213
2342
  }
2214
2343
  isAuxiliaryEntity(entityId) {
2215
2344
  // RGBIC light segments (e.g. light.tira_larga_navidad_2_segment_1) are auxiliary sub-entities of the main light strip
@@ -2217,10 +2346,17 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2217
2346
  return true;
2218
2347
  }
2219
2348
  const [domain] = entityId.split(".");
2220
- if (domain !== "button")
2221
- return false;
2222
2349
  const primary = this.getPrimaryEntityId(entityId);
2223
- return primary !== undefined && primary !== entityId;
2350
+ if (!primary || primary === entityId)
2351
+ return false;
2352
+ if (domain === "button" || domain === "select") {
2353
+ return true;
2354
+ }
2355
+ if (primary.startsWith("vacuum.") &&
2356
+ (domain === "sensor" || domain === "binary_sensor")) {
2357
+ return true;
2358
+ }
2359
+ return false;
2224
2360
  }
2225
2361
  constructor(matterbridge, log, config) {
2226
2362
  super(matterbridge, log, config);
@@ -2818,7 +2954,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2818
2954
  this.cameraAiDetector.dispatchDetection(this, cuiId, {
2819
2955
  cameraId: cuiId,
2820
2956
  timestamp: Date.now(),
2821
- targets: ["person"],
2957
+ targets: [],
2822
2958
  labels: [`MQTT (${friendlyName || entityId})`],
2823
2959
  confidence: 0.95,
2824
2960
  rawDetails: `MQTT motion event: ${entityId}`,
@@ -2833,6 +2969,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2833
2969
  * Called when the platform shuts down.
2834
2970
  */
2835
2971
  async onShutdown(reason) {
2972
+ this.cameraAiDetector?.dispose();
2836
2973
  this.log.warn(`Shutting down platform: ${reason ?? ""}`);
2837
2974
  // 1. Log memory usage diagnostics at shutdown
2838
2975
  try {
@@ -2881,10 +3018,42 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
2881
3018
  }
2882
3019
  }
2883
3020
  }
3021
+ for (const accessory of this.hapAccessories.values()) {
3022
+ try {
3023
+ await accessory.unpublish();
3024
+ }
3025
+ catch (error) {
3026
+ this.log.warn(`HAP shutdown failed: ${error}`);
3027
+ }
3028
+ }
3029
+ this.hapAccessories.clear();
3030
+ if (this.cameraUiHealthMonitor)
3031
+ clearInterval(this.cameraUiHealthMonitor);
3032
+ if (this.cameraUiHealthStartupTimer)
3033
+ clearTimeout(this.cameraUiHealthStartupTimer);
3034
+ this.cameraUiHealthStartupTimer = undefined;
3035
+ if (this.haDisconnectGraceTimer)
3036
+ clearTimeout(this.haDisconnectGraceTimer);
3037
+ this.haDisconnectGraceTimer = undefined;
3038
+ for (const timer of this.cameraUiActiveMotionTimers.values())
3039
+ clearTimeout(timer);
3040
+ this.cameraUiActiveMotionTimers.clear();
3041
+ if (this.cameraUiMotionPoller)
3042
+ clearInterval(this.cameraUiMotionPoller);
3043
+ if (this.cameraUiRetryTimer)
3044
+ clearTimeout(this.cameraUiRetryTimer);
3045
+ this.cameraUiHealthMonitor = null;
3046
+ this.cameraUiMotionPoller = null;
3047
+ this.cameraUiRetryTimer = undefined;
2884
3048
  // 5. Persist records and overrides to disk
2885
3049
  try {
2886
- this.saveHomeKitCameraRecords();
3050
+ await this.saveHomeKitCameraRecords();
2887
3051
  await this.saveDeviceOverrides();
3052
+ if (this.diagnosticSaveTimer) {
3053
+ clearTimeout(this.diagnosticSaveTimer);
3054
+ this.diagnosticSaveTimer = undefined;
3055
+ await this.atomicJsonStore.write("/data/entity-diagnostics.json", Object.fromEntries(this.entityDiagnostics.entries()));
3056
+ }
2888
3057
  }
2889
3058
  catch { }
2890
3059
  // 6. Stop intervals and close connections
@@ -3014,8 +3183,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3014
3183
  const states = Array.from(this.ha?.hassStates?.values() || []);
3015
3184
  this.log.info(`Fetched ${states.length} entity states. Registering matching devices...`);
3016
3185
  if (states.length > 0) {
3017
- for (const hassState of states)
3186
+ this.catalogedHaEntityIds.clear();
3187
+ for (const hassState of states) {
3188
+ this.catalogedHaEntityIds.add(hassState.entity_id);
3018
3189
  await this.registerHAEntity(hassState);
3190
+ }
3019
3191
  const currentEntityIds = new Set(states.map((state) => state.entity_id));
3020
3192
  for (const entityId of [...this.entities.keys()]) {
3021
3193
  if (currentEntityIds.has(entityId))
@@ -3033,6 +3205,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3033
3205
  await this.restoreHapAccessories();
3034
3206
  await this.restoreExportedDevices();
3035
3207
  // Ensure all exported Matter serverNodes are running and online
3208
+ let failedNodes = 0;
3036
3209
  for (const [key, dev] of this.matterbridgeDevices.entries()) {
3037
3210
  const sn = dev?.serverNode;
3038
3211
  if (sn && !sn.lifecycle?.isOnline) {
@@ -3041,6 +3214,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3041
3214
  this.log.info(`[Startup] Started offline Matter serverNode for ${key}`);
3042
3215
  }
3043
3216
  catch (err) {
3217
+ failedNodes++;
3044
3218
  this.log.error(`[Startup] Failed to start serverNode for ${key}: ${err}`);
3045
3219
  }
3046
3220
  }
@@ -3053,7 +3227,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3053
3227
  if (!isUnavailable(entity.state))
3054
3228
  this.clearEntityProblem(entity.entityId);
3055
3229
  }
3056
- this.log.notice("Home Assistant recovery sync completed; Matter accessories are current.");
3230
+ if (failedNodes) {
3231
+ this.log.warn(`Home Assistant recovery sync completed with ${failedNodes} Matter node(s) unavailable.`);
3232
+ }
3233
+ else {
3234
+ this.log.notice("Home Assistant recovery sync completed; Matter accessories are current.");
3235
+ }
3057
3236
  this.syncRetryAttempt = 0;
3058
3237
  return true;
3059
3238
  }
@@ -3097,13 +3276,17 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3097
3276
  "humidifier",
3098
3277
  "siren",
3099
3278
  ];
3279
+ const isVacuumCompanion = !this.isDpsGenericEntity(entityId) &&
3280
+ this.isVacuumCompanionEntity(entityId);
3100
3281
  if (!allowedDomains.includes(domain) &&
3101
- !(domain === "button" && override === "PetFeeder"))
3282
+ !(domain === "button" && override === "PetFeeder") &&
3283
+ !(isVacuumCompanion && (domain === "select" || domain === "button")))
3102
3284
  return;
3103
3285
  // Strict device_class whitelist for sensors to avoid exporting system/unsupported sensors
3104
3286
  // (power and energy are mapped to Matter 1.3 electrical measurement; monetary fails closed)
3105
3287
  const deviceClass = state.attributes.device_class;
3106
3288
  if (domain === "sensor" &&
3289
+ !isVacuumCompanion &&
3107
3290
  ![
3108
3291
  "temperature",
3109
3292
  "humidity",
@@ -3114,6 +3297,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3114
3297
  ].includes(deviceClass ?? ""))
3115
3298
  return;
3116
3299
  if (domain === "binary_sensor" &&
3300
+ !isVacuumCompanion &&
3117
3301
  ![
3118
3302
  "door",
3119
3303
  "window",
@@ -3164,7 +3348,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3164
3348
  entityInstance = new SoilSensorEntity(this, state, deviceType);
3165
3349
  }
3166
3350
  else if (domain === "sensor" &&
3167
- (deviceClass === "monetary" || deviceClass === "power" || deviceClass === "energy")) {
3351
+ (deviceClass === "monetary" ||
3352
+ deviceClass === "power" ||
3353
+ deviceClass === "energy")) {
3168
3354
  entityInstance = new EnergyTariffEntity(this, state, deviceType);
3169
3355
  }
3170
3356
  else if (domain === "valve" || deviceType.name === "WaterValve") {
@@ -3223,7 +3409,6 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3223
3409
  }
3224
3410
  /** Restore persisted legacy entities and grouped physical devices after discovery in parallel batches. */
3225
3411
  async restoreExportedDevices() {
3226
- let migratedLegacyEntries = false;
3227
3412
  const entries = Array.from(this.exportedDevices);
3228
3413
  const cameraEntries = entries.filter((entry) => entry.startsWith("camera."));
3229
3414
  const nonCameraEntries = entries.filter((entry) => !entry.startsWith("camera."));
@@ -3235,30 +3420,18 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3235
3420
  try {
3236
3421
  if (exportedId.startsWith("device:")) {
3237
3422
  const deviceId = exportedId.substring("device:".length);
3238
- if (this.isMultiSwitchDevice(deviceId)) {
3239
- this.log.notice(`[MultiSwitch] Disbanding legacy composite for multi-switch device ${deviceId} to allow independent button export.`);
3240
- this.exportedDevices.delete(exportedId);
3241
- await this.disposeCompositeNode(deviceId);
3242
- migratedLegacyEntries = true;
3243
- return;
3244
- }
3245
3423
  const entityId = Array.from(this.entities.keys()).find((id) => this.ha.hassEntities.get(id)?.device_id === deviceId);
3246
3424
  if (!entityId) {
3247
3425
  this.deferRestore(exportedId);
3248
3426
  return;
3249
3427
  }
3250
- this.pendingRestore.delete(exportedId);
3251
- if (entityId) {
3252
- try {
3253
- await this.activateComposite(entityId);
3254
- }
3255
- catch (error) {
3256
- if (!this.isCompositeNodeCreationFailure(error))
3257
- throw error;
3258
- await this.restoreCompositeAsPrimary(entityId, deviceId);
3259
- migratedLegacyEntries = true;
3260
- }
3428
+ if (!this.getCompositeCandidate(entityId)) {
3429
+ this.deferRestore(exportedId);
3430
+ this.log.warn(`[Restore] Composite ${deviceId} is incomplete; preserving its identity until all required entities are available.`);
3431
+ return;
3261
3432
  }
3433
+ await this.activateComposite(entityId);
3434
+ this.pendingRestore.delete(exportedId);
3262
3435
  return;
3263
3436
  }
3264
3437
  if (exportedId.startsWith("mqtt.")) {
@@ -3274,28 +3447,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3274
3447
  this.pendingRestore.delete(exportedId);
3275
3448
  if (this.hapAccessoryRecords.get(exportedId)?.published)
3276
3449
  return;
3277
- const composite = this.getCompositeCandidate(exportedId);
3278
- const isMulti = composite?.deviceId ? this.isMultiSwitchDevice(composite.deviceId) : false;
3279
- const pinnedMulti = composite?.deviceId ? this.nodeIdentities.get(`mode:${composite.deviceId}`) === "multi" : false;
3280
- if (composite && !isMulti && !pinnedMulti) {
3281
- try {
3282
- await this.activateComposite(exportedId);
3283
- this.exportedDevices.add(this.compositeStorageKey(composite.deviceId));
3284
- composite.members.forEach((member) => this.exportedDevices.delete(member.entityId));
3285
- migratedLegacyEntries = true;
3286
- }
3287
- catch (error) {
3288
- if (!this.isCompositeNodeCreationFailure(error))
3289
- throw error;
3290
- await this.restoreCompositeAsPrimary(exportedId, composite.deviceId);
3291
- migratedLegacyEntries = true;
3292
- }
3293
- }
3294
- else {
3295
- await this.activateEntity(exportedId);
3296
- }
3450
+ // Entity-keyed exports retain their original Matter identity.
3451
+ await this.activateEntity(exportedId);
3297
3452
  }
3298
3453
  catch (err) {
3454
+ this.deferRestore(exportedId);
3299
3455
  this.log.error(`Failed to restore exported device ${exportedId}: ${err}`);
3300
3456
  }
3301
3457
  }));
@@ -3316,14 +3472,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3316
3472
  this.log.error(`Failed to restore HAP camera ${exportedId}: ${err}`);
3317
3473
  }
3318
3474
  }
3319
- if (migratedLegacyEntries)
3320
- await this.saveExportedDevices();
3321
3475
  }
3322
3476
  /**
3323
- * An exported accessory whose HA entity is not loaded yet (slow integration
3324
- * after a power outage). Its identity stays reserved; it is activated as soon
3325
- * as the entity shows up (see handleEntityStateChange).
3326
- */
3477
+ * An exported accessory whose HA entity is not loaded yet (slow integration
3478
+ * after a power outage). Its identity stays reserved; it is activated as soon
3479
+ * as the entity shows up (see handleEntityStateChange).
3480
+ */
3327
3481
  deferRestore(exportedId) {
3328
3482
  if (!this.pendingRestore.has(exportedId)) {
3329
3483
  this.log.warn(`[Restore] ${exportedId} aún no está disponible en Home Assistant; se reactivará automáticamente cuando aparezca (su vinculación Matter se conserva).`);
@@ -3347,101 +3501,39 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3347
3501
  }, 5_000);
3348
3502
  this.pendingRestoreTimer.unref?.();
3349
3503
  }
3350
- isCompositeNodeCreationFailure(error) {
3351
- return String(error).includes("Matter server node was not created for device");
3352
- }
3353
- /** Keep a working paired accessory when this Matterbridge runtime cannot host a composite node. */
3354
- async restoreCompositeAsPrimary(entityId, deviceId) {
3355
- const candidate = this.getCompositeCandidate(entityId);
3356
- const primaryEntityId = candidate?.config?.primary_entity ??
3357
- candidate?.members.find((member) => member.entityId.startsWith("camera."))
3358
- ?.entityId ??
3359
- candidate?.members.find((member) => member.entityId.startsWith("humidifier."))?.entityId ??
3360
- candidate?.members.find((member) => member.entityId.startsWith("lock."))
3361
- ?.entityId ??
3362
- candidate?.members.find((member) => member.entityId.startsWith("fan."))
3363
- ?.entityId ??
3364
- candidate?.members[0]?.entityId ??
3365
- entityId;
3366
- this.exportedDevices.delete(this.compositeStorageKey(deviceId));
3367
- if (candidate)
3368
- candidate.members.forEach((member) => this.exportedDevices.delete(member.entityId));
3369
- this.exportedDevices.add(primaryEntityId);
3370
- await this.activateEntity(primaryEntityId);
3371
- this.log.warn(`Composite Matter node for device ${deviceId} is unavailable; preserved the existing paired endpoint ${primaryEntityId}.`);
3372
- }
3373
3504
  /**
3374
3505
  * Ensure that an endpoint about to be registered with Matterbridge has no
3375
3506
  * stale, conflicting or duplicate endpoints in MatterbridgePlatform's registry.
3376
3507
  * If another distinct device already claims the same friendly name, disambiguate it.
3377
3508
  */
3378
3509
  async prepareEndpointForRegistration(endpoint, identifier) {
3379
- try {
3380
- // 1. Gather all existing devices registered in MatterbridgePlatform
3381
- const registeredDevices = (typeof this.getDevices === "function"
3382
- ? this.getDevices()
3383
- : []);
3384
- // Find any devices matching uniqueId, deviceName, or serialNumber
3385
- const matchingDevices = registeredDevices.filter((d) => d !== endpoint &&
3386
- (d.uniqueId === endpoint.uniqueId ||
3387
- d.deviceName === endpoint.deviceName ||
3388
- (endpoint.serialNumber && d.serialNumber === endpoint.serialNumber)));
3389
- for (const stale of matchingDevices) {
3390
- this.log.notice(`[Cleanup] Unregistering stale or conflicting Matter endpoint "${stale.deviceName}" (${stale.uniqueId}) before registering ${identifier}`);
3391
- // Matterbridge 3.10.13 owns shutdown/destruction of dependent server
3392
- // nodes in unregisterDevice(). Calling serverNode.close() first races
3393
- // that lifecycle and can leave the old MatterNode registered.
3394
- await this.unregisterDeviceBounded(stale, `stale endpoint for ${identifier}`);
3395
- }
3396
- // Also clean up from matterbridgeDevices map if an old reference lingered
3397
- const inMemoryOld = this.matterbridgeDevices.get(identifier);
3398
- if (inMemoryOld && inMemoryOld !== endpoint) {
3399
- await this.unregisterDeviceBounded(inMemoryOld, `inMemoryOld for ${identifier}`);
3400
- this.matterbridgeDevices.delete(identifier);
3401
- }
3402
- // 2. Preserve pinned identity or disambiguate endpoint.deviceName
3403
- const pinnedName = this.nodeIdentities.get(identifier);
3404
- if (pinnedName) {
3405
- endpoint.deviceName = pinnedName;
3406
- if (this.hasDeviceName(pinnedName)) {
3407
- const existing = this.getDeviceByName(pinnedName);
3408
- if (existing && existing !== endpoint) {
3409
- await this.unregisterDeviceBounded(existing, `lingering pinned name for ${identifier}`);
3410
- }
3411
- }
3412
- }
3413
- else {
3414
- const baseName = endpoint.deviceName || identifier;
3415
- let counter = 1;
3416
- while (this.hasDeviceName(endpoint.deviceName)) {
3417
- const existing = this.getDeviceByName(endpoint.deviceName);
3418
- if (existing) {
3419
- if (existing === endpoint ||
3420
- existing.uniqueId === endpoint.uniqueId ||
3421
- (endpoint.serialNumber && existing.serialNumber === endpoint.serialNumber) ||
3422
- existing.id === endpoint.id) {
3423
- await this.unregisterDeviceBounded(existing, `lingering name for ${identifier}`);
3424
- if (!this.hasDeviceName(endpoint.deviceName))
3425
- break;
3426
- }
3427
- }
3428
- const suffix = ` (${counter++})`;
3429
- const maxLen = 32 - suffix.length;
3430
- const newName = `${baseName.slice(0, maxLen).trim()}${suffix}`;
3431
- this.log.notice(`Disambiguating duplicate Matter deviceName for ${identifier}: '${endpoint.deviceName}' -> '${newName}'`);
3432
- endpoint.deviceName = newName;
3433
- }
3434
- }
3435
- // 3. Ensure uniqueId is not duplicated
3436
- if (this.hasDeviceUniqueId(endpoint.uniqueId)) {
3437
- const existing = this.getDeviceByUniqueId(endpoint.uniqueId);
3438
- if (existing && existing !== endpoint) {
3439
- await this.unregisterDeviceBounded(existing, `lingering uniqueId for ${identifier}`);
3440
- }
3441
- }
3442
- }
3443
- catch (err) {
3444
- this.log.warn(`[prepareEndpointForRegistration] Non-fatal error during pre-registration cleanup for ${identifier}: ${err}`);
3510
+ if (endpoint.uniqueId && this.unregisterInFlight.has(endpoint.uniqueId)) {
3511
+ throw new Error(`Matter cleanup for ${identifier} is still running; retry when it finishes.`);
3512
+ }
3513
+ const pinnedName = this.nodeIdentities.get(identifier);
3514
+ if (pinnedName)
3515
+ endpoint.deviceName = pinnedName;
3516
+ const registered = typeof this.getDevices === "function"
3517
+ ? this.getDevices()
3518
+ : [];
3519
+ const duplicate = registered.find((item) => item !== endpoint &&
3520
+ item.uniqueId &&
3521
+ item.uniqueId === endpoint.uniqueId);
3522
+ if (duplicate)
3523
+ await this.unregisterDeviceBounded(duplicate, `duplicate identity for ${identifier}`);
3524
+ const ownOld = this.matterbridgeDevices.get(identifier);
3525
+ if (ownOld && ownOld !== endpoint && ownOld !== duplicate) {
3526
+ await this.unregisterDeviceBounded(ownOld, `previous endpoint for ${identifier}`);
3527
+ this.matterbridgeDevices.delete(identifier);
3528
+ }
3529
+ const base = endpoint.deviceName || identifier;
3530
+ if (pinnedName && this.hasDeviceName(pinnedName)) {
3531
+ throw new Error(`Saved Matter identity ${pinnedName} is already in use; refusing to replace another accessory.`);
3532
+ }
3533
+ let counter = 1;
3534
+ while (this.hasDeviceName(endpoint.deviceName)) {
3535
+ const suffix = ` (${counter++})`;
3536
+ endpoint.deviceName = `${base.slice(0, 32 - suffix.length).trim()}${suffix}`;
3445
3537
  }
3446
3538
  }
3447
3539
  async activateComposite(entityId, forceRecreate = false) {
@@ -3467,7 +3559,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3467
3559
  // UNLESS this is an explicit factory reset (forceRecreate = true).
3468
3560
  if (!forceRecreate) {
3469
3561
  const existingEndpoint = this.getDeviceByName(nodeName);
3470
- if (existingEndpoint?.serverNode) {
3562
+ if (existingEndpoint?.serverNode &&
3563
+ existingEndpoint.uniqueId ===
3564
+ `device_${candidate.deviceId}`.substring(0, 32)) {
3471
3565
  const composite = new CompositeDeviceEntity(this, candidate.deviceId, nodeName, candidate.members, candidate.config?.primary_entity);
3472
3566
  composite.adoptEndpoint(existingEndpoint);
3473
3567
  for (const member of candidate.members) {
@@ -3552,8 +3646,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3552
3646
  }
3553
3647
  /** Create a bridged endpoint and let Matterbridge own its lifecycle. */
3554
3648
  async activateEntity(entityId, forceRecreate = false) {
3555
- if (this.matterbridgeDevices.has(entityId) && !forceRecreate)
3556
- return;
3649
+ const mapped = this.matterbridgeDevices.get(entityId);
3650
+ if (mapped && !forceRecreate) {
3651
+ if (!mapped.lifecycle?.isGone && !mapped.serverNode?.lifecycle?.isGone)
3652
+ return;
3653
+ this.matterbridgeDevices.delete(entityId);
3654
+ }
3557
3655
  const entity = this.entities.get(entityId);
3558
3656
  if (!entity)
3559
3657
  throw new Error(`Entity ${entityId} was not discovered.`);
@@ -3568,7 +3666,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3568
3666
  record.state = cameraEntity.state?.state || "idle";
3569
3667
  await this.saveHomeKitCameraRecords();
3570
3668
  this.exportedDevices.add(entityId);
3571
- this.log.notice(`Exported HomeKit standalone camera accessory for ${idn}${entityId}${rs} (port ${record.port}, PIN: ${record.pincode})`);
3669
+ this.log.notice(`Exported HomeKit standalone camera accessory for ${idn}${entityId}${rs} (port ${record.port})`);
3572
3670
  return;
3573
3671
  }
3574
3672
  try {
@@ -3579,7 +3677,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3579
3677
  : endpoint.deviceName
3580
3678
  ? this.getDeviceByName(endpoint.deviceName)
3581
3679
  : undefined;
3582
- if (!forceRecreate && existingEndpoint?.serverNode) {
3680
+ if (!forceRecreate &&
3681
+ existingEndpoint?.serverNode &&
3682
+ !existingEndpoint.lifecycle?.isGone &&
3683
+ !existingEndpoint.serverNode.lifecycle?.isGone) {
3583
3684
  entity.adoptEndpoint(existingEndpoint);
3584
3685
  this.installMatterCommandResponsePolicy(existingEndpoint, entityId);
3585
3686
  this.matterbridgeDevices.set(entityId, existingEndpoint);
@@ -3588,7 +3689,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3588
3689
  await existingEndpoint.serverNode.start();
3589
3690
  }
3590
3691
  catch (err) {
3591
- this.log.error(`Failed to start adopted serverNode for ${entityId}: ${err}`);
3692
+ this.matterbridgeDevices.delete(entityId);
3693
+ throw new Error(`Failed to start existing Matter node for ${entityId}: ${err}`);
3592
3694
  }
3593
3695
  }
3594
3696
  await entity.syncInitialState();
@@ -3604,11 +3706,24 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3604
3706
  }
3605
3707
  await this.prepareEndpointForRegistration(endpoint, entityId);
3606
3708
  await this.registerDevice(endpoint);
3709
+ if (endpoint.lifecycle?.isGone || endpoint.lifecycle?.isReady === false) {
3710
+ throw new Error(`Matter endpoint initialization failed for ${entityId}; refusing to publish a destroyed or unready endpoint.`);
3711
+ }
3607
3712
  // Matterbridge creates the ServerNode during registerDevice(), but nodes
3608
3713
  // added dynamically after the initial startup interval are not started
3609
3714
  // by that interval. Start this node explicitly so its commissionable
3610
3715
  // mDNS record (_matterc._udp) is present before showing its QR code.
3611
- const serverNode = endpoint.serverNode;
3716
+ let serverNode = endpoint.serverNode;
3717
+ if (!serverNode) {
3718
+ const registered = (endpoint.uniqueId &&
3719
+ this.getDeviceByUniqueId?.(endpoint.uniqueId)) ||
3720
+ (endpoint.deviceName &&
3721
+ this.getDeviceByName?.(endpoint.deviceName));
3722
+ if (registered?.serverNode) {
3723
+ serverNode = registered.serverNode;
3724
+ endpoint.serverNode = serverNode;
3725
+ }
3726
+ }
3612
3727
  if (!serverNode) {
3613
3728
  this.log.error(`Matter server node was not created for ${entityId} (deviceName: "${endpoint.deviceName}", uniqueId: "${endpoint.uniqueId}", mode: "${endpoint.mode}").`);
3614
3729
  throw new Error(`Matter server node was not created for ${entityId}.`);
@@ -3616,6 +3731,18 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3616
3731
  if (!serverNode.lifecycle?.isOnline) {
3617
3732
  await serverNode.start();
3618
3733
  }
3734
+ if (serverNode && typeof serverNode.setStateOf === "function") {
3735
+ try {
3736
+ const { BasicInformationServer } = await import("matterbridge/matter/behaviors");
3737
+ await serverNode.setStateOf(BasicInformationServer, {
3738
+ nodeLabel: endpoint.deviceName,
3739
+ productLabel: endpoint.productLabel ?? endpoint.deviceName,
3740
+ });
3741
+ }
3742
+ catch (e) {
3743
+ this.log.debug(`Failed to update basicInformation on serverNode for ${entityId}: ${e}`);
3744
+ }
3745
+ }
3619
3746
  this.matterbridgeDevices.set(entityId, endpoint);
3620
3747
  await entity.syncInitialState();
3621
3748
  if (isUnavailable(entity.state)) {
@@ -3671,6 +3798,18 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3671
3798
  if (!serverNode.lifecycle?.isOnline) {
3672
3799
  await serverNode.start();
3673
3800
  }
3801
+ if (serverNode && typeof serverNode.setStateOf === "function") {
3802
+ try {
3803
+ const { BasicInformationServer } = await import("matterbridge/matter/behaviors");
3804
+ await serverNode.setStateOf(BasicInformationServer, {
3805
+ nodeLabel: endpoint.deviceName,
3806
+ productLabel: endpoint.productLabel ?? endpoint.deviceName,
3807
+ });
3808
+ }
3809
+ catch (e) {
3810
+ this.log.debug(`Failed to update basicInformation on serverNode for ${entityId}: ${e}`);
3811
+ }
3812
+ }
3674
3813
  this.matterbridgeDevices.set(entityId, endpoint);
3675
3814
  await entity.syncInitialState();
3676
3815
  this.log.notice(`Exported bridged MQTT endpoint ${idn}${entityId}${rs}`);
@@ -3731,11 +3870,13 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3731
3870
  this.nodeIdentities.pin(`mode:${deviceId}`, isMultiSwitch ? "multi" : "composite");
3732
3871
  if (isMultiSwitch && deviceId) {
3733
3872
  const compKey = this.compositeStorageKey(deviceId);
3734
- if (this.exportedDevices.has(compKey)) {
3735
- this.log.notice(`[MultiSwitch] Migrating device ${deviceId} from composite to independent export for ${entityId}`);
3736
- this.exportedDevices.delete(compKey);
3873
+ if (this.exportedDevices.has(compKey) ||
3874
+ this.compositeDevices.has(deviceId)) {
3875
+ return {
3876
+ success: false,
3877
+ error: "El dispositivo ya tiene un accesorio compuesto. Se conserva su vinculación existente.",
3878
+ };
3737
3879
  }
3738
- await this.disposeCompositeNode(deviceId);
3739
3880
  }
3740
3881
  try {
3741
3882
  const composite = isMultiSwitch
@@ -3788,96 +3929,153 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3788
3929
  * Manually unregister an Accessory and save to config.
3789
3930
  */
3790
3931
  async manualUnregister(entityId) {
3932
+ const previousSelection = new Set(this.exportedDevices);
3933
+ const affectedSelections = new Set([entityId]);
3934
+ const candidateDeviceId = this.compositeMembership.get(entityId) ??
3935
+ this.getCompositeCandidate(entityId)?.deviceId;
3936
+ if (candidateDeviceId) {
3937
+ affectedSelections.add(this.compositeStorageKey(candidateDeviceId));
3938
+ for (const member of this.getCompositeCandidate(entityId)?.members ?? [])
3939
+ affectedSelections.add(member.entityId);
3940
+ }
3791
3941
  try {
3792
- if (entityId.startsWith("mqtt.")) {
3793
- this.exportedDevices.delete(entityId);
3794
- const endpoint = this.matterbridgeDevices.get(entityId);
3795
- if (endpoint) {
3796
- await this.unregisterDeviceBounded(endpoint, `manual MQTT unregister ${entityId}`);
3797
- this.matterbridgeDevices.delete(entityId);
3798
- }
3799
- await this.saveExportedDevices();
3800
- this.log.notice(`Manually unregistered MQTT endpoint ${entityId}`);
3801
- return { success: true };
3802
- }
3803
3942
  if (entityId.startsWith("camera.")) {
3804
- this.exportedDevices.delete(entityId);
3805
- const cameraEntity = this.entities.get(entityId);
3806
- if (cameraEntity?.homekitAccessory) {
3807
- await cameraEntity.homekitAccessory.unpublish();
3808
- }
3943
+ const camera = this.entities.get(entityId);
3944
+ if (camera?.homekitAccessory)
3945
+ await camera.homekitAccessory.unpublish();
3809
3946
  const record = this.homekitCameraRecords.get(entityId);
3810
3947
  if (record) {
3811
3948
  record.published = false;
3812
3949
  await this.saveHomeKitCameraRecords();
3813
3950
  }
3814
- await this.saveExportedDevices();
3815
- this.log.notice(`Manually unregistered HomeKit camera ${entityId}`);
3816
- return { success: true };
3817
3951
  }
3818
- const compositeDeviceId = this.compositeMembership.get(entityId) ??
3819
- this.getCompositeCandidate(entityId)?.deviceId;
3820
- if (compositeDeviceId) {
3821
- const key = this.compositeStorageKey(compositeDeviceId);
3822
- this.exportedDevices.delete(key);
3823
- const candidate = this.getCompositeCandidate(entityId);
3824
- candidate?.members.forEach((member) => this.exportedDevices.delete(member.entityId));
3825
- // Persist the requested state before waiting for Matterbridge teardown.
3826
- // A stale controller session must not leave the UI permanently active.
3827
- await this.saveExportedDevices();
3828
- // A reconnect can reuse a Matterbridge-owned node before this process
3829
- // has a CompositeDeviceEntity wrapper for it. It still needs teardown,
3830
- // but disposal is bounded so the toggle can recover.
3831
- await this.disposeCompositeNode(compositeDeviceId);
3832
- return { success: true };
3952
+ else if (!entityId.startsWith("mqtt.")) {
3953
+ const deviceId = this.compositeMembership.get(entityId) ??
3954
+ this.getCompositeCandidate(entityId)?.deviceId;
3955
+ if (deviceId) {
3956
+ const candidate = this.getCompositeCandidate(entityId);
3957
+ await this.disposeCompositeNode(deviceId);
3958
+ this.exportedDevices.delete(this.compositeStorageKey(deviceId));
3959
+ candidate?.members.forEach((member) => this.exportedDevices.delete(member.entityId));
3960
+ }
3961
+ else {
3962
+ const endpoint = this.matterbridgeDevices.get(entityId);
3963
+ if (endpoint)
3964
+ await this.unregisterDeviceBounded(endpoint, `manual unregister ${entityId}`);
3965
+ this.matterbridgeDevices.delete(entityId);
3966
+ }
3833
3967
  }
3834
- this.exportedDevices.delete(entityId);
3835
- const endpoint = this.matterbridgeDevices.get(entityId);
3836
- if (endpoint) {
3837
- // Matterbridge 3.10.13 stops and destroys the dependent MatterNode as
3838
- // part of unregisterDevice(); don't close its ServerNode separately.
3839
- await this.unregisterDeviceBounded(endpoint, `manual unregister ${entityId}`);
3968
+ else {
3969
+ const endpoint = this.matterbridgeDevices.get(entityId);
3970
+ if (endpoint)
3971
+ await this.unregisterDeviceBounded(endpoint, `manual MQTT unregister ${entityId}`);
3840
3972
  this.matterbridgeDevices.delete(entityId);
3841
3973
  }
3974
+ this.exportedDevices.delete(entityId);
3842
3975
  await this.saveExportedDevices();
3843
- this.log.notice(`Removed bridged endpoint for ${entityId}`);
3844
3976
  return { success: true };
3845
3977
  }
3846
- catch (err) {
3847
- this.log.error(`Failed to manually unregister ${entityId}: ${err}`);
3848
- this.recordEntityDiagnostic(entityId, `No se pudo retirar el accesorio: ${String(err)}`);
3849
- return { success: false, error: String(err) };
3978
+ catch (error) {
3979
+ for (const entry of affectedSelections) {
3980
+ if (previousSelection.has(entry))
3981
+ this.exportedDevices.add(entry);
3982
+ else
3983
+ this.exportedDevices.delete(entry);
3984
+ }
3985
+ if (!this.matterbridgeDevices.has(entityId) &&
3986
+ previousSelection.has(entityId)) {
3987
+ this.deferRestore(entityId);
3988
+ this.schedulePendingRestore(entityId);
3989
+ }
3990
+ this.log.error(`Failed to manually unregister ${entityId}: ${error}`);
3991
+ return { success: false, error: String(error) };
3850
3992
  }
3851
3993
  }
3852
3994
  /**
3853
3995
  * Matterbridge can leave unregisterDevice pending while a controller has just
3854
3996
  * removed its fabric. Do not leave the UI toggle blocked behind that cleanup.
3855
3997
  */
3856
- async unregisterDeviceBounded(endpoint, context) {
3857
- let completed = false;
3858
- const operation = this.unregisterDevice(endpoint)
3859
- .catch((error) => {
3860
- this.log.warn(`[Matter] ${context}: unregister failed: ${error}`);
3861
- })
3862
- .finally(() => {
3863
- completed = true;
3864
- });
3865
- await Promise.race([
3866
- operation,
3867
- new Promise((resolve) => setTimeout(resolve, 5000)),
3868
- ]);
3869
- if (!completed) {
3870
- this.log.warn(`[Matter] ${context}: unregister is still cleaning up; export state was removed.`);
3998
+ async unregisterDeviceBounded(endpoint, context, timeoutMs = 5000) {
3999
+ const identity = String(endpoint.uniqueId || endpoint.id || context);
4000
+ let operation = this.unregisterInFlight.get(identity);
4001
+ if (!operation) {
4002
+ operation = this.unregisterDevice(endpoint);
4003
+ this.unregisterInFlight.set(identity, operation);
4004
+ const current = operation;
4005
+ void operation.then(() => {
4006
+ if (this.unregisterTimedOut.delete(identity))
4007
+ this.reconcileLateUnregister(endpoint, context);
4008
+ if (this.unregisterInFlight.get(identity) === current)
4009
+ this.unregisterInFlight.delete(identity);
4010
+ }, () => {
4011
+ this.unregisterTimedOut.delete(identity);
4012
+ if (this.unregisterInFlight.get(identity) === current)
4013
+ this.unregisterInFlight.delete(identity);
4014
+ });
4015
+ }
4016
+ let timer;
4017
+ try {
4018
+ await Promise.race([
4019
+ operation,
4020
+ new Promise((_, reject) => {
4021
+ timer = setTimeout(() => {
4022
+ this.unregisterTimedOut.add(identity);
4023
+ reject(new Error(`${context}: cleanup is still running`));
4024
+ }, timeoutMs);
4025
+ }),
4026
+ ]);
4027
+ }
4028
+ finally {
4029
+ if (timer)
4030
+ clearTimeout(timer);
3871
4031
  }
3872
4032
  }
4033
+ /** Reconcile a successful Matter cleanup that finished after its UI timeout. */
4034
+ reconcileLateUnregister(endpoint, context) {
4035
+ const affected = Array.from(this.matterbridgeDevices.entries())
4036
+ .filter(([, registered]) => registered === endpoint)
4037
+ .map(([key]) => key);
4038
+ for (const key of affected) {
4039
+ this.matterbridgeDevices.delete(key);
4040
+ if (key.startsWith("device:")) {
4041
+ const deviceId = key.slice("device:".length);
4042
+ const composite = this.compositeDevices.get(deviceId);
4043
+ const members = composite?.members.map((member) => member.entityId) ??
4044
+ Array.from(this.compositeMembership.entries())
4045
+ .filter(([, id]) => id === deviceId)
4046
+ .map(([entityId]) => entityId);
4047
+ this.compositeDevices.delete(deviceId);
4048
+ for (const entityId of members) {
4049
+ this.compositeMembership.delete(entityId);
4050
+ this.deferRestore(key);
4051
+ this.schedulePendingRestore(entityId);
4052
+ }
4053
+ }
4054
+ else if (this.exportedDevices.has(key)) {
4055
+ this.deferRestore(key);
4056
+ this.schedulePendingRestore(key);
4057
+ }
4058
+ }
4059
+ this.log.warn(`[Matter] Cleanup completed after timeout (${context}); preserved export selection and queued restoration.`);
4060
+ }
3873
4061
  /** Stop and unregister a composite node while keeping its export selection. */
3874
- async disposeCompositeNode(deviceId) {
4062
+ async disposeCompositeNode(deviceId, closeNode = false) {
3875
4063
  const key = this.compositeStorageKey(deviceId);
3876
4064
  const endpoint = this.matterbridgeDevices.get(key) ||
3877
4065
  this.getDeviceByUniqueId(`device_${deviceId}`) ||
3878
4066
  this.getDeviceById(`device_${deviceId}`);
3879
- if (endpoint)
4067
+ if (endpoint) {
4068
+ if (closeNode && endpoint.serverNode?.lifecycle?.isOnline) {
4069
+ try {
4070
+ await Promise.race([
4071
+ endpoint.serverNode.close(),
4072
+ new Promise((res) => setTimeout(res, 1500)),
4073
+ ]);
4074
+ }
4075
+ catch { }
4076
+ }
3880
4077
  await this.unregisterDeviceBounded(endpoint, `composite ${deviceId}`);
4078
+ }
3881
4079
  this.matterbridgeDevices.delete(key);
3882
4080
  const members = this.compositeDevices.get(deviceId)?.members ??
3883
4081
  Array.from(this.compositeMembership.entries())
@@ -3895,202 +4093,39 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
3895
4093
  async resetMatterAccessory(entityId) {
3896
4094
  const compositeDeviceId = this.compositeMembership.get(entityId) ??
3897
4095
  this.getCompositeCandidate(entityId)?.deviceId;
3898
- let endpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
3899
- if (!endpoint) {
3900
- endpoint =
3901
- (typeof this.getDeviceByUniqueId === "function"
3902
- ? this.getDeviceByUniqueId(entityId.replaceAll(".", "_"))
3903
- : undefined) ||
3904
- (this.entities.get(entityId)?.state?.attributes?.friendly_name &&
3905
- typeof this.getDeviceByName === "function"
3906
- ? this.getDeviceByName(String(this.entities.get(entityId).state.attributes.friendly_name))
3907
- : undefined);
3908
- }
3909
- const serverNode = endpoint?.serverNode;
3910
- const entity = this.entities.get(entityId);
3911
- if (!endpoint && !entity && !compositeDeviceId) {
4096
+ const endpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
4097
+ const node = endpoint?.serverNode;
4098
+ if (!node || typeof node.erase !== "function") {
3912
4099
  return {
3913
4100
  success: false,
3914
- error: "El accesorio Matter no está activo ni se encontró en las entidades descubiertas.",
4101
+ error: "El nodo Matter no está disponible para restablecerse de forma segura. Reconéctalo y vuelve a intentarlo.",
3915
4102
  };
3916
4103
  }
3917
4104
  try {
3918
- const friendlyName = entity?.state?.attributes?.friendly_name ?? entityId;
3919
- const storeId = String(endpoint?.deviceName ?? friendlyName).replace(/[ .]/g, "");
3920
- // 1. In-memory cleanup before stopping the node
3921
- if (serverNode) {
3922
- try {
3923
- if (typeof serverNode.resetStorage === "function") {
3924
- await serverNode.resetStorage();
3925
- }
3926
- }
3927
- catch (e) {
3928
- this.log.debug(`[Reset] ServerNode resetStorage: ${e}`);
3929
- }
3930
- }
3931
- // 2. Shut down and unregister all matching old endpoints across all registries
3932
- if (compositeDeviceId) {
3933
- await this.disposeCompositeNode(compositeDeviceId);
3934
- }
3935
- else {
3936
- const uniqueId = entityId.replaceAll(".", "_");
3937
- const endpointsToUnregister = new Set();
3938
- if (endpoint)
3939
- endpointsToUnregister.add(endpoint);
3940
- const inMem = this.matterbridgeDevices.get(entityId);
3941
- if (inMem)
3942
- endpointsToUnregister.add(inMem);
3943
- if (typeof this.getDevices === "function") {
3944
- for (const d of this.getDevices()) {
3945
- if (d.uniqueId === uniqueId ||
3946
- d.deviceName === endpoint?.deviceName ||
3947
- d.deviceName === friendlyName ||
3948
- d.id === uniqueId) {
3949
- endpointsToUnregister.add(d);
3950
- }
3951
- }
3952
- }
3953
- if (typeof this.getDeviceByUniqueId === "function") {
3954
- const byUid = this.getDeviceByUniqueId(uniqueId);
3955
- if (byUid)
3956
- endpointsToUnregister.add(byUid);
3957
- }
3958
- if (typeof this.getDeviceByName === "function") {
3959
- const byNm1 = endpoint?.deviceName ? this.getDeviceByName(endpoint.deviceName) : undefined;
3960
- if (byNm1)
3961
- endpointsToUnregister.add(byNm1);
3962
- const byNm2 = friendlyName ? this.getDeviceByName(friendlyName) : undefined;
3963
- if (byNm2)
3964
- endpointsToUnregister.add(byNm2);
3965
- }
3966
- for (const ep of endpointsToUnregister) {
3967
- const node = ep?.serverNode;
3968
- if (node?.lifecycle?.isOnline) {
3969
- try {
3970
- await Promise.race([
3971
- node.close(),
3972
- new Promise((res) => setTimeout(res, 2000)),
3973
- ]);
3974
- }
3975
- catch (e) {
3976
- this.log.debug(`[Reset] Error closing serverNode: ${e}`);
3977
- }
3978
- }
3979
- await this.unregisterDeviceBounded(ep, `reset ${entityId}`);
3980
- }
3981
- this.matterbridgeDevices.delete(entityId);
3982
- }
3983
- // 3. Purge all persisted storage folders for this node from disk
3984
- const candidates = [
3985
- this.matterbridge.matterbridgeDirectory,
3986
- path.join(process.env.HOME || "/root", ".matterbridge"),
3987
- "/data/.matterbridge",
3988
- "/data",
3989
- "/root/.matterbridge",
3990
- ].filter(Boolean);
3991
- const possibleIds = new Set([
3992
- storeId,
3993
- String(endpoint?.deviceName ?? "").replace(/[ .]/g, ""),
3994
- String(endpoint?.name ?? "").replace(/[ .]/g, ""),
3995
- String(endpoint?.id ?? "").replace(/[ .]/g, ""),
3996
- String(friendlyName).replace(/[ .]/g, ""),
3997
- entityId.replace(/[ .]/g, ""),
3998
- entityId.replaceAll(".", "_"),
3999
- serverNode?.id,
4000
- ].filter(Boolean));
4001
- if (compositeDeviceId) {
4002
- possibleIds.add(compositeDeviceId.replace(/[ .]/g, ""));
4003
- possibleIds.add(`device_${compositeDeviceId}`);
4004
- }
4005
- for (const baseDir of candidates) {
4006
- const storageDir = path.join(baseDir, "matterstorage");
4007
- if (!fsSync.existsSync(storageDir))
4008
- continue;
4009
- try {
4010
- const dirs = await fs.readdir(storageDir);
4011
- for (const d of dirs) {
4012
- const match = Array.from(possibleIds).some((id) => d.toLowerCase() === id.toLowerCase() ||
4013
- (id.length > 5 && d.toLowerCase().includes(id.toLowerCase())));
4014
- if (match) {
4015
- const fullPath = path.join(storageDir, d);
4016
- await fs.rm(fullPath, { recursive: true, force: true });
4017
- this.log.notice(`[Reset] Purged storage folder: ${fullPath}`);
4018
- }
4019
- }
4020
- }
4021
- catch (err) {
4022
- this.log.debug(`[Reset] Storage scan error for ${storageDir}: ${err}`);
4023
- }
4024
- }
4025
- // 4. Legacy storage service context clear
4026
- const bridgeRuntime = this.matterbridge;
4027
- const managedStorage = bridgeRuntime.serverNodeStorageManagers?.get?.(storeId);
4028
- const storageService = bridgeRuntime.matterStorageService;
4029
- const storageManager = managedStorage ??
4030
- (await storageService?.open?.(storeId).catch(() => undefined));
4031
- if (storageManager) {
4032
- try {
4033
- await storageManager.createContext?.("persist")?.clearAll?.();
4034
- await storageManager.createContext?.("fabrics")?.clearAll?.();
4035
- await storageManager.createContext?.("commissioning")?.clearAll?.();
4036
- await storageManager
4037
- .createContext?.("operationalCredentials")
4038
- ?.clearAll?.();
4039
- }
4040
- catch (e) {
4041
- this.log.debug(`[Reset] Storage context clear error for ${storeId}: ${e}`);
4042
- }
4043
- finally {
4044
- try {
4045
- await storageManager.close?.();
4046
- }
4047
- catch { }
4048
- bridgeRuntime.serverNodeStorageManagers?.delete?.(storeId);
4049
- }
4050
- }
4051
- // Guarantee that any remaining device with the same name/uniqueId in MatterbridgePlatform is evicted before recreate
4052
- if (typeof this.hasDeviceName === "function") {
4053
- for (const nameCandidate of [endpoint?.deviceName, friendlyName].filter(Boolean)) {
4054
- if (this.hasDeviceName(nameCandidate)) {
4055
- const lingering = this.getDeviceByName(nameCandidate);
4056
- if (lingering) {
4057
- await this.unregisterDeviceBounded(lingering, `purge lingering name ${nameCandidate}`);
4058
- }
4059
- }
4060
- }
4061
- }
4062
- if (compositeDeviceId) {
4063
- await this.activateComposite(entityId, true);
4064
- }
4065
- else {
4066
- await this.activateEntity(entityId, true);
4105
+ await node.erase();
4106
+ if (!node.lifecycle?.isOnline)
4107
+ await node.start();
4108
+ let connection = this.getMatterConnectionInfo(endpoint);
4109
+ for (let attempt = 0; attempt < 30 &&
4110
+ (connection.fabricCount !== 0 ||
4111
+ (!connection.pairingCode && !connection.manualPairingCode)); attempt++) {
4112
+ await new Promise((resolve) => setTimeout(resolve, 200));
4113
+ connection = this.getMatterConnectionInfo(endpoint);
4114
+ }
4115
+ if (connection.fabricCount !== 0 ||
4116
+ (!connection.pairingCode && !connection.manualPairingCode)) {
4117
+ throw new Error("El nodo todavía no confirma la eliminación de fabrics y un código de vinculación disponible.");
4067
4118
  }
4068
4119
  this.clearMatterAccessoryProblems(entityId, compositeDeviceId);
4069
- // Actively wait for the new serverNode to come online and return its QR immediately
4070
- const newEndpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
4071
- let connection = newEndpoint
4072
- ? this.getMatterConnectionInfo(newEndpoint)
4073
- : undefined;
4074
- if (!connection?.pairingCode && newEndpoint) {
4075
- for (let attempt = 0; attempt < 30; attempt++) {
4076
- await new Promise((r) => setTimeout(r, 200));
4077
- connection = this.getMatterConnectionInfo(newEndpoint);
4078
- if (connection?.pairingCode)
4079
- break;
4080
- }
4081
- }
4082
- this.log.notice(`Matter factory reset and capability rebuild completed for ${idn}${compositeDeviceId ? `device:${compositeDeviceId}` : entityId}${rs}`);
4083
- this.recordEntityDiagnostic(entityId, `✓ Accesorio desvinculado de todas las casas. Nuevo código QR generado.`, "info");
4084
4120
  this.pushEntityUpdate(entityId);
4085
4121
  return {
4086
4122
  success: true,
4087
- pairingCode: connection?.pairingCode ?? null,
4088
- manualPairingCode: connection?.manualPairingCode ?? null,
4123
+ pairingCode: connection.pairingCode,
4124
+ manualPairingCode: connection.manualPairingCode,
4089
4125
  };
4090
4126
  }
4091
4127
  catch (error) {
4092
- this.log.error(`Failed to factory reset Matter accessory ${entityId}: ${error}`);
4093
- this.recordEntityDiagnostic(entityId, `No se pudo restablecer Matter: ${String(error)}`);
4128
+ this.log.error(`Failed to reset Matter accessory ${entityId}: ${error}`);
4094
4129
  return { success: false, error: String(error) };
4095
4130
  }
4096
4131
  }
@@ -4173,7 +4208,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4173
4208
  cam.identity.homeKitPairingState = "not_paired";
4174
4209
  await ScryptedStorage.save(store);
4175
4210
  }
4176
- this.log.notice(`[ScryptedHomeKit] Reset HomeKit pairing for ${entityId}: New port ${newRecord.port}, setupId ${newRecord.setupId}, URI ${acc.setupUri}`);
4211
+ this.log.notice(`[ScryptedHomeKit] Reset HomeKit pairing for ${entityId}: New port ${newRecord.port}, setupId ${newRecord.setupId} `);
4177
4212
  return {
4178
4213
  success: true,
4179
4214
  record: newRecord,
@@ -4214,7 +4249,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4214
4249
  cam.isPaired = false;
4215
4250
  await CameraUiStorage.save(store);
4216
4251
  }
4217
- this.log.notice(`[CameraUiHomeKit] Reset HomeKit pairing for ${entityId}: New port ${newRecord.port}, setupId ${newRecord.setupId}, URI ${acc.setupUri}`);
4252
+ this.log.notice(`[CameraUiHomeKit] Reset HomeKit pairing for ${entityId}: New port ${newRecord.port}, setupId ${newRecord.setupId} `);
4218
4253
  return {
4219
4254
  success: true,
4220
4255
  record: newRecord,
@@ -4235,7 +4270,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4235
4270
  const newRecord = await cameraEntity.homekitAccessory.resetPairing();
4236
4271
  this.homekitCameraRecords.set(entityId, newRecord);
4237
4272
  await this.saveHomeKitCameraRecords();
4238
- this.log.notice(`Reset HomeKit pairing for ${entityId}: New PIN ${newRecord.pincode}, port ${newRecord.port}, MAC ${newRecord.username}`);
4273
+ this.log.notice(`Reset HomeKit pairing for ${entityId}: port ${newRecord.port}`);
4239
4274
  this.pushEntityUpdate(entityId);
4240
4275
  return {
4241
4276
  success: true,
@@ -4295,10 +4330,6 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4295
4330
  this.getCompositeCandidate(entityId)?.deviceId;
4296
4331
  let endpoint = this.getMatterEndpointForEntity(entityId, compositeDeviceId);
4297
4332
  let serverNode = endpoint?.serverNode;
4298
- if (!serverNode && this.matterbridge?.serverNode) {
4299
- serverNode = this.matterbridge.serverNode;
4300
- endpoint = this.matterbridge;
4301
- }
4302
4333
  if (!endpoint || !serverNode) {
4303
4334
  return {
4304
4335
  success: false,
@@ -4391,18 +4422,16 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4391
4422
  ? liveFabricSource
4392
4423
  : Object.values(liveFabricSource);
4393
4424
  }
4394
- // If only 1 fabric exists or none, removing it is a full reset
4395
- if (rawFabrics.length <= 1) {
4396
- return await this.resetMatterAccessory(entityId);
4397
- }
4398
4425
  const matchedFabric = rawFabrics.find((f) => String(f?.fabricIndex) === targetStr ||
4399
4426
  String(f?.fabricId) === targetStr ||
4400
4427
  Number(f?.fabricIndex) === targetNum);
4401
- const fabricIndex = matchedFabric && matchedFabric.fabricIndex !== undefined
4402
- ? Number(matchedFabric.fabricIndex)
4403
- : targetNum <= 254 && targetNum > 0
4404
- ? targetNum
4405
- : 1;
4428
+ if (!matchedFabric || matchedFabric.fabricIndex === undefined) {
4429
+ return {
4430
+ success: false,
4431
+ error: "No se encontró la fabric solicitada; no se modificaron otras vinculaciones.",
4432
+ };
4433
+ }
4434
+ const fabricIndex = Number(matchedFabric.fabricIndex);
4406
4435
  // 1. Try deleting fabric directly via dynamic import of FabricManager if available
4407
4436
  try {
4408
4437
  const { FabricManager } = (await import("@matter/protocol"));
@@ -4446,8 +4475,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4446
4475
  }
4447
4476
  }
4448
4477
  const connection = this.getMatterConnectionInfo(endpoint);
4449
- if (connection.fabricCount === 0 || !removed) {
4450
- return await this.resetMatterAccessory(entityId);
4478
+ if (!removed ||
4479
+ connection.fabrics.some((fabric) => Number(fabric.fabricIndex) === fabricIndex)) {
4480
+ return {
4481
+ success: false,
4482
+ error: "No se pudo confirmar la eliminación de la fabric solicitada.",
4483
+ };
4451
4484
  }
4452
4485
  const controllerName = matchedFabric
4453
4486
  ? (MATTER_CONTROLLER_VENDORS[matchedFabric.rootNodeId?.vendorId ??
@@ -4468,8 +4501,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4468
4501
  };
4469
4502
  }
4470
4503
  catch (error) {
4471
- this.log.notice(`Resetting Matter accessory ${entityId} on fabric removal: ${error}`);
4472
- return await this.resetMatterAccessory(entityId);
4504
+ this.log.warn(`Failed to remove requested Matter fabric from ${entityId}: ${error}`);
4505
+ return { success: false, error: String(error) };
4473
4506
  }
4474
4507
  }
4475
4508
  /** A successful connection or state sync means the accessory is healthy again. */
@@ -4483,10 +4516,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4483
4516
  }
4484
4517
  async saveExportedDevices() {
4485
4518
  try {
4486
- await fs.writeFile("/data/exported-devices.json", JSON.stringify(Array.from(this.exportedDevices)), "utf8");
4519
+ await this.atomicJsonStore.write("/data/exported-devices.json", Array.from(this.exportedDevices));
4487
4520
  }
4488
4521
  catch (err) {
4489
4522
  this.log.error(`Failed to save exported-devices.json: ${err}`);
4523
+ throw err;
4490
4524
  }
4491
4525
  }
4492
4526
  /** Broadcast an entity state update to all connected SSE clients. */
@@ -4504,6 +4538,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4504
4538
  if (!entity)
4505
4539
  return;
4506
4540
  const payload = JSON.stringify({
4541
+ type: "device_update",
4507
4542
  entityId,
4508
4543
  commissioned: connection?.commissioned ?? false,
4509
4544
  pairingCode: connection?.pairingCode ?? null,
@@ -4559,10 +4594,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4559
4594
  }
4560
4595
  async saveDeviceOverrides() {
4561
4596
  try {
4562
- await fs.writeFile("/data/device-overrides.json", JSON.stringify(this.deviceOverrides, null, 2), "utf8");
4597
+ await this.atomicJsonStore.write("/data/device-overrides.json", this.deviceOverrides);
4563
4598
  }
4564
4599
  catch (err) {
4565
4600
  this.log.error(`Failed to save device-overrides.json: ${err}`);
4601
+ throw err;
4566
4602
  }
4567
4603
  }
4568
4604
  async setDeviceProfile(entityId, profileId) {
@@ -4583,21 +4619,67 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4583
4619
  error: "Auxiliary actions inherit the profile of their main device.",
4584
4620
  };
4585
4621
  }
4622
+ const wasExported = this.exportedDevices.has(entityId);
4623
+ const state = entity.state;
4624
+ const previousOverride = this.deviceOverrides[entityId];
4625
+ let profilePersisted = false;
4626
+ let previousEndpointRemoved = false;
4586
4627
  try {
4587
- const wasExported = this.exportedDevices.has(entityId);
4588
- const state = entity.state;
4589
- if (wasExported)
4590
- await this.manualUnregister(entityId);
4628
+ if (wasExported) {
4629
+ const removal = await this.manualUnregister(entityId);
4630
+ if (!removal.success)
4631
+ throw new Error(removal.error || "Unable to remove the previous profile.");
4632
+ previousEndpointRemoved = true;
4633
+ }
4591
4634
  this.deviceOverrides[entityId] = profileId;
4592
- await this.saveDeviceOverrides();
4635
+ try {
4636
+ await this.saveDeviceOverrides();
4637
+ profilePersisted = true;
4638
+ }
4639
+ catch (error) {
4640
+ if (previousOverride === undefined)
4641
+ delete this.deviceOverrides[entityId];
4642
+ else
4643
+ this.deviceOverrides[entityId] = previousOverride;
4644
+ throw error;
4645
+ }
4593
4646
  this.entities.delete(entityId);
4594
4647
  this.matterbridgeDevices.delete(entityId);
4595
4648
  await this.registerHAEntity(state);
4596
- if (wasExported)
4597
- await this.manualRegister(entityId);
4649
+ if (wasExported) {
4650
+ const registration = await this.manualRegister(entityId);
4651
+ if (!registration.success)
4652
+ throw new Error(registration.error || "Unable to publish the new profile.");
4653
+ }
4598
4654
  return { success: true };
4599
4655
  }
4600
4656
  catch (error) {
4657
+ if (profilePersisted || previousEndpointRemoved) {
4658
+ try {
4659
+ if (previousOverride === undefined)
4660
+ delete this.deviceOverrides[entityId];
4661
+ else
4662
+ this.deviceOverrides[entityId] = previousOverride;
4663
+ try {
4664
+ await this.saveDeviceOverrides();
4665
+ }
4666
+ catch (saveError) {
4667
+ this.log.error(`Could not persist profile rollback for ${entityId}: ${saveError}`);
4668
+ }
4669
+ this.entities.delete(entityId);
4670
+ await this.registerHAEntity(state);
4671
+ if (wasExported && !this.exportedDevices.has(entityId)) {
4672
+ const restored = await this.manualRegister(entityId);
4673
+ if (!restored.success)
4674
+ throw new Error(restored.error || "previous profile could not be re-exported");
4675
+ }
4676
+ }
4677
+ catch (rollbackError) {
4678
+ this.log.error(`Failed to restore previous profile for ${entityId}: ${rollbackError}`);
4679
+ this.deferRestore(entityId);
4680
+ this.schedulePendingRestore(entityId);
4681
+ }
4682
+ }
4601
4683
  this.log.error(`Failed to update Matter profile for ${entityId}: ${error}`);
4602
4684
  this.recordEntityDiagnostic(entityId, `No se pudo actualizar el perfil Matter: ${String(error)}`);
4603
4685
  return { success: false, error: String(error) };
@@ -4608,7 +4690,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4608
4690
  if (!entityId.startsWith("binary_sensor."))
4609
4691
  return;
4610
4692
  const isActive = state.state === "on";
4611
- for (const [cameraId, accessory] of CameraUiHomeKitBridge.getAllAccessories()) {
4693
+ for (const [cameraId, accessory,] of CameraUiHomeKitBridge.getAllAccessories()) {
4612
4694
  if (accessory?.linkedMotionEntityId !== entityId)
4613
4695
  continue;
4614
4696
  this.log.notice(`[Camera.UI][HAP] Movimiento (${isActive ? "DETECTADO" : "REPOSO"}) desde ${entityId} para ${accessory.record?.name || cameraId}`);
@@ -4663,7 +4745,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4663
4745
  continue;
4664
4746
  if (/_segment_\d+$/i.test(id) || /_segment_/i.test(id))
4665
4747
  continue;
4666
- const matchesPrefix = entityId.startsWith(id + "_segment_") || entityId.startsWith(id + "_");
4748
+ const matchesPrefix = entityId.startsWith(id + "_segment_") ||
4749
+ entityId.startsWith(id + "_");
4667
4750
  const sameDevice = deviceId &&
4668
4751
  this.ha?.hassEntities?.get(id)?.device_id === deviceId;
4669
4752
  if ((matchesPrefix || sameDevice) && this.isEntityExported(id)) {
@@ -4675,17 +4758,19 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4675
4758
  entityId.startsWith("event.")) {
4676
4759
  const isEvent = entityId.startsWith("event.");
4677
4760
  const isMotionState = isEvent
4678
- ? !["unavailable", "unknown", ""].includes(String(newState.state || "").trim().toLowerCase())
4761
+ ? !["unavailable", "unknown", ""].includes(String(newState.state || "")
4762
+ .trim()
4763
+ .toLowerCase())
4679
4764
  : newState.state === "on";
4680
4765
  const devState = this.ha?.hassStates?.get(entityId);
4681
- const entityFriendlyName = devState?.attributes?.friendly_name || "";
4766
+ const entityFriendlyName = getHaEntitySearchText(this.ha, entityId);
4682
4767
  const deviceClass = (devState?.attributes?.device_class || "").toLowerCase();
4683
4768
  const isMotionClass = isEvent ||
4684
4769
  ["motion", "occupancy", "presence"].includes(deviceClass) ||
4685
4770
  /motion|movimiento|celda|vehicle|vehiculo|car|auto|person|persona|animal|pet|mascota|detection|deteccion|occupancy|presence|line_crossing|tamper/i.test(`${entityId} ${entityFriendlyName}`);
4686
4771
  for (const cam of this.entities.values()) {
4687
4772
  if (cam instanceof CameraEntity && cam.homekitAccessory) {
4688
- const camFriendlyName = cam.state?.attributes?.friendly_name || "";
4773
+ const camFriendlyName = getHaEntitySearchText(this.ha, cam.entityId);
4689
4774
  const isTapoC402Entity = /tapo[-_ ]?c402|frente[-_ ]?de[-_ ]?calle|tapo[-_ ]?frente|\bc402\b/i.test(`${entityId} ${entityFriendlyName}`);
4690
4775
  const isTapoC402Cam = /tapo[-_ ]?c402|frente[-_ ]?de[-_ ]?calle|tapo[-_ ]?frente|\bc402\b/i.test(`${cam.entityId} ${camFriendlyName}`);
4691
4776
  const isC402Match = isTapoC402Entity && isTapoC402Cam && isMotionClass;
@@ -4781,7 +4866,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4781
4866
  (sameDevice && isMotionClass) ||
4782
4867
  isC402Match ||
4783
4868
  isC120Match ||
4784
- (isTapoC120Cam && (isTapoC120Entity || sameDevice || linkedId === entityId) && isMotionClass) ||
4869
+ (isTapoC120Cam &&
4870
+ (isTapoC120Entity || sameDevice || linkedId === entityId) &&
4871
+ isMotionClass) ||
4785
4872
  isWyzeMatch ||
4786
4873
  isEzvizMatch ||
4787
4874
  isVimtagMatch ||
@@ -4842,13 +4929,16 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4842
4929
  }
4843
4930
  }
4844
4931
  }
4845
- if (entityId.startsWith("select.")) {
4846
- const deviceId = this.ha.hassEntities.get(entityId)?.device_id;
4932
+ if (entityId.startsWith("select.") ||
4933
+ entityId.startsWith("sensor.") ||
4934
+ entityId.startsWith("binary_sensor.") ||
4935
+ entityId.startsWith("button.")) {
4936
+ const deviceId = this.ha?.hassEntities?.get(entityId)?.device_id;
4847
4937
  for (const [vId, vEntity] of this.entities.entries()) {
4848
4938
  if (vId.startsWith("vacuum.") &&
4849
4939
  vEntity instanceof VacuumEntity &&
4850
4940
  this.isEntityExported(vId)) {
4851
- const vDeviceId = this.ha.hassEntities.get(vId)?.device_id;
4941
+ const vDeviceId = this.ha?.hassEntities?.get(vId)?.device_id;
4852
4942
  if ((deviceId && vDeviceId === deviceId) ||
4853
4943
  entityId.includes(vId.split(".")[1])) {
4854
4944
  this.queueStateUpdate(vId, vEntity.state);
@@ -4889,24 +4979,31 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4889
4979
  }
4890
4980
  })());
4891
4981
  }
4892
- // Sync individual entities
4893
- for (const [entityId, entity] of this.entities.entries()) {
4894
- if (!this.isEntityExported(entityId))
4895
- continue;
4896
- if (this.compositeMembership.has(entityId))
4897
- continue; // handled above
4898
- tasks.push((async () => {
4899
- try {
4900
- if (!isUnavailable(entity.state) &&
4901
- !entity.hasCommandCommunicationFailure) {
4902
- await entity.setReachability?.(true);
4982
+ // Sync individual entities; index only while scheduling this synchronous loop.
4983
+ this.buildInventoryIndex();
4984
+ try {
4985
+ for (const [entityId, entity] of this.entities.entries()) {
4986
+ if (!this.isEntityExported(entityId))
4987
+ continue;
4988
+ if (this.compositeMembership.has(entityId))
4989
+ continue; // handled above
4990
+ tasks.push((async () => {
4991
+ try {
4992
+ if (!isUnavailable(entity.state) &&
4993
+ !entity.hasCommandCommunicationFailure) {
4994
+ await entity.setReachability?.(true);
4995
+ }
4996
+ await entity.forceSyncStateToMatter?.();
4903
4997
  }
4904
- await entity.forceSyncStateToMatter?.();
4905
- }
4906
- catch (err) {
4907
- this.log.debug(`[forceSyncAllEntities] entity ${entityId}: ${err}`);
4908
- }
4909
- })());
4998
+ catch (err) {
4999
+ this.log.debug(`[forceSyncAllEntities] entity ${entityId}: ${err}`);
5000
+ }
5001
+ })());
5002
+ }
5003
+ }
5004
+ finally {
5005
+ this.inventoryMembers = undefined;
5006
+ this.inventoryRegistry = undefined;
4910
5007
  }
4911
5008
  await Promise.allSettled(tasks);
4912
5009
  this.log.notice(`[forceSyncAllEntities] Resync completo: ${tasks.length} entidades/composites actualizados en Matter.`);
@@ -4927,6 +5024,22 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4927
5024
  const updates = [...this.pendingStateUpdates.entries()];
4928
5025
  this.pendingStateUpdates.clear();
4929
5026
  const results = await Promise.allSettled(updates.map(async ([entityId, state]) => {
5027
+ // A vacuum's battery and charging status can be separate HA entities.
5028
+ // Refresh the RVC endpoint when a sensor on the same device changes.
5029
+ if (entityId.startsWith("sensor.")) {
5030
+ const deviceId = this.ha?.hassEntities?.get(entityId)?.device_id;
5031
+ if (deviceId) {
5032
+ for (const [vacuumId, vacuum] of this.entities) {
5033
+ if (vacuumId.startsWith("vacuum.") &&
5034
+ this.isEntityExported(vacuumId) &&
5035
+ this.ha?.hassEntities?.get(vacuumId)?.device_id === deviceId) {
5036
+ const current = this.ha?.hassStates?.get(vacuumId) ?? vacuum.state;
5037
+ if (current)
5038
+ this.queueStateUpdate(vacuumId, current);
5039
+ }
5040
+ }
5041
+ }
5042
+ }
4930
5043
  const compositeDeviceId = this.compositeMembership.get(entityId);
4931
5044
  if (compositeDeviceId) {
4932
5045
  const composite = this.compositeDevices.get(compositeDeviceId);
@@ -4941,7 +5054,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4941
5054
  const entity = this.entities.get(entityId);
4942
5055
  if (entity && this.isEntityExported(entityId)) {
4943
5056
  await entity.updateState(state);
4944
- if (!isUnavailable(state) && !entity.hasCommandCommunicationFailure) {
5057
+ if (!isUnavailable(state) &&
5058
+ !entity.hasCommandCommunicationFailure) {
4945
5059
  this.clearEntityProblem(entityId);
4946
5060
  }
4947
5061
  }
@@ -4949,7 +5063,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4949
5063
  // only its primary entity. Forward changes from every discovered
4950
5064
  // member so its real sensors stay current in Apple Home.
4951
5065
  for (const hapAcc of this.hapAccessories.values()) {
4952
- if (hapAcc.entityId !== entityId && hapAcc.handlesEntityId(entityId)) {
5066
+ if (hapAcc.entityId !== entityId &&
5067
+ hapAcc.handlesEntityId(entityId)) {
4953
5068
  hapAcc.updateFromHassState(state, entityId);
4954
5069
  }
4955
5070
  }
@@ -4982,6 +5097,30 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
4982
5097
  /**
4983
5098
  * Start custom HTTP server on port 8285 for Liquid Glass UI.
4984
5099
  */
5100
+ getReadOnlyCameraDiagnostics() {
5101
+ const cameras = [...this.entities.values()]
5102
+ .filter((entity) => entity instanceof CameraEntity)
5103
+ .map((camera) => {
5104
+ const record = this.homekitCameraRecords.get(camera.entityId);
5105
+ const accessory = camera.homekitAccessory;
5106
+ const telemetry = accessory?.getLiveViewTelemetry();
5107
+ return buildCameraAiDiagnostics({
5108
+ entityId: camera.entityId,
5109
+ sourceType: camera.streamSource?.sourceType,
5110
+ available: !isUnavailable(camera.state),
5111
+ hapPublished: accessory?.isPublished ?? false,
5112
+ hapPaired: accessory?.isPaired() ?? record?.isPaired ?? false,
5113
+ motionEntityId: accessory?.linkedMotionEntityId,
5114
+ audioAvailable: camera.capabilities?.hasAudio ?? false,
5115
+ hksvState: record?.hksvState,
5116
+ hksvVerified: record?.hksvVerified ?? false,
5117
+ activeLiveView: telemetry?.active ?? [],
5118
+ recentLiveView: telemetry?.recent ?? [],
5119
+ omniAllocation: this.ha?.getOmniCameraAllocationMetrics(camera.entityId)[0],
5120
+ });
5121
+ });
5122
+ return { generatedAt: new Date().toISOString(), cameras };
5123
+ }
4985
5124
  startUiServer() {
4986
5125
  const server = http.createServer(async (req, res) => {
4987
5126
  const urlObj = new URL(req.url ?? "", `http://${req.headers.host ?? "localhost"}`);
@@ -5015,7 +5154,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5015
5154
  }
5016
5155
  this.log.debug(`[UI Server] ${req.method} ${pathname} (raw: ${urlObj.pathname})`);
5017
5156
  const adminToken = process.env.MATTER_AIO_ADMIN_TOKEN;
5018
- if (req.method === "POST" &&
5157
+ if (["POST", "PUT", "PATCH", "DELETE"].includes(req.method ?? "") &&
5019
5158
  adminToken &&
5020
5159
  req.headers["x-matter-aio-token"] !== adminToken) {
5021
5160
  res.writeHead(403, {
@@ -5025,6 +5164,35 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5025
5164
  return;
5026
5165
  }
5027
5166
  try {
5167
+ // An opt-in, read-only integration point for an external MCP adapter.
5168
+ // No diagnostics API is available until a dedicated secret is configured.
5169
+ if (pathname === "/api/custom/ai/camera-diagnostics") {
5170
+ if (req.method !== "GET") {
5171
+ res.writeHead(405, { Allow: "GET" });
5172
+ res.end();
5173
+ return;
5174
+ }
5175
+ const secret = process.env.MATTER_AIO_DIAGNOSTICS_TOKEN;
5176
+ if (!secret || secret.length < 24) {
5177
+ res.writeHead(404);
5178
+ res.end();
5179
+ return;
5180
+ }
5181
+ if (!isCameraDiagnosticsAuthorized(secret, req.headers.authorization)) {
5182
+ res.writeHead(401, {
5183
+ "Content-Type": "application/json",
5184
+ "Cache-Control": "no-store",
5185
+ });
5186
+ res.end(JSON.stringify({ error: "Unauthorized" }));
5187
+ return;
5188
+ }
5189
+ res.writeHead(200, {
5190
+ "Content-Type": "application/json; charset=utf-8",
5191
+ "Cache-Control": "no-store",
5192
+ });
5193
+ res.end(JSON.stringify(this.getReadOnlyCameraDiagnostics()));
5194
+ return;
5195
+ }
5028
5196
  if (req.method === "GET" &&
5029
5197
  (pathname === "/" || pathname === "/index.html")) {
5030
5198
  let content = await this.readFrontendFile("index.html");
@@ -5247,7 +5415,9 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5247
5415
  const state = this.ha.hassStates?.get(entityId);
5248
5416
  this.ptzManager.registerCamera(entityId, state, cam.rtspUrl);
5249
5417
  }
5250
- const cameras = this.ptzManager.getAllPtzCameras().filter((c) => c.hasPtz);
5418
+ const cameras = this.ptzManager
5419
+ .getAllPtzCameras()
5420
+ .filter((c) => c.hasPtz);
5251
5421
  res.writeHead(200, {
5252
5422
  "Content-Type": "application/json; charset=utf-8",
5253
5423
  });
@@ -5265,7 +5435,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5265
5435
  const cmd = JSON.parse(bodyStr || "{}");
5266
5436
  this.log.info(`[HTTP] PTZ command for ${entityId}: ${JSON.stringify(cmd)}`);
5267
5437
  let result = { success: true };
5268
- if (cmd.command === "move_to_preset" || cmd.command === "set_zone_active") {
5438
+ if (cmd.command === "move_to_preset" ||
5439
+ cmd.command === "set_zone_active") {
5269
5440
  const zoneId = Number(cmd.preset_id || cmd.zone_id || cmd.preset || 1);
5270
5441
  result = await this.ptzManager.setActiveZone(entityId, zoneId);
5271
5442
  }
@@ -5284,10 +5455,15 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5284
5455
  speed: 5,
5285
5456
  });
5286
5457
  }
5287
- else if (lowerId.includes("vimtag") || lowerId.includes("onvif")) {
5458
+ else if (lowerId.includes("vimtag") ||
5459
+ lowerId.includes("onvif")) {
5288
5460
  await this.ha.callService("onvif", "ptz", entityId, {
5289
5461
  tilt: dir === "up" ? "UP" : dir === "down" ? "DOWN" : "HOME",
5290
- pan: dir === "left" ? "LEFT" : dir === "right" ? "RIGHT" : "HOME",
5462
+ pan: dir === "left"
5463
+ ? "LEFT"
5464
+ : dir === "right"
5465
+ ? "RIGHT"
5466
+ : "HOME",
5291
5467
  distance: cmd.step || 0.1,
5292
5468
  speed: 0.5,
5293
5469
  });
@@ -5322,10 +5498,15 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5322
5498
  speed: 5,
5323
5499
  });
5324
5500
  }
5325
- else if (lowerId.includes("vimtag") || lowerId.includes("onvif")) {
5501
+ else if (lowerId.includes("vimtag") ||
5502
+ lowerId.includes("onvif")) {
5326
5503
  await this.ha.callService("onvif", "ptz", entityId, {
5327
5504
  tilt: dir === "up" ? "UP" : dir === "down" ? "DOWN" : "HOME",
5328
- pan: dir === "left" ? "LEFT" : dir === "right" ? "RIGHT" : "HOME",
5505
+ pan: dir === "left"
5506
+ ? "LEFT"
5507
+ : dir === "right"
5508
+ ? "RIGHT"
5509
+ : "HOME",
5329
5510
  distance: step,
5330
5511
  speed: 0.5,
5331
5512
  });
@@ -5437,6 +5618,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5437
5618
  if (req.method === "GET" && pathname === "/api/custom/devices") {
5438
5619
  try {
5439
5620
  await this.refreshDiscoveryCatalog();
5621
+ this.buildInventoryIndex();
5440
5622
  const errorPattern = /\b(error|warn|warning|failed|failure|exception|unable|timeout)\b/i;
5441
5623
  const allErrorLogs = getLogs().filter((line) => errorPattern.test(line));
5442
5624
  const homeLocation = this.ha?.hassConfig?.location_name || null;
@@ -5477,6 +5659,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5477
5659
  media_player: "Speaker",
5478
5660
  sensor: "Sensor",
5479
5661
  binary_sensor: "BinarySensor",
5662
+ select: "Selector",
5663
+ button: "Button",
5480
5664
  };
5481
5665
  const typeLabel = e.constructor.matterTypeLabel ||
5482
5666
  domainLabels[domain] ||
@@ -5491,7 +5675,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5491
5675
  name: friendlyName,
5492
5676
  domain: domain,
5493
5677
  state: e.state.state,
5494
- attributes: { friendly_name: friendlyName, ...e.state.attributes },
5678
+ attributes: {
5679
+ friendly_name: friendlyName,
5680
+ ...e.state.attributes,
5681
+ },
5495
5682
  deviceTypeLabel: typeLabel,
5496
5683
  matterType: domain === "fan"
5497
5684
  ? "fan"
@@ -5522,7 +5709,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5522
5709
  matterFabrics: connection.fabrics,
5523
5710
  // Detect issues strictly on exported accessories (connection drops, unavailable state, active problems)
5524
5711
  hasIssue: this.isEntityExported(e.entityId) &&
5525
- (this.entityProblems.has(e.entityId) || isUnavailable(e.state)),
5712
+ (this.entityProblems.has(e.entityId) ||
5713
+ isUnavailable(e.state)),
5526
5714
  diagnostics: this.entityDiagnostics.get(e.entityId) ?? [],
5527
5715
  nodeDiagnostics: {
5528
5716
  pinnedName: this.nodeIdentities.get(compositeDeviceId
@@ -5554,8 +5742,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5554
5742
  ? "waiting_hub"
5555
5743
  : "configurable"
5556
5744
  : "not_capable");
5557
- const linkedMotion = e.homekitAccessory
5558
- ?.linkedMotionEntityId;
5745
+ const linkedMotion = e
5746
+ .homekitAccessory?.linkedMotionEntityId;
5559
5747
  let recordingStatus = "🔴 HKSV bloqueado (Sin fuente STREAM)";
5560
5748
  if (!cap?.hasLiveStream) {
5561
5749
  recordingStatus =
@@ -5580,7 +5768,11 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5580
5768
  "⚠️ HKSV con error (Live View activo)";
5581
5769
  }
5582
5770
  return {
5583
- published: rec?.published ?? false,
5771
+ published: e.homekitAccessory?.isPublished ??
5772
+ false,
5773
+ setupId: rec?.setupId,
5774
+ liveViewCapabilities: e.homekitAccessory?.getLiveViewCapabilitiesDiagnostic(),
5775
+ liveViewTelemetry: e.homekitAccessory?.getLiveViewTelemetry(),
5584
5776
  isPaired: e.homekitAccessory?.isPaired() ??
5585
5777
  rec?.isPaired ??
5586
5778
  false,
@@ -5589,9 +5781,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5589
5781
  hksvVerified,
5590
5782
  hksvState,
5591
5783
  port: rec?.port ?? 51830,
5592
- pincode: rec?.pincode ?? "031-45-154",
5784
+ pincode: rec?.pincode,
5593
5785
  username: rec?.username,
5594
- setupUri: e.homekitAccessory?.setupUri || "",
5786
+ setupUri: e.homekitAccessory?.setupUri ||
5787
+ "",
5595
5788
  strategy: rec?.strategy || cap?.strategy || "unsupported",
5596
5789
  hasAudio: cap?.hasAudio ?? false,
5597
5790
  audioCodec: cap?.audioCodec ?? "none",
@@ -5634,7 +5827,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5634
5827
  isPaired: hapAcc?.isPaired() ?? hapRec.isPaired ?? false,
5635
5828
  hapProfile: hapRec.hapProfile,
5636
5829
  alarmCodeConfigured: Boolean(hapRec.alarmCode),
5637
- profileLabel: HAP_PROFILE_LABELS[hapRec.hapProfile] || hapRec.hapProfile,
5830
+ profileLabel: HAP_PROFILE_LABELS[hapRec.hapProfile] ||
5831
+ hapRec.hapProfile,
5638
5832
  pincode: hapRec.pincode,
5639
5833
  port: hapRec.port,
5640
5834
  username: hapRec.username,
@@ -5657,7 +5851,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5657
5851
  domain: m.domain,
5658
5852
  state: m.getStateString(),
5659
5853
  origin: "mqtt",
5660
- attributes: { friendly_name: m.friendlyName, ...m.attributes },
5854
+ attributes: {
5855
+ friendly_name: m.friendlyName,
5856
+ ...m.attributes,
5857
+ },
5661
5858
  deviceTypeLabel: "MQTT " +
5662
5859
  (m.domain.charAt(0).toUpperCase() + m.domain.slice(1)),
5663
5860
  matterType: m.deviceType.name,
@@ -5680,7 +5877,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5680
5877
  profiles: [],
5681
5878
  pairingCode: connection.pairingCode,
5682
5879
  manualPairingCode: connection.manualPairingCode,
5683
- commissioned: this.isEntityExported(m.entityId) && connection.commissioned,
5880
+ commissioned: this.isEntityExported(m.entityId) &&
5881
+ connection.commissioned,
5684
5882
  homeName: connection.homeName,
5685
5883
  controllerNames: connection.controllerNames,
5686
5884
  fabricCount: connection.fabricCount,
@@ -5703,10 +5901,14 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5703
5901
  }
5704
5902
  catch (err) {
5705
5903
  this.log.error(`Error in /api/custom/devices: ${err?.message || err}`);
5706
- res.writeHead(200, {
5904
+ res.writeHead(500, {
5707
5905
  "Content-Type": "application/json; charset=utf-8",
5708
5906
  });
5709
- res.end(JSON.stringify([]));
5907
+ res.end(JSON.stringify({ error: "No se pudo cargar el inventario" }));
5908
+ }
5909
+ finally {
5910
+ this.inventoryMembers = undefined;
5911
+ this.inventoryRegistry = undefined;
5710
5912
  }
5711
5913
  return;
5712
5914
  }
@@ -5714,7 +5916,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5714
5916
  if (req.method === "POST" &&
5715
5917
  pathname.startsWith("/api/custom/register/")) {
5716
5918
  const entityId = decodeURIComponent(pathname.substring("/api/custom/register/".length));
5717
- const result = await this.manualRegister(entityId);
5919
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.manualRegister(entityId));
5718
5920
  res.writeHead(200, {
5719
5921
  "Content-Type": "application/json; charset=utf-8",
5720
5922
  });
@@ -5725,7 +5927,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5725
5927
  if (req.method === "POST" &&
5726
5928
  pathname.startsWith("/api/custom/unregister/")) {
5727
5929
  const entityId = decodeURIComponent(pathname.substring("/api/custom/unregister/".length));
5728
- const result = await this.manualUnregister(entityId);
5930
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.manualUnregister(entityId));
5729
5931
  res.writeHead(200, {
5730
5932
  "Content-Type": "application/json; charset=utf-8",
5731
5933
  });
@@ -5744,7 +5946,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5744
5946
  hapProfile = data.hapProfile;
5745
5947
  }
5746
5948
  catch { }
5747
- const result = await this.manualRegisterHap(entityId, hapProfile);
5949
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.manualRegisterHap(entityId, hapProfile));
5748
5950
  res.writeHead(result.success ? 200 : 400, {
5749
5951
  "Content-Type": "application/json; charset=utf-8",
5750
5952
  });
@@ -5755,7 +5957,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5755
5957
  if (req.method === "POST" &&
5756
5958
  pathname.startsWith("/api/custom/unregister-hap/")) {
5757
5959
  const entityId = decodeURIComponent(pathname.substring("/api/custom/unregister-hap/".length));
5758
- const result = await this.manualUnregisterHap(entityId);
5960
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.manualUnregisterHap(entityId));
5759
5961
  res.writeHead(result.success ? 200 : 400, {
5760
5962
  "Content-Type": "application/json; charset=utf-8",
5761
5963
  });
@@ -5800,9 +6002,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5800
6002
  return;
5801
6003
  }
5802
6004
  // DELETE /api/custom/diagnostics/:entityId OR POST /api/custom/clear-diagnostics/:entityId
5803
- if ((req.method === "DELETE" && pathname.startsWith("/api/custom/diagnostics/")) ||
5804
- (req.method === "POST" && pathname.startsWith("/api/custom/clear-diagnostics/")) ||
5805
- ((req.method === "DELETE" || req.method === "POST") && /^\/api\/custom\/devices\/[^/]+\/diagnostics$/.test(pathname))) {
6005
+ if ((req.method === "DELETE" &&
6006
+ pathname.startsWith("/api/custom/diagnostics/")) ||
6007
+ (req.method === "POST" &&
6008
+ pathname.startsWith("/api/custom/clear-diagnostics/")) ||
6009
+ ((req.method === "DELETE" || req.method === "POST") &&
6010
+ /^\/api\/custom\/devices\/[^/]+\/diagnostics$/.test(pathname))) {
5806
6011
  let entityId = "";
5807
6012
  if (pathname.startsWith("/api/custom/diagnostics/")) {
5808
6013
  entityId = decodeURIComponent(pathname.substring("/api/custom/diagnostics/".length));
@@ -5897,7 +6102,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5897
6102
  if (req.method === "POST" &&
5898
6103
  pathname.startsWith("/api/custom/open-commissioning/")) {
5899
6104
  const entityId = decodeURIComponent(pathname.substring("/api/custom/open-commissioning/".length));
5900
- const result = await this.openMatterCommissioningWindow(entityId);
6105
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.openMatterCommissioningWindow(entityId));
5901
6106
  res.writeHead(result.success ? 200 : 400, {
5902
6107
  "Content-Type": "application/json; charset=utf-8",
5903
6108
  });
@@ -5926,7 +6131,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
5926
6131
  const body = await this.readRequestBody(req);
5927
6132
  const data = JSON.parse(body);
5928
6133
  const targetProfile = data.profileId || data.profile || "";
5929
- const result = await this.setDeviceProfile(entityId, targetProfile);
6134
+ const result = await this.runMatterAccessoryOperation(entityId, () => this.setDeviceProfile(entityId, targetProfile));
5930
6135
  res.writeHead(result.success ? 200 : 400, {
5931
6136
  "Content-Type": "application/json; charset=utf-8",
5932
6137
  });
@@ -6809,11 +7014,37 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
6809
7014
  c.name.toLowerCase() === cameraId.toLowerCase());
6810
7015
  const haState = this.ha?.hassStates?.get(cameraId) ||
6811
7016
  this.ha?.hassStates?.get(`camera.${cleanId}`);
6812
- let targetUrl = String(parsed.streamUrl || "").trim() ||
6813
- scryptedCam?.source.streamReference?.directUrl ||
6814
- cuiCam?.rtspUrl ||
6815
- haState?.attributes?.stream_source ||
6816
- "";
7017
+ const requestedUrl = String(parsed.streamUrl || "").trim();
7018
+ const haEntityId = this.ha?.hassEntities?.has(cameraId)
7019
+ ? cameraId
7020
+ : `camera.${cleanId}`;
7021
+ const isOmniTuyaCamera = haState &&
7022
+ this.ha?.hassEntities?.get(haEntityId)?.platform ===
7023
+ "omni_tuya_local";
7024
+ let usesEphemeralOmniUrl = false;
7025
+ let targetUrl = "";
7026
+ // A Camera.UI record can contain an old go2rtc URL entered during
7027
+ // setup. It must not override Omni's short-lived, single-session
7028
+ // RTSP credential. Allocate a new URL for every verification just
7029
+ // as the HAP delegate does; never persist that URL below.
7030
+ if (isOmniTuyaCamera && this.ha?.requestOmniTuyaCameraStream) {
7031
+ try {
7032
+ targetUrl =
7033
+ (await this.ha.requestOmniTuyaCameraStream(haEntityId)) || "";
7034
+ usesEphemeralOmniUrl = Boolean(targetUrl);
7035
+ }
7036
+ catch { }
7037
+ }
7038
+ if (!targetUrl) {
7039
+ targetUrl =
7040
+ requestedUrl ||
7041
+ scryptedCam?.source.streamReference?.directUrl ||
7042
+ cuiCam?.rtspUrl ||
7043
+ "";
7044
+ }
7045
+ if (!targetUrl) {
7046
+ targetUrl = haState?.attributes?.stream_source || "";
7047
+ }
6817
7048
  if (!targetUrl && haState) {
6818
7049
  try {
6819
7050
  if (this.ha?.requestCameraStream) {
@@ -6833,7 +7064,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
6833
7064
  if (isVimtag && targetUrl.startsWith("rtsp://")) {
6834
7065
  try {
6835
7066
  const u = new URL(targetUrl);
6836
- if (!u.pathname || u.pathname === "/" || u.pathname === "/stream1" || u.pathname === "/stream2") {
7067
+ if (!u.pathname ||
7068
+ u.pathname === "/" ||
7069
+ u.pathname === "/stream1" ||
7070
+ u.pathname === "/stream2") {
6837
7071
  u.pathname = "/live/ch0";
6838
7072
  targetUrl = u.toString();
6839
7073
  }
@@ -6911,7 +7145,12 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
6911
7145
  }
6912
7146
  if (cuiCam) {
6913
7147
  await CameraUiStorage.updateCamera(cuiCam.id, (cam) => {
6914
- cam.rtspUrl = targetUrl;
7148
+ // Tuya RTSP URLs are credentials with a one-session lifetime.
7149
+ // Persisting one makes the next HA/add-on restart reuse an
7150
+ // expired stream and is the root of intermittent 401/404 live
7151
+ // view failures. Keep the configured URL untouched for Omni.
7152
+ if (!usesEphemeralOmniUrl)
7153
+ cam.rtspUrl = targetUrl;
6915
7154
  if (validation.status === "verified") {
6916
7155
  cam.status = "online";
6917
7156
  cam.videoCodecSource = "ffprobe";
@@ -6999,11 +7238,33 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
6999
7238
  res.end(JSON.stringify({ error: "Cámara no encontrada" }));
7000
7239
  return;
7001
7240
  }
7002
- let targetUrl = String(parsed.streamUrl || "").trim() ||
7003
- scryptedCam?.source.streamReference?.directUrl ||
7004
- cuiCam?.rtspUrl ||
7005
- haState?.attributes?.stream_source ||
7006
- "";
7241
+ const requestedUrl = String(parsed.streamUrl || "").trim();
7242
+ const haEntityId = this.ha?.hassEntities?.has(cameraId)
7243
+ ? cameraId
7244
+ : `camera.${cleanId}`;
7245
+ const isOmniTuyaCamera = haState &&
7246
+ this.ha?.hassEntities?.get(haEntityId)?.platform ===
7247
+ "omni_tuya_local";
7248
+ let targetUrl = "";
7249
+ // Diagnostics must exercise the exact renewable source that HAP
7250
+ // uses. This deliberately wins over Camera.UI's saved go2rtc URL.
7251
+ if (isOmniTuyaCamera && this.ha?.requestOmniTuyaCameraStream) {
7252
+ try {
7253
+ targetUrl =
7254
+ (await this.ha.requestOmniTuyaCameraStream(haEntityId)) || "";
7255
+ }
7256
+ catch { }
7257
+ }
7258
+ if (!targetUrl) {
7259
+ targetUrl =
7260
+ requestedUrl ||
7261
+ scryptedCam?.source.streamReference?.directUrl ||
7262
+ cuiCam?.rtspUrl ||
7263
+ "";
7264
+ }
7265
+ if (!targetUrl) {
7266
+ targetUrl = haState?.attributes?.stream_source || "";
7267
+ }
7007
7268
  try {
7008
7269
  if ((targetUrl.startsWith("rtsp://localhost") ||
7009
7270
  targetUrl.startsWith("rtsp://127.0.0.1") ||
@@ -7040,7 +7301,10 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7040
7301
  if (isVimtag && targetUrl.startsWith("rtsp://")) {
7041
7302
  try {
7042
7303
  const u = new URL(targetUrl);
7043
- if (!u.pathname || u.pathname === "/" || u.pathname === "/stream1" || u.pathname === "/stream2") {
7304
+ if (!u.pathname ||
7305
+ u.pathname === "/" ||
7306
+ u.pathname === "/stream1" ||
7307
+ u.pathname === "/stream2") {
7044
7308
  u.pathname = "/live/ch0";
7045
7309
  targetUrl = u.toString();
7046
7310
  }
@@ -7069,8 +7333,15 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7069
7333
  this.log.notice(`[DiagnoseStream][${cameraId}] Iniciando diagnóstico de stream RTSP/HTTP: ${sanitizedUrl}`);
7070
7334
  const transport = parsed.transport === "udp" ? "udp" : "tcp";
7071
7335
  const timeoutMs = parsed.timeoutMs ? Number(parsed.timeoutMs) : 15000;
7336
+ // HLS URLs returned by Home Assistant's camera/stream websocket are
7337
+ // protected endpoints. The diagnostic must use the same HA token as
7338
+ // the HAP and HKSV FFmpeg pipelines, otherwise it produces a false
7339
+ // 401 even when the freshly-created HLS stream is usable.
7340
+ const httpBearerToken = /^https?:\/\//i.test(targetUrl) && /\/api\/hls\//i.test(targetUrl)
7341
+ ? this.ha?.getAccessToken?.() || this.ha?.wsAccessToken
7342
+ : undefined;
7072
7343
  ScryptedStreamValidator.clearCache();
7073
- const metrics = await ScryptedStreamValidator.diagnoseStreamUrl(targetUrl, cameraId, timeoutMs, transport);
7344
+ const metrics = await ScryptedStreamValidator.diagnoseStreamUrl(targetUrl, cameraId, timeoutMs, transport, httpBearerToken);
7074
7345
  if (scryptedCam) {
7075
7346
  scryptedCam.capabilities.latencyMetrics = metrics;
7076
7347
  if (metrics.observedGopSeconds?.value) {
@@ -7586,24 +7857,30 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7586
7857
  .toLowerCase();
7587
7858
  const isVehicle = /vehicle|vehiculo|vehículo|car|auto|camion|camión|truck|bus|motorcycle|moto/i.test(allText);
7588
7859
  const isPerson = /person|persona|humano|human|face|cara/i.test(allText);
7589
- const isPet = /dog|perro|cat|gato|pet|animal|mascota|bird|ave/i.test(allText);
7860
+ const isDog = /dog|perro/i.test(allText);
7861
+ const isCat = /cat|gato/i.test(allText);
7862
+ const isBird = /bird|ave|pajaro|pájaro/i.test(allText);
7590
7863
  const targets = [];
7591
7864
  if (isVehicle)
7592
7865
  targets.push("vehicle");
7593
7866
  if (isPerson)
7594
7867
  targets.push("person");
7595
- if (isPet)
7868
+ if (isDog)
7596
7869
  targets.push("dog");
7597
- if (targets.length === 0)
7598
- targets.push("person");
7599
- this.cameraAiDetector.dispatchDetection(this, cuiId, {
7600
- cameraId: cuiId,
7601
- timestamp: Date.now(),
7602
- targets,
7603
- labels: [String(triggerInfo)],
7604
- confidence: 0.95,
7605
- rawDetails: `Camera.UI Webhook: ${triggerInfo}`,
7606
- });
7870
+ if (isCat)
7871
+ targets.push("cat");
7872
+ if (isBird)
7873
+ targets.push("bird");
7874
+ if (targets.length > 0) {
7875
+ this.cameraAiDetector.dispatchDetection(this, cuiId, {
7876
+ cameraId: cuiId,
7877
+ timestamp: Date.now(),
7878
+ targets,
7879
+ labels: [String(triggerInfo)],
7880
+ confidence: 0.95,
7881
+ rawDetails: `Camera.UI webhook: ${triggerInfo}`,
7882
+ });
7883
+ }
7607
7884
  // Auto-reset motion after 10 seconds if Camera.UI only pushes active events
7608
7885
  const existingTimer = this.cameraUiActiveMotionTimers.get(cuiId);
7609
7886
  if (existingTimer)
@@ -7867,7 +8144,7 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7867
8144
  hksvVerified: acc?.record?.hksvVerified,
7868
8145
  audioIncompatibleReason: acc?.record?.audioIncompatibleReason,
7869
8146
  liveViewCapabilities: acc?.getLiveViewCapabilitiesDiagnostic(),
7870
- liveViewTelemetry: acc?.delegate?.getLiveViewTelemetry(),
8147
+ liveViewTelemetry: acc?.getLiveViewTelemetry(),
7871
8148
  hksvConfiguration: acc?.recordingDelegate?.selectedConfiguration
7872
8149
  ? {
7873
8150
  resolution: acc.recordingDelegate.selectedConfiguration.videoCodec
@@ -7954,7 +8231,14 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7954
8231
  await this.manualUnregister(cameraId);
7955
8232
  }
7956
8233
  else {
7957
- await this.manualRegister(cameraId);
8234
+ const result = await this.manualRegister(cameraId);
8235
+ if (!result.success) {
8236
+ res.writeHead(409, {
8237
+ "Content-Type": "application/json; charset=utf-8",
8238
+ });
8239
+ res.end(JSON.stringify(result));
8240
+ return;
8241
+ }
7958
8242
  }
7959
8243
  const record = this.homekitCameraRecords.get(cameraId);
7960
8244
  res.writeHead(200, {
@@ -7997,14 +8281,8 @@ export class HomeAssistantPlatform extends MatterbridgeDynamicPlatform {
7997
8281
  res.end(JSON.stringify({ success: false, error: "entityId requerido" }));
7998
8282
  return;
7999
8283
  }
8000
- const domain = entityId.split(".")[0];
8001
- const service = action === "turn_on"
8002
- ? "turn_on"
8003
- : action === "turn_off"
8004
- ? "turn_off"
8005
- : "toggle";
8006
- await this.ha?.callService(domain, service, entityId);
8007
- const newState = this.ha?.hassStates?.get(entityId)?.state === "on";
8284
+ const result = await controlCameraEntity(this.ha, entityId, action);
8285
+ const newState = result.state;
8008
8286
  this.broadcastSseMessage("entity_state_changed", {
8009
8287
  entityId,
8010
8288
  state: newState,