matterbridge 3.2.9-dev-20250926-85736bb → 3.2.9

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