matterbridge 3.1.6-dev-20250720-88d6141 → 3.1.6

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 (236) hide show
  1. package/CHANGELOG.md +6 -4
  2. package/README-DOCKER.md +35 -0
  3. package/dist/cli.d.ts +26 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +91 -2
  6. package/dist/cli.js.map +1 -0
  7. package/dist/cliEmitter.d.ts +34 -0
  8. package/dist/cliEmitter.d.ts.map +1 -0
  9. package/dist/cliEmitter.js +30 -0
  10. package/dist/cliEmitter.js.map +1 -0
  11. package/dist/clusters/export.d.ts +2 -0
  12. package/dist/clusters/export.d.ts.map +1 -0
  13. package/dist/clusters/export.js +2 -0
  14. package/dist/clusters/export.js.map +1 -0
  15. package/dist/defaultConfigSchema.d.ts +28 -0
  16. package/dist/defaultConfigSchema.d.ts.map +1 -0
  17. package/dist/defaultConfigSchema.js +24 -0
  18. package/dist/defaultConfigSchema.js.map +1 -0
  19. package/dist/deviceManager.d.ts +112 -0
  20. package/dist/deviceManager.d.ts.map +1 -0
  21. package/dist/deviceManager.js +94 -1
  22. package/dist/deviceManager.js.map +1 -0
  23. package/dist/devices/batteryStorage.d.ts +48 -0
  24. package/dist/devices/batteryStorage.d.ts.map +1 -0
  25. package/dist/devices/batteryStorage.js +48 -1
  26. package/dist/devices/batteryStorage.js.map +1 -0
  27. package/dist/devices/dishwasher.d.ts +91 -0
  28. package/dist/devices/dishwasher.d.ts.map +1 -0
  29. package/dist/devices/dishwasher.js +78 -3
  30. package/dist/devices/dishwasher.js.map +1 -0
  31. package/dist/devices/evse.d.ts +75 -0
  32. package/dist/devices/evse.d.ts.map +1 -0
  33. package/dist/devices/evse.js +74 -10
  34. package/dist/devices/evse.js.map +1 -0
  35. package/dist/devices/export.d.ts +11 -0
  36. package/dist/devices/export.d.ts.map +1 -0
  37. package/dist/devices/export.js +2 -0
  38. package/dist/devices/export.js.map +1 -0
  39. package/dist/devices/extractorHood.d.ts +46 -0
  40. package/dist/devices/extractorHood.d.ts.map +1 -0
  41. package/dist/devices/extractorHood.js +42 -0
  42. package/dist/devices/extractorHood.js.map +1 -0
  43. package/dist/devices/heatPump.d.ts +47 -0
  44. package/dist/devices/heatPump.d.ts.map +1 -0
  45. package/dist/devices/heatPump.js +50 -2
  46. package/dist/devices/heatPump.js.map +1 -0
  47. package/dist/devices/laundryDryer.d.ts +87 -0
  48. package/dist/devices/laundryDryer.d.ts.map +1 -0
  49. package/dist/devices/laundryDryer.js +83 -6
  50. package/dist/devices/laundryDryer.js.map +1 -0
  51. package/dist/devices/laundryWasher.d.ts +242 -0
  52. package/dist/devices/laundryWasher.d.ts.map +1 -0
  53. package/dist/devices/laundryWasher.js +91 -7
  54. package/dist/devices/laundryWasher.js.map +1 -0
  55. package/dist/devices/roboticVacuumCleaner.d.ts +112 -0
  56. package/dist/devices/roboticVacuumCleaner.d.ts.map +1 -0
  57. package/dist/devices/roboticVacuumCleaner.js +93 -7
  58. package/dist/devices/roboticVacuumCleaner.js.map +1 -0
  59. package/dist/devices/solarPower.d.ts +40 -0
  60. package/dist/devices/solarPower.d.ts.map +1 -0
  61. package/dist/devices/solarPower.js +38 -0
  62. package/dist/devices/solarPower.js.map +1 -0
  63. package/dist/devices/waterHeater.d.ts +111 -0
  64. package/dist/devices/waterHeater.d.ts.map +1 -0
  65. package/dist/devices/waterHeater.js +82 -2
  66. package/dist/devices/waterHeater.js.map +1 -0
  67. package/dist/dgram/dgram.d.ts +140 -0
  68. package/dist/dgram/dgram.d.ts.map +1 -0
  69. package/dist/dgram/dgram.js +348 -0
  70. package/dist/dgram/dgram.js.map +1 -0
  71. package/dist/dgram/mdns.d.ts +288 -0
  72. package/dist/dgram/mdns.d.ts.map +1 -0
  73. package/dist/dgram/mdns.js +840 -0
  74. package/dist/dgram/mdns.js.map +1 -0
  75. package/dist/dgram/multicast.d.ts +65 -0
  76. package/dist/dgram/multicast.d.ts.map +1 -0
  77. package/dist/dgram/multicast.js +170 -0
  78. package/dist/dgram/multicast.js.map +1 -0
  79. package/dist/dgram/unicast.d.ts +56 -0
  80. package/dist/dgram/unicast.d.ts.map +1 -0
  81. package/dist/dgram/unicast.js +91 -0
  82. package/dist/dgram/unicast.js.map +1 -0
  83. package/dist/frontend.d.ts +304 -0
  84. package/dist/frontend.d.ts.map +1 -0
  85. package/dist/frontend.js +435 -21
  86. package/dist/frontend.js.map +1 -0
  87. package/dist/globalMatterbridge.d.ts +59 -0
  88. package/dist/globalMatterbridge.d.ts.map +1 -0
  89. package/dist/globalMatterbridge.js +47 -0
  90. package/dist/globalMatterbridge.js.map +1 -0
  91. package/dist/helpers.d.ts +48 -0
  92. package/dist/helpers.d.ts.map +1 -0
  93. package/dist/helpers.js +53 -0
  94. package/dist/helpers.js.map +1 -0
  95. package/dist/index.d.ts +33 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +30 -1
  98. package/dist/index.js.map +1 -0
  99. package/dist/logger/export.d.ts +2 -0
  100. package/dist/logger/export.d.ts.map +1 -0
  101. package/dist/logger/export.js +1 -0
  102. package/dist/logger/export.js.map +1 -0
  103. package/dist/matter/behaviors.d.ts +2 -0
  104. package/dist/matter/behaviors.d.ts.map +1 -0
  105. package/dist/matter/behaviors.js +2 -0
  106. package/dist/matter/behaviors.js.map +1 -0
  107. package/dist/matter/clusters.d.ts +2 -0
  108. package/dist/matter/clusters.d.ts.map +1 -0
  109. package/dist/matter/clusters.js +2 -0
  110. package/dist/matter/clusters.js.map +1 -0
  111. package/dist/matter/devices.d.ts +2 -0
  112. package/dist/matter/devices.d.ts.map +1 -0
  113. package/dist/matter/devices.js +2 -0
  114. package/dist/matter/devices.js.map +1 -0
  115. package/dist/matter/endpoints.d.ts +2 -0
  116. package/dist/matter/endpoints.d.ts.map +1 -0
  117. package/dist/matter/endpoints.js +2 -0
  118. package/dist/matter/endpoints.js.map +1 -0
  119. package/dist/matter/export.d.ts +5 -0
  120. package/dist/matter/export.d.ts.map +1 -0
  121. package/dist/matter/export.js +3 -0
  122. package/dist/matter/export.js.map +1 -0
  123. package/dist/matter/types.d.ts +3 -0
  124. package/dist/matter/types.d.ts.map +1 -0
  125. package/dist/matter/types.js +3 -0
  126. package/dist/matter/types.js.map +1 -0
  127. package/dist/matterbridge.d.ts +460 -0
  128. package/dist/matterbridge.d.ts.map +1 -0
  129. package/dist/matterbridge.js +810 -52
  130. package/dist/matterbridge.js.map +1 -0
  131. package/dist/matterbridgeAccessoryPlatform.d.ts +42 -0
  132. package/dist/matterbridgeAccessoryPlatform.d.ts.map +1 -0
  133. package/dist/matterbridgeAccessoryPlatform.js +36 -0
  134. package/dist/matterbridgeAccessoryPlatform.js.map +1 -0
  135. package/dist/matterbridgeBehaviors.d.ts +1351 -0
  136. package/dist/matterbridgeBehaviors.d.ts.map +1 -0
  137. package/dist/matterbridgeBehaviors.js +68 -5
  138. package/dist/matterbridgeBehaviors.js.map +1 -0
  139. package/dist/matterbridgeDeviceTypes.d.ts +709 -0
  140. package/dist/matterbridgeDeviceTypes.d.ts.map +1 -0
  141. package/dist/matterbridgeDeviceTypes.js +579 -15
  142. package/dist/matterbridgeDeviceTypes.js.map +1 -0
  143. package/dist/matterbridgeDynamicPlatform.d.ts +42 -0
  144. package/dist/matterbridgeDynamicPlatform.d.ts.map +1 -0
  145. package/dist/matterbridgeDynamicPlatform.js +36 -0
  146. package/dist/matterbridgeDynamicPlatform.js.map +1 -0
  147. package/dist/matterbridgeEndpoint.d.ts +1328 -0
  148. package/dist/matterbridgeEndpoint.d.ts.map +1 -0
  149. package/dist/matterbridgeEndpoint.js +1200 -43
  150. package/dist/matterbridgeEndpoint.js.map +1 -0
  151. package/dist/matterbridgeEndpointHelpers.d.ts +3198 -0
  152. package/dist/matterbridgeEndpointHelpers.d.ts.map +1 -0
  153. package/dist/matterbridgeEndpointHelpers.js +322 -12
  154. package/dist/matterbridgeEndpointHelpers.js.map +1 -0
  155. package/dist/matterbridgePlatform.d.ts +310 -0
  156. package/dist/matterbridgePlatform.d.ts.map +1 -0
  157. package/dist/matterbridgePlatform.js +233 -0
  158. package/dist/matterbridgePlatform.js.map +1 -0
  159. package/dist/matterbridgeTypes.d.ts +195 -0
  160. package/dist/matterbridgeTypes.d.ts.map +1 -0
  161. package/dist/matterbridgeTypes.js +25 -0
  162. package/dist/matterbridgeTypes.js.map +1 -0
  163. package/dist/pluginManager.d.ts +270 -0
  164. package/dist/pluginManager.d.ts.map +1 -0
  165. package/dist/pluginManager.js +249 -3
  166. package/dist/pluginManager.js.map +1 -0
  167. package/dist/shelly.d.ts +174 -0
  168. package/dist/shelly.d.ts.map +1 -0
  169. package/dist/shelly.js +168 -7
  170. package/dist/shelly.js.map +1 -0
  171. package/dist/storage/export.d.ts +2 -0
  172. package/dist/storage/export.d.ts.map +1 -0
  173. package/dist/storage/export.js +1 -0
  174. package/dist/storage/export.js.map +1 -0
  175. package/dist/update.d.ts +59 -0
  176. package/dist/update.d.ts.map +1 -0
  177. package/dist/update.js +54 -0
  178. package/dist/update.js.map +1 -0
  179. package/dist/utils/colorUtils.d.ts +117 -0
  180. package/dist/utils/colorUtils.d.ts.map +1 -0
  181. package/dist/utils/colorUtils.js +263 -2
  182. package/dist/utils/colorUtils.js.map +1 -0
  183. package/dist/utils/commandLine.d.ts +59 -0
  184. package/dist/utils/commandLine.d.ts.map +1 -0
  185. package/dist/utils/commandLine.js +54 -0
  186. package/dist/utils/commandLine.js.map +1 -0
  187. package/dist/utils/copyDirectory.d.ts +33 -0
  188. package/dist/utils/copyDirectory.d.ts.map +1 -0
  189. package/dist/utils/copyDirectory.js +38 -1
  190. package/dist/utils/copyDirectory.js.map +1 -0
  191. package/dist/utils/createDirectory.d.ts +34 -0
  192. package/dist/utils/createDirectory.d.ts.map +1 -0
  193. package/dist/utils/createDirectory.js +33 -0
  194. package/dist/utils/createDirectory.js.map +1 -0
  195. package/dist/utils/createZip.d.ts +39 -0
  196. package/dist/utils/createZip.d.ts.map +1 -0
  197. package/dist/utils/createZip.js +47 -2
  198. package/dist/utils/createZip.js.map +1 -0
  199. package/dist/utils/deepCopy.d.ts +32 -0
  200. package/dist/utils/deepCopy.d.ts.map +1 -0
  201. package/dist/utils/deepCopy.js +39 -0
  202. package/dist/utils/deepCopy.js.map +1 -0
  203. package/dist/utils/deepEqual.d.ts +54 -0
  204. package/dist/utils/deepEqual.d.ts.map +1 -0
  205. package/dist/utils/deepEqual.js +72 -1
  206. package/dist/utils/deepEqual.js.map +1 -0
  207. package/dist/utils/error.d.ts +44 -0
  208. package/dist/utils/error.d.ts.map +1 -0
  209. package/dist/utils/error.js +41 -0
  210. package/dist/utils/error.js.map +1 -0
  211. package/dist/utils/export.d.ts +12 -0
  212. package/dist/utils/export.d.ts.map +1 -0
  213. package/dist/utils/export.js +1 -0
  214. package/dist/utils/export.js.map +1 -0
  215. package/dist/utils/hex.d.ts +49 -0
  216. package/dist/utils/hex.d.ts.map +1 -0
  217. package/dist/utils/hex.js +58 -0
  218. package/dist/utils/hex.js.map +1 -0
  219. package/dist/utils/isvalid.d.ts +103 -0
  220. package/dist/utils/isvalid.d.ts.map +1 -0
  221. package/dist/utils/isvalid.js +101 -0
  222. package/dist/utils/isvalid.js.map +1 -0
  223. package/dist/utils/network.d.ts +74 -0
  224. package/dist/utils/network.d.ts.map +1 -0
  225. package/dist/utils/network.js +81 -5
  226. package/dist/utils/network.js.map +1 -0
  227. package/dist/utils/spawn.d.ts +33 -0
  228. package/dist/utils/spawn.d.ts.map +1 -0
  229. package/dist/utils/spawn.js +40 -0
  230. package/dist/utils/spawn.js.map +1 -0
  231. package/dist/utils/wait.d.ts +56 -0
  232. package/dist/utils/wait.d.ts.map +1 -0
  233. package/dist/utils/wait.js +62 -9
  234. package/dist/utils/wait.js.map +1 -0
  235. package/npm-shrinkwrap.json +2 -2
  236. package/package.json +2 -1
@@ -1,15 +1,43 @@
1
+ /**
2
+ * This file contains the class Matterbridge.
3
+ *
4
+ * @file matterbridge.ts
5
+ * @author Luca Liguori
6
+ * @created 2023-12-29
7
+ * @version 1.6.0
8
+ * @license Apache-2.0
9
+ *
10
+ * Copyright 2023, 2024, 2025 Luca Liguori.
11
+ *
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * you may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ *
16
+ * http://www.apache.org/licenses/LICENSE-2.0
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ */
24
+ // Node.js modules
1
25
  import os from 'node:os';
2
26
  import path from 'node:path';
3
27
  import { promises as fs } from 'node:fs';
4
28
  import EventEmitter from 'node:events';
5
29
  import { inspect } from 'node:util';
30
+ // AnsiLogger module
6
31
  import { AnsiLogger, UNDERLINE, UNDERLINEOFF, db, debugStringify, BRIGHT, RESET, er, nf, rs, wr, RED, GREEN, zb, CYAN, nt, BLUE } from 'node-ansi-logger';
32
+ // NodeStorage module
7
33
  import { NodeStorageManager } from 'node-persist-manager';
34
+ // @matter
8
35
  import { DeviceTypeId, Endpoint, Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, VendorId, StorageService, Environment, ServerNode, UINT32_MAX, UINT16_MAX, Crypto, } from '@matter/main';
9
36
  import { DeviceCommissioner, FabricAction, MdnsService, PaseClient } from '@matter/main/protocol';
10
37
  import { AggregatorEndpoint } from '@matter/main/endpoints';
11
38
  import { BasicInformationServer } from '@matter/main/behaviors/basic-information';
12
39
  import { BridgedDeviceBasicInformationServer } from '@matter/main/behaviors/bridged-device-basic-information';
40
+ // Matterbridge
13
41
  import { getParameter, getIntParameter, hasParameter, copyDirectory, isValidString, parseVersionString, isValidNumber, createDirectory } from './utils/export.js';
14
42
  import { withTimeout, waiter, wait } from './utils/wait.js';
15
43
  import { dev, plg, typ } from './matterbridgeTypes.js';
@@ -19,6 +47,9 @@ import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
19
47
  import { bridge } from './matterbridgeDeviceTypes.js';
20
48
  import { Frontend } from './frontend.js';
21
49
  import { addVirtualDevices } from './helpers.js';
50
+ /**
51
+ * Represents the Matterbridge application.
52
+ */
22
53
  export class Matterbridge extends EventEmitter {
23
54
  systemInformation = {
24
55
  interfaceName: '',
@@ -67,7 +98,7 @@ export class Matterbridge extends EventEmitter {
67
98
  shellySysUpdate: false,
68
99
  shellyMainUpdate: false,
69
100
  profile: getParameter('profile'),
70
- loggerLevel: "info",
101
+ loggerLevel: "info" /* LogLevel.INFO */,
71
102
  fileLogger: false,
72
103
  matterLoggerLevel: MatterLogLevel.INFO,
73
104
  matterFileLogger: false,
@@ -95,19 +126,23 @@ export class Matterbridge extends EventEmitter {
95
126
  shutdown = false;
96
127
  edge = true;
97
128
  failCountLimit = hasParameter('shelly') ? 600 : 120;
98
- log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4, logLevel: hasParameter('debug') ? "debug" : "info" });
129
+ // Matterbridge log files
130
+ log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: hasParameter('debug') ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */ });
99
131
  matterbridgeLoggerFile = 'matterbridge' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.log';
100
132
  matterLoggerFile = 'matter' + (getParameter('profile') ? '.' + getParameter('profile') : '') + '.log';
101
133
  plugins = new PluginManager(this);
102
134
  devices = new DeviceManager(this);
103
135
  frontend = new Frontend(this);
136
+ // Matterbridge storage
104
137
  nodeStorageName = 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : '');
105
138
  nodeStorage;
106
139
  nodeContext;
140
+ // Cleanup
107
141
  hasCleanupStarted = false;
108
142
  initialized = false;
109
143
  execRunningCount = 0;
110
144
  startMatterInterval;
145
+ startMatterIntervalMs = 1000;
111
146
  checkUpdateInterval;
112
147
  checkUpdateTimeout;
113
148
  configureTimeout;
@@ -117,19 +152,23 @@ export class Matterbridge extends EventEmitter {
117
152
  sigtermHandler;
118
153
  exceptionHandler;
119
154
  rejectionHandler;
155
+ // Matter environment
120
156
  environment = Environment.default;
157
+ // Matter storage
121
158
  matterStorageName = 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : '');
122
159
  matterStorageService;
123
160
  matterStorageManager;
124
161
  matterbridgeContext;
125
162
  controllerContext;
126
- mdnsInterface;
127
- ipv4address;
128
- ipv6address;
129
- port;
130
- passcode;
131
- discriminator;
132
- certification;
163
+ // Matter parameters
164
+ mdnsInterface; // matter server node mdnsInterface: e.g. 'eth0' or 'wlan0' or 'WiFi'
165
+ ipv4address; // matter server node listeningAddressIpv4
166
+ ipv6address; // matter server node listeningAddressIpv6
167
+ port; // first server node port
168
+ passcode; // first server node passcode
169
+ discriminator; // first server node discriminator
170
+ certification; // device certification
171
+ // Matter nodes
133
172
  serverNode;
134
173
  aggregatorNode;
135
174
  aggregatorVendorId = VendorId(getIntParameter('vendorId') ?? 0xfff1);
@@ -137,15 +176,31 @@ export class Matterbridge extends EventEmitter {
137
176
  aggregatorProductId = getIntParameter('productId') ?? 0x8000;
138
177
  aggregatorProductName = getParameter('productName') ?? 'Matterbridge aggregator';
139
178
  static instance;
179
+ // We load asyncronously so is private
140
180
  constructor() {
141
181
  super();
142
182
  }
183
+ /**
184
+ * Retrieves the list of Matterbridge devices.
185
+ *
186
+ * @returns {MatterbridgeEndpoint[]} An array of MatterbridgeDevice objects.
187
+ */
143
188
  getDevices() {
144
189
  return this.devices.array();
145
190
  }
191
+ /**
192
+ * Retrieves the list of registered plugins.
193
+ *
194
+ * @returns {RegisteredPlugin[]} An array of RegisteredPlugin objects.
195
+ */
146
196
  getPlugins() {
147
197
  return this.plugins.array();
148
198
  }
199
+ /**
200
+ * Set the logger logLevel for the Matterbridge classes and call onChangeLoggerLevel() for each plugin.
201
+ *
202
+ * @param {LogLevel} logLevel The logger logLevel to set.
203
+ */
149
204
  async setLogLevel(logLevel) {
150
205
  if (this.log)
151
206
  this.log.logLevel = logLevel;
@@ -159,19 +214,31 @@ export class Matterbridge extends EventEmitter {
159
214
  for (const plugin of this.plugins) {
160
215
  if (!plugin.platform || !plugin.platform.log || !plugin.platform.config)
161
216
  continue;
162
- plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" : this.log.logLevel;
163
- await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" : this.log.logLevel);
164
- }
165
- let callbackLogLevel = "notice";
166
- if (this.matterbridgeInformation.loggerLevel === "info" || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.INFO)
167
- callbackLogLevel = "info";
168
- if (this.matterbridgeInformation.loggerLevel === "debug" || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.DEBUG)
169
- callbackLogLevel = "debug";
217
+ plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : this.log.logLevel;
218
+ await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : this.log.logLevel);
219
+ }
220
+ // Set the global logger callback for the WebSocketServer to the common minimum logLevel
221
+ let callbackLogLevel = "notice" /* LogLevel.NOTICE */;
222
+ if (this.matterbridgeInformation.loggerLevel === "info" /* LogLevel.INFO */ || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.INFO)
223
+ callbackLogLevel = "info" /* LogLevel.INFO */;
224
+ if (this.matterbridgeInformation.loggerLevel === "debug" /* LogLevel.DEBUG */ || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.DEBUG)
225
+ callbackLogLevel = "debug" /* LogLevel.DEBUG */;
170
226
  AnsiLogger.setGlobalCallback(this.frontend.wssSendMessage.bind(this.frontend), callbackLogLevel);
171
227
  this.log.debug(`WebSocketServer logger global callback set to ${callbackLogLevel}`);
172
228
  }
229
+ //* ************************************************************************************************************************************ */
230
+ // loadInstance() and cleanup() methods */
231
+ //* ************************************************************************************************************************************ */
232
+ /**
233
+ * Loads an instance of the Matterbridge class.
234
+ * If an instance already exists, return that instance.
235
+ *
236
+ * @param {boolean} initialize - Whether to initialize the Matterbridge instance after loading. Defaults to false.
237
+ * @returns {Matterbridge} A promise that resolves to the Matterbridge instance.
238
+ */
173
239
  static async loadInstance(initialize = false) {
174
240
  if (!Matterbridge.instance) {
241
+ // eslint-disable-next-line no-console
175
242
  if (hasParameter('debug'))
176
243
  console.log(GREEN + 'Creating a new instance of Matterbridge.', initialize ? 'Initializing...' : 'Not initializing...', rs);
177
244
  Matterbridge.instance = new Matterbridge();
@@ -180,8 +247,17 @@ export class Matterbridge extends EventEmitter {
180
247
  }
181
248
  return Matterbridge.instance;
182
249
  }
250
+ /**
251
+ * Call cleanup() and dispose MdnsService.
252
+ *
253
+ * @param {number} [timeout] - The timeout duration to wait for the cleanup to complete in milliseconds. Default is 1000.
254
+ * @param {number} [pause] - The pause duration after the cleanup in milliseconds. Default is 250.
255
+ *
256
+ * @deprecated This method is deprecated and is ONLY used for jest tests.
257
+ */
183
258
  async destroyInstance(timeout = 1000, pause = 250) {
184
259
  this.log.info(`Destroy instance...`);
260
+ // Save server nodes to close
185
261
  const servers = [];
186
262
  if (this.bridgeMode === 'bridge') {
187
263
  if (this.serverNode)
@@ -199,72 +275,105 @@ export class Matterbridge extends EventEmitter {
199
275
  servers.push(device.serverNode);
200
276
  }
201
277
  }
278
+ // Let any already‐queued microtasks run first
202
279
  await Promise.resolve();
280
+ // Wait for the cleanup to finish
203
281
  await wait(pause, 'destroyInstance start', true);
282
+ // Cleanup
204
283
  await this.cleanup('destroying instance...', false, timeout);
284
+ // Close servers mdns service
205
285
  this.log.info(`Dispose ${servers.length} MdnsService...`);
206
286
  for (const server of servers) {
207
287
  await server.env.get(MdnsService)[Symbol.asyncDispose]();
208
288
  this.log.info(`Closed ${server.id} MdnsService`);
209
289
  }
290
+ // Let any already‐queued microtasks run first
210
291
  await Promise.resolve();
292
+ // Wait for the cleanup to finish
211
293
  await wait(pause, 'destroyInstance stop', true);
212
294
  }
295
+ /**
296
+ * Initializes the Matterbridge application.
297
+ *
298
+ * @remarks
299
+ * This method performs the necessary setup and initialization steps for the Matterbridge application.
300
+ * It displays the help information if the 'help' parameter is provided, sets up the logger, checks the
301
+ * node version, registers signal handlers, initializes storage, and parses the command line.
302
+ *
303
+ * @returns {Promise<void>} A Promise that resolves when the initialization is complete.
304
+ */
213
305
  async initialize() {
306
+ // Emit the initialize_started event
214
307
  this.emit('initialize_started');
308
+ // Set the restart mode
215
309
  if (hasParameter('service'))
216
310
  this.restartMode = 'service';
217
311
  if (hasParameter('docker'))
218
312
  this.restartMode = 'docker';
313
+ // Set the matterbridge home directory
219
314
  this.homeDirectory = getParameter('homedir') ?? os.homedir();
220
315
  this.matterbridgeInformation.homeDirectory = this.homeDirectory;
221
316
  await createDirectory(this.homeDirectory, 'Matterbridge Home Directory', this.log);
317
+ // Set the matterbridge directory
222
318
  this.matterbridgeDirectory = path.join(this.homeDirectory, '.matterbridge');
223
319
  this.matterbridgeInformation.matterbridgeDirectory = this.matterbridgeDirectory;
224
320
  await createDirectory(this.matterbridgeDirectory, 'Matterbridge Directory', this.log);
225
321
  await createDirectory(path.join(this.matterbridgeDirectory, 'certs'), 'Matterbridge Frontend Certificate Directory', this.log);
226
322
  await createDirectory(path.join(this.matterbridgeDirectory, 'uploads'), 'Matterbridge Frontend Uploads Directory', this.log);
323
+ // Set the matterbridge plugin directory
227
324
  this.matterbridgePluginDirectory = path.join(this.homeDirectory, 'Matterbridge');
228
325
  this.matterbridgeInformation.matterbridgePluginDirectory = this.matterbridgePluginDirectory;
229
326
  await createDirectory(this.matterbridgePluginDirectory, 'Matterbridge Plugin Directory', this.log);
327
+ // Set the matterbridge cert directory
230
328
  this.matterbridgeCertDirectory = path.join(this.homeDirectory, '.mattercert');
231
329
  this.matterbridgeInformation.matterbridgeCertDirectory = this.matterbridgeCertDirectory;
232
330
  await createDirectory(this.matterbridgeCertDirectory, 'Matterbridge Matter Certificate Directory', this.log);
331
+ // Set the matterbridge root directory
233
332
  const { fileURLToPath } = await import('node:url');
234
333
  const currentFileDirectory = path.dirname(fileURLToPath(import.meta.url));
235
334
  this.rootDirectory = path.resolve(currentFileDirectory, '../');
236
335
  this.matterbridgeInformation.rootDirectory = this.rootDirectory;
336
+ // Setup the matter environment
237
337
  this.environment.vars.set('log.level', MatterLogLevel.INFO);
238
338
  this.environment.vars.set('log.format', MatterLogFormat.ANSI);
239
339
  this.environment.vars.set('path.root', path.join(this.matterbridgeDirectory, this.matterStorageName));
240
340
  this.environment.vars.set('runtime.signals', false);
241
341
  this.environment.vars.set('runtime.exitcode', false);
342
+ // Register process handlers
242
343
  this.registerProcessHandlers();
344
+ // Initialize nodeStorage and nodeContext
243
345
  try {
244
346
  this.log.debug(`Creating node storage manager: ${CYAN}${this.nodeStorageName}${db}`);
245
347
  this.nodeStorage = new NodeStorageManager({ dir: path.join(this.matterbridgeDirectory, this.nodeStorageName), writeQueue: false, expiredInterval: undefined, logging: false });
246
348
  this.log.debug('Creating node storage context for matterbridge');
247
349
  this.nodeContext = await this.nodeStorage.createStorage('matterbridge');
350
+ // TODO: Remove this code when node-persist-manager is updated
351
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
248
352
  const keys = (await this.nodeStorage?.storage.keys());
249
353
  for (const key of keys) {
250
354
  this.log.debug(`Checking node storage manager key: ${CYAN}${key}${db}`);
355
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
251
356
  await this.nodeStorage?.storage.get(key);
252
357
  }
253
358
  const storages = await this.nodeStorage.getStorageNames();
254
359
  for (const storage of storages) {
255
360
  this.log.debug(`Checking storage: ${CYAN}${storage}${db}`);
256
361
  const nodeContext = await this.nodeStorage?.createStorage(storage);
362
+ // TODO: Remove this code when node-persist-manager is updated
363
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
257
364
  const keys = (await nodeContext?.storage.keys());
258
365
  keys.forEach(async (key) => {
259
366
  this.log.debug(`Checking key: ${CYAN}${storage}:${key}${db}`);
260
367
  await nodeContext?.get(key);
261
368
  });
262
369
  }
370
+ // Creating a backup of the node storage since it is not corrupted
263
371
  this.log.debug('Creating node storage backup...');
264
372
  await copyDirectory(path.join(this.matterbridgeDirectory, this.nodeStorageName), path.join(this.matterbridgeDirectory, this.nodeStorageName + '.backup'));
265
373
  this.log.debug('Created node storage backup');
266
374
  }
267
375
  catch (error) {
376
+ // Restoring the backup of the node storage since it is corrupted
268
377
  this.log.error(`Error creating node storage manager and context: ${error instanceof Error ? error.message : error}`);
269
378
  if (hasParameter('norestore')) {
270
379
  this.log.fatal(`The matterbridge storage is corrupted. Found -norestore parameter: exiting...`);
@@ -278,14 +387,20 @@ export class Matterbridge extends EventEmitter {
278
387
  if (!this.nodeStorage || !this.nodeContext) {
279
388
  throw new Error('Fatal error creating node storage manager and context for matterbridge');
280
389
  }
390
+ // Set the first port to use for the commissioning server (will be incremented in childbridge mode)
281
391
  this.port = getIntParameter('port') ?? (await this.nodeContext.get('matterport', 5540)) ?? 5540;
392
+ // Set the first passcode to use for the commissioning server (will be incremented in childbridge mode)
282
393
  this.passcode = getIntParameter('passcode') ?? (await this.nodeContext.get('matterpasscode')) ?? PaseClient.generateRandomPasscode(this.environment.get(Crypto));
394
+ // Set the first discriminator to use for the commissioning server (will be incremented in childbridge mode)
283
395
  this.discriminator = getIntParameter('discriminator') ?? (await this.nodeContext.get('matterdiscriminator')) ?? PaseClient.generateRandomDiscriminator(this.environment.get(Crypto));
396
+ // Certificate management
284
397
  const pairingFilePath = path.join(this.matterbridgeCertDirectory, 'pairing.json');
285
398
  try {
399
+ // eslint-disable-next-line n/no-unsupported-features/node-builtins
286
400
  await fs.access(pairingFilePath, fs.constants.R_OK);
287
401
  const pairingFileContent = await fs.readFile(pairingFilePath, 'utf8');
288
402
  const pairingFileJson = JSON.parse(pairingFileContent);
403
+ // Set the vendorId, vendorName, productId and productName if they are present in the pairing file
289
404
  if (isValidNumber(pairingFileJson.vendorId))
290
405
  this.aggregatorVendorId = VendorId(pairingFileJson.vendorId);
291
406
  if (isValidString(pairingFileJson.vendorName, 3))
@@ -294,11 +409,14 @@ export class Matterbridge extends EventEmitter {
294
409
  this.aggregatorProductId = pairingFileJson.productId;
295
410
  if (isValidString(pairingFileJson.productName, 3))
296
411
  this.aggregatorProductName = pairingFileJson.productName;
412
+ // Override the passcode and discriminator if they are present in the pairing file
297
413
  if (isValidNumber(pairingFileJson.passcode) && isValidNumber(pairingFileJson.discriminator)) {
298
414
  this.passcode = pairingFileJson.passcode;
299
415
  this.discriminator = pairingFileJson.discriminator;
300
416
  this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using passcode ${CYAN}${this.passcode}${nf} and discriminator ${CYAN}${this.discriminator}${nf} from pairing file.`);
301
417
  }
418
+ // Set the certification if it is present in the pairing file
419
+ /* istanbul ignore next if */
302
420
  if (pairingFileJson.privateKey && pairingFileJson.certificate && pairingFileJson.intermediateCertificate && pairingFileJson.declaration) {
303
421
  const hexStringToUint8Array = (hexString) => {
304
422
  const matches = hexString.match(/.{1,2}/g);
@@ -316,41 +434,44 @@ export class Matterbridge extends EventEmitter {
316
434
  catch (error) {
317
435
  this.log.debug(`Pairing file ${CYAN}${pairingFilePath}${db} not found: ${error instanceof Error ? error.message : error}`);
318
436
  }
437
+ // Store the passcode, discriminator and port in the node context
319
438
  await this.nodeContext.set('matterport', this.port);
320
439
  await this.nodeContext.set('matterpasscode', this.passcode);
321
440
  await this.nodeContext.set('matterdiscriminator', this.discriminator);
322
441
  this.log.debug(`Initializing server node for Matterbridge on port ${this.port} with passcode ${this.passcode} and discriminator ${this.discriminator}`);
442
+ // Set matterbridge logger level (context: matterbridgeLogLevel)
323
443
  if (hasParameter('logger')) {
324
444
  const level = getParameter('logger');
325
445
  if (level === 'debug') {
326
- this.log.logLevel = "debug";
446
+ this.log.logLevel = "debug" /* LogLevel.DEBUG */;
327
447
  }
328
448
  else if (level === 'info') {
329
- this.log.logLevel = "info";
449
+ this.log.logLevel = "info" /* LogLevel.INFO */;
330
450
  }
331
451
  else if (level === 'notice') {
332
- this.log.logLevel = "notice";
452
+ this.log.logLevel = "notice" /* LogLevel.NOTICE */;
333
453
  }
334
454
  else if (level === 'warn') {
335
- this.log.logLevel = "warn";
455
+ this.log.logLevel = "warn" /* LogLevel.WARN */;
336
456
  }
337
457
  else if (level === 'error') {
338
- this.log.logLevel = "error";
458
+ this.log.logLevel = "error" /* LogLevel.ERROR */;
339
459
  }
340
460
  else if (level === 'fatal') {
341
- this.log.logLevel = "fatal";
461
+ this.log.logLevel = "fatal" /* LogLevel.FATAL */;
342
462
  }
343
463
  else {
344
464
  this.log.warn(`Invalid matterbridge logger level: ${level}. Using default level "info".`);
345
- this.log.logLevel = "info";
465
+ this.log.logLevel = "info" /* LogLevel.INFO */;
346
466
  }
347
467
  }
348
468
  else {
349
- this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.matterbridgeInformation.shellyBoard ? "notice" : "info");
469
+ this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.matterbridgeInformation.shellyBoard ? "notice" /* LogLevel.NOTICE */ : "info" /* LogLevel.INFO */);
350
470
  }
351
471
  this.frontend.logLevel = this.log.logLevel;
352
472
  MatterbridgeEndpoint.logLevel = this.log.logLevel;
353
473
  this.matterbridgeInformation.loggerLevel = this.log.logLevel;
474
+ // Create the file logger for matterbridge (context: matterbridgeFileLog)
354
475
  if (hasParameter('filelogger') || (await this.nodeContext.get('matterbridgeFileLog', false))) {
355
476
  AnsiLogger.setGlobalLogfile(path.join(this.matterbridgeDirectory, this.matterbridgeLoggerFile), this.log.logLevel, true);
356
477
  this.matterbridgeInformation.fileLogger = true;
@@ -359,6 +480,7 @@ export class Matterbridge extends EventEmitter {
359
480
  this.log.debug(`Matterbridge logLevel: ${this.log.logLevel} fileLoger: ${this.matterbridgeInformation.fileLogger}.`);
360
481
  if (this.profile !== undefined)
361
482
  this.log.debug(`Matterbridge profile: ${this.profile}.`);
483
+ // Set matter.js logger level, format and logger (context: matterLogLevel)
362
484
  if (hasParameter('matterlogger')) {
363
485
  const level = getParameter('matterlogger');
364
486
  if (level === 'debug') {
@@ -389,7 +511,9 @@ export class Matterbridge extends EventEmitter {
389
511
  }
390
512
  Logger.format = MatterLogFormat.ANSI;
391
513
  Logger.setLogger('default', this.createMatterLogger());
514
+ // Logger.destinations.default.write = this.createMatterLogger();
392
515
  this.matterbridgeInformation.matterLoggerLevel = Logger.level;
516
+ // Create the file logger for matter.js (context: matterFileLog)
393
517
  if (hasParameter('matterfilelogger') || (await this.nodeContext.get('matterFileLog', false))) {
394
518
  this.matterbridgeInformation.matterFileLogger = true;
395
519
  Logger.addLogger('matterfilelogger', await this.createMatterFileLogger(path.join(this.matterbridgeDirectory, this.matterLoggerFile), true), {
@@ -398,7 +522,9 @@ export class Matterbridge extends EventEmitter {
398
522
  });
399
523
  }
400
524
  this.log.debug(`Matter logLevel: ${Logger.level} fileLoger: ${this.matterbridgeInformation.matterFileLogger}.`);
525
+ // Log network interfaces
401
526
  const networkInterfaces = os.networkInterfaces();
527
+ // console.log(`Network interfaces:`, networkInterfaces);
402
528
  const availableAddresses = Object.entries(networkInterfaces);
403
529
  const availableInterfaces = Object.keys(networkInterfaces);
404
530
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -410,6 +536,7 @@ export class Matterbridge extends EventEmitter {
410
536
  });
411
537
  }
412
538
  }
539
+ // Set the interface to use for matter server node mdnsInterface
413
540
  if (hasParameter('mdnsinterface')) {
414
541
  this.mdnsInterface = getParameter('mdnsinterface');
415
542
  }
@@ -418,6 +545,7 @@ export class Matterbridge extends EventEmitter {
418
545
  if (this.mdnsInterface === '')
419
546
  this.mdnsInterface = undefined;
420
547
  }
548
+ // Validate mdnsInterface
421
549
  if (this.mdnsInterface) {
422
550
  if (!availableInterfaces.includes(this.mdnsInterface)) {
423
551
  this.log.error(`Invalid mdnsinterface: ${this.mdnsInterface}. Available interfaces are: ${availableInterfaces.join(', ')}. Using all available interfaces.`);
@@ -430,6 +558,7 @@ export class Matterbridge extends EventEmitter {
430
558
  }
431
559
  if (this.mdnsInterface)
432
560
  this.environment.vars.set('mdns.networkInterface', this.mdnsInterface);
561
+ // Set the listeningAddressIpv4 for the matter commissioning server
433
562
  if (hasParameter('ipv4address')) {
434
563
  this.ipv4address = getParameter('ipv4address');
435
564
  }
@@ -438,6 +567,7 @@ export class Matterbridge extends EventEmitter {
438
567
  if (this.ipv4address === '')
439
568
  this.ipv4address = undefined;
440
569
  }
570
+ // Validate ipv4address
441
571
  if (this.ipv4address) {
442
572
  let isValid = false;
443
573
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -453,6 +583,7 @@ export class Matterbridge extends EventEmitter {
453
583
  await this.nodeContext.remove('matteripv4address');
454
584
  }
455
585
  }
586
+ // Set the listeningAddressIpv6 for the matter commissioning server
456
587
  if (hasParameter('ipv6address')) {
457
588
  this.ipv6address = getParameter('ipv6address');
458
589
  }
@@ -461,6 +592,7 @@ export class Matterbridge extends EventEmitter {
461
592
  if (this.ipv6address === '')
462
593
  this.ipv6address = undefined;
463
594
  }
595
+ // Validate ipv6address
464
596
  if (this.ipv6address) {
465
597
  let isValid = false;
466
598
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -469,6 +601,7 @@ export class Matterbridge extends EventEmitter {
469
601
  isValid = true;
470
602
  break;
471
603
  }
604
+ /* istanbul ignore next */
472
605
  if (ifaces && ifaces.find((iface) => iface.scopeid && iface.scopeid > 0 && iface.address + '%' + (process.platform === 'win32' ? iface.scopeid : ifaceName) === this.ipv6address)) {
473
606
  this.log.info(`Using ipv6address ${CYAN}${this.ipv6address}${nf} on interface ${CYAN}${ifaceName}${nf} for the Matter server node.`);
474
607
  isValid = true;
@@ -481,6 +614,7 @@ export class Matterbridge extends EventEmitter {
481
614
  await this.nodeContext.remove('matteripv6address');
482
615
  }
483
616
  }
617
+ // Initialize the virtual mode
484
618
  if (hasParameter('novirtual')) {
485
619
  this.matterbridgeInformation.virtualMode = 'disabled';
486
620
  await this.nodeContext.set('virtualmode', 'disabled');
@@ -489,12 +623,17 @@ export class Matterbridge extends EventEmitter {
489
623
  this.matterbridgeInformation.virtualMode = (await this.nodeContext.get('virtualmode', 'outlet'));
490
624
  }
491
625
  this.log.debug(`Virtual mode ${this.matterbridgeInformation.virtualMode}.`);
626
+ // Initialize PluginManager
492
627
  this.plugins.logLevel = this.log.logLevel;
493
628
  await this.plugins.loadFromStorage();
629
+ // Initialize DeviceManager
494
630
  this.devices.logLevel = this.log.logLevel;
631
+ // Get the plugins from node storage and create the plugins node storage contexts
495
632
  for (const plugin of this.plugins) {
496
633
  const packageJson = await this.plugins.parse(plugin);
497
634
  if (packageJson === null && !hasParameter('add') && !hasParameter('remove') && !hasParameter('enable') && !hasParameter('disable') && !hasParameter('reset') && !hasParameter('factoryreset')) {
635
+ // Try to reinstall the plugin from npm (for Docker pull and external plugins)
636
+ // We don't do this when the add and other parameters are set because we shut down the process after adding the plugin
498
637
  this.log.info(`Error parsing plugin ${plg}${plugin.name}${nf}. Trying to reinstall it from npm.`);
499
638
  try {
500
639
  const { spawnCommand } = await import('./utils/spawn.js');
@@ -517,6 +656,7 @@ export class Matterbridge extends EventEmitter {
517
656
  await plugin.nodeContext.set('description', plugin.description);
518
657
  await plugin.nodeContext.set('author', plugin.author);
519
658
  }
659
+ // Log system info and create .matterbridge directory
520
660
  await this.logNodeAndSystemInfo();
521
661
  this.log.notice(`Matterbridge version ${this.matterbridgeVersion} ` +
522
662
  `${hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge') ? 'mode bridge ' : ''}` +
@@ -524,6 +664,7 @@ export class Matterbridge extends EventEmitter {
524
664
  `${hasParameter('controller') ? 'mode controller ' : ''}` +
525
665
  `${this.restartMode !== '' ? 'restart mode ' + this.restartMode + ' ' : ''}` +
526
666
  `running on ${this.systemInformation.osType} (v.${this.systemInformation.osRelease}) platform ${this.systemInformation.osPlatform} arch ${this.systemInformation.osArch}`);
667
+ // Check node version and throw error
527
668
  const minNodeVersion = 18;
528
669
  const nodeVersion = process.versions.node;
529
670
  const versionMajor = parseInt(nodeVersion.split('.')[0]);
@@ -531,10 +672,18 @@ export class Matterbridge extends EventEmitter {
531
672
  this.log.error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
532
673
  throw new Error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
533
674
  }
675
+ // Parse command line
534
676
  await this.parseCommandLine();
677
+ // Emit the initialize_completed event
535
678
  this.emit('initialize_completed');
536
679
  this.initialized = true;
537
680
  }
681
+ /**
682
+ * Parses the command line arguments and performs the corresponding actions.
683
+ *
684
+ * @private
685
+ * @returns {Promise<void>} A promise that resolves when the command line arguments have been processed, or the process exits.
686
+ */
538
687
  async parseCommandLine() {
539
688
  if (hasParameter('help')) {
540
689
  this.log.info(`\nUsage: matterbridge [options]\n
@@ -596,6 +745,19 @@ export class Matterbridge extends EventEmitter {
596
745
  }
597
746
  index++;
598
747
  }
748
+ /*
749
+ const serializedRegisteredDevices = await this.nodeContext?.get<SerializedMatterbridgeEndpoint[]>('devices', []);
750
+ this.log.info(`│ Registered devices (${serializedRegisteredDevices?.length})`);
751
+ serializedRegisteredDevices?.forEach((device, index) => {
752
+ if (index !== serializedRegisteredDevices.length - 1) {
753
+ this.log.info(`├─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
754
+ this.log.info(`│ └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
755
+ } else {
756
+ this.log.info(`└─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
757
+ this.log.info(` └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
758
+ }
759
+ });
760
+ */
599
761
  this.shutdown = true;
600
762
  return;
601
763
  }
@@ -645,6 +807,7 @@ export class Matterbridge extends EventEmitter {
645
807
  this.shutdown = true;
646
808
  return;
647
809
  }
810
+ // Start the matter storage and create the matterbridge context
648
811
  try {
649
812
  await this.startMatterStorage();
650
813
  }
@@ -652,18 +815,21 @@ export class Matterbridge extends EventEmitter {
652
815
  this.log.fatal(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
653
816
  throw new Error(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
654
817
  }
818
+ // Clear the matterbridge context if the reset parameter is set
655
819
  if (hasParameter('reset') && getParameter('reset') === undefined) {
656
820
  this.initialized = true;
657
821
  await this.shutdownProcessAndReset();
658
822
  this.shutdown = true;
659
823
  return;
660
824
  }
825
+ // Clear matterbridge plugin context if the reset parameter is set
661
826
  if (hasParameter('reset') && getParameter('reset') !== undefined) {
662
827
  this.log.debug(`Reset plugin ${getParameter('reset')}`);
663
828
  const plugin = this.plugins.get(getParameter('reset'));
664
829
  if (plugin) {
665
830
  const matterStorageManager = await this.matterStorageService?.open(plugin.name);
666
831
  if (!matterStorageManager) {
832
+ /* istanbul ignore next */
667
833
  this.log.error(`Plugin ${plg}${plugin.name}${er} storageManager not found`);
668
834
  }
669
835
  else {
@@ -682,32 +848,39 @@ export class Matterbridge extends EventEmitter {
682
848
  this.shutdown = true;
683
849
  return;
684
850
  }
851
+ // Initialize frontend
685
852
  if (getIntParameter('frontend') !== 0 || getIntParameter('frontend') === undefined)
686
853
  await this.frontend.start(getIntParameter('frontend'));
854
+ // Check in 30 seconds the latest and dev versions of matterbridge and the plugins
687
855
  clearTimeout(this.checkUpdateTimeout);
688
856
  this.checkUpdateTimeout = setTimeout(async () => {
689
857
  const { checkUpdates } = await import('./update.js');
690
858
  checkUpdates(this);
691
859
  }, 30 * 1000).unref();
860
+ // Check each 12 hours the latest and dev versions of matterbridge and the plugins
692
861
  clearInterval(this.checkUpdateInterval);
693
862
  this.checkUpdateInterval = setInterval(async () => {
694
863
  const { checkUpdates } = await import('./update.js');
695
864
  checkUpdates(this);
696
865
  }, 12 * 60 * 60 * 1000).unref();
866
+ // Start the matterbridge in mode test
697
867
  if (hasParameter('test')) {
698
868
  this.bridgeMode = 'bridge';
699
869
  MatterbridgeEndpoint.bridgeMode = 'bridge';
700
870
  return;
701
871
  }
872
+ // Start the matterbridge in mode controller
702
873
  if (hasParameter('controller')) {
703
874
  this.bridgeMode = 'controller';
704
875
  await this.startController();
705
876
  return;
706
877
  }
878
+ // Check if the bridge mode is set and start matterbridge in bridge mode if not set
707
879
  if (!hasParameter('bridge') && !hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === '') {
708
880
  this.log.info('Setting default matterbridge start mode to bridge');
709
881
  await this.nodeContext?.set('bridgeMode', 'bridge');
710
882
  }
883
+ // Start matterbridge in bridge mode
711
884
  if (hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge')) {
712
885
  this.bridgeMode = 'bridge';
713
886
  MatterbridgeEndpoint.bridgeMode = 'bridge';
@@ -715,6 +888,7 @@ export class Matterbridge extends EventEmitter {
715
888
  await this.startBridge();
716
889
  return;
717
890
  }
891
+ // Start matterbridge in childbridge mode
718
892
  if (hasParameter('childbridge') || (!hasParameter('bridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'childbridge')) {
719
893
  this.bridgeMode = 'childbridge';
720
894
  MatterbridgeEndpoint.bridgeMode = 'childbridge';
@@ -723,10 +897,20 @@ export class Matterbridge extends EventEmitter {
723
897
  return;
724
898
  }
725
899
  }
900
+ /**
901
+ * Asynchronously loads and starts the registered plugins.
902
+ *
903
+ * This method is responsible for initializing and starting all enabled plugins.
904
+ * It ensures that each plugin is properly loaded and started before the bridge starts.
905
+ *
906
+ * @returns {Promise<void>} A promise that resolves when all plugins have been loaded and started.
907
+ */
726
908
  async startPlugins() {
909
+ // Check, load and start the plugins
727
910
  for (const plugin of this.plugins) {
728
911
  plugin.configJson = await this.plugins.loadConfig(plugin);
729
912
  plugin.schemaJson = await this.plugins.loadSchema(plugin);
913
+ // Check if the plugin is available
730
914
  if (!(await this.plugins.resolve(plugin.path))) {
731
915
  this.log.error(`Plugin ${plg}${plugin.name}${er} not found or not validated. Disabling it.`);
732
916
  plugin.enabled = false;
@@ -744,10 +928,14 @@ export class Matterbridge extends EventEmitter {
744
928
  plugin.configured = false;
745
929
  plugin.registeredDevices = undefined;
746
930
  plugin.addedDevices = undefined;
747
- this.plugins.load(plugin, true, 'Matterbridge is starting');
931
+ this.plugins.load(plugin, true, 'Matterbridge is starting'); // No await do it asyncronously
748
932
  }
749
933
  this.frontend.wssSendRefreshRequired('plugins');
750
934
  }
935
+ /**
936
+ * Registers the process handlers for uncaughtException, unhandledRejection, SIGINT and SIGTERM.
937
+ * When either of these signals are received, the cleanup method is called with an appropriate message.
938
+ */
751
939
  registerProcessHandlers() {
752
940
  this.log.debug(`Registering uncaughtException and unhandledRejection handlers...`);
753
941
  process.removeAllListeners('uncaughtException');
@@ -774,6 +962,9 @@ export class Matterbridge extends EventEmitter {
774
962
  };
775
963
  process.on('SIGTERM', this.sigtermHandler);
776
964
  }
965
+ /**
966
+ * Deregisters the process uncaughtException, unhandledRejection, SIGINT and SIGTERM signal handlers.
967
+ */
777
968
  deregisterProcessHandlers() {
778
969
  this.log.debug(`Deregistering uncaughtException and unhandledRejection handlers...`);
779
970
  if (this.exceptionHandler)
@@ -790,12 +981,17 @@ export class Matterbridge extends EventEmitter {
790
981
  process.off('SIGTERM', this.sigtermHandler);
791
982
  this.sigtermHandler = undefined;
792
983
  }
984
+ /**
985
+ * Logs the node and system information.
986
+ */
793
987
  async logNodeAndSystemInfo() {
988
+ // IP address information
794
989
  const networkInterfaces = os.networkInterfaces();
795
990
  this.systemInformation.interfaceName = '';
796
991
  this.systemInformation.ipv4Address = '';
797
992
  this.systemInformation.ipv6Address = '';
798
993
  for (const [interfaceName, interfaceDetails] of Object.entries(networkInterfaces)) {
994
+ // this.log.debug(`Checking interface: '${interfaceName}' for '${this.mdnsInterface}'`);
799
995
  if (this.mdnsInterface && interfaceName !== this.mdnsInterface)
800
996
  continue;
801
997
  if (!interfaceDetails) {
@@ -821,19 +1017,22 @@ export class Matterbridge extends EventEmitter {
821
1017
  break;
822
1018
  }
823
1019
  }
1020
+ // Node information
824
1021
  this.systemInformation.nodeVersion = process.versions.node;
825
1022
  const versionMajor = parseInt(this.systemInformation.nodeVersion.split('.')[0]);
826
1023
  const versionMinor = parseInt(this.systemInformation.nodeVersion.split('.')[1]);
827
1024
  const versionPatch = parseInt(this.systemInformation.nodeVersion.split('.')[2]);
1025
+ // Host system information
828
1026
  this.systemInformation.hostname = os.hostname();
829
1027
  this.systemInformation.user = os.userInfo().username;
830
- this.systemInformation.osType = os.type();
831
- this.systemInformation.osRelease = os.release();
832
- this.systemInformation.osPlatform = os.platform();
833
- this.systemInformation.osArch = os.arch();
834
- this.systemInformation.totalMemory = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) + ' GB';
835
- this.systemInformation.freeMemory = (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB';
836
- this.systemInformation.systemUptime = (os.uptime() / 60 / 60).toFixed(2) + ' hours';
1028
+ this.systemInformation.osType = os.type(); // "Windows_NT", "Darwin", etc.
1029
+ this.systemInformation.osRelease = os.release(); // Kernel version
1030
+ this.systemInformation.osPlatform = os.platform(); // "win32", "linux", "darwin", etc.
1031
+ this.systemInformation.osArch = os.arch(); // "x64", "arm", etc.
1032
+ this.systemInformation.totalMemory = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) + ' GB'; // Convert to GB
1033
+ this.systemInformation.freeMemory = (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB'; // Convert to GB
1034
+ this.systemInformation.systemUptime = (os.uptime() / 60 / 60).toFixed(2) + ' hours'; // Convert to hours
1035
+ // Log the system information
837
1036
  this.log.debug('Host System Information:');
838
1037
  this.log.debug(`- Hostname: ${this.systemInformation.hostname}`);
839
1038
  this.log.debug(`- User: ${this.systemInformation.user}`);
@@ -849,14 +1048,17 @@ export class Matterbridge extends EventEmitter {
849
1048
  this.log.debug(`- Total Memory: ${this.systemInformation.totalMemory}`);
850
1049
  this.log.debug(`- Free Memory: ${this.systemInformation.freeMemory}`);
851
1050
  this.log.debug(`- System Uptime: ${this.systemInformation.systemUptime}`);
1051
+ // Log directories
852
1052
  this.log.debug(`Root Directory: ${this.rootDirectory}`);
853
1053
  this.log.debug(`Home Directory: ${this.homeDirectory}`);
854
1054
  this.log.debug(`Matterbridge Directory: ${this.matterbridgeDirectory}`);
855
1055
  this.log.debug(`Matterbridge Plugin Directory: ${this.matterbridgePluginDirectory}`);
856
1056
  this.log.debug(`Matterbridge Matter Certificate Directory: ${this.matterbridgeCertDirectory}`);
1057
+ // Global node_modules directory
857
1058
  if (this.nodeContext)
858
1059
  this.globalModulesDirectory = this.matterbridgeInformation.globalModulesDirectory = await this.nodeContext.get('globalModulesDirectory', '');
859
1060
  if (this.globalModulesDirectory === '') {
1061
+ // First run of Matterbridge so the node storage is empty
860
1062
  try {
861
1063
  const { getGlobalNodeModules } = await import('./utils/network.js');
862
1064
  this.execRunningCount++;
@@ -866,55 +1068,87 @@ export class Matterbridge extends EventEmitter {
866
1068
  await this.nodeContext?.set('globalModulesDirectory', this.globalModulesDirectory);
867
1069
  }
868
1070
  catch (error) {
1071
+ // istanbul ignore next
869
1072
  this.log.error(`Error getting global node_modules directory: ${error}`);
870
1073
  }
871
1074
  }
872
1075
  else
873
1076
  this.log.debug(`Global node_modules Directory: ${this.globalModulesDirectory}`);
1077
+ /* removed cause is too expensive for the shelly board and not really needed. Why should the globalModulesDirectory change?
1078
+ else {
1079
+ this.getGlobalNodeModules()
1080
+ .then(async (globalModulesDirectory) => {
1081
+ this.globalModulesDirectory = globalModulesDirectory;
1082
+ this.matterbridgeInformation.globalModulesDirectory = this.globalModulesDirectory;
1083
+ this.log.debug(`Global node_modules Directory: ${this.globalModulesDirectory}`);
1084
+ await this.nodeContext?.set<string>('globalModulesDirectory', this.globalModulesDirectory);
1085
+ })
1086
+ .catch((error) => {
1087
+ this.log.error(`Error getting global node_modules directory: ${error}`);
1088
+ });
1089
+ }*/
1090
+ // Matterbridge version
874
1091
  const packageJson = JSON.parse(await fs.readFile(path.join(this.rootDirectory, 'package.json'), 'utf-8'));
875
1092
  this.matterbridgeVersion = this.matterbridgeLatestVersion = this.matterbridgeDevVersion = packageJson.version;
876
1093
  this.matterbridgeInformation.matterbridgeVersion = this.matterbridgeInformation.matterbridgeLatestVersion = this.matterbridgeInformation.matterbridgeDevVersion = packageJson.version;
877
1094
  this.log.debug(`Matterbridge Version: ${this.matterbridgeVersion}`);
1095
+ // Matterbridge latest version (will be set in the checkUpdate function)
878
1096
  if (this.nodeContext)
879
1097
  this.matterbridgeLatestVersion = this.matterbridgeInformation.matterbridgeLatestVersion = await this.nodeContext.get('matterbridgeLatestVersion', this.matterbridgeVersion);
880
1098
  this.log.debug(`Matterbridge Latest Version: ${this.matterbridgeLatestVersion}`);
1099
+ // Matterbridge dev version (will be set in the checkUpdate function)
881
1100
  if (this.nodeContext)
882
1101
  this.matterbridgeDevVersion = this.matterbridgeInformation.matterbridgeDevVersion = await this.nodeContext.get('matterbridgeDevVersion', this.matterbridgeVersion);
883
1102
  this.log.debug(`Matterbridge Dev Version: ${this.matterbridgeDevVersion}`);
1103
+ // Current working directory
884
1104
  const currentDir = process.cwd();
885
1105
  this.log.debug(`Current Working Directory: ${currentDir}`);
1106
+ // Command line arguments (excluding 'node' and the script name)
886
1107
  const cmdArgs = process.argv.slice(2).join(' ');
887
1108
  this.log.debug(`Command Line Arguments: ${cmdArgs}`);
888
1109
  }
1110
+ /**
1111
+ * Creates a MatterLogger function to show the matter.js log messages in AnsiLogger (for the frontend).
1112
+ *
1113
+ * @returns {Function} The MatterLogger function.
1114
+ */
889
1115
  createMatterLogger() {
890
- const matterLogger = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4, logLevel: "debug" });
1116
+ const matterLogger = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: "debug" /* LogLevel.DEBUG */ });
891
1117
  return (level, formattedLog) => {
892
1118
  const logger = formattedLog.slice(44, 44 + 20).trim();
893
1119
  const message = formattedLog.slice(65);
894
1120
  matterLogger.logName = logger;
895
1121
  switch (level) {
896
1122
  case MatterLogLevel.DEBUG:
897
- matterLogger.log("debug", message);
1123
+ matterLogger.log("debug" /* LogLevel.DEBUG */, message);
898
1124
  break;
899
1125
  case MatterLogLevel.INFO:
900
- matterLogger.log("info", message);
1126
+ matterLogger.log("info" /* LogLevel.INFO */, message);
901
1127
  break;
902
1128
  case MatterLogLevel.NOTICE:
903
- matterLogger.log("notice", message);
1129
+ matterLogger.log("notice" /* LogLevel.NOTICE */, message);
904
1130
  break;
905
1131
  case MatterLogLevel.WARN:
906
- matterLogger.log("warn", message);
1132
+ matterLogger.log("warn" /* LogLevel.WARN */, message);
907
1133
  break;
908
1134
  case MatterLogLevel.ERROR:
909
- matterLogger.log("error", message);
1135
+ matterLogger.log("error" /* LogLevel.ERROR */, message);
910
1136
  break;
911
1137
  case MatterLogLevel.FATAL:
912
- matterLogger.log("fatal", message);
1138
+ matterLogger.log("fatal" /* LogLevel.FATAL */, message);
913
1139
  break;
914
1140
  }
915
1141
  };
916
1142
  }
1143
+ /**
1144
+ * Creates a Matter File Logger.
1145
+ *
1146
+ * @param {string} filePath - The path to the log file.
1147
+ * @param {boolean} [unlink] - Whether to unlink the log file before creating a new one.
1148
+ * @returns {Function} - A function that logs formatted messages to the log file.
1149
+ */
917
1150
  async createMatterFileLogger(filePath, unlink = false) {
1151
+ // 2024-08-21 08:55:19.488 DEBUG InteractionMessenger Sending DataReport chunk with 28 attributes and 0 events: 1004 bytes
918
1152
  let fileSize = 0;
919
1153
  if (unlink) {
920
1154
  try {
@@ -925,10 +1159,12 @@ export class Matterbridge extends EventEmitter {
925
1159
  }
926
1160
  }
927
1161
  return async (level, formattedLog) => {
1162
+ /* istanbul ignore if */
928
1163
  if (fileSize > 100000000) {
929
- return;
1164
+ return; // Stop logging if the file size is greater than 100MB
930
1165
  }
931
1166
  fileSize += formattedLog.length;
1167
+ /* istanbul ignore if */
932
1168
  if (fileSize > 100000000) {
933
1169
  await fs.appendFile(filePath, `Logging on file has been stopped because the file size is greater than 100MB.` + os.EOL);
934
1170
  return;
@@ -961,12 +1197,27 @@ export class Matterbridge extends EventEmitter {
961
1197
  }
962
1198
  };
963
1199
  }
1200
+ /**
1201
+ * Restarts the process by exiting the current instance and loading a new instance (/api/restart).
1202
+ *
1203
+ * @returns {Promise<void>} A promise that resolves when the restart is completed.
1204
+ */
964
1205
  async restartProcess() {
965
1206
  await this.cleanup('restarting...', true);
966
1207
  }
1208
+ /**
1209
+ * Shut down the process (/api/shutdown).
1210
+ *
1211
+ * @returns {Promise<void>} A promise that resolves when the shutdown is completed.
1212
+ */
967
1213
  async shutdownProcess() {
968
1214
  await this.cleanup('shutting down...', false);
969
1215
  }
1216
+ /**
1217
+ * Update matterbridge and shut down the process (virtual device 'Update Matterbridge').
1218
+ *
1219
+ * @returns {Promise<void>} A promise that resolves when the update is completed.
1220
+ */
970
1221
  async updateProcess() {
971
1222
  this.log.info('Updating matterbridge...');
972
1223
  try {
@@ -980,55 +1231,91 @@ export class Matterbridge extends EventEmitter {
980
1231
  this.frontend.wssSendRestartRequired();
981
1232
  await this.cleanup('updating...', false);
982
1233
  }
1234
+ /**
1235
+ * Unregister all devices and shut down the process (/api/unregister).
1236
+ *
1237
+ * @param {number} [timeout] - The timeout duration to wait for the message exchange to complete in milliseconds. Default is 1000.
1238
+ *
1239
+ * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1240
+ */
983
1241
  async unregisterAndShutdownProcess(timeout = 1000) {
984
1242
  this.log.info('Unregistering all devices and shutting down...');
985
1243
  for (const plugin of this.plugins.array()) {
986
1244
  if (plugin.error || !plugin.enabled)
987
1245
  continue;
1246
+ const registeredDevices = plugin.registeredDevices;
1247
+ const addedDevices = plugin.addedDevices;
988
1248
  await this.plugins.shutdown(plugin, 'unregistering all devices and shutting down...', false, true);
1249
+ plugin.registeredDevices = registeredDevices;
1250
+ plugin.addedDevices = addedDevices;
989
1251
  await this.removeAllBridgedEndpoints(plugin.name, 100);
990
1252
  }
991
1253
  this.log.debug('Waiting for the MessageExchange to finish...');
992
- await wait(timeout);
1254
+ await wait(timeout); // Wait for MessageExchange to finish
993
1255
  this.log.debug('Cleaning up and shutting down...');
994
1256
  await this.cleanup('unregistered all devices and shutting down...', false, timeout);
995
1257
  }
1258
+ /**
1259
+ * Reset commissioning and shut down the process (/api/reset).
1260
+ *
1261
+ * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1262
+ */
996
1263
  async shutdownProcessAndReset() {
997
1264
  await this.cleanup('shutting down with reset...', false);
998
1265
  }
1266
+ /**
1267
+ * Factory reset and shut down the process (/api/factory-reset).
1268
+ *
1269
+ * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1270
+ */
999
1271
  async shutdownProcessAndFactoryReset() {
1000
1272
  await this.cleanup('shutting down with factory reset...', false);
1001
1273
  }
1274
+ /**
1275
+ * Cleans up the Matterbridge instance.
1276
+ *
1277
+ * @param {string} message - The cleanup message.
1278
+ * @param {boolean} [restart] - Indicates whether to restart the instance after cleanup. Default is `false`.
1279
+ * @param {number} [timeout] - The timeout duration to wait for the message exchange to complete in milliseconds. Default is 1000.
1280
+ *
1281
+ * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1282
+ */
1002
1283
  async cleanup(message, restart = false, timeout = 1000) {
1003
1284
  if (this.initialized && !this.hasCleanupStarted) {
1004
1285
  this.emit('cleanup_started');
1005
1286
  this.hasCleanupStarted = true;
1006
1287
  this.log.info(message);
1288
+ // Clear the start matter interval
1007
1289
  if (this.startMatterInterval) {
1008
1290
  clearInterval(this.startMatterInterval);
1009
1291
  this.startMatterInterval = undefined;
1010
1292
  this.log.debug('Start matter interval cleared');
1011
1293
  }
1294
+ // Clear the check update timeout
1012
1295
  if (this.checkUpdateTimeout) {
1013
1296
  clearTimeout(this.checkUpdateTimeout);
1014
1297
  this.checkUpdateTimeout = undefined;
1015
1298
  this.log.debug('Check update timeout cleared');
1016
1299
  }
1300
+ // Clear the check update interval
1017
1301
  if (this.checkUpdateInterval) {
1018
1302
  clearInterval(this.checkUpdateInterval);
1019
1303
  this.checkUpdateInterval = undefined;
1020
1304
  this.log.debug('Check update interval cleared');
1021
1305
  }
1306
+ // Clear the configure timeout
1022
1307
  if (this.configureTimeout) {
1023
1308
  clearTimeout(this.configureTimeout);
1024
1309
  this.configureTimeout = undefined;
1025
1310
  this.log.debug('Matterbridge configure timeout cleared');
1026
1311
  }
1312
+ // Clear the reachability timeout
1027
1313
  if (this.reachabilityTimeout) {
1028
1314
  clearTimeout(this.reachabilityTimeout);
1029
1315
  this.reachabilityTimeout = undefined;
1030
1316
  this.log.debug('Matterbridge reachability timeout cleared');
1031
1317
  }
1318
+ // Call the shutdown method of each plugin and clear the plugins reachability timeout
1032
1319
  for (const plugin of this.plugins) {
1033
1320
  if (!plugin.enabled || plugin.error)
1034
1321
  continue;
@@ -1039,6 +1326,7 @@ export class Matterbridge extends EventEmitter {
1039
1326
  this.log.debug(`Plugin ${plg}${plugin.name}${db} reachability timeout cleared`);
1040
1327
  }
1041
1328
  }
1329
+ // Stop matter server nodes
1042
1330
  this.log.notice(`Stopping matter server nodes in ${this.bridgeMode} mode...`);
1043
1331
  this.log.debug('Waiting for the MessageExchange to finish...');
1044
1332
  await wait(timeout, 'Waiting for the MessageExchange to finish...', true);
@@ -1063,6 +1351,7 @@ export class Matterbridge extends EventEmitter {
1063
1351
  }
1064
1352
  }
1065
1353
  this.log.notice('Stopped matter server nodes');
1354
+ // Matter commisioning reset
1066
1355
  if (message === 'shutting down with reset...') {
1067
1356
  this.log.info('Resetting Matterbridge commissioning information...');
1068
1357
  await this.matterStorageManager?.createContext('events')?.clearAll();
@@ -1072,6 +1361,7 @@ export class Matterbridge extends EventEmitter {
1072
1361
  await this.matterbridgeContext?.clearAll();
1073
1362
  this.log.info('Matter storage reset done! Remove the bridge from the controller.');
1074
1363
  }
1364
+ // Unregister all devices
1075
1365
  if (message === 'unregistered all devices and shutting down...') {
1076
1366
  if (this.bridgeMode === 'bridge') {
1077
1367
  await this.matterStorageManager?.createContext('root')?.createContext('parts')?.createContext('Matterbridge')?.createContext('parts')?.clearAll();
@@ -1089,18 +1379,36 @@ export class Matterbridge extends EventEmitter {
1089
1379
  }
1090
1380
  this.log.info('Matter storage reset done!');
1091
1381
  }
1382
+ // Stop matter storage
1092
1383
  await this.stopMatterStorage();
1384
+ // Stop the frontend
1093
1385
  await this.frontend.stop();
1386
+ // Remove the matterfilelogger
1094
1387
  try {
1095
1388
  Logger.removeLogger('matterfilelogger');
1096
1389
  }
1097
1390
  catch (error) {
1098
1391
  this.log.debug(`Error removing the matterfilelogger for file ${CYAN}${path.join(this.matterbridgeDirectory, this.matterLoggerFile)}${db}: ${error instanceof Error ? error.message : String(error)}`);
1099
1392
  }
1393
+ // Close the matterbridge node storage and context
1100
1394
  if (this.nodeStorage && this.nodeContext) {
1395
+ /*
1396
+ TODO: Implement serialization of registered devices in edge mode
1397
+ this.log.info('Saving registered devices...');
1398
+ const serializedRegisteredDevices: SerializedMatterbridgeEndpoint[] = [];
1399
+ this.devices.forEach(async (device) => {
1400
+ const serializedMatterbridgeDevice = MatterbridgeEndpoint.serialize(device);
1401
+ // this.log.info(`- ${serializedMatterbridgeDevice.deviceName}${rs}\n`, serializedMatterbridgeDevice);
1402
+ if (serializedMatterbridgeDevice) serializedRegisteredDevices.push(serializedMatterbridgeDevice);
1403
+ });
1404
+ await this.nodeContext.set<SerializedMatterbridgeEndpoint[]>('devices', serializedRegisteredDevices);
1405
+ this.log.info(`Saved registered devices (${serializedRegisteredDevices?.length})`);
1406
+ */
1407
+ // Clear nodeContext and nodeStorage (they just need 1000ms to write the data to disk)
1101
1408
  this.log.debug(`Closing node storage context for ${plg}Matterbridge${db}...`);
1102
1409
  await this.nodeContext.close();
1103
1410
  this.nodeContext = undefined;
1411
+ // Clear nodeContext for each plugin (they just need 1000ms to write the data to disk)
1104
1412
  for (const plugin of this.plugins) {
1105
1413
  if (plugin.nodeContext) {
1106
1414
  this.log.debug(`Closing node storage context for plugin ${plg}${plugin.name}${db}...`);
@@ -1117,8 +1425,10 @@ export class Matterbridge extends EventEmitter {
1117
1425
  }
1118
1426
  this.plugins.clear();
1119
1427
  this.devices.clear();
1428
+ // Factory reset
1120
1429
  if (message === 'shutting down with factory reset...') {
1121
1430
  try {
1431
+ // Delete matter storage directory with its subdirectories and backup
1122
1432
  const dir = path.join(this.matterbridgeDirectory, this.matterStorageName);
1123
1433
  this.log.info(`Removing matter storage directory: ${dir}`);
1124
1434
  await fs.rm(dir, { recursive: true });
@@ -1127,11 +1437,13 @@ export class Matterbridge extends EventEmitter {
1127
1437
  await fs.rm(backup, { recursive: true });
1128
1438
  }
1129
1439
  catch (error) {
1440
+ // istanbul ignore next if
1130
1441
  if (error instanceof Error && error.code !== 'ENOENT') {
1131
1442
  this.log.error(`Error removing matter storage directory: ${error}`);
1132
1443
  }
1133
1444
  }
1134
1445
  try {
1446
+ // Delete matterbridge storage directory with its subdirectories and backup
1135
1447
  const dir = path.join(this.matterbridgeDirectory, this.nodeStorageName);
1136
1448
  this.log.info(`Removing matterbridge storage directory: ${dir}`);
1137
1449
  await fs.rm(dir, { recursive: true });
@@ -1140,18 +1452,20 @@ export class Matterbridge extends EventEmitter {
1140
1452
  await fs.rm(backup, { recursive: true });
1141
1453
  }
1142
1454
  catch (error) {
1455
+ // istanbul ignore next if
1143
1456
  if (error instanceof Error && error.code !== 'ENOENT') {
1144
1457
  this.log.error(`Error removing matterbridge storage directory: ${error}`);
1145
1458
  }
1146
1459
  }
1147
1460
  this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
1148
1461
  }
1462
+ // Deregisters the process handlers
1149
1463
  this.deregisterProcessHandlers();
1150
1464
  if (restart) {
1151
1465
  if (message === 'updating...') {
1152
1466
  this.log.info('Cleanup completed. Updating...');
1153
1467
  Matterbridge.instance = undefined;
1154
- this.emit('update');
1468
+ this.emit('update'); // Restart the process but the update has been done before. TODO move all updates to the cli
1155
1469
  }
1156
1470
  else if (message === 'restarting...') {
1157
1471
  this.log.info('Cleanup completed. Restarting...');
@@ -1172,6 +1486,13 @@ export class Matterbridge extends EventEmitter {
1172
1486
  this.log.debug('Cleanup already started...');
1173
1487
  }
1174
1488
  }
1489
+ /**
1490
+ * Creates and configures the server node for a single not bridged device.
1491
+ *
1492
+ * @param {RegisteredPlugin} plugin - The plugin to configure.
1493
+ * @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
1494
+ * @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
1495
+ */
1175
1496
  async createDeviceServerNode(plugin, device) {
1176
1497
  if (device.mode === 'server' && !device.serverNode && device.deviceType && device.deviceName && device.vendorId && device.vendorName && device.productId && device.productName) {
1177
1498
  this.log.debug(`Creating device ${plg}${plugin.name}${db}:${dev}${device.deviceName}${db} server node...`);
@@ -1182,6 +1503,13 @@ export class Matterbridge extends EventEmitter {
1182
1503
  this.log.debug(`Added ${plg}${plugin.name}${db}:${dev}${device.deviceName}${db} to server node`);
1183
1504
  }
1184
1505
  }
1506
+ /**
1507
+ * Creates and configures the server node for an accessory plugin for a given device.
1508
+ *
1509
+ * @param {RegisteredPlugin} plugin - The plugin to configure.
1510
+ * @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
1511
+ * @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
1512
+ */
1185
1513
  async createAccessoryPlugin(plugin, device) {
1186
1514
  if (!plugin.locked && device.deviceType && device.deviceName && device.vendorId && device.productId && device.vendorName && device.productName) {
1187
1515
  plugin.locked = true;
@@ -1193,6 +1521,12 @@ export class Matterbridge extends EventEmitter {
1193
1521
  await plugin.serverNode.add(device);
1194
1522
  }
1195
1523
  }
1524
+ /**
1525
+ * Creates and configures the server node and the aggregator node for a dynamic plugin.
1526
+ *
1527
+ * @param {RegisteredPlugin} plugin - The plugin to configure.
1528
+ * @returns {Promise<void>} A promise that resolves when the server node and the aggregator node for the dynamic plugin is created and configured.
1529
+ */
1196
1530
  async createDynamicPlugin(plugin) {
1197
1531
  if (!plugin.locked) {
1198
1532
  plugin.locked = true;
@@ -1203,7 +1537,14 @@ export class Matterbridge extends EventEmitter {
1203
1537
  await plugin.serverNode.add(plugin.aggregatorNode);
1204
1538
  }
1205
1539
  }
1540
+ /**
1541
+ * Starts the Matterbridge in bridge mode.
1542
+ *
1543
+ * @private
1544
+ * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1545
+ */
1206
1546
  async startBridge() {
1547
+ // Plugins are configured by a timer when matter server is started and plugin.configured is set to true
1207
1548
  if (!this.matterStorageManager)
1208
1549
  throw new Error('No storage manager initialized');
1209
1550
  if (!this.matterbridgeContext)
@@ -1242,13 +1583,16 @@ export class Matterbridge extends EventEmitter {
1242
1583
  clearInterval(this.startMatterInterval);
1243
1584
  this.startMatterInterval = undefined;
1244
1585
  this.log.debug('Cleared startMatterInterval interval for Matterbridge');
1245
- this.startServerNode(this.serverNode);
1586
+ // Start the Matter server node
1587
+ this.startServerNode(this.serverNode); // We don't await this, because the server node is started in the background
1588
+ // Start the Matter server node of single devices in mode 'server'
1246
1589
  for (const device of this.devices.array()) {
1247
1590
  if (device.mode === 'server' && device.serverNode) {
1248
1591
  this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
1249
- this.startServerNode(device.serverNode);
1592
+ this.startServerNode(device.serverNode); // We don't await this, because the server node is started in the background
1250
1593
  }
1251
1594
  }
1595
+ // Configure the plugins
1252
1596
  this.configureTimeout = setTimeout(async () => {
1253
1597
  for (const plugin of this.plugins.array()) {
1254
1598
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1266,16 +1610,25 @@ export class Matterbridge extends EventEmitter {
1266
1610
  }
1267
1611
  this.frontend.wssSendRefreshRequired('plugins');
1268
1612
  }, 30 * 1000).unref();
1613
+ // Setting reachability to true
1269
1614
  this.reachabilityTimeout = setTimeout(() => {
1270
1615
  this.log.info(`Setting reachability to true for ${plg}Matterbridge${db}`);
1271
1616
  if (this.aggregatorNode)
1272
1617
  this.setAggregatorReachability(this.aggregatorNode, true);
1273
1618
  this.frontend.wssSendRefreshRequired('reachability');
1274
1619
  }, 60 * 1000).unref();
1620
+ // Logger.get('LogServerNode').info(this.serverNode);
1275
1621
  this.emit('bridge_started');
1276
1622
  this.log.notice('Matterbridge bridge started successfully');
1277
- }, 1000);
1623
+ }, this.startMatterIntervalMs);
1278
1624
  }
1625
+ /**
1626
+ * Starts the Matterbridge in childbridge mode.
1627
+ *
1628
+ * @param {number} [delay] - The delay before starting the childbridge. Default is 1000 milliseconds.
1629
+ *
1630
+ * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1631
+ */
1279
1632
  async startChildbridge(delay = 1000) {
1280
1633
  if (!this.matterStorageManager)
1281
1634
  throw new Error('No storage manager initialized');
@@ -1313,8 +1666,9 @@ export class Matterbridge extends EventEmitter {
1313
1666
  clearInterval(this.startMatterInterval);
1314
1667
  this.startMatterInterval = undefined;
1315
1668
  if (delay > 0)
1316
- await wait(delay);
1669
+ await wait(delay); // Wait for the specified delay to ensure all plugins server nodes are ready
1317
1670
  this.log.debug('Cleared startMatterInterval interval in childbridge mode');
1671
+ // Configure the plugins
1318
1672
  this.configureTimeout = setTimeout(async () => {
1319
1673
  for (const plugin of this.plugins.array()) {
1320
1674
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1351,7 +1705,9 @@ export class Matterbridge extends EventEmitter {
1351
1705
  this.log.error(`Node storage context not found for plugin ${plg}${plugin.name}${er}`);
1352
1706
  continue;
1353
1707
  }
1354
- this.startServerNode(plugin.serverNode);
1708
+ // Start the Matter server node
1709
+ this.startServerNode(plugin.serverNode); // We don't await this, because the server node is started in the background
1710
+ // Setting reachability to true
1355
1711
  plugin.reachabilityTimeout = setTimeout(() => {
1356
1712
  this.log.info(`Setting reachability to true for ${plg}${plugin.name}${nf} type ${plugin.type} server node ${plugin.serverNode !== undefined} aggregator node ${plugin.aggregatorNode !== undefined} device ${plugin.device !== undefined}`);
1357
1713
  if (plugin.type === 'DynamicPlatform' && plugin.aggregatorNode)
@@ -1359,19 +1715,241 @@ export class Matterbridge extends EventEmitter {
1359
1715
  this.frontend.wssSendRefreshRequired('reachability');
1360
1716
  }, 60 * 1000).unref();
1361
1717
  }
1718
+ // Start the Matter server node of single devices in mode 'server'
1362
1719
  for (const device of this.devices.array()) {
1363
1720
  if (device.mode === 'server' && device.serverNode) {
1364
1721
  this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
1365
- this.startServerNode(device.serverNode);
1722
+ this.startServerNode(device.serverNode); // We don't await this, because the server node is started in the background
1366
1723
  }
1367
1724
  }
1725
+ // Logger.get('LogServerNode').info(this.serverNode);
1368
1726
  this.emit('childbridge_started');
1369
1727
  this.log.notice('Matterbridge childbridge started successfully');
1370
- }, 1000);
1728
+ }, this.startMatterIntervalMs);
1371
1729
  }
1730
+ /**
1731
+ * Starts the Matterbridge controller.
1732
+ *
1733
+ * @private
1734
+ * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1735
+ */
1372
1736
  async startController() {
1737
+ /*
1738
+ if (!this.matterStorageManager) {
1739
+ this.log.error('No storage manager initialized');
1740
+ await this.cleanup('No storage manager initialized');
1741
+ return;
1742
+ }
1743
+ this.log.info('Creating context: mattercontrollerContext');
1744
+ this.controllerContext = this.matterStorageManager.createContext('mattercontrollerContext');
1745
+ if (!this.controllerContext) {
1746
+ this.log.error('No storage context mattercontrollerContext initialized');
1747
+ await this.cleanup('No storage context mattercontrollerContext initialized');
1748
+ return;
1749
+ }
1750
+
1751
+ this.log.debug('Starting matterbridge in mode', this.bridgeMode);
1752
+ this.matterServer = await this.createMatterServer(this.storageManager);
1753
+ this.log.info('Creating matter commissioning controller');
1754
+ this.commissioningController = new CommissioningController({
1755
+ autoConnect: false,
1756
+ });
1757
+ this.log.info('Adding matter commissioning controller to matter server');
1758
+ await this.matterServer.addCommissioningController(this.commissioningController);
1759
+
1760
+ this.log.info('Starting matter server');
1761
+ await this.matterServer.start();
1762
+ this.log.info('Matter server started');
1763
+ const commissioningOptions: ControllerCommissioningFlowOptions = {
1764
+ regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
1765
+ regulatoryCountryCode: 'XX',
1766
+ };
1767
+ const commissioningController = new CommissioningController({
1768
+ environment: {
1769
+ environment,
1770
+ id: uniqueId,
1771
+ },
1772
+ autoConnect: false, // Do not auto connect to the commissioned nodes
1773
+ adminFabricLabel,
1774
+ });
1775
+
1776
+ if (hasParameter('pairingcode')) {
1777
+ this.log.info('Pairing device with pairingcode:', getParameter('pairingcode'));
1778
+ const pairingCode = getParameter('pairingcode');
1779
+ const ip = this.controllerContext.has('ip') ? this.controllerContext.get<string>('ip') : undefined;
1780
+ const port = this.controllerContext.has('port') ? this.controllerContext.get<number>('port') : undefined;
1781
+
1782
+ let longDiscriminator, setupPin, shortDiscriminator;
1783
+ if (pairingCode !== undefined) {
1784
+ const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
1785
+ shortDiscriminator = pairingCodeCodec.shortDiscriminator;
1786
+ longDiscriminator = undefined;
1787
+ setupPin = pairingCodeCodec.passcode;
1788
+ this.log.info(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
1789
+ } else {
1790
+ longDiscriminator = await this.controllerContext.get('longDiscriminator', 3840);
1791
+ if (longDiscriminator > 4095) throw new Error('Discriminator value must be less than 4096');
1792
+ setupPin = this.controllerContext.get('pin', 20202021);
1793
+ }
1794
+ if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {
1795
+ throw new Error('Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode');
1796
+ }
1797
+
1798
+ const options = {
1799
+ commissioning: commissioningOptions,
1800
+ discovery: {
1801
+ knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: 'udp' } : undefined,
1802
+ identifierData: longDiscriminator !== undefined ? { longDiscriminator } : shortDiscriminator !== undefined ? { shortDiscriminator } : {},
1803
+ },
1804
+ passcode: setupPin,
1805
+ } as NodeCommissioningOptions;
1806
+ this.log.info('Commissioning with options:', options);
1807
+ const nodeId = await this.commissioningController.commissionNode(options);
1808
+ this.log.info(`Commissioning successfully done with nodeId: ${nodeId}`);
1809
+ this.log.info('ActiveSessionInformation:', this.commissioningController.getActiveSessionInformation());
1810
+ } // (hasParameter('pairingcode'))
1811
+
1812
+ if (hasParameter('unpairall')) {
1813
+ this.log.info('***Commissioning controller unpairing all nodes...');
1814
+ const nodeIds = this.commissioningController.getCommissionedNodes();
1815
+ for (const nodeId of nodeIds) {
1816
+ this.log.info('***Commissioning controller unpairing node:', nodeId);
1817
+ await this.commissioningController.removeNode(nodeId);
1818
+ }
1819
+ return;
1820
+ }
1821
+
1822
+ if (hasParameter('discover')) {
1823
+ // const discover = await this.commissioningController.discoverCommissionableDevices({ productId: 0x8000, deviceType: 0xfff1 });
1824
+ // console.log(discover);
1825
+ }
1826
+
1827
+ if (!this.commissioningController.isCommissioned()) {
1828
+ this.log.info('***Commissioning controller is not commissioned: use matterbridge -controller -pairingcode [pairingcode] to commission a device');
1829
+ return;
1830
+ }
1831
+
1832
+ const nodeIds = this.commissioningController.getCommissionedNodes();
1833
+ this.log.info(`***Commissioning controller is commissioned ${this.commissioningController.isCommissioned()} and has ${nodeIds.length} nodes commisioned: `);
1834
+ for (const nodeId of nodeIds) {
1835
+ this.log.info(`***Connecting to commissioned node: ${nodeId}`);
1836
+
1837
+ const node = await this.commissioningController.connectNode(nodeId, {
1838
+ autoSubscribe: false,
1839
+ attributeChangedCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, attributeName }, value }) =>
1840
+ this.log.info(`***Commissioning controller attributeChangedCallback ${peerNodeId}: attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(value)}`),
1841
+ eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>
1842
+ this.log.info(`***Commissioning controller eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(events)}`),
1843
+ stateInformationCallback: (peerNodeId, info) => {
1844
+ switch (info) {
1845
+ case NodeStateInformation.Connected:
1846
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
1847
+ break;
1848
+ case NodeStateInformation.Disconnected:
1849
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
1850
+ break;
1851
+ case NodeStateInformation.Reconnecting:
1852
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
1853
+ break;
1854
+ case NodeStateInformation.WaitingForDeviceDiscovery:
1855
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`);
1856
+ break;
1857
+ case NodeStateInformation.StructureChanged:
1858
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
1859
+ break;
1860
+ case NodeStateInformation.Decommissioned:
1861
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
1862
+ break;
1863
+ default:
1864
+ this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} NodeStateInformation.${info}`);
1865
+ break;
1866
+ }
1867
+ },
1868
+ });
1869
+
1870
+ node.logStructure();
1871
+
1872
+ // Get the interaction client
1873
+ this.log.info('Getting the interaction client');
1874
+ const interactionClient = await node.getInteractionClient();
1875
+ let cluster;
1876
+ let attributes;
1877
+
1878
+ // Log BasicInformationCluster
1879
+ cluster = BasicInformationCluster;
1880
+ attributes = await interactionClient.getMultipleAttributes({
1881
+ attributes: [{ clusterId: cluster.id }],
1882
+ });
1883
+ if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1884
+ attributes.forEach((attribute) => {
1885
+ this.log.info(
1886
+ `- endpoint ${or}${attribute.path.endpointId}${nf} cluster ${hk}${getClusterNameById(attribute.path.clusterId)}${nf} (${hk}0x${attribute.path.clusterId.toString(16)}${nf}) attribute ${zb}${attribute.path.attributeName}${nf} (${zb}0x${attribute.path.attributeId.toString(16)}${nf}): ${typeof attribute.value === 'object' ? stringify(attribute.value) : attribute.value}`,
1887
+ );
1888
+ });
1889
+
1890
+ // Log PowerSourceCluster
1891
+ cluster = PowerSourceCluster;
1892
+ attributes = await interactionClient.getMultipleAttributes({
1893
+ attributes: [{ clusterId: cluster.id }],
1894
+ });
1895
+ if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1896
+ attributes.forEach((attribute) => {
1897
+ this.log.info(
1898
+ `- endpoint ${or}${attribute.path.endpointId}${nf} cluster ${hk}${getClusterNameById(attribute.path.clusterId)}${nf} (${hk}0x${attribute.path.clusterId.toString(16)}${nf}) attribute ${zb}${attribute.path.attributeName}${nf} (${zb}0x${attribute.path.attributeId.toString(16)}${nf}): ${typeof attribute.value === 'object' ? stringify(attribute.value) : attribute.value}`,
1899
+ );
1900
+ });
1901
+
1902
+ // Log ThreadNetworkDiagnostics
1903
+ cluster = ThreadNetworkDiagnosticsCluster;
1904
+ attributes = await interactionClient.getMultipleAttributes({
1905
+ attributes: [{ clusterId: cluster.id }],
1906
+ });
1907
+ if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1908
+ attributes.forEach((attribute) => {
1909
+ this.log.info(
1910
+ `- endpoint ${or}${attribute.path.endpointId}${nf} cluster ${hk}${getClusterNameById(attribute.path.clusterId)}${nf} (${hk}0x${attribute.path.clusterId.toString(16)}${nf}) attribute ${zb}${attribute.path.attributeName}${nf} (${zb}0x${attribute.path.attributeId.toString(16)}${nf}): ${typeof attribute.value === 'object' ? stringify(attribute.value) : attribute.value}`,
1911
+ );
1912
+ });
1913
+
1914
+ // Log SwitchCluster
1915
+ cluster = SwitchCluster;
1916
+ attributes = await interactionClient.getMultipleAttributes({
1917
+ attributes: [{ clusterId: cluster.id }],
1918
+ });
1919
+ if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1920
+ attributes.forEach((attribute) => {
1921
+ this.log.info(
1922
+ `- endpoint ${or}${attribute.path.endpointId}${nf} cluster ${hk}${getClusterNameById(attribute.path.clusterId)}${nf} (${hk}0x${attribute.path.clusterId.toString(16)}${nf}) attribute ${zb}${attribute.path.attributeName}${nf} (${zb}0x${attribute.path.attributeId.toString(16)}${nf}): ${typeof attribute.value === 'object' ? stringify(attribute.value) : attribute.value}`,
1923
+ );
1924
+ });
1925
+
1926
+ this.log.info('Subscribing to all attributes and events');
1927
+ await node.subscribeAllAttributesAndEvents({
1928
+ ignoreInitialTriggers: false,
1929
+ attributeChangedCallback: ({ path: { nodeId, clusterId, endpointId, attributeName }, version, value }) =>
1930
+ this.log.info(
1931
+ `***${db}Commissioning controller attributeChangedCallback version ${version}: attribute ${BLUE}${nodeId}${db}/${or}${endpointId}${db}/${hk}${getClusterNameById(clusterId)}${db}/${zb}${attributeName}${db} changed to ${typeof value === 'object' ? debugStringify(value ?? { none: true }) : value}`,
1932
+ ),
1933
+ eventTriggeredCallback: ({ path: { nodeId, clusterId, endpointId, eventName }, events }) => {
1934
+ this.log.info(
1935
+ `***${db}Commissioning controller eventTriggeredCallback: event ${BLUE}${nodeId}${db}/${or}${endpointId}${db}/${hk}${getClusterNameById(clusterId)}${db}/${zb}${eventName}${db} triggered with ${debugStringify(events ?? { none: true })}`,
1936
+ );
1937
+ },
1938
+ });
1939
+ this.log.info('Subscribed to all attributes and events');
1940
+ }
1941
+ */
1373
1942
  }
1943
+ /** */
1944
+ /** Matter.js methods */
1945
+ /** */
1946
+ /**
1947
+ * Starts the matter storage with name Matterbridge, create the matterbridge context and performs a backup.
1948
+ *
1949
+ * @returns {Promise<void>} - A promise that resolves when the storage is started.
1950
+ */
1374
1951
  async startMatterStorage() {
1952
+ // Setup Matter storage
1375
1953
  this.log.info(`Starting matter node storage...`);
1376
1954
  this.matterStorageService = this.environment.get(StorageService);
1377
1955
  this.log.info(`Matter node storage service created: ${this.matterStorageService.location}`);
@@ -1380,8 +1958,17 @@ export class Matterbridge extends EventEmitter {
1380
1958
  this.matterbridgeContext = await this.createServerNodeContext('Matterbridge', 'Matterbridge', bridge.code, this.aggregatorVendorId, this.aggregatorVendorName, this.aggregatorProductId, this.aggregatorProductName);
1381
1959
  this.matterbridgeInformation.matterbridgeSerialNumber = await this.matterbridgeContext.get('serialNumber', '');
1382
1960
  this.log.info('Matter node storage started');
1961
+ // Backup matter storage since it is created/opened correctly
1383
1962
  await this.backupMatterStorage(path.join(this.matterbridgeDirectory, this.matterStorageName), path.join(this.matterbridgeDirectory, this.matterStorageName + '.backup'));
1384
1963
  }
1964
+ /**
1965
+ * Makes a backup copy of the specified matter storage directory.
1966
+ *
1967
+ * @param {string} storageName - The name of the storage directory to be backed up.
1968
+ * @param {string} backupName - The name of the backup directory to be created.
1969
+ * @private
1970
+ * @returns {Promise<void>} A promise that resolves when the has been done.
1971
+ */
1385
1972
  async backupMatterStorage(storageName, backupName) {
1386
1973
  this.log.info('Creating matter node storage backup...');
1387
1974
  try {
@@ -1392,6 +1979,11 @@ export class Matterbridge extends EventEmitter {
1392
1979
  this.log.error(`Error creating matter node storage backup from ${storageName} to ${backupName}:`, error);
1393
1980
  }
1394
1981
  }
1982
+ /**
1983
+ * Stops the matter storage.
1984
+ *
1985
+ * @returns {Promise<void>} A promise that resolves when the storage is stopped.
1986
+ */
1395
1987
  async stopMatterStorage() {
1396
1988
  this.log.info('Closing matter node storage...');
1397
1989
  await this.matterStorageManager?.close();
@@ -1400,6 +1992,19 @@ export class Matterbridge extends EventEmitter {
1400
1992
  this.matterbridgeContext = undefined;
1401
1993
  this.log.info('Matter node storage closed');
1402
1994
  }
1995
+ /**
1996
+ * Creates a server node storage context.
1997
+ *
1998
+ * @param {string} pluginName - The name of the plugin.
1999
+ * @param {string} deviceName - The name of the device.
2000
+ * @param {DeviceTypeId} deviceType - The device type of the device.
2001
+ * @param {number} vendorId - The vendor ID.
2002
+ * @param {string} vendorName - The vendor name.
2003
+ * @param {number} productId - The product ID.
2004
+ * @param {string} productName - The product name.
2005
+ * @param {string} [serialNumber] - The serial number of the device (optional).
2006
+ * @returns {Promise<StorageContext>} The storage context for the commissioning server.
2007
+ */
1403
2008
  async createServerNodeContext(pluginName, deviceName, deviceType, vendorId, vendorName, productId, productName, serialNumber) {
1404
2009
  const { randomBytes } = await import('node:crypto');
1405
2010
  if (!this.matterStorageService)
@@ -1433,6 +2038,15 @@ export class Matterbridge extends EventEmitter {
1433
2038
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
1434
2039
  return storageContext;
1435
2040
  }
2041
+ /**
2042
+ * Creates a server node.
2043
+ *
2044
+ * @param {StorageContext} storageContext - The storage context for the server node.
2045
+ * @param {number} [port] - The port number for the server node. Defaults to 5540.
2046
+ * @param {number} [passcode] - The passcode for the server node. Defaults to 20242025.
2047
+ * @param {number} [discriminator] - The discriminator for the server node. Defaults to 3850.
2048
+ * @returns {Promise<ServerNode<ServerNode.RootEndpoint>>} A promise that resolves to the created server node.
2049
+ */
1436
2050
  async createServerNode(storageContext, port = 5540, passcode = 20242025, discriminator = 3850) {
1437
2051
  const storeId = await storageContext.get('storeId');
1438
2052
  this.log.notice(`Creating server node for ${storeId} on port ${port} with passcode ${passcode} and discriminator ${discriminator}...`);
@@ -1442,24 +2056,37 @@ export class Matterbridge extends EventEmitter {
1442
2056
  this.log.debug(`- uniqueId: ${await storageContext.get('uniqueId')}`);
1443
2057
  this.log.debug(`- softwareVersion: ${await storageContext.get('softwareVersion')} softwareVersionString: ${await storageContext.get('softwareVersionString')}`);
1444
2058
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
2059
+ /**
2060
+ * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
2061
+ */
1445
2062
  const serverNode = await ServerNode.create({
2063
+ // Required: Give the Node a unique ID which is used to store the state of this node
1446
2064
  id: storeId,
2065
+ // Provide Network relevant configuration like the port
2066
+ // Optional when operating only one device on a host, Default port is 5540
1447
2067
  network: {
1448
2068
  listeningAddressIpv4: this.ipv4address,
1449
2069
  listeningAddressIpv6: this.ipv6address,
1450
2070
  port,
1451
2071
  },
2072
+ // Provide the certificate for the device
1452
2073
  operationalCredentials: {
1453
2074
  certification: this.certification,
1454
2075
  },
2076
+ // Provide Commissioning relevant settings
2077
+ // Optional for development/testing purposes
1455
2078
  commissioning: {
1456
2079
  passcode,
1457
2080
  discriminator,
1458
2081
  },
2082
+ // Provide Node announcement settings
2083
+ // Optional: If Ommitted some development defaults are used
1459
2084
  productDescription: {
1460
2085
  name: await storageContext.get('deviceName'),
1461
2086
  deviceType: DeviceTypeId(await storageContext.get('deviceType')),
1462
2087
  },
2088
+ // Provide defaults for the BasicInformation cluster on the Root endpoint
2089
+ // Optional: If Omitted some development defaults are used
1463
2090
  basicInformation: {
1464
2091
  vendorId: VendorId(await storageContext.get('vendorId')),
1465
2092
  vendorName: await storageContext.get('vendorName'),
@@ -1476,14 +2103,20 @@ export class Matterbridge extends EventEmitter {
1476
2103
  reachable: true,
1477
2104
  },
1478
2105
  });
2106
+ /**
2107
+ * This event is triggered when the device is initially commissioned successfully.
2108
+ * This means: It is added to the first fabric.
2109
+ */
1479
2110
  serverNode.lifecycle.commissioned.on(() => {
1480
2111
  this.log.notice(`Server node for ${storeId} was initially commissioned successfully!`);
1481
2112
  clearTimeout(this.endAdvertiseTimeout);
1482
2113
  });
2114
+ /** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
1483
2115
  serverNode.lifecycle.decommissioned.on(() => {
1484
2116
  this.log.notice(`Server node for ${storeId} was fully decommissioned successfully!`);
1485
2117
  clearTimeout(this.endAdvertiseTimeout);
1486
2118
  });
2119
+ /** This event is triggered when the device went online. This means that it is discoverable in the network. */
1487
2120
  serverNode.lifecycle.online.on(async () => {
1488
2121
  this.log.notice(`Server node for ${storeId} is online`);
1489
2122
  if (!serverNode.lifecycle.isCommissioned) {
@@ -1491,9 +2124,11 @@ export class Matterbridge extends EventEmitter {
1491
2124
  const { qrPairingCode, manualPairingCode } = serverNode.state.commissioning.pairingCodes;
1492
2125
  this.log.notice(`QR Code URL: https://project-chip.github.io/connectedhomeip/qrcode.html?data=${qrPairingCode}`);
1493
2126
  this.log.notice(`Manual pairing code: ${manualPairingCode}`);
2127
+ // Set a timeout to show that advertising stops after 15 minutes if not commissioned
1494
2128
  this.startEndAdvertiseTimer(serverNode);
1495
2129
  }
1496
2130
  else {
2131
+ // istanbul ignore next
1497
2132
  this.log.notice(`Server node for ${storeId} is already commissioned. Waiting for controllers to connect ...`);
1498
2133
  }
1499
2134
  this.frontend.wssSendRefreshRequired('plugins');
@@ -1501,14 +2136,19 @@ export class Matterbridge extends EventEmitter {
1501
2136
  this.frontend.wssSendSnackbarMessage(`${storeId} is online`, 5, 'success');
1502
2137
  this.emit('online', storeId);
1503
2138
  });
2139
+ /** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
1504
2140
  serverNode.lifecycle.offline.on(() => {
1505
2141
  this.log.notice(`Server node for ${storeId} is offline`);
1506
- this.matterbridgeInformation.matterbridgeEndAdvertise = true;
2142
+ this.matterbridgeInformation.matterbridgeEndAdvertise = true; // Set the end advertise flag to true, so the frontend won't show the QR code anymore
1507
2143
  this.frontend.wssSendRefreshRequired('plugins');
1508
2144
  this.frontend.wssSendRefreshRequired('settings');
1509
2145
  this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
1510
2146
  this.emit('offline', storeId);
1511
2147
  });
2148
+ /**
2149
+ * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
2150
+ * information is needed.
2151
+ */
1512
2152
  serverNode.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {
1513
2153
  let action = '';
1514
2154
  switch (fabricAction) {
@@ -1525,14 +2165,22 @@ export class Matterbridge extends EventEmitter {
1525
2165
  this.log.notice(`Commissioned fabric index ${fabricIndex} ${action} on server node for ${storeId}: ${debugStringify(serverNode.state.commissioning.fabrics[fabricIndex])}`);
1526
2166
  this.frontend.wssSendRefreshRequired('fabrics');
1527
2167
  });
2168
+ /**
2169
+ * This event is triggered when an operative new session was opened by a Controller.
2170
+ * It is not triggered for the initial commissioning process, just afterwards for real connections.
2171
+ */
1528
2172
  serverNode.events.sessions.opened.on((session) => {
1529
2173
  this.log.notice(`Session opened on server node for ${storeId}: ${debugStringify(session)}`);
1530
2174
  this.frontend.wssSendRefreshRequired('sessions');
1531
2175
  });
2176
+ /**
2177
+ * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
2178
+ */
1532
2179
  serverNode.events.sessions.closed.on((session) => {
1533
2180
  this.log.notice(`Session closed on server node for ${storeId}: ${debugStringify(session)}`);
1534
2181
  this.frontend.wssSendRefreshRequired('sessions');
1535
2182
  });
2183
+ /** This event is triggered when a subscription gets added or removed on an operative session. */
1536
2184
  serverNode.events.sessions.subscriptionsChanged.on((session) => {
1537
2185
  this.log.notice(`Session subscriptions changed on server node for ${storeId}: ${debugStringify(session)}`);
1538
2186
  this.frontend.wssSendRefreshRequired('sessions');
@@ -1540,6 +2188,11 @@ export class Matterbridge extends EventEmitter {
1540
2188
  this.log.info(`Created server node for ${storeId}`);
1541
2189
  return serverNode;
1542
2190
  }
2191
+ /**
2192
+ * Starts the 15 minutes timer to advice that advertising for the specified server node is ended.
2193
+ *
2194
+ * @param {ServerNode} [matterServerNode] - The server node to start.
2195
+ */
1543
2196
  startEndAdvertiseTimer(matterServerNode) {
1544
2197
  if (this.endAdvertiseTimeout) {
1545
2198
  this.log.debug(`Clear ${matterServerNode.id} server node end advertise timer`);
@@ -1558,12 +2211,25 @@ export class Matterbridge extends EventEmitter {
1558
2211
  this.log.notice(`Advertising on server node for ${matterServerNode.id} stopped. Restart to commission.`);
1559
2212
  }, 15 * 60 * 1000).unref();
1560
2213
  }
2214
+ /**
2215
+ * Starts the specified server node.
2216
+ *
2217
+ * @param {ServerNode} [matterServerNode] - The server node to start.
2218
+ * @returns {Promise<void>} A promise that resolves when the server node has started.
2219
+ */
1561
2220
  async startServerNode(matterServerNode) {
1562
2221
  if (!matterServerNode)
1563
2222
  return;
1564
2223
  this.log.notice(`Starting ${matterServerNode.id} server node`);
1565
2224
  await matterServerNode.start();
1566
2225
  }
2226
+ /**
2227
+ * Stops the specified server node.
2228
+ *
2229
+ * @param {ServerNode} matterServerNode - The server node to stop.
2230
+ * @param {number} [timeout] - The timeout in milliseconds for stopping the server node. Defaults to 30 seconds.
2231
+ * @returns {Promise<void>} A promise that resolves when the server node has stopped.
2232
+ */
1567
2233
  async stopServerNode(matterServerNode, timeout = 30000) {
1568
2234
  if (!matterServerNode)
1569
2235
  return;
@@ -1576,6 +2242,12 @@ export class Matterbridge extends EventEmitter {
1576
2242
  this.log.error(`Failed to close ${matterServerNode.id} server node: ${error instanceof Error ? error.message : error}`);
1577
2243
  }
1578
2244
  }
2245
+ /**
2246
+ * Advertises the specified server node.
2247
+ *
2248
+ * @param {ServerNode} [matterServerNode] - The server node to advertise.
2249
+ * @returns {Promise<{ qrPairingCode: string, manualPairingCode: string } | undefined>} A promise that resolves to the pairing codes if the server node is advertised, or undefined if not.
2250
+ */
1579
2251
  async advertiseServerNode(matterServerNode) {
1580
2252
  if (matterServerNode) {
1581
2253
  await matterServerNode.env.get(DeviceCommissioner)?.allowBasicCommissioning();
@@ -1584,19 +2256,39 @@ export class Matterbridge extends EventEmitter {
1584
2256
  return { qrPairingCode, manualPairingCode };
1585
2257
  }
1586
2258
  }
2259
+ /**
2260
+ * Stop advertise the specified server node.
2261
+ *
2262
+ * @param {ServerNode} [matterServerNode] - The server node to advertise.
2263
+ * @returns {Promise<void>} A promise that resolves when the server node has stopped advertising.
2264
+ */
1587
2265
  async stopAdvertiseServerNode(matterServerNode) {
1588
2266
  if (matterServerNode && matterServerNode.lifecycle.isOnline) {
1589
2267
  await matterServerNode.env.get(DeviceCommissioner)?.endCommissioning();
1590
2268
  this.log.notice(`Stopped advertising for ${matterServerNode.id}`);
1591
2269
  }
1592
2270
  }
2271
+ /**
2272
+ * Creates an aggregator node with the specified storage context.
2273
+ *
2274
+ * @param {StorageContext} storageContext - The storage context for the aggregator node.
2275
+ * @returns {Promise<Endpoint<AggregatorEndpoint>>} A promise that resolves to the created aggregator node.
2276
+ */
1593
2277
  async createAggregatorNode(storageContext) {
1594
2278
  this.log.notice(`Creating ${await storageContext.get('storeId')} aggregator...`);
1595
2279
  const aggregatorNode = new Endpoint(AggregatorEndpoint, { id: `${await storageContext.get('storeId')}` });
1596
2280
  this.log.info(`Created ${await storageContext.get('storeId')} aggregator`);
1597
2281
  return aggregatorNode;
1598
2282
  }
2283
+ /**
2284
+ * Adds a MatterbridgeEndpoint to the specified plugin.
2285
+ *
2286
+ * @param {string} pluginName - The name of the plugin.
2287
+ * @param {MatterbridgeEndpoint} device - The device to add as a bridged endpoint.
2288
+ * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been added.
2289
+ */
1599
2290
  async addBridgedEndpoint(pluginName, device) {
2291
+ // Check if the plugin is registered
1600
2292
  const plugin = this.plugins.get(pluginName);
1601
2293
  if (!plugin) {
1602
2294
  this.log.error(`Error adding bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.id}${er}) plugin ${plg}${pluginName}${er} not found`);
@@ -1616,6 +2308,7 @@ export class Matterbridge extends EventEmitter {
1616
2308
  }
1617
2309
  else if (this.bridgeMode === 'bridge') {
1618
2310
  if (device.mode === 'matter') {
2311
+ // Register and add the device to the matterbridge server node
1619
2312
  this.log.debug(`Adding matter endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge server node...`);
1620
2313
  if (!this.serverNode) {
1621
2314
  this.log.error('Server node not found for Matterbridge');
@@ -1632,6 +2325,7 @@ export class Matterbridge extends EventEmitter {
1632
2325
  }
1633
2326
  }
1634
2327
  else {
2328
+ // Register and add the device to the matterbridge aggregator node
1635
2329
  this.log.debug(`Adding bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge aggregator node`);
1636
2330
  if (!this.aggregatorNode) {
1637
2331
  this.log.error('Aggregator node not found for Matterbridge');
@@ -1649,6 +2343,7 @@ export class Matterbridge extends EventEmitter {
1649
2343
  }
1650
2344
  }
1651
2345
  else if (this.bridgeMode === 'childbridge') {
2346
+ // Register and add the device to the plugin server node
1652
2347
  if (plugin.type === 'AccessoryPlatform') {
1653
2348
  try {
1654
2349
  this.log.debug(`Creating endpoint ${dev}${device.deviceName}${db} for AccessoryPlatform plugin ${plg}${plugin.name}${db} server node`);
@@ -1672,10 +2367,12 @@ export class Matterbridge extends EventEmitter {
1672
2367
  return;
1673
2368
  }
1674
2369
  }
2370
+ // Register and add the device to the plugin aggregator node
1675
2371
  if (plugin.type === 'DynamicPlatform') {
1676
2372
  try {
1677
2373
  this.log.debug(`Adding bridged endpoint ${dev}${device.deviceName}${db} for DynamicPlatform plugin ${plg}${plugin.name}${db} aggregator node`);
1678
2374
  await this.createDynamicPlugin(plugin);
2375
+ // Fast plugins can add another device before the server node is ready, so we wait for the server node to be ready
1679
2376
  await waiter(`createDynamicPlugin(${plugin.name})`, () => plugin.serverNode?.hasParts === true);
1680
2377
  if (!plugin.aggregatorNode) {
1681
2378
  this.log.error(`Aggregator node not found for plugin ${plg}${plugin.name}${er}`);
@@ -1698,17 +2395,28 @@ export class Matterbridge extends EventEmitter {
1698
2395
  plugin.registeredDevices++;
1699
2396
  if (plugin.addedDevices !== undefined)
1700
2397
  plugin.addedDevices++;
2398
+ // Add the device to the DeviceManager
1701
2399
  this.devices.set(device);
2400
+ // Subscribe to the reachable$Changed event
1702
2401
  await this.subscribeAttributeChanged(plugin, device);
1703
2402
  this.log.info(`Added and registered bridged endpoint (${plugin.registeredDevices}/${plugin.addedDevices}) ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) for plugin ${plg}${pluginName}${nf}`);
1704
2403
  }
2404
+ /**
2405
+ * Removes a MatterbridgeEndpoint from the specified plugin.
2406
+ *
2407
+ * @param {string} pluginName - The name of the plugin.
2408
+ * @param {MatterbridgeEndpoint} device - The device to remove as a bridged endpoint.
2409
+ * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been removed.
2410
+ */
1705
2411
  async removeBridgedEndpoint(pluginName, device) {
1706
2412
  this.log.debug(`Removing bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} (${zb}${device.name}${db}) for plugin ${plg}${pluginName}${db}`);
2413
+ // Check if the plugin is registered
1707
2414
  const plugin = this.plugins.get(pluginName);
1708
2415
  if (!plugin) {
1709
2416
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: plugin not found`);
1710
2417
  return;
1711
2418
  }
2419
+ // Register and add the device to the matterbridge aggregator node
1712
2420
  if (this.bridgeMode === 'bridge') {
1713
2421
  if (!this.aggregatorNode) {
1714
2422
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: aggregator node not found`);
@@ -1723,6 +2431,7 @@ export class Matterbridge extends EventEmitter {
1723
2431
  }
1724
2432
  else if (this.bridgeMode === 'childbridge') {
1725
2433
  if (plugin.type === 'AccessoryPlatform') {
2434
+ // Nothing to do here since the server node has no aggregator node but only the device itself
1726
2435
  }
1727
2436
  else if (plugin.type === 'DynamicPlatform') {
1728
2437
  if (!plugin.aggregatorNode) {
@@ -1737,8 +2446,21 @@ export class Matterbridge extends EventEmitter {
1737
2446
  if (plugin.addedDevices !== undefined)
1738
2447
  plugin.addedDevices--;
1739
2448
  }
2449
+ // Remove the device from the DeviceManager
1740
2450
  this.devices.remove(device);
1741
2451
  }
2452
+ /**
2453
+ * Removes all bridged endpoints from the specified plugin.
2454
+ *
2455
+ * @param {string} pluginName - The name of the plugin.
2456
+ * @param {number} [delay] - The delay in milliseconds between removing each bridged endpoint (default: 0).
2457
+ * @returns {Promise<void>} A promise that resolves when all bridged endpoints have been removed.
2458
+ *
2459
+ * @remarks
2460
+ * This method iterates through all devices in the DeviceManager and removes each bridged endpoint associated with the specified plugin.
2461
+ * It also applies a delay between each removal if specified.
2462
+ * The delay is useful to allow the controllers to receive a single subscription for each device removed.
2463
+ */
1742
2464
  async removeAllBridgedEndpoints(pluginName, delay = 0) {
1743
2465
  this.log.debug(`Removing all bridged endpoints for plugin ${plg}${pluginName}${db}${delay > 0 ? ` with delay ${delay} ms` : ''}`);
1744
2466
  for (const device of this.devices.array().filter((device) => device.plugin === pluginName)) {
@@ -1749,6 +2471,15 @@ export class Matterbridge extends EventEmitter {
1749
2471
  if (delay > 0)
1750
2472
  await wait(2000);
1751
2473
  }
2474
+ /**
2475
+ * Subscribes to the attribute change event for the given device and plugin.
2476
+ * Specifically, it listens for changes in the 'reachable' attribute of the
2477
+ * BridgedDeviceBasicInformationServer cluster server of the bridged device or BasicInformationServer cluster server of server node.
2478
+ *
2479
+ * @param {RegisteredPlugin} plugin - The plugin associated with the device.
2480
+ * @param {MatterbridgeEndpoint} device - The device to subscribe to attribute changes for.
2481
+ * @returns {Promise<void>} A promise that resolves when the subscription is set up.
2482
+ */
1752
2483
  async subscribeAttributeChanged(plugin, device) {
1753
2484
  this.log.info(`Subscribing attributes for endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) plugin ${plg}${plugin.name}${nf}`);
1754
2485
  if (this.bridgeMode === 'childbridge' && plugin.type === 'AccessoryPlatform' && plugin.serverNode) {
@@ -1764,6 +2495,12 @@ export class Matterbridge extends EventEmitter {
1764
2495
  });
1765
2496
  }
1766
2497
  }
2498
+ /**
2499
+ * Sanitizes the fabric information by converting bigint properties to strings because `res.json` doesn't support bigint.
2500
+ *
2501
+ * @param {ExposedFabricInformation[]} fabricInfo - The array of exposed fabric information objects.
2502
+ * @returns {SanitizedExposedFabricInformation[]} An array of sanitized exposed fabric information objects.
2503
+ */
1767
2504
  sanitizeFabricInformations(fabricInfo) {
1768
2505
  return fabricInfo.map((info) => {
1769
2506
  return {
@@ -1777,6 +2514,12 @@ export class Matterbridge extends EventEmitter {
1777
2514
  };
1778
2515
  });
1779
2516
  }
2517
+ /**
2518
+ * Sanitizes the session information by converting bigint properties to strings because `res.json` doesn't support bigint.
2519
+ *
2520
+ * @param {SessionsBehavior.Session[]} sessions - The array of session information objects.
2521
+ * @returns {SanitizedSession[]} An array of sanitized session information objects.
2522
+ */
1780
2523
  sanitizeSessionInformation(sessions) {
1781
2524
  return sessions
1782
2525
  .filter((session) => session.isPeerActive)
@@ -1803,7 +2546,21 @@ export class Matterbridge extends EventEmitter {
1803
2546
  };
1804
2547
  });
1805
2548
  }
2549
+ /**
2550
+ * Sets the reachability of the specified aggregator node bridged devices and trigger.
2551
+ *
2552
+ * @param {Endpoint<AggregatorEndpoint>} aggregatorNode - The aggregator node to set the reachability for.
2553
+ * @param {boolean} reachable - A boolean indicating the reachability status to set.
2554
+ */
2555
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
1806
2556
  async setAggregatorReachability(aggregatorNode, reachable) {
2557
+ /*
2558
+ for (const child of aggregatorNode.parts) {
2559
+ this.log.debug(`Setting reachability of ${(child as unknown as MatterbridgeEndpoint)?.deviceName} to ${reachable}`);
2560
+ await child.setStateOf(BridgedDeviceBasicInformationServer, { reachable });
2561
+ child.act((agent) => child.eventsOf(BridgedDeviceBasicInformationServer).reachableChanged.emit({ reachableNewValue: true }, agent.context));
2562
+ }
2563
+ */
1807
2564
  }
1808
2565
  getVendorIdName = (vendorId) => {
1809
2566
  if (!vendorId)
@@ -1843,10 +2600,11 @@ export class Matterbridge extends EventEmitter {
1843
2600
  case 0x1488:
1844
2601
  vendorName = '(ShortcutLabsFlic)';
1845
2602
  break;
1846
- case 65521:
2603
+ case 65521: // 0xFFF1
1847
2604
  vendorName = '(MatterTest)';
1848
2605
  break;
1849
2606
  }
1850
2607
  return vendorName;
1851
2608
  };
1852
2609
  }
2610
+ //# sourceMappingURL=matterbridge.js.map