matterbridge 3.1.5 → 3.1.6-dev-20250720-88d6141

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