matterbridge 3.1.8-dev-20250727-662308b → 3.1.8

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