matterbridge 3.2.0 → 3.2.1-dev-20250802-f978b33

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