matterbridge 3.1.7-dev-20250724-c3522e6 → 3.1.7

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