matterbridge 3.0.7 → 3.0.8-dev-20250622-9a6255a

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 (207) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/bin/matterbridge +2 -0
  3. package/dist/cli.js +5 -66
  4. package/dist/clusters/export.js +0 -2
  5. package/dist/defaultConfigSchema.js +0 -23
  6. package/dist/deviceManager.js +2 -95
  7. package/dist/devices/export.js +0 -2
  8. package/dist/evse.js +9 -65
  9. package/dist/frontend.js +47 -383
  10. package/dist/globalMatterbridge.js +0 -20
  11. package/dist/helpers.js +4 -52
  12. package/dist/index.js +2 -29
  13. package/dist/laundryWasher.js +7 -92
  14. package/dist/logger/export.js +0 -1
  15. package/dist/matter/behaviors.js +0 -2
  16. package/dist/matter/clusters.js +0 -2
  17. package/dist/matter/devices.js +0 -2
  18. package/dist/matter/endpoints.js +0 -2
  19. package/dist/matter/export.js +0 -2
  20. package/dist/matter/types.js +0 -2
  21. package/dist/matterbridge.js +53 -755
  22. package/dist/matterbridgeAccessoryPlatform.js +0 -34
  23. package/dist/matterbridgeBehaviors.js +1 -54
  24. package/dist/matterbridgeDeviceTypes.js +15 -578
  25. package/dist/matterbridgeDynamicPlatform.js +0 -34
  26. package/dist/matterbridgeEndpoint.js +45 -1000
  27. package/dist/matterbridgeEndpointHelpers.js +12 -206
  28. package/dist/matterbridgePlatform.js +13 -225
  29. package/dist/matterbridgeTypes.js +0 -24
  30. package/dist/pluginManager.js +4 -270
  31. package/dist/roboticVacuumCleaner.js +9 -84
  32. package/dist/shelly.js +9 -156
  33. package/dist/storage/export.js +0 -1
  34. package/dist/update.js +0 -53
  35. package/dist/utils/colorUtils.js +2 -205
  36. package/dist/utils/commandLine.js +0 -53
  37. package/dist/utils/copyDirectory.js +1 -37
  38. package/dist/utils/createDirectory.js +0 -31
  39. package/dist/utils/createZip.js +2 -42
  40. package/dist/utils/deepCopy.js +0 -38
  41. package/dist/utils/deepEqual.js +1 -71
  42. package/dist/utils/export.js +0 -1
  43. package/dist/utils/hex.js +0 -57
  44. package/dist/utils/isvalid.js +0 -100
  45. package/dist/utils/network.js +6 -77
  46. package/dist/utils/spawn.js +0 -16
  47. package/dist/utils/wait.js +10 -58
  48. package/dist/waterHeater.js +5 -65
  49. package/frontend/build/matterbridge 1250x1250.png +0 -0
  50. package/frontend/build/matterbridge 624x624.png +0 -0
  51. package/frontend/package-lock.json +19176 -0
  52. package/frontend/package.json +79 -0
  53. package/frontend/public/Shelly.svg +1 -0
  54. package/frontend/public/bmc-button.svg +22 -0
  55. package/frontend/public/discord.svg +5 -0
  56. package/frontend/public/favicon.ico +0 -0
  57. package/frontend/public/index.html +19 -0
  58. package/frontend/public/manifest.json +15 -0
  59. package/frontend/public/matter.png +0 -0
  60. package/frontend/public/matterbridge 1250x1250.png +0 -0
  61. package/frontend/public/matterbridge 32x32.png +0 -0
  62. package/frontend/public/matterbridge 624x624.png +0 -0
  63. package/frontend/public/matterbridge 64x64.png +0 -0
  64. package/frontend/public/matterbridge.svg +50 -0
  65. package/frontend/public/robots.txt +3 -0
  66. package/npm-shrinkwrap.json +33 -42
  67. package/package.json +3 -4
  68. package/dist/cli.d.ts +0 -29
  69. package/dist/cli.d.ts.map +0 -1
  70. package/dist/cli.js.map +0 -1
  71. package/dist/clusters/export.d.ts +0 -2
  72. package/dist/clusters/export.d.ts.map +0 -1
  73. package/dist/clusters/export.js.map +0 -1
  74. package/dist/defaultConfigSchema.d.ts +0 -27
  75. package/dist/defaultConfigSchema.d.ts.map +0 -1
  76. package/dist/defaultConfigSchema.js.map +0 -1
  77. package/dist/deviceManager.d.ts +0 -114
  78. package/dist/deviceManager.d.ts.map +0 -1
  79. package/dist/deviceManager.js.map +0 -1
  80. package/dist/devices/export.d.ts +0 -5
  81. package/dist/devices/export.d.ts.map +0 -1
  82. package/dist/devices/export.js.map +0 -1
  83. package/dist/evse.d.ts +0 -67
  84. package/dist/evse.d.ts.map +0 -1
  85. package/dist/evse.js.map +0 -1
  86. package/dist/frontend.d.ts +0 -256
  87. package/dist/frontend.d.ts.map +0 -1
  88. package/dist/frontend.js.map +0 -1
  89. package/dist/globalMatterbridge.d.ts +0 -32
  90. package/dist/globalMatterbridge.d.ts.map +0 -1
  91. package/dist/globalMatterbridge.js.map +0 -1
  92. package/dist/helpers.d.ts +0 -47
  93. package/dist/helpers.d.ts.map +0 -1
  94. package/dist/helpers.js.map +0 -1
  95. package/dist/index.d.ts +0 -37
  96. package/dist/index.d.ts.map +0 -1
  97. package/dist/index.js.map +0 -1
  98. package/dist/laundryWasher.d.ts +0 -243
  99. package/dist/laundryWasher.d.ts.map +0 -1
  100. package/dist/laundryWasher.js.map +0 -1
  101. package/dist/logger/export.d.ts +0 -2
  102. package/dist/logger/export.d.ts.map +0 -1
  103. package/dist/logger/export.js.map +0 -1
  104. package/dist/matter/behaviors.d.ts +0 -2
  105. package/dist/matter/behaviors.d.ts.map +0 -1
  106. package/dist/matter/behaviors.js.map +0 -1
  107. package/dist/matter/clusters.d.ts +0 -2
  108. package/dist/matter/clusters.d.ts.map +0 -1
  109. package/dist/matter/clusters.js.map +0 -1
  110. package/dist/matter/devices.d.ts +0 -2
  111. package/dist/matter/devices.d.ts.map +0 -1
  112. package/dist/matter/devices.js.map +0 -1
  113. package/dist/matter/endpoints.d.ts +0 -2
  114. package/dist/matter/endpoints.d.ts.map +0 -1
  115. package/dist/matter/endpoints.js.map +0 -1
  116. package/dist/matter/export.d.ts +0 -5
  117. package/dist/matter/export.d.ts.map +0 -1
  118. package/dist/matter/export.js.map +0 -1
  119. package/dist/matter/types.d.ts +0 -3
  120. package/dist/matter/types.d.ts.map +0 -1
  121. package/dist/matter/types.js.map +0 -1
  122. package/dist/matterbridge.d.ts +0 -445
  123. package/dist/matterbridge.d.ts.map +0 -1
  124. package/dist/matterbridge.js.map +0 -1
  125. package/dist/matterbridgeAccessoryPlatform.d.ts +0 -40
  126. package/dist/matterbridgeAccessoryPlatform.d.ts.map +0 -1
  127. package/dist/matterbridgeAccessoryPlatform.js.map +0 -1
  128. package/dist/matterbridgeBehaviors.d.ts +0 -1333
  129. package/dist/matterbridgeBehaviors.d.ts.map +0 -1
  130. package/dist/matterbridgeBehaviors.js.map +0 -1
  131. package/dist/matterbridgeDeviceTypes.d.ts +0 -644
  132. package/dist/matterbridgeDeviceTypes.d.ts.map +0 -1
  133. package/dist/matterbridgeDeviceTypes.js.map +0 -1
  134. package/dist/matterbridgeDynamicPlatform.d.ts +0 -40
  135. package/dist/matterbridgeDynamicPlatform.d.ts.map +0 -1
  136. package/dist/matterbridgeDynamicPlatform.js.map +0 -1
  137. package/dist/matterbridgeEndpoint.d.ts +0 -1145
  138. package/dist/matterbridgeEndpoint.d.ts.map +0 -1
  139. package/dist/matterbridgeEndpoint.js.map +0 -1
  140. package/dist/matterbridgeEndpointHelpers.d.ts +0 -3083
  141. package/dist/matterbridgeEndpointHelpers.d.ts.map +0 -1
  142. package/dist/matterbridgeEndpointHelpers.js.map +0 -1
  143. package/dist/matterbridgePlatform.d.ts +0 -290
  144. package/dist/matterbridgePlatform.d.ts.map +0 -1
  145. package/dist/matterbridgePlatform.js.map +0 -1
  146. package/dist/matterbridgeTypes.d.ts +0 -196
  147. package/dist/matterbridgeTypes.d.ts.map +0 -1
  148. package/dist/matterbridgeTypes.js.map +0 -1
  149. package/dist/pluginManager.d.ts +0 -273
  150. package/dist/pluginManager.d.ts.map +0 -1
  151. package/dist/pluginManager.js.map +0 -1
  152. package/dist/roboticVacuumCleaner.d.ts +0 -102
  153. package/dist/roboticVacuumCleaner.d.ts.map +0 -1
  154. package/dist/roboticVacuumCleaner.js.map +0 -1
  155. package/dist/shelly.d.ts +0 -161
  156. package/dist/shelly.d.ts.map +0 -1
  157. package/dist/shelly.js.map +0 -1
  158. package/dist/storage/export.d.ts +0 -2
  159. package/dist/storage/export.d.ts.map +0 -1
  160. package/dist/storage/export.js.map +0 -1
  161. package/dist/update.d.ts +0 -58
  162. package/dist/update.d.ts.map +0 -1
  163. package/dist/update.js.map +0 -1
  164. package/dist/utils/colorUtils.d.ts +0 -61
  165. package/dist/utils/colorUtils.d.ts.map +0 -1
  166. package/dist/utils/colorUtils.js.map +0 -1
  167. package/dist/utils/commandLine.d.ts +0 -58
  168. package/dist/utils/commandLine.d.ts.map +0 -1
  169. package/dist/utils/commandLine.js.map +0 -1
  170. package/dist/utils/copyDirectory.d.ts +0 -32
  171. package/dist/utils/copyDirectory.d.ts.map +0 -1
  172. package/dist/utils/copyDirectory.js.map +0 -1
  173. package/dist/utils/createDirectory.d.ts +0 -32
  174. package/dist/utils/createDirectory.d.ts.map +0 -1
  175. package/dist/utils/createDirectory.js.map +0 -1
  176. package/dist/utils/createZip.d.ts +0 -38
  177. package/dist/utils/createZip.d.ts.map +0 -1
  178. package/dist/utils/createZip.js.map +0 -1
  179. package/dist/utils/deepCopy.d.ts +0 -31
  180. package/dist/utils/deepCopy.d.ts.map +0 -1
  181. package/dist/utils/deepCopy.js.map +0 -1
  182. package/dist/utils/deepEqual.d.ts +0 -53
  183. package/dist/utils/deepEqual.d.ts.map +0 -1
  184. package/dist/utils/deepEqual.js.map +0 -1
  185. package/dist/utils/export.d.ts +0 -12
  186. package/dist/utils/export.d.ts.map +0 -1
  187. package/dist/utils/export.js.map +0 -1
  188. package/dist/utils/hex.d.ts +0 -48
  189. package/dist/utils/hex.d.ts.map +0 -1
  190. package/dist/utils/hex.js.map +0 -1
  191. package/dist/utils/isvalid.d.ts +0 -102
  192. package/dist/utils/isvalid.d.ts.map +0 -1
  193. package/dist/utils/isvalid.js.map +0 -1
  194. package/dist/utils/network.d.ts +0 -69
  195. package/dist/utils/network.d.ts.map +0 -1
  196. package/dist/utils/network.js.map +0 -1
  197. package/dist/utils/spawn.d.ts +0 -12
  198. package/dist/utils/spawn.d.ts.map +0 -1
  199. package/dist/utils/spawn.js.map +0 -1
  200. package/dist/utils/wait.d.ts +0 -52
  201. package/dist/utils/wait.d.ts.map +0 -1
  202. package/dist/utils/wait.js.map +0 -1
  203. package/dist/waterHeater.d.ts +0 -90
  204. package/dist/waterHeater.d.ts.map +0 -1
  205. package/dist/waterHeater.js.map +0 -1
  206. package/tsconfig.jest.json +0 -8
  207. package/tsconfig.production.json +0 -13
@@ -1,36 +1,15 @@
1
- /**
2
- * This file contains the class Matterbridge.
3
- *
4
- * @file matterbridge.ts
5
- * @author Luca Liguori
6
- * @date 2023-12-29
7
- * @version 1.6.0
8
- *
9
- * Copyright 2023, 2024, 2025 Luca Liguori.
10
- *
11
- * Licensed under the Apache License, Version 2.0 (the "License");
12
- * you may not use this file except in compliance with the License.
13
- * You may obtain a copy of the License at
14
- *
15
- * http://www.apache.org/licenses/LICENSE-2.0
16
- *
17
- * Unless required by applicable law or agreed to in writing, software
18
- * distributed under the License is distributed on an "AS IS" BASIS,
19
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
- * See the License for the specific language governing permissions and
21
- * limitations under the License. *
22
- */
23
- // Node.js modules
24
1
  import os from 'node:os';
25
2
  import path from 'node:path';
26
3
  import { promises as fs } from 'node:fs';
27
4
  import EventEmitter from 'node:events';
28
5
  import { inspect } from 'node:util';
29
- // AnsiLogger module
30
- import { AnsiLogger, UNDERLINE, UNDERLINEOFF, YELLOW, db, debugStringify, BRIGHT, RESET, er, nf, rs, wr, RED, GREEN, zb, CYAN } from './logger/export.js';
31
- // NodeStorage module
32
- import { NodeStorageManager } from './storage/export.js';
33
- // Matterbridge
6
+ import { AnsiLogger, UNDERLINE, UNDERLINEOFF, YELLOW, db, debugStringify, BRIGHT, RESET, er, nf, rs, wr, RED, GREEN, zb, CYAN } from 'node-ansi-logger';
7
+ import { NodeStorageManager } from 'node-persist-manager';
8
+ import { DeviceTypeId, Endpoint, Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, VendorId, StorageService, Environment, ServerNode, UINT32_MAX, UINT16_MAX, } from '@matter/main';
9
+ import { DeviceCommissioner, FabricAction, MdnsService, PaseClient } from '@matter/main/protocol';
10
+ import { AggregatorEndpoint } from '@matter/main/endpoints';
11
+ import { BasicInformationServer } from '@matter/main/behaviors/basic-information';
12
+ import { BridgedDeviceBasicInformationServer } from '@matter/main/behaviors/bridged-device-basic-information';
34
13
  import { getParameter, getIntParameter, hasParameter, copyDirectory, withTimeout, waiter, isValidString, parseVersionString, isValidNumber, createDirectory } from './utils/export.js';
35
14
  import { logInterfaces, getGlobalNodeModules } from './utils/network.js';
36
15
  import { dev, plg, typ } from './matterbridgeTypes.js';
@@ -41,15 +20,6 @@ import { bridge } from './matterbridgeDeviceTypes.js';
41
20
  import { Frontend } from './frontend.js';
42
21
  import { addVirtualDevices } from './helpers.js';
43
22
  import spawn from './utils/spawn.js';
44
- // @matter
45
- import { DeviceTypeId, Endpoint, Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, VendorId, StorageService, Environment, ServerNode, UINT32_MAX, UINT16_MAX, } from '@matter/main';
46
- import { DeviceCommissioner, FabricAction, MdnsService, PaseClient } from '@matter/main/protocol';
47
- import { AggregatorEndpoint } from '@matter/main/endpoints';
48
- import { BasicInformationServer } from '@matter/main/behaviors/basic-information';
49
- import { BridgedDeviceBasicInformationServer } from '@matter/main/behaviors/bridged-device-basic-information';
50
- /**
51
- * Represents the Matterbridge application.
52
- */
53
23
  export class Matterbridge extends EventEmitter {
54
24
  systemInformation = {
55
25
  interfaceName: '',
@@ -97,7 +67,7 @@ export class Matterbridge extends EventEmitter {
97
67
  shellySysUpdate: false,
98
68
  shellyMainUpdate: false,
99
69
  profile: getParameter('profile'),
100
- loggerLevel: "info" /* LogLevel.INFO */,
70
+ loggerLevel: "info",
101
71
  fileLogger: false,
102
72
  matterLoggerLevel: MatterLogLevel.INFO,
103
73
  matterFileLogger: false,
@@ -136,11 +106,9 @@ export class Matterbridge extends EventEmitter {
136
106
  plugins;
137
107
  devices;
138
108
  frontend = new Frontend(this);
139
- // Matterbridge storage
140
109
  nodeStorage;
141
110
  nodeContext;
142
111
  nodeStorageName = 'storage' + (getParameter('profile') ? '.' + getParameter('profile') : '');
143
- // Cleanup
144
112
  hasCleanupStarted = false;
145
113
  initialized = false;
146
114
  execRunningCount = 0;
@@ -154,22 +122,19 @@ export class Matterbridge extends EventEmitter {
154
122
  sigtermHandler;
155
123
  exceptionHandler;
156
124
  rejectionHandler;
157
- // Matter environment
158
125
  environment = Environment.default;
159
- // Matter storage
160
126
  matterStorageName = 'matterstorage' + (getParameter('profile') ? '.' + getParameter('profile') : '');
161
127
  matterStorageService;
162
128
  matterStorageManager;
163
129
  matterbridgeContext;
164
130
  controllerContext;
165
- // Matter parameters
166
- mdnsInterface; // matter server node mdnsInterface: e.g. 'eth0' or 'wlan0' or 'WiFi'
167
- ipv4address; // matter server node listeningAddressIpv4
168
- ipv6address; // matter server node listeningAddressIpv6
169
- port; // first server node port
170
- passcode; // first server node passcode
171
- discriminator; // first server node discriminator
172
- certification; // device certification
131
+ mdnsInterface;
132
+ ipv4address;
133
+ ipv6address;
134
+ port;
135
+ passcode;
136
+ discriminator;
137
+ certification;
173
138
  serverNode;
174
139
  aggregatorNode;
175
140
  aggregatorVendorId = VendorId(getIntParameter('vendorId') ?? 0xfff1);
@@ -177,50 +142,21 @@ export class Matterbridge extends EventEmitter {
177
142
  aggregatorProductId = getIntParameter('productId') ?? 0x8000;
178
143
  aggregatorProductName = getParameter('productName') ?? 'Matterbridge aggregator';
179
144
  static instance;
180
- // We load asyncronously so is private
181
145
  constructor() {
182
146
  super();
183
147
  }
184
- /**
185
- * Emits an event of the specified type with the provided arguments.
186
- *
187
- * @template K - The type of the event.
188
- * @param {K} eventName - The name of the event to emit.
189
- * @param {...MatterbridgeEvent[K]} args - The arguments to pass to the event listeners.
190
- * @returns {boolean} - Returns true if the event had listeners, false otherwise.
191
- */
192
148
  emit(eventName, ...args) {
193
149
  return super.emit(eventName, ...args);
194
150
  }
195
- /**
196
- * Registers an event listener for the specified event type.
197
- *
198
- * @template K - The type of the event.
199
- * @param {K} eventName - The name of the event to listen for.
200
- * @param {(...args: MatterbridgeEvent[K]) => void} listener - The callback function to invoke when the event is emitted.
201
- * @returns {this} - Returns the instance of the Matterbridge class.
202
- */
203
151
  on(eventName, listener) {
204
152
  return super.on(eventName, listener);
205
153
  }
206
- /**
207
- * Retrieves the list of Matterbridge devices.
208
- * @returns {MatterbridgeEndpoint[]} An array of MatterbridgeDevice objects.
209
- */
210
154
  getDevices() {
211
155
  return this.devices.array();
212
156
  }
213
- /**
214
- * Retrieves the list of registered plugins.
215
- * @returns {RegisteredPlugin[]} An array of RegisteredPlugin objects.
216
- */
217
157
  getPlugins() {
218
158
  return this.plugins.array();
219
159
  }
220
- /**
221
- * Set the logger logLevel for the Matterbridge classes and call onChangeLoggerLevel() for each plugin.
222
- * @param {LogLevel} logLevel The logger logLevel to set.
223
- */
224
160
  async setLogLevel(logLevel) {
225
161
  if (this.log)
226
162
  this.log.logLevel = logLevel;
@@ -234,31 +170,19 @@ export class Matterbridge extends EventEmitter {
234
170
  for (const plugin of this.plugins) {
235
171
  if (!plugin.platform || !plugin.platform.log || !plugin.platform.config)
236
172
  continue;
237
- plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : this.log.logLevel;
238
- await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : this.log.logLevel);
239
- }
240
- // Set the global logger callback for the WebSocketServer to the common minimum logLevel
241
- let callbackLogLevel = "notice" /* LogLevel.NOTICE */;
242
- if (this.matterbridgeInformation.loggerLevel === "info" /* LogLevel.INFO */ || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.INFO)
243
- callbackLogLevel = "info" /* LogLevel.INFO */;
244
- if (this.matterbridgeInformation.loggerLevel === "debug" /* LogLevel.DEBUG */ || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.DEBUG)
245
- callbackLogLevel = "debug" /* LogLevel.DEBUG */;
173
+ plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" : this.log.logLevel;
174
+ await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" : this.log.logLevel);
175
+ }
176
+ let callbackLogLevel = "notice";
177
+ if (this.matterbridgeInformation.loggerLevel === "info" || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.INFO)
178
+ callbackLogLevel = "info";
179
+ if (this.matterbridgeInformation.loggerLevel === "debug" || this.matterbridgeInformation.matterLoggerLevel === MatterLogLevel.DEBUG)
180
+ callbackLogLevel = "debug";
246
181
  AnsiLogger.setGlobalCallback(this.frontend.wssSendMessage.bind(this.frontend), callbackLogLevel);
247
182
  this.log.debug(`WebSocketServer logger global callback set to ${callbackLogLevel}`);
248
183
  }
249
- /** ***********************************************************************************************************************************/
250
- /** loadInstance() and cleanup() methods */
251
- /** ***********************************************************************************************************************************/
252
- /**
253
- * Loads an instance of the Matterbridge class.
254
- * If an instance already exists, return that instance.
255
- *
256
- * @param {boolean} initialize - Whether to initialize the Matterbridge instance after loading. Defaults to false.
257
- * @returns The loaded Matterbridge instance.
258
- */
259
184
  static async loadInstance(initialize = false) {
260
185
  if (!Matterbridge.instance) {
261
- // eslint-disable-next-line no-console
262
186
  if (hasParameter('debug'))
263
187
  console.log(GREEN + 'Creating a new instance of Matterbridge.', initialize ? 'Initializing...' : 'Not initializing...', rs);
264
188
  Matterbridge.instance = new Matterbridge();
@@ -267,14 +191,8 @@ export class Matterbridge extends EventEmitter {
267
191
  }
268
192
  return Matterbridge.instance;
269
193
  }
270
- /**
271
- * Call cleanup() and dispose MdnsService.
272
- *
273
- * @deprecated This method is deprecated and is ONLY used for jest tests.
274
- */
275
194
  async destroyInstance() {
276
195
  this.log.info(`Destroy instance...`);
277
- // Save server nodes to close
278
196
  const servers = [];
279
197
  if (this.bridgeMode === 'bridge') {
280
198
  if (this.serverNode)
@@ -286,107 +204,74 @@ export class Matterbridge extends EventEmitter {
286
204
  servers.push(plugin.serverNode);
287
205
  }
288
206
  }
289
- // Let any already‐queued microtasks run first
290
207
  await Promise.resolve();
291
- // Cleanup
292
208
  await this.cleanup('destroying instance...', false);
293
- // Close servers mdns service
294
209
  this.log.info(`Dispose ${servers.length} MdnsService...`);
295
210
  for (const server of servers) {
296
211
  await server.env.get(MdnsService)[Symbol.asyncDispose]();
297
212
  this.log.info(`Closed ${server.id} MdnsService`);
298
213
  }
299
- // Let any already‐queued microtasks run first
300
214
  await Promise.resolve();
301
- // Wait for the cleanup to finish
302
215
  await new Promise((resolve) => {
303
216
  setTimeout(resolve, 500);
304
217
  });
305
218
  }
306
- /**
307
- * Initializes the Matterbridge application.
308
- *
309
- * @remarks
310
- * This method performs the necessary setup and initialization steps for the Matterbridge application.
311
- * It displays the help information if the 'help' parameter is provided, sets up the logger, checks the
312
- * node version, registers signal handlers, initializes storage, and parses the command line.
313
- *
314
- * @returns A Promise that resolves when the initialization is complete.
315
- */
316
219
  async initialize() {
317
- // Emit the initialize_started event
318
220
  this.emit('initialize_started');
319
- // Create the matterbridge logger
320
- this.log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: hasParameter('debug') ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */ });
321
- // Set the restart mode
221
+ this.log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4, logLevel: hasParameter('debug') ? "debug" : "info" });
322
222
  if (hasParameter('service'))
323
223
  this.restartMode = 'service';
324
224
  if (hasParameter('docker'))
325
225
  this.restartMode = 'docker';
326
- // Set the matterbridge home directory
327
226
  this.homeDirectory = getParameter('homedir') ?? os.homedir();
328
227
  this.matterbridgeInformation.homeDirectory = this.homeDirectory;
329
228
  await createDirectory(this.homeDirectory, 'Matterbridge Home Directory', this.log);
330
- // Set the matterbridge directory
331
229
  this.matterbridgeDirectory = path.join(this.homeDirectory, '.matterbridge');
332
230
  this.matterbridgeInformation.matterbridgeDirectory = this.matterbridgeDirectory;
333
231
  await createDirectory(this.matterbridgeDirectory, 'Matterbridge Directory', this.log);
334
232
  await createDirectory(path.join(this.matterbridgeDirectory, 'certs'), 'Matterbridge Frontend Certificate Directory', this.log);
335
233
  await createDirectory(path.join(this.matterbridgeDirectory, 'uploads'), 'Matterbridge Frontend Uploads Directory', this.log);
336
- // Set the matterbridge plugin directory
337
234
  this.matterbridgePluginDirectory = path.join(this.homeDirectory, 'Matterbridge');
338
235
  this.matterbridgeInformation.matterbridgePluginDirectory = this.matterbridgePluginDirectory;
339
236
  await createDirectory(this.matterbridgePluginDirectory, 'Matterbridge Plugin Directory', this.log);
340
- // Set the matterbridge cert directory
341
237
  this.matterbridgeCertDirectory = path.join(this.homeDirectory, '.mattercert');
342
238
  this.matterbridgeInformation.matterbridgeCertDirectory = this.matterbridgeCertDirectory;
343
239
  await createDirectory(this.matterbridgeCertDirectory, 'Matterbridge Matter Certificate Directory', this.log);
344
- // Set the matterbridge root directory
345
240
  const { fileURLToPath } = await import('node:url');
346
241
  const currentFileDirectory = path.dirname(fileURLToPath(import.meta.url));
347
242
  this.rootDirectory = path.resolve(currentFileDirectory, '../');
348
243
  this.matterbridgeInformation.rootDirectory = this.rootDirectory;
349
- // Setup the matter environment
350
244
  this.environment.vars.set('log.level', MatterLogLevel.INFO);
351
245
  this.environment.vars.set('log.format', MatterLogFormat.ANSI);
352
246
  this.environment.vars.set('path.root', path.join(this.matterbridgeDirectory, this.matterStorageName));
353
247
  this.environment.vars.set('runtime.signals', false);
354
248
  this.environment.vars.set('runtime.exitcode', false);
355
- // Register process handlers
356
249
  this.registerProcessHandlers();
357
- // Initialize nodeStorage and nodeContext
358
250
  try {
359
251
  this.log.debug(`Creating node storage manager: ${CYAN}${this.nodeStorageName}${db}`);
360
252
  this.nodeStorage = new NodeStorageManager({ dir: path.join(this.matterbridgeDirectory, this.nodeStorageName), writeQueue: false, expiredInterval: undefined, logging: false });
361
253
  this.log.debug('Creating node storage context for matterbridge');
362
254
  this.nodeContext = await this.nodeStorage.createStorage('matterbridge');
363
- // TODO: Remove this code when node-persist-manager is updated
364
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
365
255
  const keys = (await this.nodeStorage?.storage.keys());
366
256
  for (const key of keys) {
367
257
  this.log.debug(`Checking node storage manager key: ${CYAN}${key}${db}`);
368
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
369
258
  await this.nodeStorage?.storage.get(key);
370
259
  }
371
260
  const storages = await this.nodeStorage.getStorageNames();
372
261
  for (const storage of storages) {
373
262
  this.log.debug(`Checking storage: ${CYAN}${storage}${db}`);
374
263
  const nodeContext = await this.nodeStorage?.createStorage(storage);
375
- // TODO: Remove this code when node-persist-manager is updated
376
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
377
264
  const keys = (await nodeContext?.storage.keys());
378
265
  keys.forEach(async (key) => {
379
266
  this.log.debug(`Checking key: ${CYAN}${storage}:${key}${db}`);
380
267
  await nodeContext?.get(key);
381
268
  });
382
269
  }
383
- // Creating a backup of the node storage since it is not corrupted
384
270
  this.log.debug('Creating node storage backup...');
385
271
  await copyDirectory(path.join(this.matterbridgeDirectory, this.nodeStorageName), path.join(this.matterbridgeDirectory, this.nodeStorageName + '.backup'));
386
272
  this.log.debug('Created node storage backup');
387
273
  }
388
274
  catch (error) {
389
- // Restoring the backup of the node storage since it is corrupted
390
275
  this.log.error(`Error creating node storage manager and context: ${error instanceof Error ? error.message : error}`);
391
276
  if (hasParameter('norestore')) {
392
277
  this.log.fatal(`The matterbridge node storage is corrupted. Parameter -norestore found: exiting...`);
@@ -401,19 +286,14 @@ export class Matterbridge extends EventEmitter {
401
286
  this.log.fatal('Fatal error creating node storage manager and context for matterbridge');
402
287
  throw new Error('Fatal error creating node storage manager and context for matterbridge');
403
288
  }
404
- // Set the first port to use for the commissioning server (will be incremented in childbridge mode)
405
289
  this.port = getIntParameter('port') ?? (await this.nodeContext.get('matterport', 5540)) ?? 5540;
406
- // Set the first passcode to use for the commissioning server (will be incremented in childbridge mode)
407
290
  this.passcode = getIntParameter('passcode') ?? (await this.nodeContext.get('matterpasscode')) ?? PaseClient.generateRandomPasscode();
408
- // Set the first discriminator to use for the commissioning server (will be incremented in childbridge mode)
409
291
  this.discriminator = getIntParameter('discriminator') ?? (await this.nodeContext.get('matterdiscriminator')) ?? PaseClient.generateRandomDiscriminator();
410
- // Certificate management
411
292
  const pairingFilePath = path.join(this.matterbridgeCertDirectory, 'pairing.json');
412
293
  try {
413
294
  await fs.access(pairingFilePath, fs.constants.R_OK);
414
295
  const pairingFileContent = await fs.readFile(pairingFilePath, 'utf8');
415
296
  const pairingFileJson = JSON.parse(pairingFileContent);
416
- // Set the vendorId, vendorName, productId and productName if they are present in the pairing file
417
297
  if (isValidNumber(pairingFileJson.vendorId))
418
298
  this.aggregatorVendorId = VendorId(pairingFileJson.vendorId);
419
299
  if (isValidString(pairingFileJson.vendorName, 3))
@@ -422,20 +302,16 @@ export class Matterbridge extends EventEmitter {
422
302
  this.aggregatorProductId = VendorId(pairingFileJson.productId);
423
303
  if (isValidString(pairingFileJson.productName, 3))
424
304
  this.aggregatorProductName = pairingFileJson.productName;
425
- // Override the passcode and discriminator if they are present in the pairing file
426
305
  if (isValidNumber(pairingFileJson.passcode) && isValidNumber(pairingFileJson.discriminator)) {
427
306
  this.passcode = pairingFileJson.passcode;
428
307
  this.discriminator = pairingFileJson.discriminator;
429
308
  this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using passcode ${CYAN}${this.passcode}${nf} and discriminator ${CYAN}${this.discriminator}${nf} from pairing file.`);
430
309
  }
431
- // Set the certification if it is present in the pairing file
432
310
  if (pairingFileJson.privateKey && pairingFileJson.certificate && pairingFileJson.intermediateCertificate && pairingFileJson.declaration) {
433
311
  const hexStringToUint8Array = (hexString) => {
434
312
  const matches = hexString.match(/.{1,2}/g);
435
313
  return matches ? new Uint8Array(matches.map((byte) => parseInt(byte, 16))) : new Uint8Array();
436
314
  };
437
- // const hexString = Buffer.from('Test string', 'utf-8').toString('hex');
438
- // console.log(hexString, Buffer.from(hexStringToUint8Array(hexString)).toString('utf-8'));
439
315
  this.certification = {
440
316
  privateKey: hexStringToUint8Array(pairingFileJson.privateKey),
441
317
  certificate: hexStringToUint8Array(pairingFileJson.certificate),
@@ -448,44 +324,41 @@ export class Matterbridge extends EventEmitter {
448
324
  catch (error) {
449
325
  this.log.debug(`Pairing file ${CYAN}${pairingFilePath}${db} not found: ${error instanceof Error ? error.message : error}`);
450
326
  }
451
- // Store the passcode, discriminator and port in the node context
452
327
  await this.nodeContext.set('matterport', this.port);
453
328
  await this.nodeContext.set('matterpasscode', this.passcode);
454
329
  await this.nodeContext.set('matterdiscriminator', this.discriminator);
455
330
  this.log.debug(`Initializing server node for Matterbridge on port ${this.port} with passcode ${this.passcode} and discriminator ${this.discriminator}`);
456
- // Set matterbridge logger level (context: matterbridgeLogLevel)
457
331
  if (hasParameter('logger')) {
458
332
  const level = getParameter('logger');
459
333
  if (level === 'debug') {
460
- this.log.logLevel = "debug" /* LogLevel.DEBUG */;
334
+ this.log.logLevel = "debug";
461
335
  }
462
336
  else if (level === 'info') {
463
- this.log.logLevel = "info" /* LogLevel.INFO */;
337
+ this.log.logLevel = "info";
464
338
  }
465
339
  else if (level === 'notice') {
466
- this.log.logLevel = "notice" /* LogLevel.NOTICE */;
340
+ this.log.logLevel = "notice";
467
341
  }
468
342
  else if (level === 'warn') {
469
- this.log.logLevel = "warn" /* LogLevel.WARN */;
343
+ this.log.logLevel = "warn";
470
344
  }
471
345
  else if (level === 'error') {
472
- this.log.logLevel = "error" /* LogLevel.ERROR */;
346
+ this.log.logLevel = "error";
473
347
  }
474
348
  else if (level === 'fatal') {
475
- this.log.logLevel = "fatal" /* LogLevel.FATAL */;
349
+ this.log.logLevel = "fatal";
476
350
  }
477
351
  else {
478
352
  this.log.warn(`Invalid matterbridge logger level: ${level}. Using default level "info".`);
479
- this.log.logLevel = "info" /* LogLevel.INFO */;
353
+ this.log.logLevel = "info";
480
354
  }
481
355
  }
482
356
  else {
483
- this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.matterbridgeInformation.shellyBoard ? "notice" /* LogLevel.NOTICE */ : "info" /* LogLevel.INFO */);
357
+ this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.matterbridgeInformation.shellyBoard ? "notice" : "info");
484
358
  }
485
359
  this.frontend.logLevel = this.log.logLevel;
486
360
  MatterbridgeEndpoint.logLevel = this.log.logLevel;
487
361
  this.matterbridgeInformation.loggerLevel = this.log.logLevel;
488
- // Create the file logger for matterbridge (context: matterbridgeFileLog)
489
362
  if (hasParameter('filelogger') || (await this.nodeContext.get('matterbridgeFileLog', false))) {
490
363
  AnsiLogger.setGlobalLogfile(path.join(this.matterbridgeDirectory, this.matterbrideLoggerFile), this.log.logLevel, true);
491
364
  this.matterbridgeInformation.fileLogger = true;
@@ -494,7 +367,6 @@ export class Matterbridge extends EventEmitter {
494
367
  this.log.debug(`Matterbridge logLevel: ${this.log.logLevel} fileLoger: ${this.matterbridgeInformation.fileLogger}.`);
495
368
  if (this.profile !== undefined)
496
369
  this.log.debug(`Matterbridge profile: ${this.profile}.`);
497
- // Set matter.js logger level, format and logger (context: matterLogLevel)
498
370
  if (hasParameter('matterlogger')) {
499
371
  const level = getParameter('matterlogger');
500
372
  if (level === 'debug') {
@@ -526,7 +398,6 @@ export class Matterbridge extends EventEmitter {
526
398
  Logger.format = MatterLogFormat.ANSI;
527
399
  Logger.setLogger('default', this.createMatterLogger());
528
400
  this.matterbridgeInformation.matterLoggerLevel = Logger.defaultLogLevel;
529
- // Create the file logger for matter.js (context: matterFileLog)
530
401
  if (hasParameter('matterfilelogger') || (await this.nodeContext.get('matterFileLog', false))) {
531
402
  this.matterbridgeInformation.matterFileLogger = true;
532
403
  Logger.addLogger('matterfilelogger', await this.createMatterFileLogger(path.join(this.matterbridgeDirectory, this.matterLoggerFile), true), {
@@ -535,7 +406,6 @@ export class Matterbridge extends EventEmitter {
535
406
  });
536
407
  }
537
408
  this.log.debug(`Matter logLevel: ${Logger.defaultLogLevel} fileLoger: ${this.matterbridgeInformation.matterFileLogger}.`);
538
- // Log network interfaces
539
409
  const networkInterfaces = os.networkInterfaces();
540
410
  const availableAddresses = Object.entries(networkInterfaces);
541
411
  const availableInterfaces = Object.keys(networkInterfaces);
@@ -547,7 +417,6 @@ export class Matterbridge extends EventEmitter {
547
417
  });
548
418
  }
549
419
  }
550
- // Set the interface to use for matter server node mdnsInterface
551
420
  if (hasParameter('mdnsinterface')) {
552
421
  this.mdnsInterface = getParameter('mdnsinterface');
553
422
  }
@@ -556,7 +425,6 @@ export class Matterbridge extends EventEmitter {
556
425
  if (this.mdnsInterface === '')
557
426
  this.mdnsInterface = undefined;
558
427
  }
559
- // Validate mdnsInterface
560
428
  if (this.mdnsInterface) {
561
429
  if (!availableInterfaces.includes(this.mdnsInterface)) {
562
430
  this.log.error(`Invalid mdnsInterface: ${this.mdnsInterface}. Available interfaces are: ${availableInterfaces.join(', ')}. Using all available interfaces.`);
@@ -569,7 +437,6 @@ export class Matterbridge extends EventEmitter {
569
437
  }
570
438
  if (this.mdnsInterface)
571
439
  this.environment.vars.set('mdns.networkInterface', this.mdnsInterface);
572
- // Set the listeningAddressIpv4 for the matter commissioning server
573
440
  if (hasParameter('ipv4address')) {
574
441
  this.ipv4address = getParameter('ipv4address');
575
442
  }
@@ -578,7 +445,6 @@ export class Matterbridge extends EventEmitter {
578
445
  if (this.ipv4address === '')
579
446
  this.ipv4address = undefined;
580
447
  }
581
- // Validate ipv4address
582
448
  if (this.ipv4address) {
583
449
  let isValid = false;
584
450
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -594,7 +460,6 @@ export class Matterbridge extends EventEmitter {
594
460
  await this.nodeContext.remove('matteripv4address');
595
461
  }
596
462
  }
597
- // Set the listeningAddressIpv6 for the matter commissioning server
598
463
  if (hasParameter('ipv6address')) {
599
464
  this.ipv6address = getParameter('ipv6address');
600
465
  }
@@ -603,7 +468,6 @@ export class Matterbridge extends EventEmitter {
603
468
  if (this.ipv6address === '')
604
469
  this.ipv6address = undefined;
605
470
  }
606
- // Validate ipv6address
607
471
  if (this.ipv6address) {
608
472
  let isValid = false;
609
473
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -624,7 +488,6 @@ export class Matterbridge extends EventEmitter {
624
488
  await this.nodeContext.remove('matteripv6address');
625
489
  }
626
490
  }
627
- // Initialize the virtual mode
628
491
  if (hasParameter('novirtual')) {
629
492
  this.matterbridgeInformation.virtualMode = 'disabled';
630
493
  await this.nodeContext.set('virtualmode', 'disabled');
@@ -633,19 +496,14 @@ export class Matterbridge extends EventEmitter {
633
496
  this.matterbridgeInformation.virtualMode = (await this.nodeContext.get('virtualmode', 'outlet'));
634
497
  }
635
498
  this.log.debug(`Virtual mode ${this.matterbridgeInformation.virtualMode}.`);
636
- // Initialize PluginManager
637
499
  this.plugins = new PluginManager(this);
638
500
  await this.plugins.loadFromStorage();
639
501
  this.plugins.logLevel = this.log.logLevel;
640
- // Initialize DeviceManager
641
502
  this.devices = new DeviceManager(this, this.nodeContext);
642
503
  this.devices.logLevel = this.log.logLevel;
643
- // Get the plugins from node storage and create the plugins node storage contexts
644
504
  for (const plugin of this.plugins) {
645
505
  const packageJson = await this.plugins.parse(plugin);
646
506
  if (packageJson === null && !hasParameter('add') && !hasParameter('remove') && !hasParameter('enable') && !hasParameter('disable') && !hasParameter('reset') && !hasParameter('factoryreset')) {
647
- // Try to reinstall the plugin from npm (for Docker pull and external plugins)
648
- // We don't do this when the add and other parameters are set because we shut down the process after adding the plugin
649
507
  this.log.info(`Error parsing plugin ${plg}${plugin.name}${nf}. Trying to reinstall it from npm.`);
650
508
  try {
651
509
  await spawn.spawnCommand(this, 'npm', ['install', '-g', plugin.name, '--omit=dev', '--verbose']);
@@ -667,7 +525,6 @@ export class Matterbridge extends EventEmitter {
667
525
  await plugin.nodeContext.set('description', plugin.description);
668
526
  await plugin.nodeContext.set('author', plugin.author);
669
527
  }
670
- // Log system info and create .matterbridge directory
671
528
  await this.logNodeAndSystemInfo();
672
529
  this.log.notice(`Matterbridge version ${this.matterbridgeVersion} ` +
673
530
  `${hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge') ? 'mode bridge ' : ''}` +
@@ -675,7 +532,6 @@ export class Matterbridge extends EventEmitter {
675
532
  `${hasParameter('controller') ? 'mode controller ' : ''}` +
676
533
  `${this.restartMode !== '' ? 'restart mode ' + this.restartMode + ' ' : ''}` +
677
534
  `running on ${this.systemInformation.osType} (v.${this.systemInformation.osRelease}) platform ${this.systemInformation.osPlatform} arch ${this.systemInformation.osArch}`);
678
- // Check node version and throw error
679
535
  const minNodeVersion = 18;
680
536
  const nodeVersion = process.versions.node;
681
537
  const versionMajor = parseInt(nodeVersion.split('.')[0]);
@@ -683,17 +539,10 @@ export class Matterbridge extends EventEmitter {
683
539
  this.log.error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
684
540
  throw new Error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
685
541
  }
686
- // Parse command line
687
542
  await this.parseCommandLine();
688
- // Emit the initialize_completed event
689
543
  this.emit('initialize_completed');
690
544
  this.initialized = true;
691
545
  }
692
- /**
693
- * Parses the command line arguments and performs the corresponding actions.
694
- * @private
695
- * @returns {Promise<void>} A promise that resolves when the command line arguments have been processed, or the process exits.
696
- */
697
546
  async parseCommandLine() {
698
547
  if (hasParameter('help')) {
699
548
  this.log.info(`\nUsage: matterbridge [options]\n
@@ -815,7 +664,6 @@ export class Matterbridge extends EventEmitter {
815
664
  this.shutdown = true;
816
665
  return;
817
666
  }
818
- // Start the matter storage and create the matterbridge context
819
667
  try {
820
668
  await this.startMatterStorage();
821
669
  }
@@ -823,14 +671,12 @@ export class Matterbridge extends EventEmitter {
823
671
  this.log.fatal(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
824
672
  throw new Error(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
825
673
  }
826
- // Clear the matterbridge context if the reset parameter is set
827
674
  if (hasParameter('reset') && getParameter('reset') === undefined) {
828
675
  this.initialized = true;
829
676
  await this.shutdownProcessAndReset();
830
677
  this.shutdown = true;
831
678
  return;
832
679
  }
833
- // Clear matterbridge plugin context if the reset parameter is set
834
680
  if (hasParameter('reset') && getParameter('reset') !== undefined) {
835
681
  this.log.debug(`Reset plugin ${getParameter('reset')}`);
836
682
  const plugin = this.plugins.get(getParameter('reset'));
@@ -855,37 +701,30 @@ export class Matterbridge extends EventEmitter {
855
701
  this.shutdown = true;
856
702
  return;
857
703
  }
858
- // Initialize frontend
859
704
  if (getIntParameter('frontend') !== 0 || getIntParameter('frontend') === undefined)
860
705
  await this.frontend.start(getIntParameter('frontend'));
861
- // Check in 30 seconds the latest and dev versions of matterbridge and the plugins
862
706
  this.checkUpdateTimeout = setTimeout(async () => {
863
707
  const { checkUpdates } = await import('./update.js');
864
708
  checkUpdates(this);
865
709
  }, 30 * 1000).unref();
866
- // Check each 12 hours the latest and dev versions of matterbridge and the plugins
867
710
  this.checkUpdateInterval = setInterval(async () => {
868
711
  const { checkUpdates } = await import('./update.js');
869
712
  checkUpdates(this);
870
713
  }, 12 * 60 * 60 * 1000).unref();
871
- // Start the matterbridge in mode test
872
714
  if (hasParameter('test')) {
873
715
  this.bridgeMode = 'bridge';
874
716
  MatterbridgeEndpoint.bridgeMode = 'bridge';
875
717
  return;
876
718
  }
877
- // Start the matterbridge in mode controller
878
719
  if (hasParameter('controller')) {
879
720
  this.bridgeMode = 'controller';
880
721
  await this.startController();
881
722
  return;
882
723
  }
883
- // Check if the bridge mode is set and start matterbridge in bridge mode if not set
884
724
  if (!hasParameter('bridge') && !hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === '') {
885
725
  this.log.info('Setting default matterbridge start mode to bridge');
886
726
  await this.nodeContext?.set('bridgeMode', 'bridge');
887
727
  }
888
- // Start matterbridge in bridge mode
889
728
  if (hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge')) {
890
729
  this.bridgeMode = 'bridge';
891
730
  MatterbridgeEndpoint.bridgeMode = 'bridge';
@@ -893,7 +732,6 @@ export class Matterbridge extends EventEmitter {
893
732
  await this.startBridge();
894
733
  return;
895
734
  }
896
- // Start matterbridge in childbridge mode
897
735
  if (hasParameter('childbridge') || (!hasParameter('bridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'childbridge')) {
898
736
  this.bridgeMode = 'childbridge';
899
737
  MatterbridgeEndpoint.bridgeMode = 'childbridge';
@@ -902,20 +740,10 @@ export class Matterbridge extends EventEmitter {
902
740
  return;
903
741
  }
904
742
  }
905
- /**
906
- * Asynchronously loads and starts the registered plugins.
907
- *
908
- * This method is responsible for initializing and starting all enabled plugins.
909
- * It ensures that each plugin is properly loaded and started before the bridge starts.
910
- *
911
- * @returns {Promise<void>} A promise that resolves when all plugins have been loaded and started.
912
- */
913
743
  async startPlugins() {
914
- // Check, load and start the plugins
915
744
  for (const plugin of this.plugins) {
916
745
  plugin.configJson = await this.plugins.loadConfig(plugin);
917
746
  plugin.schemaJson = await this.plugins.loadSchema(plugin);
918
- // Check if the plugin is available
919
747
  if (!(await this.plugins.resolve(plugin.path))) {
920
748
  this.log.error(`Plugin ${plg}${plugin.name}${er} not found or not validated. Disabling it.`);
921
749
  plugin.enabled = false;
@@ -935,14 +763,10 @@ export class Matterbridge extends EventEmitter {
935
763
  plugin.addedDevices = undefined;
936
764
  plugin.qrPairingCode = undefined;
937
765
  plugin.manualPairingCode = undefined;
938
- this.plugins.load(plugin, true, 'Matterbridge is starting'); // No await do it asyncronously
766
+ this.plugins.load(plugin, true, 'Matterbridge is starting');
939
767
  }
940
768
  this.frontend.wssSendRefreshRequired('plugins');
941
769
  }
942
- /**
943
- * Registers the process handlers for uncaughtException, unhandledRejection, SIGINT and SIGTERM.
944
- * When either of these signals are received, the cleanup method is called with an appropriate message.
945
- */
946
770
  registerProcessHandlers() {
947
771
  this.log.debug(`Registering uncaughtException and unhandledRejection handlers...`);
948
772
  process.removeAllListeners('uncaughtException');
@@ -969,9 +793,6 @@ export class Matterbridge extends EventEmitter {
969
793
  };
970
794
  process.on('SIGTERM', this.sigtermHandler);
971
795
  }
972
- /**
973
- * Deregisters the process uncaughtException, unhandledRejection, SIGINT and SIGTERM signal handlers.
974
- */
975
796
  deregisterProcessHandlers() {
976
797
  this.log.debug(`Deregistering uncaughtException and unhandledRejection handlers...`);
977
798
  if (this.exceptionHandler)
@@ -988,17 +809,12 @@ export class Matterbridge extends EventEmitter {
988
809
  process.off('SIGTERM', this.sigtermHandler);
989
810
  this.sigtermHandler = undefined;
990
811
  }
991
- /**
992
- * Logs the node and system information.
993
- */
994
812
  async logNodeAndSystemInfo() {
995
- // IP address information
996
813
  const networkInterfaces = os.networkInterfaces();
997
814
  this.systemInformation.interfaceName = '';
998
815
  this.systemInformation.ipv4Address = '';
999
816
  this.systemInformation.ipv6Address = '';
1000
817
  for (const [interfaceName, interfaceDetails] of Object.entries(networkInterfaces)) {
1001
- // this.log.debug(`Checking interface: '${interfaceName}' for '${this.mdnsInterface}'`);
1002
818
  if (this.mdnsInterface && interfaceName !== this.mdnsInterface)
1003
819
  continue;
1004
820
  if (!interfaceDetails) {
@@ -1024,22 +840,19 @@ export class Matterbridge extends EventEmitter {
1024
840
  break;
1025
841
  }
1026
842
  }
1027
- // Node information
1028
843
  this.systemInformation.nodeVersion = process.versions.node;
1029
844
  const versionMajor = parseInt(this.systemInformation.nodeVersion.split('.')[0]);
1030
845
  const versionMinor = parseInt(this.systemInformation.nodeVersion.split('.')[1]);
1031
846
  const versionPatch = parseInt(this.systemInformation.nodeVersion.split('.')[2]);
1032
- // Host system information
1033
847
  this.systemInformation.hostname = os.hostname();
1034
848
  this.systemInformation.user = os.userInfo().username;
1035
- this.systemInformation.osType = os.type(); // "Windows_NT", "Darwin", etc.
1036
- this.systemInformation.osRelease = os.release(); // Kernel version
1037
- this.systemInformation.osPlatform = os.platform(); // "win32", "linux", "darwin", etc.
1038
- this.systemInformation.osArch = os.arch(); // "x64", "arm", etc.
1039
- this.systemInformation.totalMemory = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) + ' GB'; // Convert to GB
1040
- this.systemInformation.freeMemory = (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB'; // Convert to GB
1041
- this.systemInformation.systemUptime = (os.uptime() / 60 / 60).toFixed(2) + ' hours'; // Convert to hours
1042
- // Log the system information
849
+ this.systemInformation.osType = os.type();
850
+ this.systemInformation.osRelease = os.release();
851
+ this.systemInformation.osPlatform = os.platform();
852
+ this.systemInformation.osArch = os.arch();
853
+ this.systemInformation.totalMemory = (os.totalmem() / 1024 / 1024 / 1024).toFixed(2) + ' GB';
854
+ this.systemInformation.freeMemory = (os.freemem() / 1024 / 1024 / 1024).toFixed(2) + ' GB';
855
+ this.systemInformation.systemUptime = (os.uptime() / 60 / 60).toFixed(2) + ' hours';
1043
856
  this.log.debug('Host System Information:');
1044
857
  this.log.debug(`- Hostname: ${this.systemInformation.hostname}`);
1045
858
  this.log.debug(`- User: ${this.systemInformation.user}`);
@@ -1055,17 +868,14 @@ export class Matterbridge extends EventEmitter {
1055
868
  this.log.debug(`- Total Memory: ${this.systemInformation.totalMemory}`);
1056
869
  this.log.debug(`- Free Memory: ${this.systemInformation.freeMemory}`);
1057
870
  this.log.debug(`- System Uptime: ${this.systemInformation.systemUptime}`);
1058
- // Log directories
1059
871
  this.log.debug(`Root Directory: ${this.rootDirectory}`);
1060
872
  this.log.debug(`Home Directory: ${this.homeDirectory}`);
1061
873
  this.log.debug(`Matterbridge Directory: ${this.matterbridgeDirectory}`);
1062
874
  this.log.debug(`Matterbridge Plugin Directory: ${this.matterbridgePluginDirectory}`);
1063
875
  this.log.debug(`Matterbridge Matter Certificate Directory: ${this.matterbridgeCertDirectory}`);
1064
- // Global node_modules directory
1065
876
  if (this.nodeContext)
1066
877
  this.globalModulesDirectory = this.matterbridgeInformation.globalModulesDirectory = await this.nodeContext.get('globalModulesDirectory', '');
1067
878
  if (this.globalModulesDirectory === '') {
1068
- // First run of Matterbridge so the node storage is empty
1069
879
  try {
1070
880
  this.execRunningCount++;
1071
881
  this.matterbridgeInformation.globalModulesDirectory = this.globalModulesDirectory = await getGlobalNodeModules();
@@ -1079,84 +889,53 @@ export class Matterbridge extends EventEmitter {
1079
889
  }
1080
890
  else
1081
891
  this.log.debug(`Global node_modules Directory: ${this.globalModulesDirectory}`);
1082
- /* removed cause is too expensive for the shelly board and not really needed. Why should the globalModulesDirectory change?
1083
- else {
1084
- this.getGlobalNodeModules()
1085
- .then(async (globalModulesDirectory) => {
1086
- this.globalModulesDirectory = globalModulesDirectory;
1087
- this.matterbridgeInformation.globalModulesDirectory = this.globalModulesDirectory;
1088
- this.log.debug(`Global node_modules Directory: ${this.globalModulesDirectory}`);
1089
- await this.nodeContext?.set<string>('globalModulesDirectory', this.globalModulesDirectory);
1090
- })
1091
- .catch((error) => {
1092
- this.log.error(`Error getting global node_modules directory: ${error}`);
1093
- });
1094
- }*/
1095
- // Matterbridge version
1096
892
  const packageJson = JSON.parse(await fs.readFile(path.join(this.rootDirectory, 'package.json'), 'utf-8'));
1097
893
  this.matterbridgeVersion = this.matterbridgeLatestVersion = this.matterbridgeDevVersion = packageJson.version;
1098
894
  this.matterbridgeInformation.matterbridgeVersion = this.matterbridgeInformation.matterbridgeLatestVersion = this.matterbridgeInformation.matterbridgeDevVersion = packageJson.version;
1099
895
  this.log.debug(`Matterbridge Version: ${this.matterbridgeVersion}`);
1100
- // Matterbridge latest version (will be set in the checkUpdate function)
1101
896
  if (this.nodeContext)
1102
897
  this.matterbridgeLatestVersion = this.matterbridgeInformation.matterbridgeLatestVersion = await this.nodeContext.get('matterbridgeLatestVersion', this.matterbridgeVersion);
1103
898
  this.log.debug(`Matterbridge Latest Version: ${this.matterbridgeLatestVersion}`);
1104
- // Matterbridge dev version (will be set in the checkUpdate function)
1105
899
  if (this.nodeContext)
1106
900
  this.matterbridgeDevVersion = this.matterbridgeInformation.matterbridgeDevVersion = await this.nodeContext.get('matterbridgeDevVersion', this.matterbridgeVersion);
1107
901
  this.log.debug(`Matterbridge Dev Version: ${this.matterbridgeDevVersion}`);
1108
- // Current working directory
1109
902
  const currentDir = process.cwd();
1110
903
  this.log.debug(`Current Working Directory: ${currentDir}`);
1111
- // Command line arguments (excluding 'node' and the script name)
1112
904
  const cmdArgs = process.argv.slice(2).join(' ');
1113
905
  this.log.debug(`Command Line Arguments: ${cmdArgs}`);
1114
906
  }
1115
- /**
1116
- * Creates a MatterLogger function to show the matter.js log messages in AnsiLogger (for the frontend).
1117
- *
1118
- * @returns {Function} The MatterLogger function.
1119
- */
1120
907
  createMatterLogger() {
1121
- const matterLogger = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: "debug" /* LogLevel.DEBUG */ });
908
+ const matterLogger = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4, logLevel: "debug" });
1122
909
  return (level, formattedLog) => {
1123
910
  const logger = formattedLog.slice(44, 44 + 20).trim();
1124
911
  const message = formattedLog.slice(65);
1125
912
  matterLogger.logName = logger;
1126
913
  switch (level) {
1127
914
  case MatterLogLevel.DEBUG:
1128
- matterLogger.log("debug" /* LogLevel.DEBUG */, message);
915
+ matterLogger.log("debug", message);
1129
916
  break;
1130
917
  case MatterLogLevel.INFO:
1131
- matterLogger.log("info" /* LogLevel.INFO */, message);
918
+ matterLogger.log("info", message);
1132
919
  break;
1133
920
  case MatterLogLevel.NOTICE:
1134
- matterLogger.log("notice" /* LogLevel.NOTICE */, message);
921
+ matterLogger.log("notice", message);
1135
922
  break;
1136
923
  case MatterLogLevel.WARN:
1137
- matterLogger.log("warn" /* LogLevel.WARN */, message);
924
+ matterLogger.log("warn", message);
1138
925
  break;
1139
926
  case MatterLogLevel.ERROR:
1140
- matterLogger.log("error" /* LogLevel.ERROR */, message);
927
+ matterLogger.log("error", message);
1141
928
  break;
1142
929
  case MatterLogLevel.FATAL:
1143
- matterLogger.log("fatal" /* LogLevel.FATAL */, message);
930
+ matterLogger.log("fatal", message);
1144
931
  break;
1145
932
  default:
1146
- matterLogger.log("debug" /* LogLevel.DEBUG */, message);
933
+ matterLogger.log("debug", message);
1147
934
  break;
1148
935
  }
1149
936
  };
1150
937
  }
1151
- /**
1152
- * Creates a Matter File Logger.
1153
- *
1154
- * @param {string} filePath - The path to the log file.
1155
- * @param {boolean} [unlink=false] - Whether to unlink the log file before creating a new one.
1156
- * @returns {Function} - A function that logs formatted messages to the log file.
1157
- */
1158
938
  async createMatterFileLogger(filePath, unlink = false) {
1159
- // 2024-08-21 08:55:19.488 DEBUG InteractionMessenger Sending DataReport chunk with 28 attributes and 0 events: 1004 bytes
1160
939
  let fileSize = 0;
1161
940
  if (unlink) {
1162
941
  try {
@@ -1205,21 +984,12 @@ export class Matterbridge extends EventEmitter {
1205
984
  }
1206
985
  };
1207
986
  }
1208
- /**
1209
- * Restarts the process by exiting the current instance and loading a new instance.
1210
- */
1211
987
  async restartProcess() {
1212
988
  await this.cleanup('restarting...', true);
1213
989
  }
1214
- /**
1215
- * Shut down the process by exiting the current process.
1216
- */
1217
990
  async shutdownProcess() {
1218
991
  await this.cleanup('shutting down...', false);
1219
992
  }
1220
- /**
1221
- * Update matterbridge and and shut down the process.
1222
- */
1223
993
  async updateProcess() {
1224
994
  this.log.info('Updating matterbridge...');
1225
995
  try {
@@ -1232,73 +1002,52 @@ export class Matterbridge extends EventEmitter {
1232
1002
  this.frontend.wssSendRestartRequired();
1233
1003
  await this.cleanup('updating...', false);
1234
1004
  }
1235
- /**
1236
- * Unregister all devices and shut down the process.
1237
- */
1238
1005
  async unregisterAndShutdownProcess() {
1239
1006
  this.log.info('Unregistering all devices and shutting down...');
1240
1007
  for (const plugin of this.plugins) {
1241
1008
  await this.removeAllBridgedEndpoints(plugin.name, 250);
1242
1009
  }
1243
1010
  this.log.debug('Waiting for the MessageExchange to finish...');
1244
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second for MessageExchange to finish
1011
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1245
1012
  this.log.debug('Cleaning up and shutting down...');
1246
1013
  await this.cleanup('unregistered all devices and shutting down...', false);
1247
1014
  }
1248
- /**
1249
- * Reset commissioning and shut down the process.
1250
- */
1251
1015
  async shutdownProcessAndReset() {
1252
1016
  await this.cleanup('shutting down with reset...', false);
1253
1017
  }
1254
- /**
1255
- * Factory reset and shut down the process.
1256
- */
1257
1018
  async shutdownProcessAndFactoryReset() {
1258
1019
  await this.cleanup('shutting down with factory reset...', false);
1259
1020
  }
1260
- /**
1261
- * Cleans up the Matterbridge instance.
1262
- * @param {string} message - The cleanup message.
1263
- * @param {boolean} [restart=false] - Indicates whether to restart the instance after cleanup. Default is `false`.
1264
- * @returns A promise that resolves when the cleanup is completed.
1265
- */
1266
1021
  async cleanup(message, restart = false) {
1267
1022
  if (this.initialized && !this.hasCleanupStarted) {
1268
1023
  this.emit('cleanup_started');
1269
1024
  this.hasCleanupStarted = true;
1270
1025
  this.log.info(message);
1271
- // Clear the start matter interval
1272
1026
  if (this.startMatterInterval) {
1273
1027
  clearInterval(this.startMatterInterval);
1274
1028
  this.startMatterInterval = undefined;
1275
1029
  this.log.debug('Start matter interval cleared');
1276
1030
  }
1277
- // Clear the check update timeout
1278
1031
  if (this.checkUpdateTimeout) {
1279
1032
  clearInterval(this.checkUpdateTimeout);
1280
1033
  this.checkUpdateTimeout = undefined;
1281
1034
  this.log.debug('Check update timeout cleared');
1282
1035
  }
1283
- // Clear the check update interval
1284
1036
  if (this.checkUpdateInterval) {
1285
1037
  clearInterval(this.checkUpdateInterval);
1286
1038
  this.checkUpdateInterval = undefined;
1287
1039
  this.log.debug('Check update interval cleared');
1288
1040
  }
1289
- // Clear the configure timeout
1290
1041
  if (this.configureTimeout) {
1291
1042
  clearTimeout(this.configureTimeout);
1292
1043
  this.configureTimeout = undefined;
1293
1044
  this.log.debug('Matterbridge configure timeout cleared');
1294
1045
  }
1295
- // Clear the reachability timeout
1296
1046
  if (this.reachabilityTimeout) {
1297
1047
  clearTimeout(this.reachabilityTimeout);
1298
1048
  this.reachabilityTimeout = undefined;
1299
1049
  this.log.debug('Matterbridge reachability timeout cleared');
1300
1050
  }
1301
- // Calling the shutdown method of each plugin and clear the plugins reachability timeout
1302
1051
  for (const plugin of this.plugins) {
1303
1052
  if (!plugin.enabled || plugin.error)
1304
1053
  continue;
@@ -1309,10 +1058,9 @@ export class Matterbridge extends EventEmitter {
1309
1058
  this.log.debug(`Plugin ${plg}${plugin.name}${db} reachability timeout cleared`);
1310
1059
  }
1311
1060
  }
1312
- // Stop matter server nodes
1313
1061
  this.log.notice(`Stopping matter server nodes in ${this.bridgeMode} mode...`);
1314
1062
  this.log.debug('Waiting for the MessageExchange to finish...');
1315
- await new Promise((resolve) => setTimeout(resolve, 1000)); // Wait 1 second for MessageExchange to finish
1063
+ await new Promise((resolve) => setTimeout(resolve, 1000));
1316
1064
  if (this.bridgeMode === 'bridge') {
1317
1065
  if (this.serverNode) {
1318
1066
  await this.stopServerNode(this.serverNode);
@@ -1328,7 +1076,6 @@ export class Matterbridge extends EventEmitter {
1328
1076
  }
1329
1077
  }
1330
1078
  this.log.notice('Stopped matter server nodes');
1331
- // Matter commisioning reset
1332
1079
  if (message === 'shutting down with reset...') {
1333
1080
  this.log.info('Resetting Matterbridge commissioning information...');
1334
1081
  await this.matterStorageManager?.createContext('events')?.clearAll();
@@ -1338,36 +1085,18 @@ export class Matterbridge extends EventEmitter {
1338
1085
  await this.matterbridgeContext?.clearAll();
1339
1086
  this.log.info('Matter storage reset done! Remove the bridge from the controller.');
1340
1087
  }
1341
- // Stop matter storage
1342
1088
  await this.stopMatterStorage();
1343
- // Stop the frontend
1344
1089
  await this.frontend.stop();
1345
- // Remove the matterfilelogger
1346
1090
  try {
1347
1091
  Logger.removeLogger('matterfilelogger');
1348
1092
  }
1349
1093
  catch (error) {
1350
1094
  this.log.debug(`Error removing the matterfilelogger for file ${CYAN}${path.join(this.matterbridgeDirectory, this.matterLoggerFile)}${db}: ${error instanceof Error ? error.message : String(error)}`);
1351
1095
  }
1352
- // Close the matterbridge node storage and context
1353
1096
  if (this.nodeStorage && this.nodeContext) {
1354
- /*
1355
- TODO: Implement serialization of registered devices in edge mode
1356
- this.log.info('Saving registered devices...');
1357
- const serializedRegisteredDevices: SerializedMatterbridgeEndpoint[] = [];
1358
- this.devices.forEach(async (device) => {
1359
- const serializedMatterbridgeDevice = MatterbridgeEndpoint.serialize(device);
1360
- // this.log.info(`- ${serializedMatterbridgeDevice.deviceName}${rs}\n`, serializedMatterbridgeDevice);
1361
- if (serializedMatterbridgeDevice) serializedRegisteredDevices.push(serializedMatterbridgeDevice);
1362
- });
1363
- await this.nodeContext.set<SerializedMatterbridgeEndpoint[]>('devices', serializedRegisteredDevices);
1364
- this.log.info(`Saved registered devices (${serializedRegisteredDevices?.length})`);
1365
- */
1366
- // Clear nodeContext and nodeStorage (they just need 1000ms to write the data to disk)
1367
1097
  this.log.debug(`Closing node storage context for ${plg}Matterbridge${db}...`);
1368
1098
  await this.nodeContext.close();
1369
1099
  this.nodeContext = undefined;
1370
- // Clear nodeContext for each plugin (they just need 1000ms to write the data to disk)
1371
1100
  for (const plugin of this.plugins) {
1372
1101
  if (plugin.nodeContext) {
1373
1102
  this.log.debug(`Closing node storage context for plugin ${plg}${plugin.name}${db}...`);
@@ -1384,10 +1113,8 @@ export class Matterbridge extends EventEmitter {
1384
1113
  }
1385
1114
  this.plugins.clear();
1386
1115
  this.devices.clear();
1387
- // Factory reset
1388
1116
  if (message === 'shutting down with factory reset...') {
1389
1117
  try {
1390
- // Delete matter storage directory with its subdirectories and backup
1391
1118
  const dir = path.join(this.matterbridgeDirectory, this.matterStorageName);
1392
1119
  this.log.info(`Removing matter storage directory: ${dir}`);
1393
1120
  await fs.rm(dir, { recursive: true });
@@ -1401,7 +1128,6 @@ export class Matterbridge extends EventEmitter {
1401
1128
  }
1402
1129
  }
1403
1130
  try {
1404
- // Delete matterbridge storage directory with its subdirectories and backup
1405
1131
  const dir = path.join(this.matterbridgeDirectory, this.nodeStorageName);
1406
1132
  this.log.info(`Removing matterbridge storage directory: ${dir}`);
1407
1133
  await fs.rm(dir, { recursive: true });
@@ -1416,13 +1142,12 @@ export class Matterbridge extends EventEmitter {
1416
1142
  }
1417
1143
  this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
1418
1144
  }
1419
- // Deregisters the process handlers
1420
1145
  this.deregisterProcessHandlers();
1421
1146
  if (restart) {
1422
1147
  if (message === 'updating...') {
1423
1148
  this.log.info('Cleanup completed. Updating...');
1424
1149
  Matterbridge.instance = undefined;
1425
- this.emit('update'); // Restart the process but the update has been done before. TODO move all updates to the cli
1150
+ this.emit('update');
1426
1151
  }
1427
1152
  else if (message === 'restarting...') {
1428
1153
  this.log.info('Cleanup completed. Restarting...');
@@ -1443,14 +1168,6 @@ export class Matterbridge extends EventEmitter {
1443
1168
  this.log.debug('Cleanup already started...');
1444
1169
  }
1445
1170
  }
1446
- /**
1447
- * Creates and configures the server node for an accessory plugin for a given device.
1448
- *
1449
- * @param {RegisteredPlugin} plugin - The plugin to configure.
1450
- * @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
1451
- * @param {boolean} [start=false] - Whether to start the server node after adding the device.
1452
- * @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
1453
- */
1454
1171
  async createAccessoryPlugin(plugin, device, start = false) {
1455
1172
  if (!plugin.locked && device.deviceName && device.vendorId && device.productId && device.vendorName && device.productName) {
1456
1173
  plugin.locked = true;
@@ -1464,13 +1181,6 @@ export class Matterbridge extends EventEmitter {
1464
1181
  await this.startServerNode(plugin.serverNode);
1465
1182
  }
1466
1183
  }
1467
- /**
1468
- * Creates and configures the server node for a dynamic plugin.
1469
- *
1470
- * @param {RegisteredPlugin} plugin - The plugin to configure.
1471
- * @param {boolean} [start=false] - Whether to start the server node after adding the aggregator node.
1472
- * @returns {Promise<void>} A promise that resolves when the server node for the dynamic plugin is created and configured.
1473
- */
1474
1184
  async createDynamicPlugin(plugin, start = false) {
1475
1185
  if (!plugin.locked) {
1476
1186
  plugin.locked = true;
@@ -1483,13 +1193,7 @@ export class Matterbridge extends EventEmitter {
1483
1193
  await this.startServerNode(plugin.serverNode);
1484
1194
  }
1485
1195
  }
1486
- /**
1487
- * Starts the Matterbridge in bridge mode.
1488
- * @private
1489
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1490
- */
1491
1196
  async startBridge() {
1492
- // Plugins are configured by a timer when matter server is started and plugin.configured is set to true
1493
1197
  if (!this.matterStorageManager)
1494
1198
  throw new Error('No storage manager initialized');
1495
1199
  if (!this.matterbridgeContext)
@@ -1528,9 +1232,7 @@ export class Matterbridge extends EventEmitter {
1528
1232
  clearInterval(this.startMatterInterval);
1529
1233
  this.startMatterInterval = undefined;
1530
1234
  this.log.debug('Cleared startMatterInterval interval for Matterbridge');
1531
- // Start the Matter server node
1532
1235
  this.startServerNode(this.serverNode);
1533
- // Configure the plugins
1534
1236
  this.configureTimeout = setTimeout(async () => {
1535
1237
  for (const plugin of this.plugins) {
1536
1238
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1548,7 +1250,6 @@ export class Matterbridge extends EventEmitter {
1548
1250
  }
1549
1251
  this.frontend.wssSendRefreshRequired('plugins');
1550
1252
  }, 30 * 1000);
1551
- // Setting reachability to true
1552
1253
  this.reachabilityTimeout = setTimeout(() => {
1553
1254
  this.log.info(`Setting reachability to true for ${plg}Matterbridge${db}`);
1554
1255
  if (this.aggregatorNode)
@@ -1557,11 +1258,6 @@ export class Matterbridge extends EventEmitter {
1557
1258
  }, 60 * 1000);
1558
1259
  }, 1000);
1559
1260
  }
1560
- /**
1561
- * Starts the Matterbridge in childbridge mode.
1562
- * @private
1563
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1564
- */
1565
1261
  async startChildbridge() {
1566
1262
  if (!this.matterStorageManager)
1567
1263
  throw new Error('No storage manager initialized');
@@ -1599,7 +1295,6 @@ export class Matterbridge extends EventEmitter {
1599
1295
  clearInterval(this.startMatterInterval);
1600
1296
  this.startMatterInterval = undefined;
1601
1297
  this.log.debug('Cleared startMatterInterval interval in childbridge mode');
1602
- // Configure the plugins
1603
1298
  this.configureTimeout = setTimeout(async () => {
1604
1299
  for (const plugin of this.plugins) {
1605
1300
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1636,9 +1331,7 @@ export class Matterbridge extends EventEmitter {
1636
1331
  this.log.error(`Node storage context not found for plugin ${plg}${plugin.name}${er}`);
1637
1332
  continue;
1638
1333
  }
1639
- // Start the Matter server node
1640
1334
  this.startServerNode(plugin.serverNode);
1641
- // Setting reachability to true
1642
1335
  plugin.reachabilityTimeout = setTimeout(() => {
1643
1336
  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}`);
1644
1337
  if (plugin.type === 'DynamicPlatform' && plugin.aggregatorNode)
@@ -1648,227 +1341,9 @@ export class Matterbridge extends EventEmitter {
1648
1341
  }
1649
1342
  }, 1000);
1650
1343
  }
1651
- /**
1652
- * Starts the Matterbridge controller.
1653
- * @private
1654
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1655
- */
1656
1344
  async startController() {
1657
- /*
1658
- if (!this.matterStorageManager) {
1659
- this.log.error('No storage manager initialized');
1660
- await this.cleanup('No storage manager initialized');
1661
- return;
1662
- }
1663
- this.log.info('Creating context: mattercontrollerContext');
1664
- this.controllerContext = this.matterStorageManager.createContext('mattercontrollerContext');
1665
- if (!this.controllerContext) {
1666
- this.log.error('No storage context mattercontrollerContext initialized');
1667
- await this.cleanup('No storage context mattercontrollerContext initialized');
1668
- return;
1669
- }
1670
-
1671
- this.log.debug('Starting matterbridge in mode', this.bridgeMode);
1672
- this.matterServer = await this.createMatterServer(this.storageManager);
1673
- this.log.info('Creating matter commissioning controller');
1674
- this.commissioningController = new CommissioningController({
1675
- autoConnect: false,
1676
- });
1677
- this.log.info('Adding matter commissioning controller to matter server');
1678
- await this.matterServer.addCommissioningController(this.commissioningController);
1679
-
1680
- this.log.info('Starting matter server');
1681
- await this.matterServer.start();
1682
- this.log.info('Matter server started');
1683
- const commissioningOptions: ControllerCommissioningFlowOptions = {
1684
- regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
1685
- regulatoryCountryCode: 'XX',
1686
- };
1687
- const commissioningController = new CommissioningController({
1688
- environment: {
1689
- environment,
1690
- id: uniqueId,
1691
- },
1692
- autoConnect: false, // Do not auto connect to the commissioned nodes
1693
- adminFabricLabel,
1694
- });
1695
-
1696
- if (hasParameter('pairingcode')) {
1697
- this.log.info('Pairing device with pairingcode:', getParameter('pairingcode'));
1698
- const pairingCode = getParameter('pairingcode');
1699
- const ip = this.controllerContext.has('ip') ? this.controllerContext.get<string>('ip') : undefined;
1700
- const port = this.controllerContext.has('port') ? this.controllerContext.get<number>('port') : undefined;
1701
-
1702
- let longDiscriminator, setupPin, shortDiscriminator;
1703
- if (pairingCode !== undefined) {
1704
- const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
1705
- shortDiscriminator = pairingCodeCodec.shortDiscriminator;
1706
- longDiscriminator = undefined;
1707
- setupPin = pairingCodeCodec.passcode;
1708
- this.log.info(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
1709
- } else {
1710
- longDiscriminator = await this.controllerContext.get('longDiscriminator', 3840);
1711
- if (longDiscriminator > 4095) throw new Error('Discriminator value must be less than 4096');
1712
- setupPin = this.controllerContext.get('pin', 20202021);
1713
- }
1714
- if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {
1715
- throw new Error('Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode');
1716
- }
1717
-
1718
- const options = {
1719
- commissioning: commissioningOptions,
1720
- discovery: {
1721
- knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: 'udp' } : undefined,
1722
- identifierData: longDiscriminator !== undefined ? { longDiscriminator } : shortDiscriminator !== undefined ? { shortDiscriminator } : {},
1723
- },
1724
- passcode: setupPin,
1725
- } as NodeCommissioningOptions;
1726
- this.log.info('Commissioning with options:', options);
1727
- const nodeId = await this.commissioningController.commissionNode(options);
1728
- this.log.info(`Commissioning successfully done with nodeId: ${nodeId}`);
1729
- this.log.info('ActiveSessionInformation:', this.commissioningController.getActiveSessionInformation());
1730
- } // (hasParameter('pairingcode'))
1731
-
1732
- if (hasParameter('unpairall')) {
1733
- this.log.info('***Commissioning controller unpairing all nodes...');
1734
- const nodeIds = this.commissioningController.getCommissionedNodes();
1735
- for (const nodeId of nodeIds) {
1736
- this.log.info('***Commissioning controller unpairing node:', nodeId);
1737
- await this.commissioningController.removeNode(nodeId);
1738
- }
1739
- return;
1740
- }
1741
-
1742
- if (hasParameter('discover')) {
1743
- // const discover = await this.commissioningController.discoverCommissionableDevices({ productId: 0x8000, deviceType: 0xfff1 });
1744
- // console.log(discover);
1745
- }
1746
-
1747
- if (!this.commissioningController.isCommissioned()) {
1748
- this.log.info('***Commissioning controller is not commissioned: use matterbridge -controller -pairingcode [pairingcode] to commission a device');
1749
- return;
1750
- }
1751
-
1752
- const nodeIds = this.commissioningController.getCommissionedNodes();
1753
- this.log.info(`***Commissioning controller is commissioned ${this.commissioningController.isCommissioned()} and has ${nodeIds.length} nodes commisioned: `);
1754
- for (const nodeId of nodeIds) {
1755
- this.log.info(`***Connecting to commissioned node: ${nodeId}`);
1756
-
1757
- const node = await this.commissioningController.connectNode(nodeId, {
1758
- autoSubscribe: false,
1759
- attributeChangedCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, attributeName }, value }) =>
1760
- this.log.info(`***Commissioning controller attributeChangedCallback ${peerNodeId}: attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(value)}`),
1761
- eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>
1762
- this.log.info(`***Commissioning controller eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(events)}`),
1763
- stateInformationCallback: (peerNodeId, info) => {
1764
- switch (info) {
1765
- case NodeStateInformation.Connected:
1766
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
1767
- break;
1768
- case NodeStateInformation.Disconnected:
1769
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
1770
- break;
1771
- case NodeStateInformation.Reconnecting:
1772
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
1773
- break;
1774
- case NodeStateInformation.WaitingForDeviceDiscovery:
1775
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`);
1776
- break;
1777
- case NodeStateInformation.StructureChanged:
1778
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
1779
- break;
1780
- case NodeStateInformation.Decommissioned:
1781
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
1782
- break;
1783
- default:
1784
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} NodeStateInformation.${info}`);
1785
- break;
1786
- }
1787
- },
1788
- });
1789
-
1790
- node.logStructure();
1791
-
1792
- // Get the interaction client
1793
- this.log.info('Getting the interaction client');
1794
- const interactionClient = await node.getInteractionClient();
1795
- let cluster;
1796
- let attributes;
1797
-
1798
- // Log BasicInformationCluster
1799
- cluster = BasicInformationCluster;
1800
- attributes = await interactionClient.getMultipleAttributes({
1801
- attributes: [{ clusterId: cluster.id }],
1802
- });
1803
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1804
- attributes.forEach((attribute) => {
1805
- this.log.info(
1806
- `- 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}`,
1807
- );
1808
- });
1809
-
1810
- // Log PowerSourceCluster
1811
- cluster = PowerSourceCluster;
1812
- attributes = await interactionClient.getMultipleAttributes({
1813
- attributes: [{ clusterId: cluster.id }],
1814
- });
1815
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1816
- attributes.forEach((attribute) => {
1817
- this.log.info(
1818
- `- 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}`,
1819
- );
1820
- });
1821
-
1822
- // Log ThreadNetworkDiagnostics
1823
- cluster = ThreadNetworkDiagnosticsCluster;
1824
- attributes = await interactionClient.getMultipleAttributes({
1825
- attributes: [{ clusterId: cluster.id }],
1826
- });
1827
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1828
- attributes.forEach((attribute) => {
1829
- this.log.info(
1830
- `- 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}`,
1831
- );
1832
- });
1833
-
1834
- // Log SwitchCluster
1835
- cluster = SwitchCluster;
1836
- attributes = await interactionClient.getMultipleAttributes({
1837
- attributes: [{ clusterId: cluster.id }],
1838
- });
1839
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1840
- attributes.forEach((attribute) => {
1841
- this.log.info(
1842
- `- 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}`,
1843
- );
1844
- });
1845
-
1846
- this.log.info('Subscribing to all attributes and events');
1847
- await node.subscribeAllAttributesAndEvents({
1848
- ignoreInitialTriggers: false,
1849
- attributeChangedCallback: ({ path: { nodeId, clusterId, endpointId, attributeName }, version, value }) =>
1850
- this.log.info(
1851
- `***${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}`,
1852
- ),
1853
- eventTriggeredCallback: ({ path: { nodeId, clusterId, endpointId, eventName }, events }) => {
1854
- this.log.info(
1855
- `***${db}Commissioning controller eventTriggeredCallback: event ${BLUE}${nodeId}${db}/${or}${endpointId}${db}/${hk}${getClusterNameById(clusterId)}${db}/${zb}${eventName}${db} triggered with ${debugStringify(events ?? { none: true })}`,
1856
- );
1857
- },
1858
- });
1859
- this.log.info('Subscribed to all attributes and events');
1860
- }
1861
- */
1862
1345
  }
1863
- /** ***********************************************************************************************************************************/
1864
- /** Matter.js methods */
1865
- /** ***********************************************************************************************************************************/
1866
- /**
1867
- * Starts the matter storage with name Matterbridge, create the matterbridge context and performs a backup.
1868
- * @returns {Promise<void>} - A promise that resolves when the storage is started.
1869
- */
1870
1346
  async startMatterStorage() {
1871
- // Setup Matter storage
1872
1347
  this.log.info(`Starting matter node storage...`);
1873
1348
  this.matterStorageService = this.environment.get(StorageService);
1874
1349
  this.log.info(`Matter node storage service created: ${this.matterStorageService.location}`);
@@ -1877,16 +1352,8 @@ export class Matterbridge extends EventEmitter {
1877
1352
  this.matterbridgeContext = await this.createServerNodeContext('Matterbridge', 'Matterbridge', bridge.code, this.aggregatorVendorId, this.aggregatorVendorName, this.aggregatorProductId, this.aggregatorProductName);
1878
1353
  this.matterbridgeInformation.matterbridgeSerialNumber = await this.matterbridgeContext.get('serialNumber', '');
1879
1354
  this.log.info('Matter node storage started');
1880
- // Backup matter storage since it is created/opened correctly
1881
1355
  await this.backupMatterStorage(path.join(this.matterbridgeDirectory, this.matterStorageName), path.join(this.matterbridgeDirectory, this.matterStorageName + '.backup'));
1882
1356
  }
1883
- /**
1884
- * Makes a backup copy of the specified matter storage directory.
1885
- *
1886
- * @param storageName - The name of the storage directory to be backed up.
1887
- * @param backupName - The name of the backup directory to be created.
1888
- * @returns {Promise<void>} A promise that resolves when the has been done.
1889
- */
1890
1357
  async backupMatterStorage(storageName, backupName) {
1891
1358
  this.log.info('Creating matter node storage backup...');
1892
1359
  try {
@@ -1897,10 +1364,6 @@ export class Matterbridge extends EventEmitter {
1897
1364
  this.log.error(`Error creating matter node storage backup from ${storageName} to ${backupName}:`, error);
1898
1365
  }
1899
1366
  }
1900
- /**
1901
- * Stops the matter storage.
1902
- * @returns {Promise<void>} A promise that resolves when the storage is stopped.
1903
- */
1904
1367
  async stopMatterStorage() {
1905
1368
  this.log.info('Closing matter node storage...');
1906
1369
  await this.matterStorageManager?.close();
@@ -1909,19 +1372,6 @@ export class Matterbridge extends EventEmitter {
1909
1372
  this.matterbridgeContext = undefined;
1910
1373
  this.log.info('Matter node storage closed');
1911
1374
  }
1912
- /**
1913
- * Creates a server node storage context.
1914
- *
1915
- * @param {string} pluginName - The name of the plugin.
1916
- * @param {string} deviceName - The name of the device.
1917
- * @param {DeviceTypeId} deviceType - The device type of the device.
1918
- * @param {number} vendorId - The vendor ID.
1919
- * @param {string} vendorName - The vendor name.
1920
- * @param {number} productId - The product ID.
1921
- * @param {string} productName - The product name.
1922
- * @param {string} [serialNumber] - The serial number of the device (optional).
1923
- * @returns {Promise<StorageContext>} The storage context for the commissioning server.
1924
- */
1925
1375
  async createServerNodeContext(pluginName, deviceName, deviceType, vendorId, vendorName, productId, productName, serialNumber) {
1926
1376
  const { randomBytes } = await import('node:crypto');
1927
1377
  if (!this.matterStorageService)
@@ -1955,15 +1405,6 @@ export class Matterbridge extends EventEmitter {
1955
1405
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
1956
1406
  return storageContext;
1957
1407
  }
1958
- /**
1959
- * Creates a server node.
1960
- *
1961
- * @param {StorageContext} storageContext - The storage context for the server node.
1962
- * @param {number} [port=5540] - The port number for the server node. Defaults to 5540.
1963
- * @param {number} [passcode=20242025] - The passcode for the server node. Defaults to 20242025.
1964
- * @param {number} [discriminator=3850] - The discriminator for the server node. Defaults to 3850.
1965
- * @returns {Promise<ServerNode<ServerNode.RootEndpoint>>} A promise that resolves to the created server node.
1966
- */
1967
1408
  async createServerNode(storageContext, port = 5540, passcode = 20242025, discriminator = 3850) {
1968
1409
  const storeId = await storageContext.get('storeId');
1969
1410
  this.log.notice(`Creating server node for ${storeId} on port ${port} with passcode ${passcode} and discriminator ${discriminator}...`);
@@ -1973,37 +1414,24 @@ export class Matterbridge extends EventEmitter {
1973
1414
  this.log.debug(`- uniqueId: ${await storageContext.get('uniqueId')}`);
1974
1415
  this.log.debug(`- softwareVersion: ${await storageContext.get('softwareVersion')} softwareVersionString: ${await storageContext.get('softwareVersionString')}`);
1975
1416
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
1976
- /**
1977
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
1978
- */
1979
1417
  const serverNode = await ServerNode.create({
1980
- // Required: Give the Node a unique ID which is used to store the state of this node
1981
1418
  id: storeId,
1982
- // Provide Network relevant configuration like the port
1983
- // Optional when operating only one device on a host, Default port is 5540
1984
1419
  network: {
1985
1420
  listeningAddressIpv4: this.ipv4address,
1986
1421
  listeningAddressIpv6: this.ipv6address,
1987
1422
  port,
1988
1423
  },
1989
- // Provide the certificate for the device
1990
1424
  operationalCredentials: {
1991
1425
  certification: this.certification,
1992
1426
  },
1993
- // Provide Commissioning relevant settings
1994
- // Optional for development/testing purposes
1995
1427
  commissioning: {
1996
1428
  passcode,
1997
1429
  discriminator,
1998
1430
  },
1999
- // Provide Node announcement settings
2000
- // Optional: If Ommitted some development defaults are used
2001
1431
  productDescription: {
2002
1432
  name: await storageContext.get('deviceName'),
2003
1433
  deviceType: DeviceTypeId(await storageContext.get('deviceType')),
2004
1434
  },
2005
- // Provide defaults for the BasicInformation cluster on the Root endpoint
2006
- // Optional: If Omitted some development defaults are used
2007
1435
  basicInformation: {
2008
1436
  vendorId: VendorId(await storageContext.get('vendorId')),
2009
1437
  vendorName: await storageContext.get('vendorName'),
@@ -2021,13 +1449,12 @@ export class Matterbridge extends EventEmitter {
2021
1449
  },
2022
1450
  });
2023
1451
  const sanitizeFabrics = (fabrics, resetSessions = false) => {
2024
- // New type of fabric information: Record<FabricIndex, ExposedFabricInformation>
2025
1452
  const sanitizedFabrics = this.sanitizeFabricInformations(Array.from(Object.values(fabrics)));
2026
1453
  this.log.info(`Fabrics: ${debugStringify(sanitizedFabrics)}`);
2027
1454
  if (this.bridgeMode === 'bridge') {
2028
1455
  this.matterbridgeFabricInformations = sanitizedFabrics;
2029
1456
  if (resetSessions)
2030
- this.matterbridgeSessionInformations = undefined; // Changed cause Invoke Matterbridge.operationalCredentials.updateFabricLabel is sent after the session is created
1457
+ this.matterbridgeSessionInformations = undefined;
2031
1458
  this.matterbridgePaired = true;
2032
1459
  }
2033
1460
  if (this.bridgeMode === 'childbridge') {
@@ -2035,22 +1462,16 @@ export class Matterbridge extends EventEmitter {
2035
1462
  if (plugin) {
2036
1463
  plugin.fabricInformations = sanitizedFabrics;
2037
1464
  if (resetSessions)
2038
- plugin.sessionInformations = undefined; // Changed cause Invoke Matterbridge.operationalCredentials.updateFabricLabel is sent after the session is created
1465
+ plugin.sessionInformations = undefined;
2039
1466
  plugin.paired = true;
2040
1467
  }
2041
1468
  }
2042
1469
  };
2043
- /**
2044
- * This event is triggered when the device is initially commissioned successfully.
2045
- * This means: It is added to the first fabric.
2046
- */
2047
1470
  serverNode.lifecycle.commissioned.on(() => {
2048
1471
  this.log.notice(`Server node for ${storeId} was initially commissioned successfully!`);
2049
1472
  clearTimeout(this.endAdvertiseTimeout);
2050
1473
  });
2051
- /** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
2052
1474
  serverNode.lifecycle.decommissioned.on(() => this.log.notice(`Server node for ${storeId} was fully decommissioned successfully!`));
2053
- /** This event is triggered when the device went online. This means that it is discoverable in the network. */
2054
1475
  serverNode.lifecycle.online.on(async () => {
2055
1476
  this.log.notice(`Server node for ${storeId} is online`);
2056
1477
  if (!serverNode.lifecycle.isCommissioned) {
@@ -2089,7 +1510,6 @@ export class Matterbridge extends EventEmitter {
2089
1510
  }
2090
1511
  }
2091
1512
  }
2092
- // Set a timeout to show that advertising stops after 15 minutes if not commissioned
2093
1513
  this.startEndAdvertiseTimer(serverNode);
2094
1514
  }
2095
1515
  else {
@@ -2101,7 +1521,6 @@ export class Matterbridge extends EventEmitter {
2101
1521
  this.frontend.wssSendSnackbarMessage(`${storeId} is online`, 5, 'success');
2102
1522
  this.emit('online', storeId);
2103
1523
  });
2104
- /** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
2105
1524
  serverNode.lifecycle.offline.on(() => {
2106
1525
  this.log.notice(`Server node for ${storeId} is offline`);
2107
1526
  if (this.bridgeMode === 'bridge') {
@@ -2126,10 +1545,6 @@ export class Matterbridge extends EventEmitter {
2126
1545
  this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
2127
1546
  this.emit('offline', storeId);
2128
1547
  });
2129
- /**
2130
- * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
2131
- * information is needed.
2132
- */
2133
1548
  serverNode.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {
2134
1549
  let action = '';
2135
1550
  switch (fabricAction) {
@@ -2163,24 +1578,16 @@ export class Matterbridge extends EventEmitter {
2163
1578
  }
2164
1579
  }
2165
1580
  };
2166
- /**
2167
- * This event is triggered when an operative new session was opened by a Controller.
2168
- * It is not triggered for the initial commissioning process, just afterwards for real connections.
2169
- */
2170
1581
  serverNode.events.sessions.opened.on((session) => {
2171
1582
  this.log.notice(`Session opened on server node for ${storeId}: ${debugStringify(session)}`);
2172
1583
  sanitizeSessions(Object.values(serverNode.state.sessions.sessions));
2173
1584
  this.frontend.wssSendRefreshRequired('sessions');
2174
1585
  });
2175
- /**
2176
- * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
2177
- */
2178
1586
  serverNode.events.sessions.closed.on((session) => {
2179
1587
  this.log.notice(`Session closed on server node for ${storeId}: ${debugStringify(session)}`);
2180
1588
  sanitizeSessions(Object.values(serverNode.state.sessions.sessions));
2181
1589
  this.frontend.wssSendRefreshRequired('sessions');
2182
1590
  });
2183
- /** This event is triggered when a subscription gets added or removed on an operative session. */
2184
1591
  serverNode.events.sessions.subscriptionsChanged.on((session) => {
2185
1592
  this.log.notice(`Session subscriptions changed on server node for ${storeId}: ${debugStringify(session)}`);
2186
1593
  sanitizeSessions(Object.values(serverNode.state.sessions.sessions));
@@ -2189,12 +1596,6 @@ export class Matterbridge extends EventEmitter {
2189
1596
  this.log.info(`Created server node for ${storeId}`);
2190
1597
  return serverNode;
2191
1598
  }
2192
- /**
2193
- * Starts the 15 minutes timer to advice that advertising for the specified server node is ended.
2194
- *
2195
- * @param {ServerNode} [matterServerNode] - The server node to start.
2196
- * @param {string} storeId - The store ID of the server node.
2197
- */
2198
1599
  startEndAdvertiseTimer(matterServerNode) {
2199
1600
  if (this.endAdvertiseTimeout) {
2200
1601
  this.log.debug(`Clear ${matterServerNode.id} server node end advertise timer`);
@@ -2223,25 +1624,12 @@ export class Matterbridge extends EventEmitter {
2223
1624
  this.log.notice(`Advertising on server node for ${matterServerNode.id} stopped. Restart to commission.`);
2224
1625
  }, 15 * 60 * 1000).unref();
2225
1626
  }
2226
- /**
2227
- * Starts the specified server node.
2228
- *
2229
- * @param {ServerNode} [matterServerNode] - The server node to start.
2230
- * @returns {Promise<void>} A promise that resolves when the server node has started.
2231
- */
2232
1627
  async startServerNode(matterServerNode) {
2233
1628
  if (!matterServerNode)
2234
1629
  return;
2235
1630
  this.log.notice(`Starting ${matterServerNode.id} server node`);
2236
1631
  await matterServerNode.start();
2237
1632
  }
2238
- /**
2239
- * Stops the specified server node.
2240
- *
2241
- * @param {ServerNode} matterServerNode - The server node to stop.
2242
- * @param {number} [timeout=30000] - The timeout in milliseconds for stopping the server node. Defaults to 30 seconds.
2243
- * @returns {Promise<void>} A promise that resolves when the server node has stopped.
2244
- */
2245
1633
  async stopServerNode(matterServerNode, timeout = 30000) {
2246
1634
  if (!matterServerNode)
2247
1635
  return;
@@ -2254,12 +1642,6 @@ export class Matterbridge extends EventEmitter {
2254
1642
  this.log.error(`Failed to close ${matterServerNode.id} server node: ${error instanceof Error ? error.message : error}`);
2255
1643
  }
2256
1644
  }
2257
- /**
2258
- * Advertises the specified server node.
2259
- *
2260
- * @param {ServerNode} [matterServerNode] - The server node to advertise.
2261
- * @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.
2262
- */
2263
1645
  async advertiseServerNode(matterServerNode) {
2264
1646
  if (matterServerNode) {
2265
1647
  await matterServerNode.env.get(DeviceCommissioner)?.allowBasicCommissioning();
@@ -2268,46 +1650,25 @@ export class Matterbridge extends EventEmitter {
2268
1650
  return { qrPairingCode, manualPairingCode };
2269
1651
  }
2270
1652
  }
2271
- /**
2272
- * Stop advertise the specified server node.
2273
- *
2274
- * @param {ServerNode} [matterServerNode] - The server node to advertise.
2275
- * @returns {Promise<void>} A promise that resolves when the server node has stopped advertising.
2276
- */
2277
1653
  async stopAdvertiseServerNode(matterServerNode) {
2278
1654
  if (matterServerNode && matterServerNode.lifecycle.isOnline) {
2279
1655
  await matterServerNode.env.get(DeviceCommissioner)?.endCommissioning();
2280
1656
  this.log.notice(`Stopped advertising for ${matterServerNode.id}`);
2281
1657
  }
2282
1658
  }
2283
- /**
2284
- * Creates an aggregator node with the specified storage context.
2285
- *
2286
- * @param {StorageContext} storageContext - The storage context for the aggregator node.
2287
- * @returns {Promise<Endpoint<AggregatorEndpoint>>} A promise that resolves to the created aggregator node.
2288
- */
2289
1659
  async createAggregatorNode(storageContext) {
2290
1660
  this.log.notice(`Creating ${await storageContext.get('storeId')} aggregator...`);
2291
1661
  const aggregatorNode = new Endpoint(AggregatorEndpoint, { id: `${await storageContext.get('storeId')}` });
2292
1662
  this.log.info(`Created ${await storageContext.get('storeId')} aggregator`);
2293
1663
  return aggregatorNode;
2294
1664
  }
2295
- /**
2296
- * Adds a MatterbridgeEndpoint to the specified plugin.
2297
- *
2298
- * @param {string} pluginName - The name of the plugin.
2299
- * @param {MatterbridgeEndpoint} device - The device to add as a bridged endpoint.
2300
- * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been added.
2301
- */
2302
1665
  async addBridgedEndpoint(pluginName, device) {
2303
- // Check if the plugin is registered
2304
1666
  const plugin = this.plugins.get(pluginName);
2305
1667
  if (!plugin) {
2306
1668
  this.log.error(`Error adding bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.id}${er}) plugin ${plg}${pluginName}${er} not found`);
2307
1669
  return;
2308
1670
  }
2309
1671
  if (this.bridgeMode === 'bridge') {
2310
- // Register and add the device to the matterbridge aggregator node
2311
1672
  this.log.debug(`Adding bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge aggregator node`);
2312
1673
  if (!this.aggregatorNode) {
2313
1674
  this.log.error('Aggregator node not found for Matterbridge');
@@ -2324,7 +1685,6 @@ export class Matterbridge extends EventEmitter {
2324
1685
  }
2325
1686
  }
2326
1687
  else if (this.bridgeMode === 'childbridge') {
2327
- // Register and add the device to the plugin server node
2328
1688
  if (plugin.type === 'AccessoryPlatform') {
2329
1689
  try {
2330
1690
  this.log.debug(`Creating endpoint ${dev}${device.deviceName}${db} for AccessoryPlatform plugin ${plg}${plugin.name}${db} server node`);
@@ -2341,12 +1701,10 @@ export class Matterbridge extends EventEmitter {
2341
1701
  return;
2342
1702
  }
2343
1703
  }
2344
- // Register and add the device to the plugin aggregator node
2345
1704
  if (plugin.type === 'DynamicPlatform') {
2346
1705
  try {
2347
1706
  this.log.debug(`Adding bridged endpoint ${dev}${device.deviceName}${db} for DynamicPlatform plugin ${plg}${plugin.name}${db} aggregator node`);
2348
1707
  await this.createDynamicPlugin(plugin);
2349
- // Fast plugins can add another device before the server node is created
2350
1708
  await waiter(`createDynamicPlugin(${plugin.name})`, () => plugin.serverNode?.hasParts === true);
2351
1709
  if (!plugin.aggregatorNode) {
2352
1710
  this.log.error(`Aggregator node not found for plugin ${plg}${plugin.name}${er}`);
@@ -2366,28 +1724,17 @@ export class Matterbridge extends EventEmitter {
2366
1724
  plugin.registeredDevices++;
2367
1725
  if (plugin.addedDevices !== undefined)
2368
1726
  plugin.addedDevices++;
2369
- // Add the device to the DeviceManager
2370
1727
  this.devices.set(device);
2371
- // Subscribe to the reachable$Changed event
2372
1728
  await this.subscribeAttributeChanged(plugin, device);
2373
1729
  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}`);
2374
1730
  }
2375
- /**
2376
- * Removes a MatterbridgeEndpoint from the specified plugin.
2377
- *
2378
- * @param {string} pluginName - The name of the plugin.
2379
- * @param {MatterbridgeEndpoint} device - The device to remove as a bridged endpoint.
2380
- * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been removed.
2381
- */
2382
1731
  async removeBridgedEndpoint(pluginName, device) {
2383
1732
  this.log.debug(`Removing bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} (${zb}${device.name}${db}) for plugin ${plg}${pluginName}${db}`);
2384
- // Check if the plugin is registered
2385
1733
  const plugin = this.plugins.get(pluginName);
2386
1734
  if (!plugin) {
2387
1735
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: plugin not found`);
2388
1736
  return;
2389
1737
  }
2390
- // Register and add the device to the matterbridge aggregator node
2391
1738
  if (this.bridgeMode === 'bridge') {
2392
1739
  if (!this.aggregatorNode) {
2393
1740
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: aggregator node not found`);
@@ -2402,7 +1749,6 @@ export class Matterbridge extends EventEmitter {
2402
1749
  }
2403
1750
  else if (this.bridgeMode === 'childbridge') {
2404
1751
  if (plugin.type === 'AccessoryPlatform') {
2405
- // Nothing to do here since the server node has no aggregator node but only the device itself
2406
1752
  }
2407
1753
  else if (plugin.type === 'DynamicPlatform') {
2408
1754
  if (!plugin.aggregatorNode) {
@@ -2417,21 +1763,8 @@ export class Matterbridge extends EventEmitter {
2417
1763
  if (plugin.addedDevices !== undefined)
2418
1764
  plugin.addedDevices--;
2419
1765
  }
2420
- // Remove the device from the DeviceManager
2421
1766
  this.devices.remove(device);
2422
1767
  }
2423
- /**
2424
- * Removes all bridged endpoints from the specified plugin.
2425
- *
2426
- * @param {string} pluginName - The name of the plugin.
2427
- * @param {number} [delay=0] - The delay in milliseconds between removing each bridged endpoint (default: 0).
2428
- * @returns {Promise<void>} A promise that resolves when all bridged endpoints have been removed.
2429
- *
2430
- * @remarks
2431
- * This method iterates through all devices in the DeviceManager and removes each bridged endpoint associated with the specified plugin.
2432
- * It also applies a delay between each removal if specified.
2433
- * The delay is useful to allow the controllers to receive a single subscription for each device removed.
2434
- */
2435
1768
  async removeAllBridgedEndpoints(pluginName, delay = 0) {
2436
1769
  this.log.debug(`Removing all bridged endpoints for plugin ${plg}${pluginName}${db}${delay > 0 ? ` with delay ${delay} ms` : ''}`);
2437
1770
  for (const device of this.devices.array().filter((device) => device.plugin === pluginName)) {
@@ -2442,15 +1775,6 @@ export class Matterbridge extends EventEmitter {
2442
1775
  if (delay > 0)
2443
1776
  await new Promise((resolve) => setTimeout(resolve, 2000));
2444
1777
  }
2445
- /**
2446
- * Subscribes to the attribute change event for the given device and plugin.
2447
- * Specifically, it listens for changes in the 'reachable' attribute of the
2448
- * BridgedDeviceBasicInformationServer cluster server of the bridged device or BasicInformationServer cluster server of server node.
2449
- *
2450
- * @param {RegisteredPlugin} plugin - The plugin associated with the device.
2451
- * @param {MatterbridgeEndpoint} device - The device to subscribe to attribute changes for.
2452
- * @returns {Promise<void>} A promise that resolves when the subscription is set up.
2453
- */
2454
1778
  async subscribeAttributeChanged(plugin, device) {
2455
1779
  this.log.info(`Subscribing attributes for endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) plugin ${plg}${plugin.name}${nf}`);
2456
1780
  if (this.bridgeMode === 'childbridge' && plugin.type === 'AccessoryPlatform' && plugin.serverNode) {
@@ -2466,12 +1790,6 @@ export class Matterbridge extends EventEmitter {
2466
1790
  });
2467
1791
  }
2468
1792
  }
2469
- /**
2470
- * Sanitizes the fabric information by converting bigint properties to strings because `res.json` doesn't support bigint.
2471
- *
2472
- * @param {ExposedFabricInformation[]} fabricInfo - The array of exposed fabric information objects.
2473
- * @returns {SanitizedExposedFabricInformation[]} An array of sanitized exposed fabric information objects.
2474
- */
2475
1793
  sanitizeFabricInformations(fabricInfo) {
2476
1794
  return fabricInfo.map((info) => {
2477
1795
  return {
@@ -2485,12 +1803,6 @@ export class Matterbridge extends EventEmitter {
2485
1803
  };
2486
1804
  });
2487
1805
  }
2488
- /**
2489
- * Sanitizes the session information by converting bigint properties to strings because `res.json` doesn't support bigint.
2490
- *
2491
- * @param {SessionInformation[]} sessionInfo - The array of session information objects.
2492
- * @returns {SanitizedSessionInformation[]} An array of sanitized session information objects.
2493
- */
2494
1806
  sanitizeSessionInformation(sessionInfo) {
2495
1807
  return sessionInfo
2496
1808
  .filter((session) => session.isPeerActive)
@@ -2518,20 +1830,7 @@ export class Matterbridge extends EventEmitter {
2518
1830
  };
2519
1831
  });
2520
1832
  }
2521
- /**
2522
- * Sets the reachability of the specified aggregator node bridged devices and trigger.
2523
- * @param {Endpoint<AggregatorEndpoint>} aggregatorNode - The aggregator node to set the reachability for.
2524
- * @param {boolean} reachable - A boolean indicating the reachability status to set.
2525
- */
2526
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2527
1833
  async setAggregatorReachability(aggregatorNode, reachable) {
2528
- /*
2529
- for (const child of aggregatorNode.parts) {
2530
- this.log.debug(`Setting reachability of ${(child as unknown as MatterbridgeEndpoint)?.deviceName} to ${reachable}`);
2531
- await child.setStateOf(BridgedDeviceBasicInformationServer, { reachable });
2532
- child.act((agent) => child.eventsOf(BridgedDeviceBasicInformationServer).reachableChanged.emit({ reachableNewValue: true }, agent.context));
2533
- }
2534
- */
2535
1834
  }
2536
1835
  getVendorIdName = (vendorId) => {
2537
1836
  if (!vendorId)
@@ -2575,4 +1874,3 @@ export class Matterbridge extends EventEmitter {
2575
1874
  return vendorName;
2576
1875
  };
2577
1876
  }
2578
- //# sourceMappingURL=matterbridge.js.map