homebridge 2.5.1-beta.2 → 2.5.1-beta.3

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 (332) hide show
  1. package/dist/api.d.ts +253 -35
  2. package/dist/api.js +93 -5
  3. package/dist/api.js.map +1 -1
  4. package/dist/bridgeService.d.ts +63 -6
  5. package/dist/bridgeService.js +401 -99
  6. package/dist/bridgeService.js.map +1 -1
  7. package/dist/childBridgeFork.d.ts +12 -9
  8. package/dist/childBridgeFork.js +126 -40
  9. package/dist/childBridgeFork.js.map +1 -1
  10. package/dist/childBridgeService.d.ts +107 -28
  11. package/dist/childBridgeService.js +225 -28
  12. package/dist/childBridgeService.js.map +1 -1
  13. package/dist/cli.d.ts +0 -1
  14. package/dist/cli.js +28 -7
  15. package/dist/cli.js.map +1 -1
  16. package/dist/externalPortService.d.ts +4 -1
  17. package/dist/externalPortService.js +16 -4
  18. package/dist/externalPortService.js.map +1 -1
  19. package/dist/index.d.ts +36 -10
  20. package/dist/index.js +20 -4
  21. package/dist/index.js.map +1 -1
  22. package/dist/ipcService.d.ts +27 -12
  23. package/dist/ipcService.js +19 -6
  24. package/dist/ipcService.js.map +1 -1
  25. package/dist/logger.d.ts +10 -4
  26. package/dist/logger.js +27 -14
  27. package/dist/logger.js.map +1 -1
  28. package/dist/matter/BaseMatterManager.d.ts +36 -1
  29. package/dist/matter/BaseMatterManager.js +96 -39
  30. package/dist/matter/BaseMatterManager.js.map +1 -1
  31. package/dist/matter/ChildBridgeMatterManager.d.ts +27 -14
  32. package/dist/matter/ChildBridgeMatterManager.js +220 -62
  33. package/dist/matter/ChildBridgeMatterManager.js.map +1 -1
  34. package/dist/matter/ChildBridgeMatterMessageHandler.d.ts +3 -9
  35. package/dist/matter/ChildBridgeMatterMessageHandler.js +21 -7
  36. package/dist/matter/ChildBridgeMatterMessageHandler.js.map +1 -1
  37. package/dist/matter/ClusterCommandMapper.d.ts +21 -14
  38. package/dist/matter/ClusterCommandMapper.js +143 -84
  39. package/dist/matter/ClusterCommandMapper.js.map +1 -1
  40. package/dist/matter/ExternalMatterAccessoryPublisher.d.ts +2 -1
  41. package/dist/matter/ExternalMatterAccessoryPublisher.js +29 -18
  42. package/dist/matter/ExternalMatterAccessoryPublisher.js.map +1 -1
  43. package/dist/matter/MatterAPIImpl.d.ts +62 -41
  44. package/dist/matter/MatterAPIImpl.js +62 -47
  45. package/dist/matter/MatterAPIImpl.js.map +1 -1
  46. package/dist/matter/MatterBridgeManager.d.ts +2 -1
  47. package/dist/matter/MatterBridgeManager.js +58 -35
  48. package/dist/matter/MatterBridgeManager.js.map +1 -1
  49. package/dist/matter/MatterError.d.ts +15 -1
  50. package/dist/matter/MatterError.js +53 -1
  51. package/dist/matter/MatterError.js.map +1 -1
  52. package/dist/matter/MatterPortAllocator.d.ts +6 -1
  53. package/dist/matter/MatterPortAllocator.js +8 -0
  54. package/dist/matter/MatterPortAllocator.js.map +1 -1
  55. package/dist/matter/SwitchAPI.d.ts +0 -1
  56. package/dist/matter/accessoryCache.d.ts +49 -2
  57. package/dist/matter/accessoryCache.js +106 -3
  58. package/dist/matter/accessoryCache.js.map +1 -1
  59. package/dist/matter/behaviors/BehaviorRegistry.d.ts +39 -12
  60. package/dist/matter/behaviors/BehaviorRegistry.js +102 -63
  61. package/dist/matter/behaviors/BehaviorRegistry.js.map +1 -1
  62. package/dist/matter/behaviors/ClosureControlBehavior.d.ts +0 -19
  63. package/dist/matter/behaviors/ClosureControlBehavior.js +102 -68
  64. package/dist/matter/behaviors/ClosureControlBehavior.js.map +1 -1
  65. package/dist/matter/behaviors/ColorControlBehavior.d.ts +30 -10
  66. package/dist/matter/behaviors/ColorControlBehavior.js +130 -175
  67. package/dist/matter/behaviors/ColorControlBehavior.js.map +1 -1
  68. package/dist/matter/behaviors/DeviceEnergyManagementBehavior.d.ts +3 -6
  69. package/dist/matter/behaviors/DeviceEnergyManagementBehavior.js +35 -91
  70. package/dist/matter/behaviors/DeviceEnergyManagementBehavior.js.map +1 -1
  71. package/dist/matter/behaviors/DoorLockBehavior.d.ts +9 -10
  72. package/dist/matter/behaviors/DoorLockBehavior.js +41 -62
  73. package/dist/matter/behaviors/DoorLockBehavior.js.map +1 -1
  74. package/dist/matter/behaviors/EndpointContext.d.ts +7 -1
  75. package/dist/matter/behaviors/EndpointContext.js +8 -0
  76. package/dist/matter/behaviors/EndpointContext.js.map +1 -1
  77. package/dist/matter/behaviors/EnergyEvseBehavior.d.ts +6 -4
  78. package/dist/matter/behaviors/EnergyEvseBehavior.js +52 -76
  79. package/dist/matter/behaviors/EnergyEvseBehavior.js.map +1 -1
  80. package/dist/matter/behaviors/FanControlBehavior.d.ts +1 -6
  81. package/dist/matter/behaviors/FanControlBehavior.js +34 -56
  82. package/dist/matter/behaviors/FanControlBehavior.js.map +1 -1
  83. package/dist/matter/behaviors/IdentifyBehavior.d.ts +2 -5
  84. package/dist/matter/behaviors/IdentifyBehavior.js +26 -25
  85. package/dist/matter/behaviors/IdentifyBehavior.js.map +1 -1
  86. package/dist/matter/behaviors/KeypadInputBehavior.d.ts +0 -5
  87. package/dist/matter/behaviors/KeypadInputBehavior.js +18 -13
  88. package/dist/matter/behaviors/KeypadInputBehavior.js.map +1 -1
  89. package/dist/matter/behaviors/LevelControlBehavior.d.ts +41 -10
  90. package/dist/matter/behaviors/LevelControlBehavior.js +173 -191
  91. package/dist/matter/behaviors/LevelControlBehavior.js.map +1 -1
  92. package/dist/matter/behaviors/MediaPlaybackBehavior.d.ts +0 -5
  93. package/dist/matter/behaviors/MediaPlaybackBehavior.js +14 -10
  94. package/dist/matter/behaviors/MediaPlaybackBehavior.js.map +1 -1
  95. package/dist/matter/behaviors/OnOffBehavior.d.ts +1 -6
  96. package/dist/matter/behaviors/OnOffBehavior.js +41 -76
  97. package/dist/matter/behaviors/OnOffBehavior.js.map +1 -1
  98. package/dist/matter/behaviors/RegistryManager.d.ts +0 -1
  99. package/dist/matter/behaviors/RvcCleanModeBehavior.d.ts +0 -5
  100. package/dist/matter/behaviors/RvcCleanModeBehavior.js +9 -47
  101. package/dist/matter/behaviors/RvcCleanModeBehavior.js.map +1 -1
  102. package/dist/matter/behaviors/RvcOperationalStateBehavior.d.ts +5 -8
  103. package/dist/matter/behaviors/RvcOperationalStateBehavior.js +41 -38
  104. package/dist/matter/behaviors/RvcOperationalStateBehavior.js.map +1 -1
  105. package/dist/matter/behaviors/RvcRunModeBehavior.d.ts +3 -14
  106. package/dist/matter/behaviors/RvcRunModeBehavior.js +4 -50
  107. package/dist/matter/behaviors/RvcRunModeBehavior.js.map +1 -1
  108. package/dist/matter/behaviors/ServiceAreaBehavior.d.ts +1 -6
  109. package/dist/matter/behaviors/ServiceAreaBehavior.js +42 -51
  110. package/dist/matter/behaviors/ServiceAreaBehavior.js.map +1 -1
  111. package/dist/matter/behaviors/ThermostatBehavior.d.ts +6 -6
  112. package/dist/matter/behaviors/ThermostatBehavior.js +83 -106
  113. package/dist/matter/behaviors/ThermostatBehavior.js.map +1 -1
  114. package/dist/matter/behaviors/ValveConfigurationAndControlBehavior.d.ts +0 -5
  115. package/dist/matter/behaviors/ValveConfigurationAndControlBehavior.js +34 -57
  116. package/dist/matter/behaviors/ValveConfigurationAndControlBehavior.js.map +1 -1
  117. package/dist/matter/behaviors/WaterHeaterBehavior.d.ts +1 -4
  118. package/dist/matter/behaviors/WaterHeaterBehavior.js +14 -62
  119. package/dist/matter/behaviors/WaterHeaterBehavior.js.map +1 -1
  120. package/dist/matter/behaviors/WindowCoveringBehavior.d.ts +19 -10
  121. package/dist/matter/behaviors/WindowCoveringBehavior.js +94 -141
  122. package/dist/matter/behaviors/WindowCoveringBehavior.js.map +1 -1
  123. package/dist/matter/behaviors/handlerResponse.d.ts +47 -0
  124. package/dist/matter/behaviors/handlerResponse.js +79 -0
  125. package/dist/matter/behaviors/handlerResponse.js.map +1 -0
  126. package/dist/matter/behaviors/handlerScope.d.ts +16 -0
  127. package/dist/matter/behaviors/handlerScope.js +23 -0
  128. package/dist/matter/behaviors/handlerScope.js.map +1 -0
  129. package/dist/matter/behaviors/index.d.ts +0 -3
  130. package/dist/matter/behaviors/index.js +0 -7
  131. package/dist/matter/behaviors/index.js.map +1 -1
  132. package/dist/matter/behaviors/pluginUpdates.d.ts +35 -0
  133. package/dist/matter/behaviors/pluginUpdates.js +74 -0
  134. package/dist/matter/behaviors/pluginUpdates.js.map +1 -0
  135. package/dist/matter/behaviors/revertFailedChange.d.ts +28 -0
  136. package/dist/matter/behaviors/revertFailedChange.js +40 -0
  137. package/dist/matter/behaviors/revertFailedChange.js.map +1 -0
  138. package/dist/matter/behaviors/stateLock.d.ts +20 -0
  139. package/dist/matter/behaviors/stateLock.js +36 -0
  140. package/dist/matter/behaviors/stateLock.js.map +1 -0
  141. package/dist/matter/clusterFeatures.d.ts +0 -1
  142. package/dist/matter/clusterFeatures.js.map +1 -1
  143. package/dist/matter/clusterHandlerMap.d.ts +116 -25
  144. package/dist/matter/clusterHandlerMap.js +8 -0
  145. package/dist/matter/clusterHandlerMap.js.map +1 -1
  146. package/dist/matter/clusterStateMap.d.ts +9 -3
  147. package/dist/matter/clusterTypes.d.ts +66 -7
  148. package/dist/matter/clusterTypes.js +5 -3
  149. package/dist/matter/clusterTypes.js.map +1 -1
  150. package/dist/matter/config.d.ts +2 -3
  151. package/dist/matter/config.js +30 -31
  152. package/dist/matter/config.js.map +1 -1
  153. package/dist/matter/configValidator.d.ts +11 -1
  154. package/dist/matter/configValidator.js +36 -14
  155. package/dist/matter/configValidator.js.map +1 -1
  156. package/dist/matter/errorHandler.d.ts +22 -5
  157. package/dist/matter/errorHandler.js +62 -17
  158. package/dist/matter/errorHandler.js.map +1 -1
  159. package/dist/matter/errors.d.ts +0 -1
  160. package/dist/matter/index.d.ts +0 -1
  161. package/dist/matter/ipc-types.d.ts +40 -2
  162. package/dist/matter/logFormatter.d.ts +17 -1
  163. package/dist/matter/logFormatter.js +32 -32
  164. package/dist/matter/logFormatter.js.map +1 -1
  165. package/dist/matter/managerTypes.d.ts +10 -45
  166. package/dist/matter/processConfig.d.ts +15 -0
  167. package/dist/matter/processConfig.js +60 -0
  168. package/dist/matter/processConfig.js.map +1 -0
  169. package/dist/matter/server/AccessoryManager.d.ts +83 -19
  170. package/dist/matter/server/AccessoryManager.js +447 -226
  171. package/dist/matter/server/AccessoryManager.js.map +1 -1
  172. package/dist/matter/server/AccessoryQuery.d.ts +3 -3
  173. package/dist/matter/server/AccessoryQuery.js +40 -12
  174. package/dist/matter/server/AccessoryQuery.js.map +1 -1
  175. package/dist/matter/server/BehaviorMap.d.ts +4 -20
  176. package/dist/matter/server/BehaviorMap.js +4 -28
  177. package/dist/matter/server/BehaviorMap.js.map +1 -1
  178. package/dist/matter/server/CommissioningManager.d.ts +3 -16
  179. package/dist/matter/server/CommissioningManager.js +109 -137
  180. package/dist/matter/server/CommissioningManager.js.map +1 -1
  181. package/dist/matter/server/FabricManager.d.ts +9 -22
  182. package/dist/matter/server/FabricManager.js +32 -170
  183. package/dist/matter/server/FabricManager.js.map +1 -1
  184. package/dist/matter/server/ServerConfig.d.ts +0 -5
  185. package/dist/matter/server/ServerConfig.js +1 -4
  186. package/dist/matter/server/ServerConfig.js.map +1 -1
  187. package/dist/matter/server/ServerLifecycle.d.ts +64 -19
  188. package/dist/matter/server/ServerLifecycle.js +268 -174
  189. package/dist/matter/server/ServerLifecycle.js.map +1 -1
  190. package/dist/matter/server/StateManager.d.ts +17 -2
  191. package/dist/matter/server/StateManager.js +104 -52
  192. package/dist/matter/server/StateManager.js.map +1 -1
  193. package/dist/matter/server/index.d.ts +2 -3
  194. package/dist/matter/server/index.js +2 -2
  195. package/dist/matter/server/index.js.map +1 -1
  196. package/dist/matter/server/storageLock.d.ts +35 -0
  197. package/dist/matter/server/storageLock.js +121 -0
  198. package/dist/matter/server/storageLock.js.map +1 -0
  199. package/dist/matter/server.d.ts +20 -22
  200. package/dist/matter/server.js +129 -66
  201. package/dist/matter/server.js.map +1 -1
  202. package/dist/matter/serverHelpers.d.ts +17 -71
  203. package/dist/matter/serverHelpers.js +88 -207
  204. package/dist/matter/serverHelpers.js.map +1 -1
  205. package/dist/matter/sharedTypes.d.ts +7 -2
  206. package/dist/matter/sharedTypes.js.map +1 -1
  207. package/dist/matter/types.d.ts +121 -88
  208. package/dist/matter/types.js +62 -22
  209. package/dist/matter/types.js.map +1 -1
  210. package/dist/matter/utils.d.ts +32 -5
  211. package/dist/matter/utils.js +63 -14
  212. package/dist/matter/utils.js.map +1 -1
  213. package/dist/matterExports.d.ts +30 -0
  214. package/dist/matterExports.js +23 -0
  215. package/dist/matterExports.js.map +1 -0
  216. package/dist/platformAccessory.d.ts +54 -9
  217. package/dist/platformAccessory.js +38 -5
  218. package/dist/platformAccessory.js.map +1 -1
  219. package/dist/plugin.d.ts +0 -4
  220. package/dist/plugin.js +65 -33
  221. package/dist/plugin.js.map +1 -1
  222. package/dist/pluginManager.d.ts +38 -4
  223. package/dist/pluginManager.js +123 -66
  224. package/dist/pluginManager.js.map +1 -1
  225. package/dist/server.d.ts +38 -11
  226. package/dist/server.js +286 -118
  227. package/dist/server.js.map +1 -1
  228. package/dist/storageService.d.ts +12 -6
  229. package/dist/storageService.js +39 -16
  230. package/dist/storageService.js.map +1 -1
  231. package/dist/user.d.ts +0 -1
  232. package/dist/util/errorMessage.d.ts +6 -0
  233. package/dist/util/errorMessage.js +15 -0
  234. package/dist/util/errorMessage.js.map +1 -0
  235. package/dist/util/ipc.d.ts +12 -0
  236. package/dist/util/ipc.js +25 -0
  237. package/dist/util/ipc.js.map +1 -0
  238. package/dist/util/mac.d.ts +1 -2
  239. package/dist/util/mac.js.map +1 -1
  240. package/dist/util/pin.d.ts +19 -0
  241. package/dist/util/pin.js +43 -0
  242. package/dist/util/pin.js.map +1 -0
  243. package/dist/util/port.d.ts +11 -0
  244. package/dist/util/port.js +24 -0
  245. package/dist/util/port.js.map +1 -0
  246. package/dist/version.d.ts +0 -1
  247. package/package.json +28 -17
  248. package/dist/api.d.ts.map +0 -1
  249. package/dist/bridgeService.d.ts.map +0 -1
  250. package/dist/childBridgeFork.d.ts.map +0 -1
  251. package/dist/childBridgeService.d.ts.map +0 -1
  252. package/dist/cli.d.ts.map +0 -1
  253. package/dist/externalPortService.d.ts.map +0 -1
  254. package/dist/index.d.ts.map +0 -1
  255. package/dist/ipcService.d.ts.map +0 -1
  256. package/dist/logger.d.ts.map +0 -1
  257. package/dist/matter/BaseMatterManager.d.ts.map +0 -1
  258. package/dist/matter/ChildBridgeMatterManager.d.ts.map +0 -1
  259. package/dist/matter/ChildBridgeMatterMessageHandler.d.ts.map +0 -1
  260. package/dist/matter/ClusterCommandMapper.d.ts.map +0 -1
  261. package/dist/matter/ExternalMatterAccessoryPublisher.d.ts.map +0 -1
  262. package/dist/matter/MatterAPIImpl.d.ts.map +0 -1
  263. package/dist/matter/MatterBridgeManager.d.ts.map +0 -1
  264. package/dist/matter/MatterError.d.ts.map +0 -1
  265. package/dist/matter/MatterPortAllocator.d.ts.map +0 -1
  266. package/dist/matter/SwitchAPI.d.ts.map +0 -1
  267. package/dist/matter/accessoryCache.d.ts.map +0 -1
  268. package/dist/matter/behaviors/AirQualityBehavior.d.ts +0 -44
  269. package/dist/matter/behaviors/AirQualityBehavior.d.ts.map +0 -1
  270. package/dist/matter/behaviors/AirQualityBehavior.js +0 -48
  271. package/dist/matter/behaviors/AirQualityBehavior.js.map +0 -1
  272. package/dist/matter/behaviors/BehaviorRegistry.d.ts.map +0 -1
  273. package/dist/matter/behaviors/ClosureControlBehavior.d.ts.map +0 -1
  274. package/dist/matter/behaviors/ColorControlBehavior.d.ts.map +0 -1
  275. package/dist/matter/behaviors/ConcentrationMeasurementBehavior.d.ts +0 -117
  276. package/dist/matter/behaviors/ConcentrationMeasurementBehavior.d.ts.map +0 -1
  277. package/dist/matter/behaviors/ConcentrationMeasurementBehavior.js +0 -132
  278. package/dist/matter/behaviors/ConcentrationMeasurementBehavior.js.map +0 -1
  279. package/dist/matter/behaviors/DeviceEnergyManagementBehavior.d.ts.map +0 -1
  280. package/dist/matter/behaviors/DoorLockBehavior.d.ts.map +0 -1
  281. package/dist/matter/behaviors/EndpointContext.d.ts.map +0 -1
  282. package/dist/matter/behaviors/EnergyEvseBehavior.d.ts.map +0 -1
  283. package/dist/matter/behaviors/FanControlBehavior.d.ts.map +0 -1
  284. package/dist/matter/behaviors/IdentifyBehavior.d.ts.map +0 -1
  285. package/dist/matter/behaviors/KeypadInputBehavior.d.ts.map +0 -1
  286. package/dist/matter/behaviors/LevelControlBehavior.d.ts.map +0 -1
  287. package/dist/matter/behaviors/MediaPlaybackBehavior.d.ts.map +0 -1
  288. package/dist/matter/behaviors/OnOffBehavior.d.ts.map +0 -1
  289. package/dist/matter/behaviors/RegistryManager.d.ts.map +0 -1
  290. package/dist/matter/behaviors/RvcCleanModeBehavior.d.ts.map +0 -1
  291. package/dist/matter/behaviors/RvcOperationalStateBehavior.d.ts.map +0 -1
  292. package/dist/matter/behaviors/RvcRunModeBehavior.d.ts.map +0 -1
  293. package/dist/matter/behaviors/ServiceAreaBehavior.d.ts.map +0 -1
  294. package/dist/matter/behaviors/ThermostatBehavior.d.ts.map +0 -1
  295. package/dist/matter/behaviors/ValveConfigurationAndControlBehavior.d.ts.map +0 -1
  296. package/dist/matter/behaviors/WaterHeaterBehavior.d.ts.map +0 -1
  297. package/dist/matter/behaviors/WindowCoveringBehavior.d.ts.map +0 -1
  298. package/dist/matter/behaviors/index.d.ts.map +0 -1
  299. package/dist/matter/clusterFeatures.d.ts.map +0 -1
  300. package/dist/matter/clusterHandlerMap.d.ts.map +0 -1
  301. package/dist/matter/clusterStateMap.d.ts.map +0 -1
  302. package/dist/matter/clusterTypes.d.ts.map +0 -1
  303. package/dist/matter/config.d.ts.map +0 -1
  304. package/dist/matter/configValidator.d.ts.map +0 -1
  305. package/dist/matter/errorHandler.d.ts.map +0 -1
  306. package/dist/matter/errors.d.ts.map +0 -1
  307. package/dist/matter/index.d.ts.map +0 -1
  308. package/dist/matter/ipc-types.d.ts.map +0 -1
  309. package/dist/matter/logFormatter.d.ts.map +0 -1
  310. package/dist/matter/managerTypes.d.ts.map +0 -1
  311. package/dist/matter/server/AccessoryManager.d.ts.map +0 -1
  312. package/dist/matter/server/AccessoryQuery.d.ts.map +0 -1
  313. package/dist/matter/server/BehaviorMap.d.ts.map +0 -1
  314. package/dist/matter/server/CommissioningManager.d.ts.map +0 -1
  315. package/dist/matter/server/FabricManager.d.ts.map +0 -1
  316. package/dist/matter/server/ServerConfig.d.ts.map +0 -1
  317. package/dist/matter/server/ServerLifecycle.d.ts.map +0 -1
  318. package/dist/matter/server/StateManager.d.ts.map +0 -1
  319. package/dist/matter/server/index.d.ts.map +0 -1
  320. package/dist/matter/server.d.ts.map +0 -1
  321. package/dist/matter/serverHelpers.d.ts.map +0 -1
  322. package/dist/matter/sharedTypes.d.ts.map +0 -1
  323. package/dist/matter/types.d.ts.map +0 -1
  324. package/dist/matter/utils.d.ts.map +0 -1
  325. package/dist/platformAccessory.d.ts.map +0 -1
  326. package/dist/plugin.d.ts.map +0 -1
  327. package/dist/pluginManager.d.ts.map +0 -1
  328. package/dist/server.d.ts.map +0 -1
  329. package/dist/storageService.d.ts.map +0 -1
  330. package/dist/user.d.ts.map +0 -1
  331. package/dist/util/mac.d.ts.map +0 -1
  332. package/dist/version.d.ts.map +0 -1
@@ -1,9 +1,11 @@
1
- import { Accessory, Bridge, Characteristic, HAPLibraryVersion, once, Service, uuid, } from '@homebridge/hap-nodejs';
1
+ import { Accessory, AccessoryEventTypes, Bridge, Categories, Characteristic, CharacteristicEventTypes, CharacteristicWarningType, HAPLibraryVersion, once, Service, uuid, } from '@homebridge/hap-nodejs';
2
2
  import { getLogPrefix, Logger } from './logger.js';
3
3
  import { PlatformAccessory } from './platformAccessory.js';
4
4
  import { PluginManager } from './pluginManager.js';
5
5
  import { StorageService } from './storageService.js';
6
+ import { errorMessage } from './util/errorMessage.js';
6
7
  import { generate } from './util/mac.js';
8
+ import { isPortInUse } from './util/port.js';
7
9
  import getVersion from './version.js';
8
10
  export const DEFAULT_BRIDGE_DEFAULTS = {
9
11
  vendorName: 'Homebridge',
@@ -11,6 +13,14 @@ export const DEFAULT_BRIDGE_DEFAULTS = {
11
13
  model: 'homebridge',
12
14
  };
13
15
  const log = Logger.internal;
16
+ /** The most accessories HAP-NodeJS puts on one bridge (the HomeKit limit of 150, less the bridge itself). */
17
+ const MAX_BRIDGED_ACCESSORIES = 149;
18
+ /** A HomeKit setup ID: four characters, digits and capital letters. */
19
+ const SETUP_ID_FORMAT = /^[0-9A-Z]{4}$/;
20
+ /** The least time between two writes of the accessory cache that plugins ask for, in milliseconds. */
21
+ const CACHE_SAVE_INTERVAL = 1000;
22
+ /** The longest a shutdown waits for the accessories to be taken off the network, in milliseconds. */
23
+ const UNPUBLISH_TIMEOUT = 2000;
14
24
  /**
15
25
  * Whether HAP is enabled for the given bridge configuration. HAP is on by
16
26
  * default; users opt out via `hap: { enabled: false }`. Missing block or
@@ -83,6 +93,16 @@ export function validateHapConfig(bridgeConfig, opts) {
83
93
  : typeof hap}.`);
84
94
  }
85
95
  const hapBlock = hap;
96
+ // `enabled` and `externalsOnly` are only acted on as true or false. A text
97
+ // like "false" was read as "not false", so HAP stayed on with no word about
98
+ // it. The value is still not used (what the bridge does stays as it was),
99
+ // but now it is said.
100
+ for (const key of ['enabled', 'externalsOnly']) {
101
+ if (hapBlock[key] !== undefined && typeof hapBlock[key] !== 'boolean') {
102
+ log.warn(`${opts.bridgeLabel}: 'hap.${key}' must be true or false (without quotes), not ${JSON.stringify(hapBlock[key])}. Ignoring it.`);
103
+ delete hapBlock[key];
104
+ }
105
+ }
86
106
  if (hapBlock.disableIdentifyingMaterial !== undefined && typeof hapBlock.disableIdentifyingMaterial !== 'boolean') {
87
107
  throw new Error(`${opts.bridgeLabel}: 'hap.disableIdentifyingMaterial' must be a boolean.`);
88
108
  }
@@ -118,6 +138,11 @@ export class BridgeService {
118
138
  cachedAccessoriesFileLoaded = false;
119
139
  publishedExternalAccessories = new Map();
120
140
  publishedExternalAccessoriesMetadata = new Map();
141
+ cacheSaveTimer;
142
+ cacheSavePending = false;
143
+ shuttingDown = false;
144
+ unsavableAccessories = new WeakSet();
145
+ characteristicWarningListeners = new WeakMap();
121
146
  constructor(api, pluginManager, externalPortService, bridgeOptions, bridgeConfig) {
122
147
  this.api = api;
123
148
  this.pluginManager = pluginManager;
@@ -132,7 +157,7 @@ export class BridgeService {
132
157
  this.storageService.removeItemSync(this.bridgeOptions.externalAccessoriesItemName);
133
158
  }
134
159
  catch (error) {
135
- log.warn('Failed to clear stale external accessories metadata file:', error.message);
160
+ log.warn('Failed to clear stale external accessories metadata file:', errorMessage(error));
136
161
  }
137
162
  // Server is "secure by default", meaning it creates a top-level Bridge accessory that
138
163
  // will not allow unauthenticated requests. This matches the behavior of actual HomeKit
@@ -145,43 +170,119 @@ export class BridgeService {
145
170
  this.api.on("unregisterPlatformAccessories" /* InternalAPIEvent.UNREGISTER_PLATFORM_ACCESSORIES */, this.handleUnregisterPlatformAccessories.bind(this));
146
171
  this.api.on("publishExternalAccessories" /* InternalAPIEvent.PUBLISH_EXTERNAL_ACCESSORIES */, this.handlePublishExternalAccessories.bind(this));
147
172
  this.bridge = new Bridge(bridgeConfig.name, uuid.generate('HomeBridge'));
148
- this.bridge.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, () => {
173
+ this.bridge.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, (warning) => {
149
174
  // We register characteristic warning handlers on every bridged accessory (to have a reference to the plugin).
150
- // For Bridges the warnings will propagate to the main Bridge accessory, thus we need to silence them here.
151
- // Otherwise, those would be printed twice (by us and HAP-NodeJS as it detects no handlers on the bridge).
175
+ // For Bridges the warnings will propagate to the main Bridge accessory, and HAP-NodeJS only prints a warning
176
+ // itself when nothing listens for it. So this listener keeps those from being printed twice.
177
+ //
178
+ // It must not hide the warnings nobody else prints, though: one from a service of the bridge itself (a
179
+ // manufacturer or serial number from the config that HomeKit does not accept), or from an accessory whose
180
+ // plugin was not found. The handler of the accessory may run after this listener, so look once it has.
181
+ queueMicrotask(() => {
182
+ if (!BridgeService.printedWarnings.has(warning)) {
183
+ BridgeService.printUnclaimedCharacteristicWarning(warning);
184
+ }
185
+ });
152
186
  });
153
187
  }
154
- // characteristic warning event has additional parameter originatorChain: string[] which is currently unused
188
+ /** The warnings {@link printCharacteristicWriteWarning} has taken, so the bridge does not print them again. */
189
+ static printedWarnings = new WeakSet();
190
+ /**
191
+ * Print a characteristic warning that no plugin's accessory has taken, the
192
+ * way HAP-NodeJS prints one nobody listens for.
193
+ */
194
+ static printUnclaimedCharacteristicWarning(warning) {
195
+ const message = `[${warning.originatorChain.join('@')}] ${warning.message}`;
196
+ switch (warning.type) {
197
+ case CharacteristicWarningType.ERROR_MESSAGE:
198
+ case CharacteristicWarningType.TIMEOUT_READ:
199
+ case CharacteristicWarningType.TIMEOUT_WRITE:
200
+ log.error(message);
201
+ break;
202
+ case CharacteristicWarningType.DEBUG_MESSAGE:
203
+ log.debug(message);
204
+ break;
205
+ default:
206
+ log.warn(message);
207
+ break;
208
+ }
209
+ if (warning.stack) {
210
+ log.debug(warning.stack);
211
+ }
212
+ }
213
+ /**
214
+ * Print the characteristic warnings of a platform accessory under its
215
+ * plugin's name, with one listener per accessory however often the
216
+ * accessory is registered.
217
+ *
218
+ * A plugin may unregister an accessory and register the same object again.
219
+ * HAP-NodeJS up to v2.3.0 removed every listener from an accessory taken off
220
+ * the bridge, which hid that a new listener was added on each registration;
221
+ * from v2.3.1 it leaves the listeners alone, and each warning would be
222
+ * printed once per registration.
223
+ */
224
+ watchCharacteristicWarnings(plugin, hapAccessory) {
225
+ const previous = this.characteristicWarningListeners.get(hapAccessory);
226
+ if (previous) {
227
+ hapAccessory.removeListener(AccessoryEventTypes.CHARACTERISTIC_WARNING, previous);
228
+ }
229
+ const listener = BridgeService.printCharacteristicWriteWarning.bind(BridgeService, plugin, hapAccessory, {});
230
+ this.characteristicWarningListeners.set(hapAccessory, listener);
231
+ hapAccessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, listener);
232
+ }
233
+ /**
234
+ * Print a characteristic warning (for a read as well as a write) under the
235
+ * name of the plugin, with the accessory it came from.
236
+ */
155
237
  static printCharacteristicWriteWarning(plugin, accessory, opts, warning) {
156
238
  const wikiInfo = 'See https://homebridge.io/w/JtMGR for more info.';
239
+ const prefix = getLogPrefix(plugin.getPluginIdentifier());
240
+ const source = `the characteristic '${warning.characteristic.displayName}' of the accessory '${accessory.displayName}'`;
241
+ // HAP-NodeJS ends some of its messages with a full stop, and some not
242
+ const message = /[.!?]$/.test(warning.message)
243
+ ? warning.message
244
+ : `${warning.message}.`;
245
+ BridgeService.printedWarnings.add(warning);
157
246
  switch (warning.type) {
158
- case "slow-read" /* CharacteristicWarningType.SLOW_READ */:
159
- case "slow-write" /* CharacteristicWarningType.SLOW_WRITE */:
247
+ case CharacteristicWarningType.SLOW_READ:
248
+ case CharacteristicWarningType.SLOW_WRITE:
160
249
  if (!opts.ignoreSlow) {
161
- log.info(getLogPrefix(plugin.getPluginIdentifier()), 'This plugin slows down Homebridge.', warning.message, wikiInfo);
250
+ log.info(prefix, 'This plugin slows down Homebridge.', warning.message, wikiInfo);
162
251
  }
163
252
  break;
164
- case "timeout-read" /* CharacteristicWarningType.TIMEOUT_READ */:
165
- case "timeout-write" /* CharacteristicWarningType.TIMEOUT_WRITE */:
166
- log.error(getLogPrefix(plugin.getPluginIdentifier()), 'This plugin slows down Homebridge.', warning.message, wikiInfo);
253
+ case CharacteristicWarningType.TIMEOUT_READ:
254
+ case CharacteristicWarningType.TIMEOUT_WRITE:
255
+ log.error(prefix, 'This plugin did not answer in time, which slows down Homebridge.', warning.message, wikiInfo);
167
256
  break;
168
- case "warn-message" /* CharacteristicWarningType.WARN_MESSAGE */:
169
- log.info(getLogPrefix(plugin.getPluginIdentifier()), `This plugin generated a warning from the characteristic '${warning.characteristic.displayName}':`, `${warning.message}.`, wikiInfo);
257
+ case CharacteristicWarningType.WARN_MESSAGE:
258
+ log.info(prefix, `This plugin generated a warning from ${source}:`, message, wikiInfo);
170
259
  break;
171
- case "error-message" /* CharacteristicWarningType.ERROR_MESSAGE */:
172
- log.error(getLogPrefix(plugin.getPluginIdentifier()), `This plugin threw an error from the characteristic '${warning.characteristic.displayName}':`, `${warning.message}.`, wikiInfo);
260
+ case CharacteristicWarningType.ERROR_MESSAGE:
261
+ log.error(prefix, `This plugin threw an error from ${source}:`, message, wikiInfo);
173
262
  break;
174
- case "debug-message" /* CharacteristicWarningType.DEBUG_MESSAGE */:
175
- log.debug(getLogPrefix(plugin.getPluginIdentifier()), `Characteristic '${warning.characteristic.displayName}':`, `${warning.message}.`, wikiInfo);
263
+ case CharacteristicWarningType.DEBUG_MESSAGE:
264
+ log.debug(prefix, `Characteristic '${warning.characteristic.displayName}' of the accessory '${accessory.displayName}':`, message, wikiInfo);
176
265
  break;
177
266
  default: // generic message for yet unknown types
178
- log.info(getLogPrefix(plugin.getPluginIdentifier()), `This plugin generated a warning from the characteristic '${warning.characteristic.displayName}':`, `${warning.message}.`, wikiInfo);
267
+ log.info(prefix, `This plugin generated a warning from ${source}:`, message, wikiInfo);
179
268
  break;
180
269
  }
181
270
  if (warning.stack) {
182
271
  log.debug(getLogPrefix(plugin.getPluginIdentifier()), warning.stack);
183
272
  }
184
273
  }
274
+ /**
275
+ * Say so in plain words when the port set for the bridge is in use by
276
+ * another program. HAP-NodeJS can not listen on it then, and Homebridge
277
+ * stops with an EADDRINUSE error that does not name the setting.
278
+ */
279
+ async checkBridgePort() {
280
+ const port = this.bridgeConfig.port;
281
+ if (typeof port === 'number' && port > 0 && await isPortInUse(port)) {
282
+ log.error('The port %d set for the bridge \'%s\' is in use by another program, so the bridge can not start on it. '
283
+ + 'Stop the other program, or set a different port for this bridge in the config.', port, this.bridgeConfig.name);
284
+ }
285
+ }
185
286
  publishBridge() {
186
287
  const bridgeConfig = this.bridgeConfig;
187
288
  const info = this.bridge.getService(Service.AccessoryInformation);
@@ -189,20 +290,28 @@ export class BridgeService {
189
290
  info.setCharacteristic(Characteristic.Model, bridgeConfig.model || DEFAULT_BRIDGE_DEFAULTS.model);
190
291
  info.setCharacteristic(Characteristic.SerialNumber, bridgeConfig.serialNumber || bridgeConfig.username);
191
292
  info.setCharacteristic(Characteristic.FirmwareRevision, bridgeConfig.firmwareRevision || getVersion());
192
- this.bridge.on("listening" /* AccessoryEventTypes.LISTENING */, (port) => {
293
+ this.bridge.on(AccessoryEventTypes.LISTENING, (port) => {
193
294
  log.success('Homebridge v%s (HAP v%s) (%s) is running on port %s.', getVersion(), HAPLibraryVersion(), bridgeConfig.name, port);
194
295
  });
195
296
  const publishInfo = {
196
297
  username: bridgeConfig.username,
197
298
  port: bridgeConfig.port,
198
299
  pincode: bridgeConfig.pin,
199
- category: 2 /* Categories.BRIDGE */,
300
+ category: Categories.BRIDGE,
200
301
  bind: bridgeConfig.bind,
201
302
  addIdentifyingMaterial: shouldAddIdentifyingMaterial(bridgeConfig.hap),
202
303
  advertiser: bridgeConfig.advertiser,
203
304
  };
204
- if (bridgeConfig.setupID && bridgeConfig.setupID.length === 4) {
205
- publishInfo.setupID = bridgeConfig.setupID;
305
+ if (bridgeConfig.setupID !== undefined && bridgeConfig.setupID !== null) {
306
+ if (typeof bridgeConfig.setupID === 'string' && bridgeConfig.setupID.length === 4) {
307
+ publishInfo.setupID = bridgeConfig.setupID;
308
+ if (!SETUP_ID_FORMAT.test(bridgeConfig.setupID)) {
309
+ log.warn('The setupID of the bridge \'%s\' should be 4 characters from 0-9 and A-Z. The Home app may not accept the QR code with it.', bridgeConfig.name);
310
+ }
311
+ }
312
+ else {
313
+ log.warn('The setupID of the bridge \'%s\' is not 4 characters long. Ignoring it: a random one is used.', bridgeConfig.name);
314
+ }
206
315
  }
207
316
  log.debug('Publishing bridge accessory (name: %s, publishInfo: %o).', this.bridge.displayName, BridgeService.strippingPinCode(publishInfo));
208
317
  // bridge.publish() returns a promise that can reject (e.g. mDNS
@@ -210,10 +319,7 @@ export class BridgeService {
210
319
  // them silently, so a failed publish only manifested as the bridge never
211
320
  // appearing in HomeKit with no log explanation.
212
321
  this.bridge.publish(publishInfo, this.allowInsecureAccess).catch((error) => {
213
- const message = error instanceof Error
214
- ? error.message
215
- : String(error);
216
- log.error('Failed to publish bridge accessory \'%s\': %s', this.bridge.displayName, message);
322
+ log.error('Failed to publish bridge accessory \'%s\': %s', this.bridge.displayName, errorMessage(error));
217
323
  });
218
324
  }
219
325
  /**
@@ -221,26 +327,51 @@ export class BridgeService {
221
327
  */
222
328
  async loadCachedPlatformAccessoriesFromDisk() {
223
329
  let cachedAccessories = null;
330
+ let fromBackup = false;
224
331
  try {
225
332
  cachedAccessories = await this.storageService.getItem(this.bridgeOptions.cachedAccessoriesItemName);
226
333
  }
227
334
  catch (error) {
228
- log.error('Failed to load cached accessories from disk:', error.message);
335
+ log.error('Failed to load cached accessories from disk:', errorMessage(error));
229
336
  if (error instanceof SyntaxError) {
230
337
  // syntax error probably means invalid JSON / corrupted file; try and restore from backup
231
338
  cachedAccessories = await this.restoreCachedAccessoriesBackup();
339
+ fromBackup = true;
232
340
  }
233
341
  else {
342
+ // The file may be fine and only this read failed (too many open
343
+ // files, a disk error). Writing the cache now would replace it with
344
+ // the few accessories registered since, so it is left alone.
234
345
  log.error('Not restoring cached accessories - some accessories may be reset.');
346
+ log.error(`The ${this.bridgeOptions.cachedAccessoriesItemName} file is left as it is: accessories will not be saved until Homebridge is restarted.`);
347
+ return;
235
348
  }
236
349
  }
237
- if (cachedAccessories) {
350
+ // Valid JSON that is not a list of accessories is as unusable as a file that does not parse
351
+ if (cachedAccessories !== null && !Array.isArray(cachedAccessories)) {
352
+ log.error(`The ${this.bridgeOptions.cachedAccessoriesItemName} file does not hold a list of accessories.`);
353
+ cachedAccessories = fromBackup
354
+ ? null
355
+ : await this.restoreCachedAccessoriesBackup();
356
+ fromBackup = true;
357
+ }
358
+ if (Array.isArray(cachedAccessories)) {
238
359
  log.info(`Loaded ${cachedAccessories.length} cached accessories from ${this.bridgeOptions.cachedAccessoriesItemName}.`);
239
- this.cachedPlatformAccessories = cachedAccessories.map((serialized) => {
240
- return PlatformAccessory.deserialize(serialized);
241
- });
242
- if (cachedAccessories.length) {
243
- // create a backup of the cache file
360
+ // One entry that can not be turned back into an accessory must not stop
361
+ // the others loading, or stop Homebridge starting: skip it and say so.
362
+ const accessories = [];
363
+ for (const serialized of cachedAccessories) {
364
+ try {
365
+ accessories.push(PlatformAccessory.deserialize(serialized));
366
+ }
367
+ catch (error) {
368
+ log.error(`Skipping the cached accessory '${serialized?.displayName ?? 'unknown'}' as it could not be read:`, errorMessage(error));
369
+ }
370
+ }
371
+ this.cachedPlatformAccessories = accessories;
372
+ // Back the file up only when it was read in full. A file that came from
373
+ // the backup, or that holds a bad entry, must not replace a good backup.
374
+ if (!fromBackup && accessories.length > 0 && accessories.length === cachedAccessories.length) {
244
375
  await this.createCachedAccessoriesBackup();
245
376
  }
246
377
  }
@@ -261,7 +392,7 @@ export class BridgeService {
261
392
  await this.storageService.copyItem(this.bridgeOptions.cachedAccessoriesItemName, this.backupCacheFileName);
262
393
  }
263
394
  catch (error) {
264
- log.warn(`Failed to create a backup of the ${this.bridgeOptions.cachedAccessoriesItemName} cached accessories file:`, error.message);
395
+ log.warn(`Failed to create a backup of the ${this.bridgeOptions.cachedAccessoriesItemName} cached accessories file:`, errorMessage(error));
265
396
  }
266
397
  }
267
398
  /**
@@ -271,12 +402,15 @@ export class BridgeService {
271
402
  async restoreCachedAccessoriesBackup() {
272
403
  try {
273
404
  const cachedAccessories = await this.storageService.getItem(this.backupCacheFileName);
274
- if (cachedAccessories && cachedAccessories.length) {
405
+ if (!Array.isArray(cachedAccessories)) {
406
+ return null;
407
+ }
408
+ if (cachedAccessories.length) {
275
409
  log.warn(`Recovered ${cachedAccessories.length} accessories from ${this.bridgeOptions.cachedAccessoriesItemName} cache backup.`);
276
410
  }
277
411
  return cachedAccessories;
278
412
  }
279
- catch (error) {
413
+ catch {
280
414
  return null;
281
415
  }
282
416
  }
@@ -302,12 +436,23 @@ export class BridgeService {
302
436
  if (!this.cachedPlatformAccessories.includes(accessory)) {
303
437
  continue;
304
438
  }
439
+ // A second entry with the UUID of an accessory that is on the bridge
440
+ // already can not be bridged. Drop it before the plugin is given it:
441
+ // the plugin would hold an accessory that HomeKit never sees.
442
+ const uuidOnBridge = accessory._associatedHAPAccessory.UUID;
443
+ if (this.bridge.bridgedAccessories.some(bridged => bridged.UUID === uuidOnBridge)) {
444
+ log.warn('%s Removing the cached accessory \'%s\': an accessory with the same UUID (%s) is on the bridge already.', accessory._associatedPlugin
445
+ ? getLogPrefix(accessory._associatedPlugin)
446
+ : '', accessory.displayName, uuidOnBridge);
447
+ orphanedAccessories.add(accessory);
448
+ continue;
449
+ }
305
450
  let plugin = this.pluginManager.getPlugin(accessory._associatedPlugin);
306
451
  if (!plugin) { // a little explainer here. This section is basically here to resolve plugin name changes of dynamic platform plugins
307
452
  try {
308
453
  // resolve platform accessories by searching for plugins which registered a dynamic platform for the given name
309
454
  plugin = this.pluginManager.getPluginByActiveDynamicPlatform(accessory._associatedPlatform);
310
- if (plugin) { // if it's undefined the no plugin was found
455
+ if (plugin) { // if it's undefined then no plugin was found
311
456
  // could improve on this by calculating the Levenshtein distance to only allow platform ownership changes
312
457
  // when something like a typo happened. Are there other reasons the name could change?
313
458
  // And how would we define the threshold?
@@ -316,14 +461,14 @@ export class BridgeService {
316
461
  accessory._associatedPlugin = plugin.getPluginIdentifier(); // update the associated plugin to the new one
317
462
  }
318
463
  }
319
- catch (error) { // error is thrown if multiple plugins where found for the given platform name
464
+ catch (error) { // error is thrown if multiple plugins were found for the given platform name
320
465
  log.info(`Could not find the associated plugin for the accessory '${accessory.displayName}'. `
321
- + `Tried to find the plugin by the platform name but ${error.message}`);
466
+ + `Tried to find the plugin by the platform name but ${errorMessage(error)}`);
322
467
  }
323
468
  }
324
469
  const platformPlugins = plugin && plugin.getActiveDynamicPlatform(accessory._associatedPlatform);
325
470
  if (plugin) {
326
- accessory._associatedHAPAccessory.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, BridgeService.printCharacteristicWriteWarning.bind(this, plugin, accessory._associatedHAPAccessory, {}));
471
+ this.watchCharacteristicWarnings(plugin, accessory._associatedHAPAccessory);
327
472
  }
328
473
  if (!platformPlugins) {
329
474
  log.info(`Failed to find plugin to handle accessory ${accessory._associatedHAPAccessory.displayName}`);
@@ -335,8 +480,19 @@ export class BridgeService {
335
480
  }
336
481
  else {
337
482
  // We set a placeholder for FirmwareRevision before configureAccessory is called so the plugin has the opportunity to override it.
483
+ // This means the firmware revision of a cached accessory is NOT kept over a restart: a plugin that sets it
484
+ // only when it first creates the accessory shows '0' from the next start on. A plugin has to set it again
485
+ // in configureAccessory(), or later. Kept as it is, since plugins may rely on the reset by now.
338
486
  accessory.getService(Service.AccessoryInformation)?.setCharacteristic(Characteristic.FirmwareRevision, '0');
339
- platformPlugins.configureAccessory(accessory);
487
+ // A platform that only does Matter may have no configureAccessory
488
+ if (typeof platformPlugins.configureAccessory === 'function') {
489
+ platformPlugins.configureAccessory(accessory);
490
+ }
491
+ // The plugin may have unregistered this very accessory while it was
492
+ // being configured: it is out of the cache then, and must stay off the bridge.
493
+ if (!this.cachedPlatformAccessories.includes(accessory)) {
494
+ continue;
495
+ }
340
496
  }
341
497
  try {
342
498
  this.bridge.addBridgedAccessory(accessory._associatedHAPAccessory);
@@ -344,7 +500,7 @@ export class BridgeService {
344
500
  catch (error) {
345
501
  log.warn(`${accessory._associatedPlugin
346
502
  ? getLogPrefix(accessory._associatedPlugin)
347
- : ''} Could not restore cached accessory '${accessory._associatedHAPAccessory.displayName}':`, error.message);
503
+ : ''} Could not restore cached accessory '${accessory._associatedHAPAccessory.displayName}':`, errorMessage(error));
348
504
  orphanedAccessories.add(accessory); // remove it from the list
349
505
  }
350
506
  }
@@ -353,19 +509,69 @@ export class BridgeService {
353
509
  }
354
510
  }
355
511
  /**
356
- * Save the cached accessories back to disk.
512
+ * Save the cached accessories after a plugin registered, updated or
513
+ * unregistered some, without writing the file more than once in
514
+ * {@link CACHE_SAVE_INTERVAL}.
515
+ *
516
+ * Every save writes the accessories of all plugins, and blocks while it
517
+ * does. Some plugins call `updatePlatformAccessories()` on each change of
518
+ * state, which was one full write per call. The first request is written at
519
+ * once; those that follow within the interval are written together when it
520
+ * ends. From the shutdown on every request is written at once, as nothing
521
+ * may be left for a timer then.
522
+ */
523
+ requestCacheSave() {
524
+ if (this.cacheSaveTimer && !this.shuttingDown) {
525
+ this.cacheSavePending = true;
526
+ return;
527
+ }
528
+ this.saveCachedPlatformAccessoriesOnDisk();
529
+ if (!this.cacheSaveTimer && !this.shuttingDown) {
530
+ this.cacheSaveTimer = setTimeout(() => {
531
+ this.cacheSaveTimer = undefined;
532
+ if (this.cacheSavePending) {
533
+ this.requestCacheSave();
534
+ }
535
+ }, CACHE_SAVE_INTERVAL);
536
+ this.cacheSaveTimer.unref();
537
+ }
538
+ }
539
+ /**
540
+ * Save the cached accessories back to disk, now.
357
541
  */
358
542
  saveCachedPlatformAccessoriesOnDisk() {
543
+ // whatever was waiting for the timer is written by this save
544
+ this.cacheSavePending = false;
359
545
  try {
360
546
  // only save the cache file back to disk if we have already attempted to load it
361
547
  // this should prevent the cache being deleted should homebridge be shutdown before it has finished launching
362
548
  if (this.cachedAccessoriesFileLoaded) {
363
- const serializedAccessories = this.cachedPlatformAccessories.map(accessory => PlatformAccessory.serialize(accessory));
549
+ // One accessory that can not be written (a plugin put something in its
550
+ // context that JSON can not hold, like a value that refers to itself)
551
+ // must not stop the accessories of every plugin being saved.
552
+ const serializedAccessories = [];
553
+ for (const accessory of this.cachedPlatformAccessories) {
554
+ try {
555
+ const serialized = PlatformAccessory.serialize(accessory);
556
+ JSON.stringify(serialized);
557
+ serializedAccessories.push(serialized);
558
+ this.unsavableAccessories.delete(accessory);
559
+ }
560
+ catch (error) {
561
+ // said once per accessory, not on every save
562
+ if (!this.unsavableAccessories.has(accessory)) {
563
+ this.unsavableAccessories.add(accessory);
564
+ log.error('%s The accessory \'%s\' can not be saved to the accessory cache, and will not be there after a restart: %s', accessory._associatedPlugin
565
+ ? getLogPrefix(accessory._associatedPlugin)
566
+ : '', accessory.displayName, errorMessage(error));
567
+ }
568
+ }
569
+ }
364
570
  this.storageService.setItemSync(this.bridgeOptions.cachedAccessoriesItemName, serializedAccessories);
365
571
  }
366
572
  }
367
573
  catch (error) {
368
- log.error('Failed to save cached accessories to disk:', error.message);
574
+ log.error('Failed to save cached accessories to disk:', errorMessage(error));
369
575
  log.error('Your accessories will not persist between restarts until this issue is resolved.');
370
576
  }
371
577
  }
@@ -384,7 +590,7 @@ export class BridgeService {
384
590
  this.storageService.setItemSync(this.bridgeOptions.externalAccessoriesItemName, entries);
385
591
  }
386
592
  catch (error) {
387
- log.error('Failed to save external accessories metadata to disk:', error.message);
593
+ log.error('Failed to save external accessories metadata to disk:', errorMessage(error));
388
594
  }
389
595
  }
390
596
  handleRegisterPlatformAccessories(accessories) {
@@ -400,7 +606,7 @@ export class BridgeService {
400
606
  }
401
607
  const cachedAccessories = new Map(this.cachedPlatformAccessories.map(accessory => [accessory._associatedHAPAccessory.UUID, accessory]));
402
608
  const bridgedAccessories = new Map(this.bridge.bridgedAccessories.map(accessory => [accessory.UUID, accessory]));
403
- const hapAccessories = [];
609
+ let added = false;
404
610
  for (const accessory of accessories) {
405
611
  const newUUID = accessory._associatedHAPAccessory.UUID;
406
612
  // Check for UUID collision against already-cached platform accessories.
@@ -419,6 +625,24 @@ export class BridgeService {
419
625
  log.warn('Accessory \'%s\' has the same UUID as existing bridged accessory \'%s\' (UUID: %s). Skipping duplicate.', accessory.displayName, bridgedCollision.displayName, newUUID);
420
626
  continue;
421
627
  }
628
+ // Into the cache only once HAP-NodeJS has taken the accessory. It refuses
629
+ // more than its limit of accessories on one bridge, and one that was
630
+ // published on its own before. That throw went back into the plugin
631
+ // (from didFinishLaunching it stopped Homebridge starting), with the
632
+ // refused accessory and the rest of the batch in the cache but not on
633
+ // the bridge.
634
+ try {
635
+ this.bridge.addBridgedAccessory(accessory._associatedHAPAccessory, true);
636
+ }
637
+ catch (error) {
638
+ log.error('%s The accessory \'%s\' could not be added to the bridge \'%s\' and is not registered: %s%s', accessory._associatedPlugin
639
+ ? getLogPrefix(accessory._associatedPlugin)
640
+ : '', accessory.displayName, this.bridge.displayName, errorMessage(error), this.bridge.bridgedAccessories.length >= MAX_BRIDGED_ACCESSORIES
641
+ ? `. A bridge can hold ${MAX_BRIDGED_ACCESSORIES} accessories at most: run the plugin as a child bridge, or remove accessories.`
642
+ : '');
643
+ continue;
644
+ }
645
+ added = true;
422
646
  this.cachedPlatformAccessories.push(accessory);
423
647
  cachedAccessories.set(newUUID, accessory);
424
648
  const plugin = this.pluginManager.getPlugin(accessory._associatedPlugin);
@@ -427,40 +651,65 @@ export class BridgeService {
427
651
  if (!platforms) {
428
652
  log.warn('The plugin \'%s\' registered a new accessory for the platform \'%s\'. The platform couldn\'t be found though!', accessory._associatedPlugin, accessory._associatedPlatform);
429
653
  }
430
- accessory._associatedHAPAccessory.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, BridgeService.printCharacteristicWriteWarning.bind(this, plugin, accessory._associatedHAPAccessory, {}));
654
+ this.watchCharacteristicWarnings(plugin, accessory._associatedHAPAccessory);
431
655
  }
432
656
  else {
433
657
  log.warn('A platform configured a new accessory under the plugin name \'%s\'. However no loaded plugin could be found for the name!', accessory._associatedPlugin);
434
658
  }
435
- hapAccessories.push(accessory._associatedHAPAccessory);
436
659
  }
437
- this.bridge.addBridgedAccessories(hapAccessories);
438
- this.saveCachedPlatformAccessoriesOnDisk();
660
+ if (added) {
661
+ // The accessories were added one by one with the update of the
662
+ // configuration put off; adding an empty list sends that one update.
663
+ this.bridge.addBridgedAccessories([]);
664
+ }
665
+ this.requestCacheSave();
439
666
  }
440
667
  handleUpdatePlatformAccessories(accessories) {
441
668
  if (!Array.isArray(accessories)) {
442
669
  // This could be quite destructive if a non-array is passed in, so we'll just ignore it.
443
670
  return;
444
671
  }
445
- const updatedUUIDs = new Set(accessories.map(accessory => accessory.UUID));
446
- this.cachedPlatformAccessories = this.cachedPlatformAccessories.filter(accessory => !updatedUUIDs.has(accessory._associatedHAPAccessory.UUID));
447
- this.cachedPlatformAccessories.push(...accessories);
672
+ // Swap in the object the plugin passed for each accessory that is in the
673
+ // cache, in place. One that is not in the cache is left out: it was never
674
+ // registered, was unregistered since, or is an external accessory (which
675
+ // can not be saved, and would make every later save of the cache fail).
676
+ const updated = new Map();
677
+ for (const accessory of accessories) {
678
+ updated.set(accessory.UUID, accessory);
679
+ }
680
+ this.cachedPlatformAccessories = this.cachedPlatformAccessories.map((cached) => {
681
+ const replacement = updated.get(cached.UUID);
682
+ updated.delete(cached.UUID);
683
+ return replacement ?? cached;
684
+ });
685
+ for (const accessory of updated.values()) {
686
+ log.warn('Ignoring an update for the accessory \'%s\' (UUID: %s), which is not registered as a platform accessory on this bridge.', accessory.displayName, accessory.UUID);
687
+ }
448
688
  // Update persisted accessories
449
- this.saveCachedPlatformAccessoriesOnDisk();
689
+ this.requestCacheSave();
450
690
  }
451
691
  handleUnregisterPlatformAccessories(accessories) {
452
692
  const removedAccessories = new Set(accessories);
453
693
  this.cachedPlatformAccessories = this.cachedPlatformAccessories.filter(accessory => !removedAccessories.has(accessory));
454
- const hapAccessories = accessories.map(accessory => accessory._associatedHAPAccessory);
455
- this.bridge.removeBridgedAccessories(hapAccessories);
456
- this.saveCachedPlatformAccessoriesOnDisk();
694
+ // Only what is really on the bridge. HAP-NodeJS throws for anything else,
695
+ // and a plugin may well unregister an accessory that is not there (yet):
696
+ // a cached one from inside configureAccessory(), before the restore has
697
+ // reached it, or the same accessory twice. That throw went back into the
698
+ // plugin, and from configureAccessory() it stopped Homebridge starting.
699
+ const bridgedAccessories = new Set(this.bridge.bridgedAccessories);
700
+ const hapAccessories = accessories
701
+ .map(accessory => accessory._associatedHAPAccessory)
702
+ .filter(hapAccessory => bridgedAccessories.has(hapAccessory));
703
+ if (hapAccessories.length > 0) {
704
+ this.bridge.removeBridgedAccessories(hapAccessories);
705
+ }
706
+ this.requestCacheSave();
457
707
  }
458
708
  async handlePublishExternalAccessories(accessories) {
459
709
  // HAP must be enabled to publish externals, unless the bridge is in
460
710
  // externalsOnly mode (where the bridge itself is suppressed but its
461
711
  // externals continue to advertise as standalone HAP accessories).
462
- const hap = this.bridgeConfig.hap;
463
- if (!isHapConfigEnabled(hap) && !isHapExternalsOnly(hap)) {
712
+ if (!isHapActive(this.bridgeConfig.hap)) {
464
713
  log.debug('Skipping external accessory HAP publish: HAP is disabled for this bridge (hap.enabled=false).');
465
714
  return;
466
715
  }
@@ -468,30 +717,51 @@ export class BridgeService {
468
717
  for (const accessory of accessories) {
469
718
  const hapAccessory = accessory._associatedHAPAccessory;
470
719
  const advertiseAddress = generate(hapAccessory.UUID);
471
- // get external port allocation
472
- const accessoryPort = await this.externalPortService.requestPort(advertiseAddress);
473
720
  if (this.publishedExternalAccessories.has(advertiseAddress)) {
474
- throw new Error(`Accessory ${hapAccessory.displayName} experienced an address collision.`);
721
+ log.error('The external accessory \'%s\' is not published: an external accessory with the same UUID (%s) is published already.', hapAccessory.displayName, hapAccessory.UUID);
722
+ continue;
475
723
  }
476
- else {
477
- this.publishedExternalAccessories.set(advertiseAddress, accessory);
478
- this.publishedExternalAccessoriesMetadata.set(advertiseAddress, {
479
- username: advertiseAddress,
480
- plugin: accessory._associatedPlugin,
481
- displayName: hapAccessory.displayName,
482
- category: accessory.category,
483
- port: accessoryPort,
484
- });
724
+ // Taken now, before the waits below: a second call for the same
725
+ // accessory that runs at the same time (a plugin that does not await
726
+ // the first) is then refused above, and does not publish it again.
727
+ this.publishedExternalAccessories.set(advertiseAddress, accessory);
728
+ // This handler runs from an event, so the plugin can not catch what it
729
+ // throws: an error here became an unhandled rejection, which shuts
730
+ // Homebridge down. A problem with one accessory is logged, and the
731
+ // others in the batch are still published.
732
+ let accessoryPort;
733
+ try {
734
+ // get external port allocation
735
+ accessoryPort = await this.externalPortService.requestPort(advertiseAddress);
736
+ }
737
+ catch (error) {
738
+ log.error('Could not get a port for the external accessory \'%s\', so it is not published: %s', hapAccessory.displayName, errorMessage(error));
739
+ this.publishedExternalAccessories.delete(advertiseAddress);
740
+ continue;
741
+ }
742
+ // A port from the pool that another program holds would end Homebridge
743
+ // with an uncaught EADDRINUSE. Use a random free port for this accessory
744
+ // instead, as is done when the pool has run out.
745
+ if (accessoryPort !== undefined && await isPortInUse(accessoryPort)) {
746
+ log.warn('The port %d from the \'ports\' range in the config is in use by another program. The external accessory \'%s\' is given a random port instead.', accessoryPort, hapAccessory.displayName);
747
+ accessoryPort = undefined;
485
748
  }
749
+ this.publishedExternalAccessoriesMetadata.set(advertiseAddress, {
750
+ username: advertiseAddress,
751
+ plugin: accessory._associatedPlugin,
752
+ displayName: hapAccessory.displayName,
753
+ category: accessory.category,
754
+ port: accessoryPort,
755
+ });
486
756
  const plugin = this.pluginManager.getPlugin(accessory._associatedPlugin);
487
757
  if (plugin) {
488
- hapAccessory.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, BridgeService.printCharacteristicWriteWarning.bind(this, plugin, hapAccessory, { ignoreSlow: true }));
758
+ hapAccessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, BridgeService.printCharacteristicWriteWarning.bind(BridgeService, plugin, hapAccessory, { ignoreSlow: true }));
489
759
  }
490
760
  else if (PluginManager.isQualifiedPluginIdentifier(accessory._associatedPlugin)) {
491
761
  // we did already complain in api.ts if it wasn't a qualified name
492
- log.warn('A platform configured a external accessory under the plugin name \'%s\'. However no loaded plugin could be found for the name!', accessory._associatedPlugin);
762
+ log.warn('A platform configured an external accessory under the plugin name \'%s\'. However no loaded plugin could be found for the name!', accessory._associatedPlugin);
493
763
  }
494
- hapAccessory.on("listening" /* AccessoryEventTypes.LISTENING */, (port) => {
764
+ hapAccessory.on(AccessoryEventTypes.LISTENING, (port) => {
495
765
  log.success('%s is running on port %s.', hapAccessory.displayName, port);
496
766
  log.info('Please add [%s] manually in Home app. Setup Code: %s', hapAccessory.displayName, accessoryPin);
497
767
  });
@@ -506,10 +776,7 @@ export class BridgeService {
506
776
  };
507
777
  log.debug('Publishing external accessory (name: %s, publishInfo: %o).', hapAccessory.displayName, BridgeService.strippingPinCode(publishInfo));
508
778
  hapAccessory.publish(publishInfo, this.allowInsecureAccess).catch((error) => {
509
- const message = error instanceof Error
510
- ? error.message
511
- : String(error);
512
- log.error('Failed to publish external accessory \'%s\': %s', hapAccessory.displayName, message);
779
+ log.error('Failed to publish external accessory \'%s\': %s', hapAccessory.displayName, errorMessage(error));
513
780
  });
514
781
  }
515
782
  this.saveExternalAccessoriesMetadataOnDisk();
@@ -528,8 +795,9 @@ export class BridgeService {
528
795
  const accessory = new Accessory(displayName, accessoryUUID);
529
796
  // listen for the identify event if the accessory instance has defined an identify() method
530
797
  if (accessoryInstance.identify) {
531
- accessory.on("identify" /* AccessoryEventTypes.IDENTIFY */, (paired, callback) => {
532
- // @ts-expect-error: empty callback for backwards compatibility
798
+ accessory.on(AccessoryEventTypes.IDENTIFY, (paired, callback) => {
799
+ // empty callback for backwards compatibility
800
+ ;
533
801
  accessoryInstance.identify(() => { });
534
802
  callback();
535
803
  });
@@ -541,7 +809,7 @@ export class BridgeService {
541
809
  service.setCharacteristic(Characteristic.Name, displayName); // ensure display name is set
542
810
  // ensure the plugin has not hooked already some listeners (some weird ones do).
543
811
  // Otherwise, they would override our identify listener registered by the HAP-NodeJS accessory
544
- service.getCharacteristic(Characteristic.Identify).removeAllListeners("set" /* CharacteristicEventTypes.SET */);
812
+ service.getCharacteristic(Characteristic.Identify).removeAllListeners(CharacteristicEventTypes.SET);
545
813
  // pull out any values and listeners (get and set) you may have defined
546
814
  informationService.replaceCharacteristicsFromService(service);
547
815
  }
@@ -549,7 +817,7 @@ export class BridgeService {
549
817
  accessory.addService(service);
550
818
  }
551
819
  });
552
- accessory.on("characteristic-warning" /* AccessoryEventTypes.CHARACTERISTIC_WARNING */, BridgeService.printCharacteristicWriteWarning.bind(this, plugin, accessory, {}));
820
+ accessory.on(AccessoryEventTypes.CHARACTERISTIC_WARNING, BridgeService.printCharacteristicWriteWarning.bind(BridgeService, plugin, accessory, {}));
553
821
  controllers.forEach((controller) => {
554
822
  accessory.configureController(controller);
555
823
  });
@@ -558,37 +826,65 @@ export class BridgeService {
558
826
  async loadPlatformAccessories(plugin, platformInstance, platformType, logger) {
559
827
  // Plugin 1.0, load accessories
560
828
  return new Promise((resolve) => {
561
- // warn the user if the static platform is blocking the startup of Homebridge for to long
829
+ // warn the user if the static platform is blocking the startup of Homebridge for too long
562
830
  const loadDelayWarningInterval = setInterval(() => {
563
- log.warn(getLogPrefix(plugin.getPluginIdentifier()), 'This plugin is taking long time to load and preventing Homebridge from starting. See https://homebridge.io/w/JtMGR for more info.');
831
+ log.warn(getLogPrefix(plugin.getPluginIdentifier()), 'This plugin is taking a long time to load and preventing Homebridge from starting. See https://homebridge.io/w/JtMGR for more info.');
564
832
  }, 20000);
565
833
  platformInstance.accessories(once((accessories) => {
566
834
  // clear the load delay warning interval
567
835
  clearInterval(loadDelayWarningInterval);
568
836
  // loop through accessories adding them to the list and registering them
569
837
  accessories.forEach((accessoryInstance, index) => {
570
- // @ts-expect-error: assume this property was set
571
- const accessoryName = accessoryInstance.name;
572
- // @ts-expect-error: optional base uuid
573
- const uuidBase = accessoryInstance.uuid_base;
838
+ // the name is assumed to be set; the base for the uuid is optional
839
+ const { name: accessoryName, uuid_base: uuidBase } = accessoryInstance;
574
840
  log.info('Initializing platform accessory \'%s\'...', accessoryName);
575
- const accessory = this.createHAPAccessory(plugin, accessoryInstance, accessoryName, platformType, uuidBase);
576
- if (accessory) {
577
- this.bridge.addBridgedAccessory(accessory);
841
+ // One accessory the bridge refuses (HAP-NodeJS throws for a second
842
+ // accessory with the same UUID, which here means the same name) must
843
+ // not stop the others, or stop Homebridge starting.
844
+ try {
845
+ const accessory = this.createHAPAccessory(plugin, accessoryInstance, accessoryName, platformType, uuidBase);
846
+ if (accessory) {
847
+ this.bridge.addBridgedAccessory(accessory);
848
+ }
849
+ else {
850
+ logger.info('Platform %s returned an accessory at index %d with an empty set of services; not adding it to the bridge.', platformType, index);
851
+ }
578
852
  }
579
- else {
580
- logger('Platform %s returned an accessory at index %d with an empty set of services. Won\'t adding it to the bridge!', platformType, index);
853
+ catch (error) {
854
+ logger.error(`Error loading the accessory "${accessoryName}" (index ${index}) of the platform "${platformType}" from "${plugin.getPluginIdentifier()}":`, errorMessage(error));
581
855
  }
582
856
  });
583
857
  resolve();
584
858
  }));
585
859
  });
586
860
  }
861
+ /**
862
+ * Take the bridge and its external accessories off the network, save the
863
+ * cache and tell the plugins that Homebridge is shutting down.
864
+ *
865
+ * Everything but the wait happens before this returns. The promise is for
866
+ * the goodbye that HAP-NodeJS sends for each accessory: it resolves when
867
+ * they are all sent, or after {@link UNPUBLISH_TIMEOUT} at the latest, and
868
+ * never rejects (a failed unpublish is logged).
869
+ */
587
870
  teardown() {
588
- void this.bridge.unpublish();
589
- for (const accessory of this.publishedExternalAccessories.values()) {
590
- void accessory._associatedHAPAccessory.unpublish();
591
- }
871
+ const accessories = [
872
+ this.bridge,
873
+ ...Array.from(this.publishedExternalAccessories.values(), accessory => accessory._associatedHAPAccessory),
874
+ ];
875
+ const unpublished = Promise.allSettled(accessories.map(async (accessory) => accessory.unpublish()))
876
+ .then((results) => {
877
+ results.forEach((result, index) => {
878
+ if (result.status === 'rejected') {
879
+ log.warn('Could not take \'%s\' off the network cleanly: %s', accessories[index].displayName, errorMessage(result.reason));
880
+ }
881
+ });
882
+ });
883
+ // Writes what was waiting for the save timer too. From here on a save is
884
+ // not put off: the process may be gone before a timer runs.
885
+ this.shuttingDown = true;
886
+ clearTimeout(this.cacheSaveTimer);
887
+ this.cacheSaveTimer = undefined;
592
888
  this.saveCachedPlatformAccessoriesOnDisk();
593
889
  // signalShutdown fires last so plugin shutdown listeners run with the
594
890
  // UPDATE_PLATFORM_ACCESSORIES handler still attached. Plugins may do
@@ -596,6 +892,12 @@ export class BridgeService {
596
892
  // call api.updatePlatformAccessories() afterwards; that call needs the
597
893
  // handler in place to persist any context updates to disk.
598
894
  this.api.signalShutdown();
895
+ let timer;
896
+ const timeout = new Promise((resolve) => {
897
+ timer = setTimeout(resolve, UNPUBLISH_TIMEOUT);
898
+ timer.unref();
899
+ });
900
+ return Promise.race([unpublished, timeout]).finally(() => clearTimeout(timer));
599
901
  }
600
902
  static strippingPinCode(publishInfo) {
601
903
  const info = {