matterbridge 3.3.3 → 3.3.4-dev-20251020-df40d12

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 (297) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/broadcastServer.js +1 -86
  3. package/dist/broadcastServerTypes.js +0 -24
  4. package/dist/cli.js +112 -445
  5. package/dist/cliEmitter.js +0 -37
  6. package/dist/cliHistory.js +15 -95
  7. package/dist/clusters/export.js +0 -2
  8. package/dist/defaultConfigSchema.js +0 -24
  9. package/dist/deviceManager.js +1 -124
  10. package/dist/devices/airConditioner.js +2 -59
  11. package/dist/devices/batteryStorage.js +4 -51
  12. package/dist/devices/cooktop.js +0 -55
  13. package/dist/devices/dishwasher.js +4 -61
  14. package/dist/devices/evse.js +16 -79
  15. package/dist/devices/export.js +0 -5
  16. package/dist/devices/extractorHood.js +1 -43
  17. package/dist/devices/heatPump.js +4 -52
  18. package/dist/devices/laundryDryer.js +6 -65
  19. package/dist/devices/laundryWasher.js +9 -75
  20. package/dist/devices/microwaveOven.js +10 -93
  21. package/dist/devices/oven.js +5 -90
  22. package/dist/devices/refrigerator.js +4 -106
  23. package/dist/devices/roboticVacuumCleaner.js +20 -111
  24. package/dist/devices/solarPower.js +2 -40
  25. package/dist/devices/speaker.js +2 -85
  26. package/dist/devices/temperatureControl.js +5 -27
  27. package/dist/devices/waterHeater.js +8 -88
  28. package/dist/dgram/coap.js +13 -126
  29. package/dist/dgram/dgram.js +2 -114
  30. package/dist/dgram/mb_coap.js +3 -41
  31. package/dist/dgram/mb_mdns.js +15 -80
  32. package/dist/dgram/mdns.js +137 -299
  33. package/dist/dgram/multicast.js +1 -62
  34. package/dist/dgram/unicast.js +0 -54
  35. package/dist/frontend.js +61 -439
  36. package/dist/frontendTypes.js +0 -45
  37. package/dist/helpers.js +1 -54
  38. package/dist/index.js +0 -25
  39. package/dist/logger/export.js +0 -1
  40. package/dist/matter/behaviors.js +0 -2
  41. package/dist/matter/clusters.js +0 -2
  42. package/dist/matter/devices.js +0 -2
  43. package/dist/matter/endpoints.js +0 -2
  44. package/dist/matter/export.js +0 -3
  45. package/dist/matter/types.js +0 -3
  46. package/dist/matterbridge.js +67 -885
  47. package/dist/matterbridgeAccessoryPlatform.js +2 -36
  48. package/dist/matterbridgeBehaviors.js +25 -91
  49. package/dist/matterbridgeDeviceTypes.js +102 -715
  50. package/dist/matterbridgeDynamicPlatform.js +2 -36
  51. package/dist/matterbridgeEndpoint.js +122 -1473
  52. package/dist/matterbridgeEndpointHelpers.js +88 -443
  53. package/dist/matterbridgePlatform.js +3 -343
  54. package/dist/matterbridgeTypes.js +0 -26
  55. package/dist/pluginManager.js +3 -325
  56. package/dist/shelly.js +7 -168
  57. package/dist/storage/export.js +0 -1
  58. package/dist/update.js +1 -70
  59. package/dist/utils/colorUtils.js +2 -97
  60. package/dist/utils/commandLine.js +6 -55
  61. package/dist/utils/copyDirectory.js +1 -38
  62. package/dist/utils/createDirectory.js +0 -33
  63. package/dist/utils/createZip.js +2 -47
  64. package/dist/utils/deepCopy.js +0 -39
  65. package/dist/utils/deepEqual.js +1 -72
  66. package/dist/utils/error.js +0 -41
  67. package/dist/utils/export.js +0 -1
  68. package/dist/utils/format.js +29 -0
  69. package/dist/utils/hex.js +0 -124
  70. package/dist/utils/inspector.js +200 -0
  71. package/dist/utils/isvalid.js +0 -101
  72. package/dist/utils/jestHelpers.js +10 -156
  73. package/dist/utils/network.js +5 -134
  74. package/dist/utils/spawn.js +0 -71
  75. package/dist/utils/tracker.js +201 -0
  76. package/dist/utils/wait.js +8 -60
  77. package/frontend/build/assets/index.js +4 -4
  78. package/frontend/build/assets/vendor_mdi.js +1 -1
  79. package/frontend/package.json +1 -1
  80. package/npm-shrinkwrap.json +44 -44
  81. package/package.json +2 -3
  82. package/dist/broadcastServer.d.ts +0 -105
  83. package/dist/broadcastServer.d.ts.map +0 -1
  84. package/dist/broadcastServer.js.map +0 -1
  85. package/dist/broadcastServerTypes.d.ts +0 -719
  86. package/dist/broadcastServerTypes.d.ts.map +0 -1
  87. package/dist/broadcastServerTypes.js.map +0 -1
  88. package/dist/cli.d.ts +0 -26
  89. package/dist/cli.d.ts.map +0 -1
  90. package/dist/cli.js.map +0 -1
  91. package/dist/cliEmitter.d.ts +0 -50
  92. package/dist/cliEmitter.d.ts.map +0 -1
  93. package/dist/cliEmitter.js.map +0 -1
  94. package/dist/cliHistory.d.ts +0 -74
  95. package/dist/cliHistory.d.ts.map +0 -1
  96. package/dist/cliHistory.js.map +0 -1
  97. package/dist/clusters/export.d.ts +0 -2
  98. package/dist/clusters/export.d.ts.map +0 -1
  99. package/dist/clusters/export.js.map +0 -1
  100. package/dist/defaultConfigSchema.d.ts +0 -28
  101. package/dist/defaultConfigSchema.d.ts.map +0 -1
  102. package/dist/defaultConfigSchema.js.map +0 -1
  103. package/dist/deviceManager.d.ts +0 -117
  104. package/dist/deviceManager.d.ts.map +0 -1
  105. package/dist/deviceManager.js.map +0 -1
  106. package/dist/devices/airConditioner.d.ts +0 -98
  107. package/dist/devices/airConditioner.d.ts.map +0 -1
  108. package/dist/devices/airConditioner.js.map +0 -1
  109. package/dist/devices/batteryStorage.d.ts +0 -48
  110. package/dist/devices/batteryStorage.d.ts.map +0 -1
  111. package/dist/devices/batteryStorage.js.map +0 -1
  112. package/dist/devices/cooktop.d.ts +0 -60
  113. package/dist/devices/cooktop.d.ts.map +0 -1
  114. package/dist/devices/cooktop.js.map +0 -1
  115. package/dist/devices/dishwasher.d.ts +0 -71
  116. package/dist/devices/dishwasher.d.ts.map +0 -1
  117. package/dist/devices/dishwasher.js.map +0 -1
  118. package/dist/devices/evse.d.ts +0 -75
  119. package/dist/devices/evse.d.ts.map +0 -1
  120. package/dist/devices/evse.js.map +0 -1
  121. package/dist/devices/export.d.ts +0 -17
  122. package/dist/devices/export.d.ts.map +0 -1
  123. package/dist/devices/export.js.map +0 -1
  124. package/dist/devices/extractorHood.d.ts +0 -46
  125. package/dist/devices/extractorHood.d.ts.map +0 -1
  126. package/dist/devices/extractorHood.js.map +0 -1
  127. package/dist/devices/heatPump.d.ts +0 -47
  128. package/dist/devices/heatPump.d.ts.map +0 -1
  129. package/dist/devices/heatPump.js.map +0 -1
  130. package/dist/devices/laundryDryer.d.ts +0 -67
  131. package/dist/devices/laundryDryer.d.ts.map +0 -1
  132. package/dist/devices/laundryDryer.js.map +0 -1
  133. package/dist/devices/laundryWasher.d.ts +0 -81
  134. package/dist/devices/laundryWasher.d.ts.map +0 -1
  135. package/dist/devices/laundryWasher.js.map +0 -1
  136. package/dist/devices/microwaveOven.d.ts +0 -168
  137. package/dist/devices/microwaveOven.d.ts.map +0 -1
  138. package/dist/devices/microwaveOven.js.map +0 -1
  139. package/dist/devices/oven.d.ts +0 -105
  140. package/dist/devices/oven.d.ts.map +0 -1
  141. package/dist/devices/oven.js.map +0 -1
  142. package/dist/devices/refrigerator.d.ts +0 -118
  143. package/dist/devices/refrigerator.d.ts.map +0 -1
  144. package/dist/devices/refrigerator.js.map +0 -1
  145. package/dist/devices/roboticVacuumCleaner.d.ts +0 -112
  146. package/dist/devices/roboticVacuumCleaner.d.ts.map +0 -1
  147. package/dist/devices/roboticVacuumCleaner.js.map +0 -1
  148. package/dist/devices/solarPower.d.ts +0 -40
  149. package/dist/devices/solarPower.d.ts.map +0 -1
  150. package/dist/devices/solarPower.js.map +0 -1
  151. package/dist/devices/speaker.d.ts +0 -87
  152. package/dist/devices/speaker.d.ts.map +0 -1
  153. package/dist/devices/speaker.js.map +0 -1
  154. package/dist/devices/temperatureControl.d.ts +0 -166
  155. package/dist/devices/temperatureControl.d.ts.map +0 -1
  156. package/dist/devices/temperatureControl.js.map +0 -1
  157. package/dist/devices/waterHeater.d.ts +0 -111
  158. package/dist/devices/waterHeater.d.ts.map +0 -1
  159. package/dist/devices/waterHeater.js.map +0 -1
  160. package/dist/dgram/coap.d.ts +0 -205
  161. package/dist/dgram/coap.d.ts.map +0 -1
  162. package/dist/dgram/coap.js.map +0 -1
  163. package/dist/dgram/dgram.d.ts +0 -141
  164. package/dist/dgram/dgram.d.ts.map +0 -1
  165. package/dist/dgram/dgram.js.map +0 -1
  166. package/dist/dgram/mb_coap.d.ts +0 -24
  167. package/dist/dgram/mb_coap.d.ts.map +0 -1
  168. package/dist/dgram/mb_coap.js.map +0 -1
  169. package/dist/dgram/mb_mdns.d.ts +0 -24
  170. package/dist/dgram/mb_mdns.d.ts.map +0 -1
  171. package/dist/dgram/mb_mdns.js.map +0 -1
  172. package/dist/dgram/mdns.d.ts +0 -290
  173. package/dist/dgram/mdns.d.ts.map +0 -1
  174. package/dist/dgram/mdns.js.map +0 -1
  175. package/dist/dgram/multicast.d.ts +0 -67
  176. package/dist/dgram/multicast.d.ts.map +0 -1
  177. package/dist/dgram/multicast.js.map +0 -1
  178. package/dist/dgram/unicast.d.ts +0 -56
  179. package/dist/dgram/unicast.d.ts.map +0 -1
  180. package/dist/dgram/unicast.js.map +0 -1
  181. package/dist/frontend.d.ts +0 -235
  182. package/dist/frontend.d.ts.map +0 -1
  183. package/dist/frontend.js.map +0 -1
  184. package/dist/frontendTypes.d.ts +0 -529
  185. package/dist/frontendTypes.d.ts.map +0 -1
  186. package/dist/frontendTypes.js.map +0 -1
  187. package/dist/helpers.d.ts +0 -48
  188. package/dist/helpers.d.ts.map +0 -1
  189. package/dist/helpers.js.map +0 -1
  190. package/dist/index.d.ts +0 -33
  191. package/dist/index.d.ts.map +0 -1
  192. package/dist/index.js.map +0 -1
  193. package/dist/logger/export.d.ts +0 -2
  194. package/dist/logger/export.d.ts.map +0 -1
  195. package/dist/logger/export.js.map +0 -1
  196. package/dist/matter/behaviors.d.ts +0 -2
  197. package/dist/matter/behaviors.d.ts.map +0 -1
  198. package/dist/matter/behaviors.js.map +0 -1
  199. package/dist/matter/clusters.d.ts +0 -2
  200. package/dist/matter/clusters.d.ts.map +0 -1
  201. package/dist/matter/clusters.js.map +0 -1
  202. package/dist/matter/devices.d.ts +0 -2
  203. package/dist/matter/devices.d.ts.map +0 -1
  204. package/dist/matter/devices.js.map +0 -1
  205. package/dist/matter/endpoints.d.ts +0 -2
  206. package/dist/matter/endpoints.d.ts.map +0 -1
  207. package/dist/matter/endpoints.js.map +0 -1
  208. package/dist/matter/export.d.ts +0 -5
  209. package/dist/matter/export.d.ts.map +0 -1
  210. package/dist/matter/export.js.map +0 -1
  211. package/dist/matter/types.d.ts +0 -3
  212. package/dist/matter/types.d.ts.map +0 -1
  213. package/dist/matter/types.js.map +0 -1
  214. package/dist/matterbridge.d.ts +0 -469
  215. package/dist/matterbridge.d.ts.map +0 -1
  216. package/dist/matterbridge.js.map +0 -1
  217. package/dist/matterbridgeAccessoryPlatform.d.ts +0 -42
  218. package/dist/matterbridgeAccessoryPlatform.d.ts.map +0 -1
  219. package/dist/matterbridgeAccessoryPlatform.js.map +0 -1
  220. package/dist/matterbridgeBehaviors.d.ts +0 -2399
  221. package/dist/matterbridgeBehaviors.d.ts.map +0 -1
  222. package/dist/matterbridgeBehaviors.js.map +0 -1
  223. package/dist/matterbridgeDeviceTypes.d.ts +0 -761
  224. package/dist/matterbridgeDeviceTypes.d.ts.map +0 -1
  225. package/dist/matterbridgeDeviceTypes.js.map +0 -1
  226. package/dist/matterbridgeDynamicPlatform.d.ts +0 -42
  227. package/dist/matterbridgeDynamicPlatform.d.ts.map +0 -1
  228. package/dist/matterbridgeDynamicPlatform.js.map +0 -1
  229. package/dist/matterbridgeEndpoint.d.ts +0 -1545
  230. package/dist/matterbridgeEndpoint.d.ts.map +0 -1
  231. package/dist/matterbridgeEndpoint.js.map +0 -1
  232. package/dist/matterbridgeEndpointHelpers.d.ts +0 -560
  233. package/dist/matterbridgeEndpointHelpers.d.ts.map +0 -1
  234. package/dist/matterbridgeEndpointHelpers.js.map +0 -1
  235. package/dist/matterbridgePlatform.d.ts +0 -402
  236. package/dist/matterbridgePlatform.d.ts.map +0 -1
  237. package/dist/matterbridgePlatform.js.map +0 -1
  238. package/dist/matterbridgeTypes.d.ts +0 -209
  239. package/dist/matterbridgeTypes.d.ts.map +0 -1
  240. package/dist/matterbridgeTypes.js.map +0 -1
  241. package/dist/pluginManager.d.ts +0 -353
  242. package/dist/pluginManager.d.ts.map +0 -1
  243. package/dist/pluginManager.js.map +0 -1
  244. package/dist/shelly.d.ts +0 -174
  245. package/dist/shelly.d.ts.map +0 -1
  246. package/dist/shelly.js.map +0 -1
  247. package/dist/storage/export.d.ts +0 -2
  248. package/dist/storage/export.d.ts.map +0 -1
  249. package/dist/storage/export.js.map +0 -1
  250. package/dist/update.d.ts +0 -75
  251. package/dist/update.d.ts.map +0 -1
  252. package/dist/update.js.map +0 -1
  253. package/dist/utils/colorUtils.d.ts +0 -99
  254. package/dist/utils/colorUtils.d.ts.map +0 -1
  255. package/dist/utils/colorUtils.js.map +0 -1
  256. package/dist/utils/commandLine.d.ts +0 -59
  257. package/dist/utils/commandLine.d.ts.map +0 -1
  258. package/dist/utils/commandLine.js.map +0 -1
  259. package/dist/utils/copyDirectory.d.ts +0 -33
  260. package/dist/utils/copyDirectory.d.ts.map +0 -1
  261. package/dist/utils/copyDirectory.js.map +0 -1
  262. package/dist/utils/createDirectory.d.ts +0 -34
  263. package/dist/utils/createDirectory.d.ts.map +0 -1
  264. package/dist/utils/createDirectory.js.map +0 -1
  265. package/dist/utils/createZip.d.ts +0 -39
  266. package/dist/utils/createZip.d.ts.map +0 -1
  267. package/dist/utils/createZip.js.map +0 -1
  268. package/dist/utils/deepCopy.d.ts +0 -32
  269. package/dist/utils/deepCopy.d.ts.map +0 -1
  270. package/dist/utils/deepCopy.js.map +0 -1
  271. package/dist/utils/deepEqual.d.ts +0 -54
  272. package/dist/utils/deepEqual.d.ts.map +0 -1
  273. package/dist/utils/deepEqual.js.map +0 -1
  274. package/dist/utils/error.d.ts +0 -44
  275. package/dist/utils/error.d.ts.map +0 -1
  276. package/dist/utils/error.js.map +0 -1
  277. package/dist/utils/export.d.ts +0 -13
  278. package/dist/utils/export.d.ts.map +0 -1
  279. package/dist/utils/export.js.map +0 -1
  280. package/dist/utils/hex.d.ts +0 -89
  281. package/dist/utils/hex.d.ts.map +0 -1
  282. package/dist/utils/hex.js.map +0 -1
  283. package/dist/utils/isvalid.d.ts +0 -103
  284. package/dist/utils/isvalid.d.ts.map +0 -1
  285. package/dist/utils/isvalid.js.map +0 -1
  286. package/dist/utils/jestHelpers.d.ts +0 -137
  287. package/dist/utils/jestHelpers.d.ts.map +0 -1
  288. package/dist/utils/jestHelpers.js.map +0 -1
  289. package/dist/utils/network.d.ts +0 -115
  290. package/dist/utils/network.d.ts.map +0 -1
  291. package/dist/utils/network.js.map +0 -1
  292. package/dist/utils/spawn.d.ts +0 -35
  293. package/dist/utils/spawn.d.ts.map +0 -1
  294. package/dist/utils/spawn.js.map +0 -1
  295. package/dist/utils/wait.d.ts +0 -54
  296. package/dist/utils/wait.d.ts.map +0 -1
  297. package/dist/utils/wait.js.map +0 -1
@@ -1,50 +1,24 @@
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
- // eslint-disable-next-line no-console
25
1
  if (process.argv.includes('--loader') || process.argv.includes('-loader'))
26
2
  console.log('\u001B[32mMatterbridge loaded.\u001B[40;0m');
27
- // Node.js modules
28
3
  import os from 'node:os';
29
4
  import path from 'node:path';
30
5
  import { promises as fs } from 'node:fs';
31
6
  import EventEmitter from 'node:events';
32
7
  import { inspect } from 'node:util';
33
- // AnsiLogger module
34
8
  import { AnsiLogger, UNDERLINE, UNDERLINEOFF, db, debugStringify, BRIGHT, RESET, er, nf, rs, wr, RED, GREEN, zb, CYAN, nt, BLUE, or } from 'node-ansi-logger';
35
- // NodeStorage module
36
9
  import { NodeStorageManager } from 'node-persist-manager';
37
- // @matter
38
- import { DeviceTypeId, Endpoint, Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, VendorId, StorageService, Environment, ServerNode, UINT32_MAX, UINT16_MAX, Crypto, } from '@matter/main';
39
- import { FabricAction, MdnsService, PaseClient } from '@matter/main/protocol';
40
- import { AggregatorEndpoint } from '@matter/main/endpoints';
41
- import { BasicInformationServer } from '@matter/main/behaviors/basic-information';
42
- // Matterbridge
10
+ import '@matter/nodejs';
11
+ import { Endpoint, ServerNode } from '@matter/node';
12
+ import { Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, UINT32_MAX, UINT16_MAX, Crypto, Environment, StorageService } from '@matter/general';
13
+ import { DeviceTypeId, VendorId } from '@matter/types';
14
+ import { FabricAction, PaseClient } from '@matter/protocol';
15
+ import { AggregatorEndpoint } from '@matter/node/endpoints';
16
+ import { BasicInformationServer } from '@matter/node/behaviors/basic-information';
43
17
  import { getParameter, getIntParameter, hasParameter } from './utils/commandLine.js';
44
18
  import { copyDirectory } from './utils/copyDirectory.js';
45
19
  import { createDirectory } from './utils/createDirectory.js';
46
20
  import { isValidString, parseVersionString, isValidNumber, isValidObject } from './utils/isvalid.js';
47
- import { formatMemoryUsage, formatOsUpTime } from './utils/network.js';
21
+ import { formatBytes, formatPercent, formatUptime } from './utils/format.js';
48
22
  import { withTimeout, waiter, wait } from './utils/wait.js';
49
23
  import { dev, MATTER_LOGGER_FILE, MATTER_STORAGE_NAME, MATTERBRIDGE_LOGGER_FILE, NODE_STORAGE_DIR, plg, typ } from './matterbridgeTypes.js';
50
24
  import { PluginManager } from './pluginManager.js';
@@ -53,11 +27,7 @@ import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
53
27
  import { bridge } from './matterbridgeDeviceTypes.js';
54
28
  import { Frontend } from './frontend.js';
55
29
  import { addVirtualDevices } from './helpers.js';
56
- /**
57
- * Represents the Matterbridge application.
58
- */
59
30
  export class Matterbridge extends EventEmitter {
60
- /** Matterbridge system information */
61
31
  systemInformation = {
62
32
  interfaceName: '',
63
33
  macAddress: '',
@@ -80,7 +50,6 @@ export class Matterbridge extends EventEmitter {
80
50
  heapTotal: '',
81
51
  heapUsed: '',
82
52
  };
83
- // Matterbridge settings
84
53
  homeDirectory = '';
85
54
  rootDirectory = '';
86
55
  matterbridgeDirectory = '';
@@ -95,15 +64,10 @@ export class Matterbridge extends EventEmitter {
95
64
  restartMode = '';
96
65
  virtualMode = 'outlet';
97
66
  profile = getParameter('profile');
98
- /** Matterbridge logger */
99
- log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: hasParameter('debug') ? "debug" /* LogLevel.DEBUG */ : "info" /* LogLevel.INFO */ });
100
- /** Whether to log to a file */
67
+ log = new AnsiLogger({ logName: 'Matterbridge', logTimestampFormat: 4, logLevel: hasParameter('debug') ? "debug" : "info" });
101
68
  fileLogger = false;
102
- /** Matter logger */
103
- matterLog = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: "debug" /* LogLevel.DEBUG */ });
104
- /** Whether to log Matter to a file */
69
+ matterLog = new AnsiLogger({ logName: 'Matter', logTimestampFormat: 4, logLevel: "debug" });
105
70
  matterFileLogger = false;
106
- // Frontend settings
107
71
  readOnly = hasParameter('readonly') || hasParameter('shelly');
108
72
  shellyBoard = hasParameter('shelly');
109
73
  shellySysUpdate = false;
@@ -111,18 +75,12 @@ export class Matterbridge extends EventEmitter {
111
75
  restartRequired = false;
112
76
  fixedRestartRequired = false;
113
77
  updateRequired = false;
114
- // Managers
115
78
  plugins = new PluginManager(this);
116
79
  devices = new DeviceManager();
117
- // Frontend
118
80
  frontend = new Frontend(this);
119
- /** Matterbridge node storage manager created in matterbridgeDirectory with name 'storage' */
120
81
  nodeStorage;
121
- /** Matterbridge node context created with name 'matterbridge' */
122
82
  nodeContext;
123
- /** The main instance of the Matterbridge class (singleton) */
124
83
  static instance;
125
- // Instance properties
126
84
  shutdown = false;
127
85
  failCountLimit = hasParameter('shelly') ? 600 : 120;
128
86
  hasCleanupStarted = false;
@@ -137,32 +95,19 @@ export class Matterbridge extends EventEmitter {
137
95
  sigtermHandler;
138
96
  exceptionHandler;
139
97
  rejectionHandler;
140
- /** Matter environment default */
141
98
  environment = Environment.default;
142
- /** Matter storage service from environment default */
143
99
  matterStorageService;
144
- /** Matter storage manager created with name 'Matterbridge' */
145
100
  matterStorageManager;
146
- /** Matter matterbridge storage context created in the storage manager with name 'persist' */
147
101
  matterbridgeContext;
148
102
  controllerContext;
149
- /** Matter mdns interface e.g. 'eth0' or 'wlan0' or 'Wi-Fi' */
150
103
  mdnsInterface;
151
- /** Matter listeningAddressIpv4 address */
152
104
  ipv4Address;
153
- /** Matter listeningAddressIpv6 address */
154
105
  ipv6Address;
155
- /** Matter commissioning port */
156
- port; // first server node port
157
- /** Matter commissioning passcode */
158
- passcode; // first server node passcode
159
- /** Matter commissioning discriminator */
160
- discriminator; // first server node discriminator
161
- /** Matter device certification */
162
- certification; // device certification
163
- /** Matter server node in bridge mode */
106
+ port;
107
+ passcode;
108
+ discriminator;
109
+ certification;
164
110
  serverNode;
165
- /** Matter aggregator node in bridge mode */
166
111
  aggregatorNode;
167
112
  aggregatorVendorId = VendorId(getIntParameter('vendorId') ?? 0xfff1);
168
113
  aggregatorVendorName = getParameter('vendorName') ?? 'Matterbridge';
@@ -171,26 +116,13 @@ export class Matterbridge extends EventEmitter {
171
116
  aggregatorDeviceType = DeviceTypeId(getIntParameter('deviceType') ?? bridge.code);
172
117
  aggregatorSerialNumber = getParameter('serialNumber');
173
118
  aggregatorUniqueId = getParameter('uniqueId');
174
- /** Advertising nodes map: time advertising started keyed by storeId */
175
119
  advertisingNodes = new Map();
176
- /** We load asyncronously so is private */
177
120
  constructor() {
178
121
  super();
179
122
  this.log.logNameColor = '\x1b[38;5;115m';
180
123
  }
181
- //* ************************************************************************************************************************************ */
182
- // loadInstance() and cleanup() methods */
183
- //* ************************************************************************************************************************************ */
184
- /**
185
- * Loads an instance of the Matterbridge class.
186
- * If an instance already exists, return that instance.
187
- *
188
- * @param {boolean} initialize - Whether to initialize the Matterbridge instance after loading. Defaults to false.
189
- * @returns {Matterbridge} A promise that resolves to the Matterbridge instance.
190
- */
191
124
  static async loadInstance(initialize = false) {
192
125
  if (!Matterbridge.instance) {
193
- // eslint-disable-next-line no-console
194
126
  if (hasParameter('debug'))
195
127
  console.log(GREEN + 'Creating a new instance of Matterbridge.', initialize ? 'Initializing...' : 'Not initializing...', rs);
196
128
  Matterbridge.instance = new Matterbridge();
@@ -199,129 +131,62 @@ export class Matterbridge extends EventEmitter {
199
131
  }
200
132
  return Matterbridge.instance;
201
133
  }
202
- /**
203
- * Call cleanup() and dispose MdnsService.
204
- *
205
- * @param {number} [timeout] - The timeout duration to wait for the cleanup to complete in milliseconds. Default is 1000.
206
- * @param {number} [pause] - The pause duration after the cleanup in milliseconds. Default is 250.
207
- *
208
- * @deprecated This method is deprecated and is ONLY used for jest tests.
209
- */
210
134
  async destroyInstance(timeout = 1000, pause = 250) {
211
135
  this.log.info(`Destroy instance...`);
212
- // Save server nodes to close
213
- const servers = [];
214
- if (this.bridgeMode === 'bridge') {
215
- if (this.serverNode)
216
- servers.push(this.serverNode);
217
- }
218
- if (this.bridgeMode === 'childbridge' && this.plugins !== undefined) {
219
- for (const plugin of this.plugins.array()) {
220
- if (plugin.serverNode)
221
- servers.push(plugin.serverNode);
222
- }
223
- }
224
- if (this.devices !== undefined) {
225
- for (const device of this.devices.array()) {
226
- if (device.mode === 'server' && device.serverNode)
227
- servers.push(device.serverNode);
228
- }
229
- }
230
- // Let any already‐queued microtasks run first
231
- await Promise.resolve();
232
- // Wait for the cleanup to finish
233
- await wait(pause, 'destroyInstance start', true);
234
- // Cleanup
235
136
  await this.cleanup('destroying instance...', false, timeout);
236
- // Close servers mdns service
237
- this.log.info(`Dispose ${servers.length} MdnsService...`);
238
- for (const server of servers) {
239
- await server.env.get(MdnsService)[Symbol.asyncDispose]();
240
- this.log.info(`Closed ${server.id} MdnsService`);
241
- }
242
- // Let any already‐queued microtasks run first
243
- await Promise.resolve();
244
- // Wait for the cleanup to finish
245
- await wait(pause, 'destroyInstance stop', true);
137
+ if (pause)
138
+ await wait(pause, 'destroyInstance stop', true);
246
139
  }
247
- /**
248
- * Initializes the Matterbridge application.
249
- *
250
- * @remarks
251
- * This method performs the necessary setup and initialization steps for the Matterbridge application.
252
- * It displays the help information if the 'help' parameter is provided, sets up the logger, checks the
253
- * node version, registers signal handlers, initializes storage, and parses the command line.
254
- *
255
- * @returns {Promise<void>} A Promise that resolves when the initialization is complete.
256
- */
257
140
  async initialize() {
258
- // for (let i = 1; i <= 255; i++) console.log(`\x1b[38;5;${i}mColor: ${i}`);
259
- // Emit the initialize_started event
260
141
  this.emit('initialize_started');
261
- // Set the restart mode
262
142
  if (hasParameter('service'))
263
143
  this.restartMode = 'service';
264
144
  if (hasParameter('docker'))
265
145
  this.restartMode = 'docker';
266
- // Set the matterbridge home directory
267
146
  this.homeDirectory = getParameter('homedir') ?? os.homedir();
268
147
  await createDirectory(this.homeDirectory, 'Matterbridge Home Directory', this.log);
269
- // Set the matterbridge directory
270
148
  this.matterbridgeDirectory = this.profile ? path.join(this.homeDirectory, '.matterbridge', 'profiles', this.profile) : path.join(this.homeDirectory, '.matterbridge');
271
149
  await createDirectory(this.matterbridgeDirectory, 'Matterbridge Directory', this.log);
272
150
  await createDirectory(path.join(this.matterbridgeDirectory, 'certs'), 'Matterbridge Frontend Certificate Directory', this.log);
273
151
  await createDirectory(path.join(this.matterbridgeDirectory, 'uploads'), 'Matterbridge Frontend Uploads Directory', this.log);
274
- // Set the matterbridge plugin directory
275
152
  this.matterbridgePluginDirectory = this.profile ? path.join(this.homeDirectory, 'Matterbridge', 'profiles', this.profile) : path.join(this.homeDirectory, 'Matterbridge');
276
153
  await createDirectory(this.matterbridgePluginDirectory, 'Matterbridge Plugin Directory', this.log);
277
- // Set the matterbridge cert directory
278
154
  this.matterbridgeCertDirectory = this.profile ? path.join(this.homeDirectory, '.mattercert', 'profiles', this.profile) : path.join(this.homeDirectory, '.mattercert');
279
155
  await createDirectory(this.matterbridgeCertDirectory, 'Matterbridge Matter Certificate Directory', this.log);
280
- // Set the matterbridge root directory
281
156
  const { fileURLToPath } = await import('node:url');
282
157
  const currentFileDirectory = path.dirname(fileURLToPath(import.meta.url));
283
- this.rootDirectory = path.resolve(currentFileDirectory, '../'); // Adjust the path for dist directory
284
- // Setup the matter environment with default values
158
+ this.rootDirectory = path.resolve(currentFileDirectory, '../');
285
159
  this.environment.vars.set('log.level', MatterLogLevel.INFO);
286
160
  this.environment.vars.set('log.format', MatterLogFormat.ANSI);
287
161
  this.environment.vars.set('path.root', path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME));
288
162
  this.environment.vars.set('runtime.signals', false);
289
163
  this.environment.vars.set('runtime.exitcode', false);
290
- // Register process handlers
291
164
  this.registerProcessHandlers();
292
- // Initialize nodeStorage and nodeContext
293
165
  try {
294
166
  this.log.debug(`Creating node storage manager: ${CYAN}${NODE_STORAGE_DIR}${db}`);
295
167
  this.nodeStorage = new NodeStorageManager({ dir: path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR), writeQueue: false, expiredInterval: undefined, logging: false });
296
168
  this.log.debug('Creating node storage context for matterbridge');
297
169
  this.nodeContext = await this.nodeStorage.createStorage('matterbridge');
298
- // TODO: Remove this code when node-persist-manager is updated
299
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
300
170
  const keys = (await this.nodeStorage?.storage.keys());
301
171
  for (const key of keys) {
302
172
  this.log.debug(`Checking node storage manager key: ${CYAN}${key}${db}`);
303
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
304
173
  await this.nodeStorage?.storage.get(key);
305
174
  }
306
175
  const storages = await this.nodeStorage.getStorageNames();
307
176
  for (const storage of storages) {
308
177
  this.log.debug(`Checking storage: ${CYAN}${storage}${db}`);
309
178
  const nodeContext = await this.nodeStorage?.createStorage(storage);
310
- // TODO: Remove this code when node-persist-manager is updated
311
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
312
179
  const keys = (await nodeContext?.storage.keys());
313
180
  keys.forEach(async (key) => {
314
181
  this.log.debug(`Checking key: ${CYAN}${storage}:${key}${db}`);
315
182
  await nodeContext?.get(key);
316
183
  });
317
184
  }
318
- // Creating a backup of the node storage since it is not corrupted
319
185
  this.log.debug('Creating node storage backup...');
320
186
  await copyDirectory(path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR), path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR + '.backup'));
321
187
  this.log.debug('Created node storage backup');
322
188
  }
323
189
  catch (error) {
324
- // Restoring the backup of the node storage since it is corrupted
325
190
  this.log.error(`Error creating node storage manager and context: ${error instanceof Error ? error.message : error}`);
326
191
  if (hasParameter('norestore')) {
327
192
  this.log.fatal(`The matterbridge storage is corrupted. Found -norestore parameter: exiting...`);
@@ -335,19 +200,14 @@ export class Matterbridge extends EventEmitter {
335
200
  if (!this.nodeStorage || !this.nodeContext) {
336
201
  throw new Error('Fatal error creating node storage manager and context for matterbridge');
337
202
  }
338
- // Set the first port to use for the commissioning server (will be incremented in childbridge mode)
339
203
  this.port = getIntParameter('port') ?? (await this.nodeContext.get('matterport', 5540)) ?? 5540;
340
- // Set the first passcode to use for the commissioning server (will be incremented in childbridge mode)
341
204
  this.passcode = getIntParameter('passcode') ?? (await this.nodeContext.get('matterpasscode')) ?? PaseClient.generateRandomPasscode(this.environment.get(Crypto));
342
- // Set the first discriminator to use for the commissioning server (will be incremented in childbridge mode)
343
205
  this.discriminator = getIntParameter('discriminator') ?? (await this.nodeContext.get('matterdiscriminator')) ?? PaseClient.generateRandomDiscriminator(this.environment.get(Crypto));
344
- // Certificate management
345
206
  const pairingFilePath = path.join(this.matterbridgeCertDirectory, 'pairing.json');
346
207
  try {
347
208
  await fs.access(pairingFilePath, fs.constants.R_OK);
348
209
  const pairingFileContent = await fs.readFile(pairingFilePath, 'utf8');
349
210
  const pairingFileJson = JSON.parse(pairingFileContent);
350
- // Set the vendorId, vendorName, productId, productName, deviceType, serialNumber, uniqueId if they are present in the pairing file
351
211
  if (isValidNumber(pairingFileJson.vendorId)) {
352
212
  this.aggregatorVendorId = VendorId(pairingFileJson.vendorId);
353
213
  this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using vendorId ${CYAN}${this.aggregatorVendorId}${nf} from pairing file.`);
@@ -376,13 +236,11 @@ export class Matterbridge extends EventEmitter {
376
236
  this.aggregatorUniqueId = pairingFileJson.uniqueId;
377
237
  this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using uniqueId ${CYAN}${this.aggregatorUniqueId}${nf} from pairing file.`);
378
238
  }
379
- // Override the passcode and discriminator if they are present in the pairing file
380
239
  if (isValidNumber(pairingFileJson.passcode) && isValidNumber(pairingFileJson.discriminator)) {
381
240
  this.passcode = pairingFileJson.passcode;
382
241
  this.discriminator = pairingFileJson.discriminator;
383
242
  this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using passcode ${CYAN}${this.passcode}${nf} and discriminator ${CYAN}${this.discriminator}${nf} from pairing file.`);
384
243
  }
385
- // Set the certification for matter.js if it is present in the pairing file
386
244
  if (pairingFileJson.privateKey && pairingFileJson.certificate && pairingFileJson.intermediateCertificate && pairingFileJson.declaration) {
387
245
  const { hexToBuffer } = await import('./utils/hex.js');
388
246
  this.certification = {
@@ -397,43 +255,40 @@ export class Matterbridge extends EventEmitter {
397
255
  catch (error) {
398
256
  this.log.debug(`Pairing file ${CYAN}${pairingFilePath}${db} not found: ${error instanceof Error ? error.message : error}`);
399
257
  }
400
- // Store the passcode, discriminator and port in the node context
401
258
  await this.nodeContext.set('matterport', this.port);
402
259
  await this.nodeContext.set('matterpasscode', this.passcode);
403
260
  await this.nodeContext.set('matterdiscriminator', this.discriminator);
404
261
  this.log.debug(`Initializing server node for Matterbridge on port ${this.port} with passcode ${this.passcode} and discriminator ${this.discriminator}`);
405
- // Set matterbridge logger level (context: matterbridgeLogLevel)
406
262
  if (hasParameter('logger')) {
407
263
  const level = getParameter('logger');
408
264
  if (level === 'debug') {
409
- this.log.logLevel = "debug" /* LogLevel.DEBUG */;
265
+ this.log.logLevel = "debug";
410
266
  }
411
267
  else if (level === 'info') {
412
- this.log.logLevel = "info" /* LogLevel.INFO */;
268
+ this.log.logLevel = "info";
413
269
  }
414
270
  else if (level === 'notice') {
415
- this.log.logLevel = "notice" /* LogLevel.NOTICE */;
271
+ this.log.logLevel = "notice";
416
272
  }
417
273
  else if (level === 'warn') {
418
- this.log.logLevel = "warn" /* LogLevel.WARN */;
274
+ this.log.logLevel = "warn";
419
275
  }
420
276
  else if (level === 'error') {
421
- this.log.logLevel = "error" /* LogLevel.ERROR */;
277
+ this.log.logLevel = "error";
422
278
  }
423
279
  else if (level === 'fatal') {
424
- this.log.logLevel = "fatal" /* LogLevel.FATAL */;
280
+ this.log.logLevel = "fatal";
425
281
  }
426
282
  else {
427
283
  this.log.warn(`Invalid matterbridge logger level: ${level}. Using default level "info".`);
428
- this.log.logLevel = "info" /* LogLevel.INFO */;
284
+ this.log.logLevel = "info";
429
285
  }
430
286
  }
431
287
  else {
432
- this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.shellyBoard ? "notice" /* LogLevel.NOTICE */ : "info" /* LogLevel.INFO */);
288
+ this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.shellyBoard ? "notice" : "info");
433
289
  }
434
290
  this.frontend.logLevel = this.log.logLevel;
435
291
  MatterbridgeEndpoint.logLevel = this.log.logLevel;
436
- // Create the file logger for matterbridge (context: matterbridgeFileLog)
437
292
  if (hasParameter('filelogger') || (await this.nodeContext.get('matterbridgeFileLog', false))) {
438
293
  AnsiLogger.setGlobalLogfile(path.join(this.matterbridgeDirectory, MATTERBRIDGE_LOGGER_FILE), this.log.logLevel, true);
439
294
  this.fileLogger = true;
@@ -442,7 +297,6 @@ export class Matterbridge extends EventEmitter {
442
297
  this.log.debug(`Matterbridge logLevel: ${this.log.logLevel} fileLoger: ${this.fileLogger}.`);
443
298
  if (this.profile !== undefined)
444
299
  this.log.debug(`Matterbridge profile: ${this.profile}.`);
445
- // Set matter.js logger level, format and logger (context: matterLogLevel)
446
300
  if (hasParameter('matterlogger')) {
447
301
  const level = getParameter('matterlogger');
448
302
  if (level === 'debug') {
@@ -472,13 +326,11 @@ export class Matterbridge extends EventEmitter {
472
326
  Logger.level = (await this.nodeContext.get('matterLogLevel', this.shellyBoard ? MatterLogLevel.NOTICE : MatterLogLevel.INFO));
473
327
  }
474
328
  Logger.format = MatterLogFormat.ANSI;
475
- // Create the logger for matter.js with file logging (context: matterFileLog)
476
329
  if (hasParameter('matterfilelogger') || (await this.nodeContext.get('matterFileLog', false))) {
477
330
  this.matterFileLogger = true;
478
331
  }
479
332
  Logger.destinations.default.write = this.createDestinationMatterLogger(this.matterFileLogger);
480
333
  this.log.debug(`Matter logLevel: ${Logger.level} fileLoger: ${this.matterFileLogger}.`);
481
- // Log network interfaces
482
334
  const networkInterfaces = os.networkInterfaces();
483
335
  const availableAddresses = Object.entries(networkInterfaces);
484
336
  const availableInterfaceNames = Object.keys(networkInterfaces);
@@ -491,7 +343,6 @@ export class Matterbridge extends EventEmitter {
491
343
  });
492
344
  }
493
345
  }
494
- // Set the interface to use for matter server node mdnsInterface
495
346
  if (hasParameter('mdnsinterface')) {
496
347
  this.mdnsInterface = getParameter('mdnsinterface');
497
348
  }
@@ -500,7 +351,6 @@ export class Matterbridge extends EventEmitter {
500
351
  if (this.mdnsInterface === '')
501
352
  this.mdnsInterface = undefined;
502
353
  }
503
- // Validate mdnsInterface
504
354
  if (this.mdnsInterface) {
505
355
  if (!availableInterfaceNames.includes(this.mdnsInterface)) {
506
356
  this.log.error(`Invalid mdnsinterface: ${this.mdnsInterface}. Available interfaces are: ${availableInterfaceNames.join(', ')}. Using all available interfaces.`);
@@ -513,7 +363,6 @@ export class Matterbridge extends EventEmitter {
513
363
  }
514
364
  if (this.mdnsInterface)
515
365
  this.environment.vars.set('mdns.networkInterface', this.mdnsInterface);
516
- // Set the listeningAddressIpv4 for the matter commissioning server
517
366
  if (hasParameter('ipv4address')) {
518
367
  this.ipv4Address = getParameter('ipv4address');
519
368
  }
@@ -522,7 +371,6 @@ export class Matterbridge extends EventEmitter {
522
371
  if (this.ipv4Address === '')
523
372
  this.ipv4Address = undefined;
524
373
  }
525
- // Validate ipv4address
526
374
  if (this.ipv4Address) {
527
375
  let isValid = false;
528
376
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -538,7 +386,6 @@ export class Matterbridge extends EventEmitter {
538
386
  await this.nodeContext.remove('matteripv4address');
539
387
  }
540
388
  }
541
- // Set the listeningAddressIpv6 for the matter commissioning server
542
389
  if (hasParameter('ipv6address')) {
543
390
  this.ipv6Address = getParameter('ipv6address');
544
391
  }
@@ -547,7 +394,6 @@ export class Matterbridge extends EventEmitter {
547
394
  if (this.ipv6Address === '')
548
395
  this.ipv6Address = undefined;
549
396
  }
550
- // Validate ipv6address
551
397
  if (this.ipv6Address) {
552
398
  let isValid = false;
553
399
  for (const [ifaceName, ifaces] of availableAddresses) {
@@ -556,7 +402,6 @@ export class Matterbridge extends EventEmitter {
556
402
  isValid = true;
557
403
  break;
558
404
  }
559
- /* istanbul ignore next */
560
405
  if (ifaces && ifaces.find((iface) => iface.scopeid && iface.scopeid > 0 && iface.address + '%' + (process.platform === 'win32' ? iface.scopeid : ifaceName) === this.ipv6Address)) {
561
406
  this.log.info(`Using ipv6address ${CYAN}${this.ipv6Address}${nf} on interface ${CYAN}${ifaceName}${nf} for the Matter server node.`);
562
407
  isValid = true;
@@ -569,7 +414,6 @@ export class Matterbridge extends EventEmitter {
569
414
  await this.nodeContext.remove('matteripv6address');
570
415
  }
571
416
  }
572
- // Initialize the virtual mode
573
417
  if (hasParameter('novirtual')) {
574
418
  this.virtualMode = 'disabled';
575
419
  await this.nodeContext.set('virtualmode', 'disabled');
@@ -578,17 +422,12 @@ export class Matterbridge extends EventEmitter {
578
422
  this.virtualMode = (await this.nodeContext.get('virtualmode', 'outlet'));
579
423
  }
580
424
  this.log.debug(`Virtual mode ${this.virtualMode}.`);
581
- // Initialize PluginManager
582
425
  this.plugins.logLevel = this.log.logLevel;
583
426
  await this.plugins.loadFromStorage();
584
- // Initialize DeviceManager
585
427
  this.devices.logLevel = this.log.logLevel;
586
- // Get the plugins from node storage and create the plugins node storage contexts
587
428
  for (const plugin of this.plugins) {
588
429
  const packageJson = await this.plugins.parse(plugin);
589
430
  if (packageJson === null && !hasParameter('add') && !hasParameter('remove') && !hasParameter('enable') && !hasParameter('disable') && !hasParameter('reset') && !hasParameter('factoryreset')) {
590
- // Try to reinstall the plugin from npm (for Docker pull and external plugins)
591
- // We don't do this when the add and other parameters are set because we shut down the process after adding the plugin
592
431
  this.log.info(`Error parsing plugin ${plg}${plugin.name}${nf}. Trying to reinstall it from npm.`);
593
432
  try {
594
433
  const { spawnCommand } = await import('./utils/spawn.js');
@@ -611,7 +450,6 @@ export class Matterbridge extends EventEmitter {
611
450
  await plugin.nodeContext.set('description', plugin.description);
612
451
  await plugin.nodeContext.set('author', plugin.author);
613
452
  }
614
- // Log system info and create .matterbridge directory
615
453
  await this.logNodeAndSystemInfo();
616
454
  this.log.notice(`Matterbridge version ${this.matterbridgeVersion} ` +
617
455
  `${hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge') ? 'mode bridge ' : ''}` +
@@ -619,73 +457,18 @@ export class Matterbridge extends EventEmitter {
619
457
  `${hasParameter('controller') ? 'mode controller ' : ''}` +
620
458
  `${this.restartMode !== '' ? 'restart mode ' + this.restartMode + ' ' : ''}` +
621
459
  `running on ${this.systemInformation.osType} (v.${this.systemInformation.osRelease}) platform ${this.systemInformation.osPlatform} arch ${this.systemInformation.osArch}`);
622
- // Check node version and throw error
623
- const minNodeVersion = 18;
460
+ const minNodeVersion = 20;
624
461
  const nodeVersion = process.versions.node;
625
462
  const versionMajor = parseInt(nodeVersion.split('.')[0]);
626
463
  if (versionMajor < minNodeVersion) {
627
464
  this.log.error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
628
465
  throw new Error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
629
466
  }
630
- // Parse command line
631
467
  await this.parseCommandLine();
632
- // Emit the initialize_completed event
633
468
  this.emit('initialize_completed');
634
469
  this.initialized = true;
635
470
  }
636
- /**
637
- * Parses the command line arguments and performs the corresponding actions.
638
- *
639
- * @private
640
- * @returns {Promise<void>} A promise that resolves when the command line arguments have been processed, or the process exits.
641
- */
642
471
  async parseCommandLine() {
643
- if (hasParameter('help')) {
644
- this.log.info(`\nUsage: matterbridge [options]\n
645
- Options:
646
- --help: show the help
647
- --bridge: start Matterbridge in bridge mode
648
- --childbridge: start Matterbridge in childbridge mode
649
- --port [port]: start the commissioning server on the given port (default 5540)
650
- --mdnsinterface [name]: set the interface to use for the matter server mdnsInterface (default all interfaces)
651
- --ipv4address [address]: set the ipv4 interface address to use for the matter listener (default all addresses)
652
- --ipv6address [address]: set the ipv6 interface address to use for the matter listener (default all addresses)
653
- --frontend [port]: start the frontend on the given port (default 8283)
654
- --logger: set the matterbridge logger level: debug | info | notice | warn | error | fatal (default info)
655
- --filelogger enable the matterbridge file logger (matterbridge.log)
656
- --matterlogger: set the matter.js logger level: debug | info | notice | warn | error | fatal (default info)
657
- --matterfilelogger enable the matter.js file logger (matter.log)
658
- --reset: remove the commissioning for Matterbridge (bridge mode). Shutdown Matterbridge before using it!
659
- --factoryreset: remove all commissioning information and reset all internal storages. Shutdown Matterbridge before using it!
660
- --list: list the registered plugins
661
- --loginterfaces: log the network interfaces (usefull for finding the name of the interface to use with -mdnsinterface option)
662
- --logstorage: log the node storage
663
- --sudo: force the use of sudo to install or update packages if the internal logic fails
664
- --nosudo: force not to use sudo to install or update packages if the internal logic fails
665
- --norestore: force not to automatically restore the matterbridge node storage and the matter storage from backup if it is corrupted
666
- --novirtual: disable the creation of the virtual devices Restart, Update and Reboot Matterbridge
667
- --ssl: enable SSL for the frontend and the WebSocketServer (the server will use the certificates and switch to https)
668
- --mtls: enable mTLS for the frontend and the WebSocketServer (both server and client will use and require the certificates and switch to https)
669
- --vendorId: override the default vendorId 0xfff1
670
- --vendorName: override the default vendorName "Matterbridge"
671
- --productId: override the default productId 0x8000
672
- --productName: override the default productName "Matterbridge aggregator"
673
- --service: enable the service mode (used in the systemctl configuration file)
674
- --docker: enable the docker mode (used in the docker image)
675
- --homedir: override the home directory (default: os.homedir())
676
- --add [plugin path]: register the plugin from the given absolute or relative path
677
- --add [plugin name]: register the globally installed plugin with the given name
678
- --remove [plugin path]: remove the plugin from the given absolute or relative path
679
- --remove [plugin name]: remove the globally installed plugin with the given name
680
- --enable [plugin path]: enable the plugin from the given absolute or relative path
681
- --enable [plugin name]: enable the globally installed plugin with the given name
682
- --disable [plugin path]: disable the plugin from the given absolute or relative path
683
- --disable [plugin name]: disable the globally installed plugin with the given name
684
- --reset [plugin path]: remove the commissioning for the plugin from the given absolute or relative path (childbridge mode). Shutdown Matterbridge before using it!
685
- --reset [plugin name]: remove the commissioning for the globally installed plugin (childbridge mode). Shutdown Matterbridge before using it!${rs}`);
686
- this.shutdown = true;
687
- return;
688
- }
689
472
  if (hasParameter('list')) {
690
473
  this.log.info(`│ Registered plugins (${this.plugins.length})`);
691
474
  let index = 0;
@@ -700,19 +483,6 @@ export class Matterbridge extends EventEmitter {
700
483
  }
701
484
  index++;
702
485
  }
703
- /*
704
- const serializedRegisteredDevices = await this.nodeContext?.get<SerializedMatterbridgeEndpoint[]>('devices', []);
705
- this.log.info(`│ Registered devices (${serializedRegisteredDevices?.length})`);
706
- serializedRegisteredDevices?.forEach((device, index) => {
707
- if (index !== serializedRegisteredDevices.length - 1) {
708
- this.log.info(`├─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
709
- this.log.info(`│ └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
710
- } else {
711
- this.log.info(`└─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
712
- this.log.info(` └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
713
- }
714
- });
715
- */
716
486
  this.shutdown = true;
717
487
  return;
718
488
  }
@@ -762,40 +532,33 @@ export class Matterbridge extends EventEmitter {
762
532
  this.shutdown = true;
763
533
  return;
764
534
  }
765
- // Initialize frontend
766
535
  if (getIntParameter('frontend') !== 0 || getIntParameter('frontend') === undefined)
767
536
  await this.frontend.start(getIntParameter('frontend'));
768
- // Start the matter storage and create the matterbridge context
769
537
  try {
770
538
  await this.startMatterStorage();
771
539
  if (this.aggregatorSerialNumber && this.aggregatorUniqueId && this.matterStorageService) {
772
540
  const storageManager = await this.matterStorageService.open('Matterbridge');
773
541
  const storageContext = storageManager?.createContext('persist');
774
- if (this.aggregatorSerialNumber)
775
- await storageContext?.set('serialNumber', this.aggregatorSerialNumber);
776
- if (this.aggregatorUniqueId)
777
- await storageContext?.set('uniqueId', this.aggregatorUniqueId);
542
+ await storageContext?.set('serialNumber', this.aggregatorSerialNumber);
543
+ await storageContext?.set('uniqueId', this.aggregatorUniqueId);
778
544
  }
779
545
  }
780
546
  catch (error) {
781
547
  this.log.fatal(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
782
548
  throw new Error(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
783
549
  }
784
- // Clear the matterbridge context if the reset parameter is set
785
550
  if (hasParameter('reset') && getParameter('reset') === undefined) {
786
551
  this.initialized = true;
787
552
  await this.shutdownProcessAndReset();
788
553
  this.shutdown = true;
789
554
  return;
790
555
  }
791
- // Clear matterbridge plugin context if the reset parameter is set
792
556
  if (hasParameter('reset') && getParameter('reset') !== undefined) {
793
557
  this.log.debug(`Reset plugin ${getParameter('reset')}`);
794
558
  const plugin = this.plugins.get(getParameter('reset'));
795
559
  if (plugin) {
796
560
  const matterStorageManager = await this.matterStorageService?.open(plugin.name);
797
561
  if (!matterStorageManager) {
798
- /* istanbul ignore next */
799
562
  this.log.error(`Plugin ${plg}${plugin.name}${er} storageManager not found`);
800
563
  }
801
564
  else {
@@ -814,42 +577,35 @@ export class Matterbridge extends EventEmitter {
814
577
  this.shutdown = true;
815
578
  return;
816
579
  }
817
- // Check in 30 seconds the latest and dev versions of matterbridge and the plugins
818
580
  clearTimeout(this.checkUpdateTimeout);
819
581
  this.checkUpdateTimeout = setTimeout(async () => {
820
582
  const { checkUpdates } = await import('./update.js');
821
583
  checkUpdates(this);
822
584
  }, 30 * 1000).unref();
823
- // Check each 12 hours the latest and dev versions of matterbridge and the plugins
824
585
  clearInterval(this.checkUpdateInterval);
825
586
  this.checkUpdateInterval = setInterval(async () => {
826
587
  const { checkUpdates } = await import('./update.js');
827
588
  checkUpdates(this);
828
589
  }, 12 * 60 * 60 * 1000).unref();
829
- // Start the matterbridge in mode test
830
590
  if (hasParameter('test')) {
831
591
  this.bridgeMode = 'bridge';
832
592
  return;
833
593
  }
834
- // Start the matterbridge in mode controller
835
594
  if (hasParameter('controller')) {
836
595
  this.bridgeMode = 'controller';
837
596
  await this.startController();
838
597
  return;
839
598
  }
840
- // Check if the bridge mode is set and start matterbridge in bridge mode if not set
841
599
  if (!hasParameter('bridge') && !hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === '') {
842
600
  this.log.info('Setting default matterbridge start mode to bridge');
843
601
  await this.nodeContext?.set('bridgeMode', 'bridge');
844
602
  }
845
- // Start matterbridge in bridge mode
846
603
  if (hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge')) {
847
604
  this.bridgeMode = 'bridge';
848
605
  this.log.debug(`Starting matterbridge in mode ${this.bridgeMode}`);
849
606
  await this.startBridge();
850
607
  return;
851
608
  }
852
- // Start matterbridge in childbridge mode
853
609
  if (hasParameter('childbridge') || (!hasParameter('bridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'childbridge')) {
854
610
  this.bridgeMode = 'childbridge';
855
611
  this.log.debug(`Starting matterbridge in mode ${this.bridgeMode}`);
@@ -857,22 +613,10 @@ export class Matterbridge extends EventEmitter {
857
613
  return;
858
614
  }
859
615
  }
860
- /**
861
- * Asynchronously loads and starts the registered plugins.
862
- *
863
- * This method is responsible for initializing and starting all enabled plugins.
864
- * It ensures that each plugin is properly loaded and started before the bridge starts.
865
- *
866
- * @param {boolean} [wait] - If true, the method will wait for all plugins to be fully loaded and started before resolving.
867
- * @param {boolean} [start] - If true, the method will start the plugins after loading them.
868
- * @returns {Promise<void>} A promise that resolves when all plugins have been loaded and started.
869
- */
870
616
  async startPlugins(wait = false, start = true) {
871
- // Check, load and start the plugins
872
617
  for (const plugin of this.plugins) {
873
618
  plugin.configJson = await this.plugins.loadConfig(plugin);
874
619
  plugin.schemaJson = await this.plugins.loadSchema(plugin);
875
- // Check if the plugin is available
876
620
  if (!(await this.plugins.resolve(plugin.path))) {
877
621
  this.log.error(`Plugin ${plg}${plugin.name}${er} not found or not validated. Disabling it.`);
878
622
  plugin.enabled = false;
@@ -892,16 +636,10 @@ export class Matterbridge extends EventEmitter {
892
636
  if (wait)
893
637
  await this.plugins.load(plugin, start, 'Matterbridge is starting');
894
638
  else
895
- this.plugins.load(plugin, start, 'Matterbridge is starting'); // No await do it asyncronously
639
+ this.plugins.load(plugin, start, 'Matterbridge is starting');
896
640
  }
897
641
  this.frontend.wssSendRefreshRequired('plugins');
898
642
  }
899
- /**
900
- * Registers the process handlers for uncaughtException, unhandledRejection, SIGINT and SIGTERM.
901
- * - When an uncaught exception occurs, the exceptionHandler logs the error message and stack trace.
902
- * - When an unhandled promise rejection occurs, the rejectionHandler logs the reason and stack trace.
903
- * - When either of SIGINT and SIGTERM signals are received, the cleanup method is called with an appropriate message.
904
- */
905
643
  registerProcessHandlers() {
906
644
  this.log.debug(`Registering uncaughtException and unhandledRejection handlers...`);
907
645
  process.removeAllListeners('uncaughtException');
@@ -928,9 +666,6 @@ export class Matterbridge extends EventEmitter {
928
666
  };
929
667
  process.on('SIGTERM', this.sigtermHandler);
930
668
  }
931
- /**
932
- * Deregisters the process uncaughtException, unhandledRejection, SIGINT and SIGTERM signal handlers.
933
- */
934
669
  deregisterProcessHandlers() {
935
670
  this.log.debug(`Deregistering uncaughtException and unhandledRejection handlers...`);
936
671
  if (this.exceptionHandler)
@@ -947,18 +682,13 @@ export class Matterbridge extends EventEmitter {
947
682
  process.off('SIGTERM', this.sigtermHandler);
948
683
  this.sigtermHandler = undefined;
949
684
  }
950
- /**
951
- * Logs the node and system information.
952
- */
953
685
  async logNodeAndSystemInfo() {
954
- // IP address information
955
686
  const networkInterfaces = os.networkInterfaces();
956
687
  this.systemInformation.interfaceName = '';
957
688
  this.systemInformation.ipv4Address = '';
958
689
  this.systemInformation.ipv6Address = '';
959
690
  this.systemInformation.macAddress = '';
960
691
  for (const [interfaceName, interfaceDetails] of Object.entries(networkInterfaces)) {
961
- // this.log.debug(`Checking interface: '${interfaceName}' for '${this.mdnsInterface}'`);
962
692
  if (this.mdnsInterface && interfaceName !== this.mdnsInterface)
963
693
  continue;
964
694
  if (!interfaceDetails) {
@@ -984,27 +714,25 @@ export class Matterbridge extends EventEmitter {
984
714
  break;
985
715
  }
986
716
  }
987
- // Node information
988
717
  this.systemInformation.nodeVersion = process.versions.node;
989
718
  const versionMajor = parseInt(this.systemInformation.nodeVersion.split('.')[0]);
990
719
  const versionMinor = parseInt(this.systemInformation.nodeVersion.split('.')[1]);
991
720
  const versionPatch = parseInt(this.systemInformation.nodeVersion.split('.')[2]);
992
- // Host system information
993
721
  this.systemInformation.hostname = os.hostname();
994
722
  this.systemInformation.user = os.userInfo().username;
995
- this.systemInformation.osType = os.type(); // "Windows_NT", "Darwin", etc.
996
- this.systemInformation.osRelease = os.release(); // Kernel version
997
- this.systemInformation.osPlatform = os.platform(); // "win32", "linux", "darwin", etc.
998
- this.systemInformation.osArch = os.arch(); // "x64", "arm", etc.
999
- this.systemInformation.totalMemory = formatMemoryUsage(os.totalmem());
1000
- this.systemInformation.freeMemory = formatMemoryUsage(os.freemem());
1001
- this.systemInformation.systemUptime = formatOsUpTime(os.uptime());
1002
- this.systemInformation.processUptime = formatOsUpTime(Math.floor(process.uptime()));
1003
- this.systemInformation.cpuUsage = '0.00 %';
1004
- this.systemInformation.rss = formatMemoryUsage(process.memoryUsage().rss);
1005
- this.systemInformation.heapTotal = formatMemoryUsage(process.memoryUsage().heapTotal);
1006
- this.systemInformation.heapUsed = formatMemoryUsage(process.memoryUsage().heapUsed);
1007
- // Log the system information
723
+ this.systemInformation.osType = os.type();
724
+ this.systemInformation.osRelease = os.release();
725
+ this.systemInformation.osPlatform = os.platform();
726
+ this.systemInformation.osArch = os.arch();
727
+ this.systemInformation.totalMemory = formatBytes(os.totalmem());
728
+ this.systemInformation.freeMemory = formatBytes(os.freemem());
729
+ this.systemInformation.systemUptime = formatUptime(os.uptime());
730
+ this.systemInformation.processUptime = formatUptime(process.uptime());
731
+ this.systemInformation.cpuUsage = formatPercent(0);
732
+ this.systemInformation.processCpuUsage = formatPercent(0);
733
+ this.systemInformation.rss = formatBytes(process.memoryUsage().rss);
734
+ this.systemInformation.heapTotal = formatBytes(process.memoryUsage().heapTotal);
735
+ this.systemInformation.heapUsed = formatBytes(process.memoryUsage().heapUsed);
1008
736
  this.log.debug('Host System Information:');
1009
737
  this.log.debug(`- Hostname: ${this.systemInformation.hostname}`);
1010
738
  this.log.debug(`- User: ${this.systemInformation.user}`);
@@ -1024,17 +752,14 @@ export class Matterbridge extends EventEmitter {
1024
752
  this.log.debug(`- RSS: ${this.systemInformation.rss}`);
1025
753
  this.log.debug(`- Heap Total: ${this.systemInformation.heapTotal}`);
1026
754
  this.log.debug(`- Heap Used: ${this.systemInformation.heapUsed}`);
1027
- // Log directories
1028
755
  this.log.debug(`Root Directory: ${this.rootDirectory}`);
1029
756
  this.log.debug(`Home Directory: ${this.homeDirectory}`);
1030
757
  this.log.debug(`Matterbridge Directory: ${this.matterbridgeDirectory}`);
1031
758
  this.log.debug(`Matterbridge Plugin Directory: ${this.matterbridgePluginDirectory}`);
1032
759
  this.log.debug(`Matterbridge Matter Certificate Directory: ${this.matterbridgeCertDirectory}`);
1033
- // Global node_modules directory
1034
760
  if (this.nodeContext)
1035
761
  this.globalModulesDirectory = await this.nodeContext.get('globalModulesDirectory', '');
1036
762
  if (this.globalModulesDirectory === '') {
1037
- // First run of Matterbridge so the node storage is empty
1038
763
  this.log.debug(`Getting global node_modules directory...`);
1039
764
  try {
1040
765
  const { getGlobalNodeModules } = await import('./utils/network.js');
@@ -1047,7 +772,6 @@ export class Matterbridge extends EventEmitter {
1047
772
  }
1048
773
  }
1049
774
  else {
1050
- // The global node_modules directory is already set in the node storage and we check if it is still valid
1051
775
  this.log.debug(`Checking global node_modules directory: ${this.globalModulesDirectory}`);
1052
776
  try {
1053
777
  const { getGlobalNodeModules } = await import('./utils/network.js');
@@ -1059,37 +783,25 @@ export class Matterbridge extends EventEmitter {
1059
783
  this.log.error(`Error checking global node_modules directory: ${error}`);
1060
784
  }
1061
785
  }
1062
- // Matterbridge version
1063
786
  this.log.debug(`Reading matterbridge package.json...`);
1064
787
  const packageJson = JSON.parse(await fs.readFile(path.join(this.rootDirectory, 'package.json'), 'utf-8'));
1065
788
  this.matterbridgeVersion = this.matterbridgeLatestVersion = this.matterbridgeDevVersion = packageJson.version;
1066
789
  this.log.debug(`Matterbridge Version: ${this.matterbridgeVersion}`);
1067
- // Matterbridge latest version (will be set in the checkUpdate function)
1068
790
  if (this.nodeContext)
1069
791
  this.matterbridgeLatestVersion = await this.nodeContext.get('matterbridgeLatestVersion', this.matterbridgeVersion);
1070
792
  this.log.debug(`Matterbridge Latest Version: ${this.matterbridgeLatestVersion}`);
1071
- // Matterbridge dev version (will be set in the checkUpdate function)
1072
793
  if (this.nodeContext)
1073
794
  this.matterbridgeDevVersion = await this.nodeContext.get('matterbridgeDevVersion', this.matterbridgeVersion);
1074
795
  this.log.debug(`Matterbridge Dev Version: ${this.matterbridgeDevVersion}`);
1075
- // Frontend version
1076
796
  this.log.debug(`Reading frontend package.json...`);
1077
797
  const frontendPackageJson = JSON.parse(await fs.readFile(path.join(this.rootDirectory, 'frontend/package.json'), 'utf8'));
1078
798
  this.frontendVersion = frontendPackageJson.version;
1079
799
  this.log.debug(`Frontend version ${CYAN}${this.frontendVersion}${db}`);
1080
- // Current working directory
1081
800
  const currentDir = process.cwd();
1082
801
  this.log.debug(`Current Working Directory: ${currentDir}`);
1083
- // Command line arguments (excluding 'node' and the script name)
1084
802
  const cmdArgs = process.argv.slice(2).join(' ');
1085
803
  this.log.debug(`Command Line Arguments: ${cmdArgs}`);
1086
804
  }
1087
- /**
1088
- * Set the logger logLevel for the Matterbridge classes and call onChangeLoggerLevel() for each plugin.
1089
- *
1090
- * @param {LogLevel} logLevel The logger logLevel to set.
1091
- * @returns {Promise<void>} A promise that resolves when the logLevel has been set.
1092
- */
1093
805
  async setLogLevel(logLevel) {
1094
806
  this.log.logLevel = logLevel;
1095
807
  this.frontend.logLevel = logLevel;
@@ -1099,86 +811,57 @@ export class Matterbridge extends EventEmitter {
1099
811
  for (const plugin of this.plugins) {
1100
812
  if (!plugin.platform || !plugin.platform.log || !plugin.platform.config)
1101
813
  continue;
1102
- plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : logLevel;
1103
- await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" /* LogLevel.DEBUG */ : logLevel);
1104
- }
1105
- // Set the global logger callback for the WebSocketServer to the common minimum logLevel
1106
- let callbackLogLevel = "notice" /* LogLevel.NOTICE */;
1107
- if (logLevel === "info" /* LogLevel.INFO */ || Logger.level === MatterLogLevel.INFO)
1108
- callbackLogLevel = "info" /* LogLevel.INFO */;
1109
- if (logLevel === "debug" /* LogLevel.DEBUG */ || Logger.level === MatterLogLevel.DEBUG)
1110
- callbackLogLevel = "debug" /* LogLevel.DEBUG */;
814
+ plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" : logLevel;
815
+ await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" : logLevel);
816
+ }
817
+ let callbackLogLevel = "notice";
818
+ if (logLevel === "info" || Logger.level === MatterLogLevel.INFO)
819
+ callbackLogLevel = "info";
820
+ if (logLevel === "debug" || Logger.level === MatterLogLevel.DEBUG)
821
+ callbackLogLevel = "debug";
1111
822
  AnsiLogger.setGlobalCallbackLevel(callbackLogLevel);
1112
823
  this.log.debug(`WebSocketServer logger global callback set to ${callbackLogLevel}`);
1113
824
  }
1114
- /**
1115
- * Get the current logger logLevel.
1116
- *
1117
- * @returns {LogLevel} The current logger logLevel.
1118
- */
1119
825
  getLogLevel() {
1120
826
  return this.log.logLevel;
1121
827
  }
1122
- /**
1123
- * Creates a MatterLogger function to show the matter.js log messages in AnsiLogger (for the frontend).
1124
- * It also logs to file (matter.log) if fileLogger is true.
1125
- *
1126
- * @param {boolean} fileLogger - Whether to log to file or not.
1127
- * @returns {Function} The MatterLogger function. \x1b[35m for violet \x1b[34m is blue
1128
- */
1129
828
  createDestinationMatterLogger(fileLogger) {
1130
- this.matterLog.logNameColor = '\x1b[34m'; // Blue matter.js Logger
829
+ this.matterLog.logNameColor = '\x1b[34m';
1131
830
  if (fileLogger) {
1132
831
  this.matterLog.logFilePath = path.join(this.matterbridgeDirectory, MATTER_LOGGER_FILE);
1133
832
  }
1134
833
  return (text, message) => {
1135
- // 2024-08-21 08:55:19.488 DEBUG InteractionMessenger Sending DataReport chunk with 28 attributes and 0 events: 1004 bytes
1136
834
  const logger = text.slice(44, 44 + 20).trim();
1137
835
  const msg = text.slice(65);
1138
836
  this.matterLog.logName = logger;
1139
837
  switch (message.level) {
1140
838
  case MatterLogLevel.DEBUG:
1141
- this.matterLog.log("debug" /* LogLevel.DEBUG */, msg);
839
+ this.matterLog.log("debug", msg);
1142
840
  break;
1143
841
  case MatterLogLevel.INFO:
1144
- this.matterLog.log("info" /* LogLevel.INFO */, msg);
842
+ this.matterLog.log("info", msg);
1145
843
  break;
1146
844
  case MatterLogLevel.NOTICE:
1147
- this.matterLog.log("notice" /* LogLevel.NOTICE */, msg);
845
+ this.matterLog.log("notice", msg);
1148
846
  break;
1149
847
  case MatterLogLevel.WARN:
1150
- this.matterLog.log("warn" /* LogLevel.WARN */, msg);
848
+ this.matterLog.log("warn", msg);
1151
849
  break;
1152
850
  case MatterLogLevel.ERROR:
1153
- this.matterLog.log("error" /* LogLevel.ERROR */, msg);
851
+ this.matterLog.log("error", msg);
1154
852
  break;
1155
853
  case MatterLogLevel.FATAL:
1156
- this.matterLog.log("fatal" /* LogLevel.FATAL */, msg);
854
+ this.matterLog.log("fatal", msg);
1157
855
  break;
1158
856
  }
1159
857
  };
1160
858
  }
1161
- /**
1162
- * Restarts the process by exiting the current instance and loading a new instance (/api/restart).
1163
- *
1164
- * @returns {Promise<void>} A promise that resolves when the restart is completed.
1165
- */
1166
859
  async restartProcess() {
1167
860
  await this.cleanup('restarting...', true);
1168
861
  }
1169
- /**
1170
- * Shut down the process (/api/shutdown).
1171
- *
1172
- * @returns {Promise<void>} A promise that resolves when the shutdown is completed.
1173
- */
1174
862
  async shutdownProcess() {
1175
863
  await this.cleanup('shutting down...', false);
1176
864
  }
1177
- /**
1178
- * Update matterbridge and shut down the process (virtual device 'Update Matterbridge').
1179
- *
1180
- * @returns {Promise<void>} A promise that resolves when the update is completed.
1181
- */
1182
865
  async updateProcess() {
1183
866
  this.log.info('Updating matterbridge...');
1184
867
  try {
@@ -1192,13 +875,6 @@ export class Matterbridge extends EventEmitter {
1192
875
  this.frontend.wssSendRestartRequired();
1193
876
  await this.cleanup('updating...', false);
1194
877
  }
1195
- /**
1196
- * Unregister all devices and shut down the process (/api/unregister).
1197
- *
1198
- * @param {number} [timeout] - The timeout duration to wait for the message exchange to complete in milliseconds. Default is 1000.
1199
- *
1200
- * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1201
- */
1202
878
  async unregisterAndShutdownProcess(timeout = 1000) {
1203
879
  this.log.info('Unregistering all devices and shutting down...');
1204
880
  for (const plugin of this.plugins.array()) {
@@ -1210,71 +886,46 @@ export class Matterbridge extends EventEmitter {
1210
886
  await this.removeAllBridgedEndpoints(plugin.name, 100);
1211
887
  }
1212
888
  this.log.debug('Waiting for the MessageExchange to finish...');
1213
- await wait(timeout); // Wait for MessageExchange to finish
889
+ await wait(timeout);
1214
890
  this.log.debug('Cleaning up and shutting down...');
1215
891
  await this.cleanup('unregistered all devices and shutting down...', false, timeout);
1216
892
  }
1217
- /**
1218
- * Reset commissioning and shut down the process (/api/reset).
1219
- *
1220
- * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1221
- */
1222
893
  async shutdownProcessAndReset() {
1223
894
  await this.cleanup('shutting down with reset...', false);
1224
895
  }
1225
- /**
1226
- * Factory reset and shut down the process (/api/factory-reset).
1227
- *
1228
- * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1229
- */
1230
896
  async shutdownProcessAndFactoryReset() {
1231
897
  await this.cleanup('shutting down with factory reset...', false);
1232
898
  }
1233
- /**
1234
- * Cleans up the Matterbridge instance.
1235
- *
1236
- * @param {string} message - The cleanup message.
1237
- * @param {boolean} [restart] - Indicates whether to restart the instance after cleanup. Default is `false`.
1238
- * @param {number} [timeout] - The timeout duration to wait for the message exchange to complete in milliseconds. Default is 1000.
1239
- *
1240
- * @returns {Promise<void>} A promise that resolves when the cleanup is completed.
1241
- */
1242
899
  async cleanup(message, restart = false, timeout = 1000) {
1243
900
  if (this.initialized && !this.hasCleanupStarted) {
1244
901
  this.emit('cleanup_started');
1245
902
  this.hasCleanupStarted = true;
1246
903
  this.log.info(message);
1247
- // Clear the start matter interval
1248
904
  if (this.startMatterInterval) {
1249
905
  clearInterval(this.startMatterInterval);
1250
906
  this.startMatterInterval = undefined;
1251
907
  this.log.debug('Start matter interval cleared');
1252
908
  }
1253
- // Clear the check update timeout
1254
909
  if (this.checkUpdateTimeout) {
1255
910
  clearTimeout(this.checkUpdateTimeout);
1256
911
  this.checkUpdateTimeout = undefined;
1257
912
  this.log.debug('Check update timeout cleared');
1258
913
  }
1259
- // Clear the check update interval
1260
914
  if (this.checkUpdateInterval) {
1261
915
  clearInterval(this.checkUpdateInterval);
1262
916
  this.checkUpdateInterval = undefined;
1263
917
  this.log.debug('Check update interval cleared');
1264
918
  }
1265
- // Clear the configure timeout
1266
919
  if (this.configureTimeout) {
1267
920
  clearTimeout(this.configureTimeout);
1268
921
  this.configureTimeout = undefined;
1269
922
  this.log.debug('Matterbridge configure timeout cleared');
1270
923
  }
1271
- // Clear the reachability timeout
1272
924
  if (this.reachabilityTimeout) {
1273
925
  clearTimeout(this.reachabilityTimeout);
1274
926
  this.reachabilityTimeout = undefined;
1275
927
  this.log.debug('Matterbridge reachability timeout cleared');
1276
928
  }
1277
- // Call the shutdown method of each plugin and clear the plugins reachability timeout
1278
929
  for (const plugin of this.plugins) {
1279
930
  if (!plugin.enabled || plugin.error)
1280
931
  continue;
@@ -1285,7 +936,6 @@ export class Matterbridge extends EventEmitter {
1285
936
  this.log.debug(`Plugin ${plg}${plugin.name}${db} reachability timeout cleared`);
1286
937
  }
1287
938
  }
1288
- // Stop matter server nodes
1289
939
  this.log.notice(`Stopping matter server nodes in ${this.bridgeMode} mode...`);
1290
940
  if (timeout > 0) {
1291
941
  this.log.debug(`Waiting ${timeout}ms for the MessageExchange to finish...`);
@@ -1312,7 +962,6 @@ export class Matterbridge extends EventEmitter {
1312
962
  }
1313
963
  }
1314
964
  this.log.notice('Stopped matter server nodes');
1315
- // Matter commisioning reset
1316
965
  if (message === 'shutting down with reset...') {
1317
966
  this.log.info('Resetting Matterbridge commissioning information...');
1318
967
  await this.matterStorageManager?.createContext('events')?.clearAll();
@@ -1322,7 +971,6 @@ export class Matterbridge extends EventEmitter {
1322
971
  await this.matterbridgeContext?.clearAll();
1323
972
  this.log.info('Matter storage reset done! Remove the bridge from the controller.');
1324
973
  }
1325
- // Unregister all devices
1326
974
  if (message === 'unregistered all devices and shutting down...') {
1327
975
  if (this.bridgeMode === 'bridge') {
1328
976
  await this.matterStorageManager?.createContext('root')?.createContext('parts')?.createContext('Matterbridge')?.createContext('parts')?.clearAll();
@@ -1340,33 +988,15 @@ export class Matterbridge extends EventEmitter {
1340
988
  }
1341
989
  this.log.info('Matter storage reset done!');
1342
990
  }
1343
- // Stop matter storage
1344
991
  await this.stopMatterStorage();
1345
- // Stop the frontend
1346
992
  await this.frontend.stop();
1347
993
  this.frontend.destroy();
1348
- // Close PluginManager and DeviceManager
1349
994
  this.plugins.destroy();
1350
995
  this.devices.destroy();
1351
- // Close the matterbridge node storage and context
1352
996
  if (this.nodeStorage && this.nodeContext) {
1353
- /*
1354
- TODO: Implement serialization of registered devices in edge mode
1355
- this.log.info('Saving registered devices...');
1356
- const serializedRegisteredDevices: SerializedMatterbridgeEndpoint[] = [];
1357
- this.devices.forEach(async (device) => {
1358
- const serializedMatterbridgeDevice = MatterbridgeEndpoint.serialize(device);
1359
- // this.log.info(`- ${serializedMatterbridgeDevice.deviceName}${rs}\n`, serializedMatterbridgeDevice);
1360
- if (serializedMatterbridgeDevice) serializedRegisteredDevices.push(serializedMatterbridgeDevice);
1361
- });
1362
- await this.nodeContext.set<SerializedMatterbridgeEndpoint[]>('devices', serializedRegisteredDevices);
1363
- this.log.info(`Saved registered devices (${serializedRegisteredDevices?.length})`);
1364
- */
1365
- // Clear nodeContext and nodeStorage (they just need 1000ms to write the data to disk)
1366
997
  this.log.debug(`Closing node storage context for ${plg}Matterbridge${db}...`);
1367
998
  await this.nodeContext.close();
1368
999
  this.nodeContext = undefined;
1369
- // Clear nodeContext for each plugin (they just need 1000ms to write the data to disk)
1370
1000
  for (const plugin of this.plugins) {
1371
1001
  if (plugin.nodeContext) {
1372
1002
  this.log.debug(`Closing node storage context for plugin ${plg}${plugin.name}${db}...`);
@@ -1383,10 +1013,8 @@ export class Matterbridge extends EventEmitter {
1383
1013
  }
1384
1014
  this.plugins.clear();
1385
1015
  this.devices.clear();
1386
- // Factory reset
1387
1016
  if (message === 'shutting down with factory reset...') {
1388
1017
  try {
1389
- // Delete matter storage directory with its subdirectories and backup
1390
1018
  const dir = path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME);
1391
1019
  this.log.info(`Removing matter storage directory: ${dir}`);
1392
1020
  await fs.rm(dir, { recursive: true });
@@ -1395,13 +1023,11 @@ export class Matterbridge extends EventEmitter {
1395
1023
  await fs.rm(backup, { recursive: true });
1396
1024
  }
1397
1025
  catch (error) {
1398
- // istanbul ignore next if
1399
1026
  if (error instanceof Error && error.code !== 'ENOENT') {
1400
1027
  this.log.error(`Error removing matter storage directory: ${error}`);
1401
1028
  }
1402
1029
  }
1403
1030
  try {
1404
- // Delete matterbridge storage directory with its subdirectories and backup
1405
1031
  const dir = path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR);
1406
1032
  this.log.info(`Removing matterbridge storage directory: ${dir}`);
1407
1033
  await fs.rm(dir, { recursive: true });
@@ -1410,20 +1036,18 @@ export class Matterbridge extends EventEmitter {
1410
1036
  await fs.rm(backup, { recursive: true });
1411
1037
  }
1412
1038
  catch (error) {
1413
- // istanbul ignore next if
1414
1039
  if (error instanceof Error && error.code !== 'ENOENT') {
1415
1040
  this.log.error(`Error removing matterbridge storage directory: ${error}`);
1416
1041
  }
1417
1042
  }
1418
1043
  this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
1419
1044
  }
1420
- // Deregisters the process handlers
1421
1045
  this.deregisterProcessHandlers();
1422
1046
  if (restart) {
1423
1047
  if (message === 'updating...') {
1424
1048
  this.log.info('Cleanup completed. Updating...');
1425
1049
  Matterbridge.instance = undefined;
1426
- this.emit('update'); // Restart the process but the update has been done before. TODO move all updates to the cli
1050
+ this.emit('update');
1427
1051
  }
1428
1052
  else if (message === 'restarting...') {
1429
1053
  this.log.info('Cleanup completed. Restarting...');
@@ -1451,14 +1075,7 @@ export class Matterbridge extends EventEmitter {
1451
1075
  this.log.debug('Cleanup already started...');
1452
1076
  }
1453
1077
  }
1454
- /**
1455
- * Starts the Matterbridge in bridge mode.
1456
- *
1457
- * @private
1458
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1459
- */
1460
1078
  async startBridge() {
1461
- // Plugins are configured by a timer when matter server is started and plugin.configured is set to true
1462
1079
  if (!this.matterStorageManager)
1463
1080
  throw new Error('No storage manager initialized');
1464
1081
  if (!this.matterbridgeContext)
@@ -1497,16 +1114,13 @@ export class Matterbridge extends EventEmitter {
1497
1114
  clearInterval(this.startMatterInterval);
1498
1115
  this.startMatterInterval = undefined;
1499
1116
  this.log.debug('Cleared startMatterInterval interval for Matterbridge');
1500
- // Start the Matter server node
1501
- this.startServerNode(this.serverNode); // We don't await this, because the server node is started in the background
1502
- // Start the Matter server node of single devices in mode 'server'
1117
+ this.startServerNode(this.serverNode);
1503
1118
  for (const device of this.devices.array()) {
1504
1119
  if (device.mode === 'server' && device.serverNode) {
1505
1120
  this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
1506
- this.startServerNode(device.serverNode); // We don't await this, because the server node is started in the background
1121
+ this.startServerNode(device.serverNode);
1507
1122
  }
1508
1123
  }
1509
- // Configure the plugins
1510
1124
  this.configureTimeout = setTimeout(async () => {
1511
1125
  for (const plugin of this.plugins.array()) {
1512
1126
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1524,40 +1138,28 @@ export class Matterbridge extends EventEmitter {
1524
1138
  }
1525
1139
  this.frontend.wssSendRefreshRequired('plugins');
1526
1140
  }, 30 * 1000).unref();
1527
- // Setting reachability to true
1528
1141
  this.reachabilityTimeout = setTimeout(() => {
1529
1142
  this.log.info(`Setting reachability to true for ${plg}Matterbridge${db}`);
1530
1143
  if (this.aggregatorNode)
1531
1144
  this.setAggregatorReachability(this.aggregatorNode, true);
1532
1145
  }, 60 * 1000).unref();
1533
- // Logger.get('LogServerNode').info(this.serverNode);
1534
1146
  this.emit('bridge_started');
1535
1147
  this.log.notice('Matterbridge bridge started successfully');
1536
1148
  this.frontend.wssSendRefreshRequired('settings');
1537
1149
  this.frontend.wssSendRefreshRequired('plugins');
1538
1150
  }, this.startMatterIntervalMs);
1539
1151
  }
1540
- /**
1541
- * Starts the Matterbridge in childbridge mode.
1542
- *
1543
- * @param {number} [delay] - The delay before starting the childbridge. Default is 1000 milliseconds.
1544
- *
1545
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1546
- */
1547
1152
  async startChildbridge(delay = 1000) {
1548
1153
  if (!this.matterStorageManager)
1549
1154
  throw new Error('No storage manager initialized');
1550
- // Load with await all plugins but don't start them. We get the platform.type to pre-create server nodes for DynamicPlatform plugins
1551
1155
  this.log.debug('Loading all plugins in childbridge mode...');
1552
1156
  await this.startPlugins(true, false);
1553
- // Create server nodes for DynamicPlatform plugins and start all plugins in the background
1554
1157
  this.log.debug('Creating server nodes for DynamicPlatform plugins and starting all plugins in childbridge mode...');
1555
1158
  for (const plugin of this.plugins.array().filter((p) => p.enabled && !p.error)) {
1556
1159
  if (plugin.type === 'DynamicPlatform')
1557
1160
  await this.createDynamicPlugin(plugin);
1558
- this.plugins.start(plugin, 'Matterbridge is starting'); // Start the plugin in the background
1161
+ this.plugins.start(plugin, 'Matterbridge is starting');
1559
1162
  }
1560
- // Start the Matterbridge in childbridge mode when all plugins are loaded and started
1561
1163
  this.log.debug('Starting start matter interval in childbridge mode...');
1562
1164
  let failCount = 0;
1563
1165
  this.startMatterInterval = setInterval(async () => {
@@ -1591,9 +1193,8 @@ export class Matterbridge extends EventEmitter {
1591
1193
  clearInterval(this.startMatterInterval);
1592
1194
  this.startMatterInterval = undefined;
1593
1195
  if (delay > 0)
1594
- await wait(delay); // Wait for the specified delay to ensure all plugins server nodes are ready
1196
+ await wait(delay);
1595
1197
  this.log.debug('Cleared startMatterInterval interval in childbridge mode');
1596
- // Configure the plugins
1597
1198
  this.configureTimeout = setTimeout(async () => {
1598
1199
  for (const plugin of this.plugins.array()) {
1599
1200
  if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
@@ -1618,7 +1219,6 @@ export class Matterbridge extends EventEmitter {
1618
1219
  this.log.error(`Plugin ${plg}${plugin.name}${er} didn't register any devices to Matterbridge. Verify the plugin configuration.`);
1619
1220
  continue;
1620
1221
  }
1621
- // istanbul ignore next if cause is just a safety check
1622
1222
  if (!plugin.serverNode) {
1623
1223
  this.log.error(`Server node not found for plugin ${plg}${plugin.name}${er}`);
1624
1224
  continue;
@@ -1631,252 +1231,28 @@ export class Matterbridge extends EventEmitter {
1631
1231
  this.log.error(`Node storage context not found for plugin ${plg}${plugin.name}${er}`);
1632
1232
  continue;
1633
1233
  }
1634
- // Start the Matter server node
1635
- this.startServerNode(plugin.serverNode); // We don't await this, because the server node is started in the background
1636
- // Setting reachability to true
1234
+ this.startServerNode(plugin.serverNode);
1637
1235
  plugin.reachabilityTimeout = setTimeout(() => {
1638
1236
  this.log.info(`Setting reachability to true for ${plg}${plugin.name}${nf}`);
1639
1237
  if (plugin.type === 'DynamicPlatform' && plugin.aggregatorNode)
1640
1238
  this.setAggregatorReachability(plugin.aggregatorNode, true);
1641
1239
  }, 60 * 1000).unref();
1642
1240
  }
1643
- // Start the Matter server node of single devices in mode 'server'
1644
1241
  for (const device of this.devices.array()) {
1645
1242
  if (device.mode === 'server' && device.serverNode) {
1646
1243
  this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
1647
- this.startServerNode(device.serverNode); // We don't await this, because the server node is started in the background
1244
+ this.startServerNode(device.serverNode);
1648
1245
  }
1649
1246
  }
1650
- // Logger.get('LogServerNode').info(this.serverNode);
1651
1247
  this.emit('childbridge_started');
1652
1248
  this.log.notice('Matterbridge childbridge started successfully');
1653
1249
  this.frontend.wssSendRefreshRequired('settings');
1654
1250
  this.frontend.wssSendRefreshRequired('plugins');
1655
1251
  }, this.startMatterIntervalMs);
1656
1252
  }
1657
- /**
1658
- * Starts the Matterbridge controller.
1659
- *
1660
- * @private
1661
- * @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
1662
- */
1663
1253
  async startController() {
1664
- /*
1665
- if (!this.matterStorageManager) {
1666
- this.log.error('No storage manager initialized');
1667
- await this.cleanup('No storage manager initialized');
1668
- return;
1669
- }
1670
- this.log.info('Creating context: mattercontrollerContext');
1671
- this.controllerContext = this.matterStorageManager.createContext('mattercontrollerContext');
1672
- if (!this.controllerContext) {
1673
- this.log.error('No storage context mattercontrollerContext initialized');
1674
- await this.cleanup('No storage context mattercontrollerContext initialized');
1675
- return;
1676
- }
1677
-
1678
- this.log.debug('Starting matterbridge in mode', this.bridgeMode);
1679
- this.matterServer = await this.createMatterServer(this.storageManager);
1680
- this.log.info('Creating matter commissioning controller');
1681
- this.commissioningController = new CommissioningController({
1682
- autoConnect: false,
1683
- });
1684
- this.log.info('Adding matter commissioning controller to matter server');
1685
- await this.matterServer.addCommissioningController(this.commissioningController);
1686
-
1687
- this.log.info('Starting matter server');
1688
- await this.matterServer.start();
1689
- this.log.info('Matter server started');
1690
- const commissioningOptions: ControllerCommissioningFlowOptions = {
1691
- regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
1692
- regulatoryCountryCode: 'XX',
1693
- };
1694
- const commissioningController = new CommissioningController({
1695
- environment: {
1696
- environment,
1697
- id: uniqueId,
1698
- },
1699
- autoConnect: false, // Do not auto connect to the commissioned nodes
1700
- adminFabricLabel,
1701
- });
1702
-
1703
- if (hasParameter('pairingcode')) {
1704
- this.log.info('Pairing device with pairingcode:', getParameter('pairingcode'));
1705
- const pairingCode = getParameter('pairingcode');
1706
- const ip = this.controllerContext.has('ip') ? this.controllerContext.get<string>('ip') : undefined;
1707
- const port = this.controllerContext.has('port') ? this.controllerContext.get<number>('port') : undefined;
1708
-
1709
- let longDiscriminator, setupPin, shortDiscriminator;
1710
- if (pairingCode !== undefined) {
1711
- const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
1712
- shortDiscriminator = pairingCodeCodec.shortDiscriminator;
1713
- longDiscriminator = undefined;
1714
- setupPin = pairingCodeCodec.passcode;
1715
- this.log.info(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
1716
- } else {
1717
- longDiscriminator = await this.controllerContext.get('longDiscriminator', 3840);
1718
- if (longDiscriminator > 4095) throw new Error('Discriminator value must be less than 4096');
1719
- setupPin = this.controllerContext.get('pin', 20202021);
1720
- }
1721
- if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {
1722
- throw new Error('Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode');
1723
- }
1724
-
1725
- const options = {
1726
- commissioning: commissioningOptions,
1727
- discovery: {
1728
- knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: 'udp' } : undefined,
1729
- identifierData: longDiscriminator !== undefined ? { longDiscriminator } : shortDiscriminator !== undefined ? { shortDiscriminator } : {},
1730
- },
1731
- passcode: setupPin,
1732
- } as NodeCommissioningOptions;
1733
- this.log.info('Commissioning with options:', options);
1734
- const nodeId = await this.commissioningController.commissionNode(options);
1735
- this.log.info(`Commissioning successfully done with nodeId: ${nodeId}`);
1736
- this.log.info('ActiveSessionInformation:', this.commissioningController.getActiveSessionInformation());
1737
- } // (hasParameter('pairingcode'))
1738
-
1739
- if (hasParameter('unpairall')) {
1740
- this.log.info('***Commissioning controller unpairing all nodes...');
1741
- const nodeIds = this.commissioningController.getCommissionedNodes();
1742
- for (const nodeId of nodeIds) {
1743
- this.log.info('***Commissioning controller unpairing node:', nodeId);
1744
- await this.commissioningController.removeNode(nodeId);
1745
- }
1746
- return;
1747
- }
1748
-
1749
- if (hasParameter('discover')) {
1750
- // const discover = await this.commissioningController.discoverCommissionableDevices({ productId: 0x8000, deviceType: 0xfff1 });
1751
- // console.log(discover);
1752
- }
1753
-
1754
- if (!this.commissioningController.isCommissioned()) {
1755
- this.log.info('***Commissioning controller is not commissioned: use matterbridge -controller -pairingcode [pairingcode] to commission a device');
1756
- return;
1757
- }
1758
-
1759
- const nodeIds = this.commissioningController.getCommissionedNodes();
1760
- this.log.info(`***Commissioning controller is commissioned ${this.commissioningController.isCommissioned()} and has ${nodeIds.length} nodes commisioned: `);
1761
- for (const nodeId of nodeIds) {
1762
- this.log.info(`***Connecting to commissioned node: ${nodeId}`);
1763
-
1764
- const node = await this.commissioningController.connectNode(nodeId, {
1765
- autoSubscribe: false,
1766
- attributeChangedCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, attributeName }, value }) =>
1767
- this.log.info(`***Commissioning controller attributeChangedCallback ${peerNodeId}: attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(value)}`),
1768
- eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>
1769
- this.log.info(`***Commissioning controller eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(events)}`),
1770
- stateInformationCallback: (peerNodeId, info) => {
1771
- switch (info) {
1772
- case NodeStateInformation.Connected:
1773
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
1774
- break;
1775
- case NodeStateInformation.Disconnected:
1776
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
1777
- break;
1778
- case NodeStateInformation.Reconnecting:
1779
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
1780
- break;
1781
- case NodeStateInformation.WaitingForDeviceDiscovery:
1782
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`);
1783
- break;
1784
- case NodeStateInformation.StructureChanged:
1785
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
1786
- break;
1787
- case NodeStateInformation.Decommissioned:
1788
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
1789
- break;
1790
- default:
1791
- this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} NodeStateInformation.${info}`);
1792
- break;
1793
- }
1794
- },
1795
- });
1796
-
1797
- node.logStructure();
1798
-
1799
- // Get the interaction client
1800
- this.log.info('Getting the interaction client');
1801
- const interactionClient = await node.getInteractionClient();
1802
- let cluster;
1803
- let attributes;
1804
-
1805
- // Log BasicInformationCluster
1806
- cluster = BasicInformationCluster;
1807
- attributes = await interactionClient.getMultipleAttributes({
1808
- attributes: [{ clusterId: cluster.id }],
1809
- });
1810
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1811
- attributes.forEach((attribute) => {
1812
- this.log.info(
1813
- `- 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}`,
1814
- );
1815
- });
1816
-
1817
- // Log PowerSourceCluster
1818
- cluster = PowerSourceCluster;
1819
- attributes = await interactionClient.getMultipleAttributes({
1820
- attributes: [{ clusterId: cluster.id }],
1821
- });
1822
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1823
- attributes.forEach((attribute) => {
1824
- this.log.info(
1825
- `- 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}`,
1826
- );
1827
- });
1828
-
1829
- // Log ThreadNetworkDiagnostics
1830
- cluster = ThreadNetworkDiagnosticsCluster;
1831
- attributes = await interactionClient.getMultipleAttributes({
1832
- attributes: [{ clusterId: cluster.id }],
1833
- });
1834
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1835
- attributes.forEach((attribute) => {
1836
- this.log.info(
1837
- `- 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}`,
1838
- );
1839
- });
1840
-
1841
- // Log SwitchCluster
1842
- cluster = SwitchCluster;
1843
- attributes = await interactionClient.getMultipleAttributes({
1844
- attributes: [{ clusterId: cluster.id }],
1845
- });
1846
- if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
1847
- attributes.forEach((attribute) => {
1848
- this.log.info(
1849
- `- 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}`,
1850
- );
1851
- });
1852
-
1853
- this.log.info('Subscribing to all attributes and events');
1854
- await node.subscribeAllAttributesAndEvents({
1855
- ignoreInitialTriggers: false,
1856
- attributeChangedCallback: ({ path: { nodeId, clusterId, endpointId, attributeName }, version, value }) =>
1857
- this.log.info(
1858
- `***${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}`,
1859
- ),
1860
- eventTriggeredCallback: ({ path: { nodeId, clusterId, endpointId, eventName }, events }) => {
1861
- this.log.info(
1862
- `***${db}Commissioning controller eventTriggeredCallback: event ${BLUE}${nodeId}${db}/${or}${endpointId}${db}/${hk}${getClusterNameById(clusterId)}${db}/${zb}${eventName}${db} triggered with ${debugStringify(events ?? { none: true })}`,
1863
- );
1864
- },
1865
- });
1866
- this.log.info('Subscribed to all attributes and events');
1867
- }
1868
- */
1869
1254
  }
1870
- /** */
1871
- /** Matter.js methods */
1872
- /** */
1873
- /**
1874
- * Starts the matter storage with name Matterbridge, create the matterbridge context and performs a backup.
1875
- *
1876
- * @returns {Promise<void>} - A promise that resolves when the storage is started.
1877
- */
1878
1255
  async startMatterStorage() {
1879
- // Setup Matter storage
1880
1256
  this.log.info(`Starting matter node storage...`);
1881
1257
  this.matterStorageService = this.environment.get(StorageService);
1882
1258
  this.log.info(`Matter node storage service created: ${this.matterStorageService.location}`);
@@ -1884,17 +1260,8 @@ export class Matterbridge extends EventEmitter {
1884
1260
  this.log.info('Matter node storage manager "Matterbridge" created');
1885
1261
  this.matterbridgeContext = await this.createServerNodeContext('Matterbridge', 'Matterbridge', this.aggregatorDeviceType, this.aggregatorVendorId, this.aggregatorVendorName, this.aggregatorProductId, this.aggregatorProductName, this.aggregatorSerialNumber, this.aggregatorUniqueId);
1886
1262
  this.log.info('Matter node storage started');
1887
- // Backup matter storage since it is created/opened correctly
1888
1263
  await this.backupMatterStorage(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME), path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME + '.backup'));
1889
1264
  }
1890
- /**
1891
- * Makes a backup copy of the specified matter storage directory.
1892
- *
1893
- * @param {string} storageName - The name of the storage directory to be backed up.
1894
- * @param {string} backupName - The name of the backup directory to be created.
1895
- * @private
1896
- * @returns {Promise<void>} A promise that resolves when the has been done.
1897
- */
1898
1265
  async backupMatterStorage(storageName, backupName) {
1899
1266
  this.log.info('Creating matter node storage backup...');
1900
1267
  try {
@@ -1905,11 +1272,6 @@ export class Matterbridge extends EventEmitter {
1905
1272
  this.log.error(`Error creating matter node storage backup from ${storageName} to ${backupName}:`, error);
1906
1273
  }
1907
1274
  }
1908
- /**
1909
- * Stops the matter storage.
1910
- *
1911
- * @returns {Promise<void>} A promise that resolves when the storage is stopped.
1912
- */
1913
1275
  async stopMatterStorage() {
1914
1276
  this.log.info('Closing matter node storage...');
1915
1277
  await this.matterStorageManager?.close();
@@ -1918,20 +1280,6 @@ export class Matterbridge extends EventEmitter {
1918
1280
  this.matterbridgeContext = undefined;
1919
1281
  this.log.info('Matter node storage closed');
1920
1282
  }
1921
- /**
1922
- * Creates a server node storage context.
1923
- *
1924
- * @param {string} storeId - The storeId.
1925
- * @param {string} deviceName - The name of the device.
1926
- * @param {DeviceTypeId} deviceType - The device type of the device.
1927
- * @param {number} vendorId - The vendor ID.
1928
- * @param {string} vendorName - The vendor name.
1929
- * @param {number} productId - The product ID.
1930
- * @param {string} productName - The product name.
1931
- * @param {string} [serialNumber] - The serial number of the device (optional).
1932
- * @param {string} [uniqueId] - The unique ID of the device (optional).
1933
- * @returns {Promise<StorageContext>} The storage context for the commissioning server.
1934
- */
1935
1283
  async createServerNodeContext(storeId, deviceName, deviceType, vendorId, vendorName, productId, productName, serialNumber, uniqueId) {
1936
1284
  const { randomBytes } = await import('node:crypto');
1937
1285
  if (!this.matterStorageService)
@@ -1971,15 +1319,6 @@ export class Matterbridge extends EventEmitter {
1971
1319
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
1972
1320
  return storageContext;
1973
1321
  }
1974
- /**
1975
- * Creates a server node.
1976
- *
1977
- * @param {StorageContext} storageContext - The storage context for the server node.
1978
- * @param {number} [port] - The port number for the server node. Defaults to 5540.
1979
- * @param {number} [passcode] - The passcode for the server node. Defaults to 20242025.
1980
- * @param {number} [discriminator] - The discriminator for the server node. Defaults to 3850.
1981
- * @returns {Promise<ServerNode<ServerNode.RootEndpoint>>} A promise that resolves to the created server node.
1982
- */
1983
1322
  async createServerNode(storageContext, port = 5540, passcode = 20242025, discriminator = 3850) {
1984
1323
  const storeId = await storageContext.get('storeId');
1985
1324
  this.log.notice(`Creating server node for ${storeId} on port ${port} with passcode ${passcode} and discriminator ${discriminator}...`);
@@ -1989,37 +1328,24 @@ export class Matterbridge extends EventEmitter {
1989
1328
  this.log.debug(`- uniqueId: ${await storageContext.get('uniqueId')}`);
1990
1329
  this.log.debug(`- softwareVersion: ${await storageContext.get('softwareVersion')} softwareVersionString: ${await storageContext.get('softwareVersionString')}`);
1991
1330
  this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')} hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
1992
- /**
1993
- * Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
1994
- */
1995
1331
  const serverNode = await ServerNode.create({
1996
- // Required: Give the Node a unique ID which is used to store the state of this node
1997
1332
  id: storeId,
1998
- // Provide Network relevant configuration like the port
1999
- // Optional when operating only one device on a host, Default port is 5540
2000
1333
  network: {
2001
1334
  listeningAddressIpv4: this.ipv4Address,
2002
1335
  listeningAddressIpv6: this.ipv6Address,
2003
1336
  port,
2004
1337
  },
2005
- // Provide the certificate for the device
2006
1338
  operationalCredentials: {
2007
1339
  certification: this.certification,
2008
1340
  },
2009
- // Provide Commissioning relevant settings
2010
- // Optional for development/testing purposes
2011
1341
  commissioning: {
2012
1342
  passcode,
2013
1343
  discriminator,
2014
1344
  },
2015
- // Provide Node announcement settings
2016
- // Optional: If Ommitted some development defaults are used
2017
1345
  productDescription: {
2018
1346
  name: await storageContext.get('deviceName'),
2019
1347
  deviceType: DeviceTypeId(await storageContext.get('deviceType')),
2020
1348
  },
2021
- // Provide defaults for the BasicInformation cluster on the Root endpoint
2022
- // Optional: If Omitted some development defaults are used
2023
1349
  basicInformation: {
2024
1350
  vendorId: VendorId(await storageContext.get('vendorId')),
2025
1351
  vendorName: await storageContext.get('vendorName'),
@@ -2036,23 +1362,17 @@ export class Matterbridge extends EventEmitter {
2036
1362
  reachable: true,
2037
1363
  },
2038
1364
  });
2039
- /**
2040
- * This event is triggered when the device is initially commissioned successfully.
2041
- * This means: It is added to the first fabric.
2042
- */
2043
1365
  serverNode.lifecycle.commissioned.on(() => {
2044
1366
  this.log.notice(`Server node for ${storeId} was initially commissioned successfully!`);
2045
1367
  this.advertisingNodes.delete(storeId);
2046
1368
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2047
1369
  });
2048
- /** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
2049
1370
  serverNode.lifecycle.decommissioned.on(() => {
2050
1371
  this.log.notice(`Server node for ${storeId} was fully decommissioned successfully!`);
2051
1372
  this.advertisingNodes.delete(storeId);
2052
1373
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2053
1374
  this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
2054
1375
  });
2055
- /** This event is triggered when the device went online. This means that it is discoverable in the network. */
2056
1376
  serverNode.lifecycle.online.on(async () => {
2057
1377
  this.log.notice(`Server node for ${storeId} is online`);
2058
1378
  if (!serverNode.lifecycle.isCommissioned) {
@@ -2063,16 +1383,13 @@ export class Matterbridge extends EventEmitter {
2063
1383
  this.log.notice(`Manual pairing code: ${manualPairingCode}`);
2064
1384
  }
2065
1385
  else {
2066
- // istanbul ignore next
2067
1386
  this.log.notice(`Server node for ${storeId} is already commissioned. Waiting for controllers to connect ...`);
2068
- // istanbul ignore next
2069
1387
  this.advertisingNodes.delete(storeId);
2070
1388
  }
2071
1389
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2072
1390
  this.frontend.wssSendSnackbarMessage(`${storeId} is online`, 5, 'success');
2073
1391
  this.emit('online', storeId);
2074
1392
  });
2075
- /** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
2076
1393
  serverNode.lifecycle.offline.on(() => {
2077
1394
  this.log.notice(`Server node for ${storeId} is offline`);
2078
1395
  this.advertisingNodes.delete(storeId);
@@ -2080,15 +1397,11 @@ export class Matterbridge extends EventEmitter {
2080
1397
  this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
2081
1398
  this.emit('offline', storeId);
2082
1399
  });
2083
- /**
2084
- * This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
2085
- * information is needed.
2086
- */
2087
1400
  serverNode.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {
2088
1401
  let action = '';
2089
1402
  switch (fabricAction) {
2090
1403
  case FabricAction.Added:
2091
- this.advertisingNodes.delete(storeId); // The advertising stops when a fabric is added
1404
+ this.advertisingNodes.delete(storeId);
2092
1405
  action = 'added';
2093
1406
  break;
2094
1407
  case FabricAction.Removed:
@@ -2101,22 +1414,14 @@ export class Matterbridge extends EventEmitter {
2101
1414
  this.log.notice(`Commissioned fabric index ${fabricIndex} ${action} on server node for ${storeId}: ${debugStringify(serverNode.state.commissioning.fabrics[fabricIndex])}`);
2102
1415
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2103
1416
  });
2104
- /**
2105
- * This event is triggered when an operative new session was opened by a Controller.
2106
- * It is not triggered for the initial commissioning process, just afterwards for real connections.
2107
- */
2108
1417
  serverNode.events.sessions.opened.on((session) => {
2109
1418
  this.log.notice(`Session opened on server node for ${storeId}: ${debugStringify(session)}`);
2110
1419
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2111
1420
  });
2112
- /**
2113
- * This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
2114
- */
2115
1421
  serverNode.events.sessions.closed.on((session) => {
2116
1422
  this.log.notice(`Session closed on server node for ${storeId}: ${debugStringify(session)}`);
2117
1423
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
2118
1424
  });
2119
- /** This event is triggered when a subscription gets added or removed on an operative session. */
2120
1425
  serverNode.events.sessions.subscriptionsChanged.on((session) => {
2121
1426
  this.log.notice(`Session subscriptions changed on server node for ${storeId}: ${debugStringify(session)}`);
2122
1427
  this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
@@ -2124,12 +1429,6 @@ export class Matterbridge extends EventEmitter {
2124
1429
  this.log.info(`Created server node for ${storeId}`);
2125
1430
  return serverNode;
2126
1431
  }
2127
- /**
2128
- * Gets the matter sanitized data of the specified server node.
2129
- *
2130
- * @param {ServerNode} [serverNode] - The server node to start.
2131
- * @returns {ApiMatter} The sanitized data of the server node.
2132
- */
2133
1432
  getServerNodeData(serverNode) {
2134
1433
  const advertiseTime = this.advertisingNodes.get(serverNode.id) || 0;
2135
1434
  return {
@@ -2146,25 +1445,12 @@ export class Matterbridge extends EventEmitter {
2146
1445
  serialNumber: serverNode.state.basicInformation.serialNumber,
2147
1446
  };
2148
1447
  }
2149
- /**
2150
- * Starts the specified server node.
2151
- *
2152
- * @param {ServerNode} [matterServerNode] - The server node to start.
2153
- * @returns {Promise<void>} A promise that resolves when the server node has started.
2154
- */
2155
1448
  async startServerNode(matterServerNode) {
2156
1449
  if (!matterServerNode)
2157
1450
  return;
2158
1451
  this.log.notice(`Starting ${matterServerNode.id} server node`);
2159
1452
  await matterServerNode.start();
2160
1453
  }
2161
- /**
2162
- * Stops the specified server node.
2163
- *
2164
- * @param {ServerNode} matterServerNode - The server node to stop.
2165
- * @param {number} [timeout] - The timeout in milliseconds for stopping the server node. Defaults to 30 seconds.
2166
- * @returns {Promise<void>} A promise that resolves when the server node has stopped.
2167
- */
2168
1454
  async stopServerNode(matterServerNode, timeout = 30000) {
2169
1455
  if (!matterServerNode)
2170
1456
  return;
@@ -2177,25 +1463,12 @@ export class Matterbridge extends EventEmitter {
2177
1463
  this.log.error(`Failed to close ${matterServerNode.id} server node: ${error instanceof Error ? error.message : error}`);
2178
1464
  }
2179
1465
  }
2180
- /**
2181
- * Creates an aggregator node with the specified storage context.
2182
- *
2183
- * @param {StorageContext} storageContext - The storage context for the aggregator node.
2184
- * @returns {Promise<Endpoint<AggregatorEndpoint>>} A promise that resolves to the created aggregator node.
2185
- */
2186
1466
  async createAggregatorNode(storageContext) {
2187
1467
  this.log.notice(`Creating ${await storageContext.get('storeId')} aggregator...`);
2188
1468
  const aggregatorNode = new Endpoint(AggregatorEndpoint, { id: `${await storageContext.get('storeId')}` });
2189
1469
  this.log.info(`Created ${await storageContext.get('storeId')} aggregator`);
2190
1470
  return aggregatorNode;
2191
1471
  }
2192
- /**
2193
- * Creates and configures the server node for an accessory plugin for a given device.
2194
- *
2195
- * @param {Plugin} plugin - The plugin to configure.
2196
- * @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
2197
- * @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
2198
- */
2199
1472
  async createAccessoryPlugin(plugin, device) {
2200
1473
  if (!plugin.locked && device.deviceType && device.deviceName && device.vendorId && device.productId && device.vendorName && device.productName) {
2201
1474
  plugin.locked = true;
@@ -2207,12 +1480,6 @@ export class Matterbridge extends EventEmitter {
2207
1480
  await plugin.serverNode.add(device);
2208
1481
  }
2209
1482
  }
2210
- /**
2211
- * Creates and configures the server node and the aggregator node for a dynamic plugin.
2212
- *
2213
- * @param {Plugin} plugin - The plugin to configure.
2214
- * @returns {Promise<void>} A promise that resolves when the server node and the aggregator node for the dynamic plugin is created and configured.
2215
- */
2216
1483
  async createDynamicPlugin(plugin) {
2217
1484
  if (!plugin.locked) {
2218
1485
  plugin.locked = true;
@@ -2225,13 +1492,6 @@ export class Matterbridge extends EventEmitter {
2225
1492
  await plugin.serverNode.add(plugin.aggregatorNode);
2226
1493
  }
2227
1494
  }
2228
- /**
2229
- * Creates and configures the server node for a single not bridged device.
2230
- *
2231
- * @param {Plugin} plugin - The plugin to configure.
2232
- * @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
2233
- * @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
2234
- */
2235
1495
  async createDeviceServerNode(plugin, device) {
2236
1496
  if (device.mode === 'server' && !device.serverNode && device.deviceType && device.deviceName && device.vendorId && device.vendorName && device.productId && device.productName) {
2237
1497
  this.log.debug(`Creating device ${plg}${plugin.name}${db}:${dev}${device.deviceName}${db} server node...`);
@@ -2242,15 +1502,7 @@ export class Matterbridge extends EventEmitter {
2242
1502
  this.log.debug(`Added ${plg}${plugin.name}${db}:${dev}${device.deviceName}${db} to server node`);
2243
1503
  }
2244
1504
  }
2245
- /**
2246
- * Adds a MatterbridgeEndpoint to the specified plugin.
2247
- *
2248
- * @param {string} pluginName - The name of the plugin.
2249
- * @param {MatterbridgeEndpoint} device - The device to add as a bridged endpoint.
2250
- * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been added.
2251
- */
2252
1505
  async addBridgedEndpoint(pluginName, device) {
2253
- // Check if the plugin is registered
2254
1506
  const plugin = this.plugins.get(pluginName);
2255
1507
  if (!plugin) {
2256
1508
  this.log.error(`Error adding bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.id}${er}) plugin ${plg}${pluginName}${er} not found`);
@@ -2270,7 +1522,6 @@ export class Matterbridge extends EventEmitter {
2270
1522
  }
2271
1523
  else if (this.bridgeMode === 'bridge') {
2272
1524
  if (device.mode === 'matter') {
2273
- // Register and add the device to the matterbridge server node
2274
1525
  this.log.debug(`Adding matter endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge server node...`);
2275
1526
  if (!this.serverNode) {
2276
1527
  this.log.error('Server node not found for Matterbridge');
@@ -2287,7 +1538,6 @@ export class Matterbridge extends EventEmitter {
2287
1538
  }
2288
1539
  }
2289
1540
  else {
2290
- // Register and add the device to the matterbridge aggregator node
2291
1541
  this.log.debug(`Adding bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge aggregator node`);
2292
1542
  if (!this.aggregatorNode) {
2293
1543
  this.log.error('Aggregator node not found for Matterbridge');
@@ -2305,7 +1555,6 @@ export class Matterbridge extends EventEmitter {
2305
1555
  }
2306
1556
  }
2307
1557
  else if (this.bridgeMode === 'childbridge') {
2308
- // Register and add the device to the plugin server node
2309
1558
  if (plugin.type === 'AccessoryPlatform') {
2310
1559
  try {
2311
1560
  this.log.debug(`Creating endpoint ${dev}${device.deviceName}${db} for AccessoryPlatform plugin ${plg}${plugin.name}${db} server node`);
@@ -2329,12 +1578,10 @@ export class Matterbridge extends EventEmitter {
2329
1578
  return;
2330
1579
  }
2331
1580
  }
2332
- // Register and add the device to the plugin aggregator node
2333
1581
  if (plugin.type === 'DynamicPlatform') {
2334
1582
  try {
2335
1583
  this.log.debug(`Adding bridged endpoint ${dev}${device.deviceName}${db} for DynamicPlatform plugin ${plg}${plugin.name}${db} aggregator node`);
2336
1584
  await this.createDynamicPlugin(plugin);
2337
- // Fast plugins can add another device before the server node is ready, so we wait for the server node to be ready
2338
1585
  await waiter(`createDynamicPlugin(${plugin.name})`, () => plugin.serverNode?.hasParts === true);
2339
1586
  if (!plugin.aggregatorNode) {
2340
1587
  this.log.error(`Aggregator node not found for plugin ${plg}${plugin.name}${er}`);
@@ -2355,28 +1602,17 @@ export class Matterbridge extends EventEmitter {
2355
1602
  }
2356
1603
  if (plugin.registeredDevices !== undefined)
2357
1604
  plugin.registeredDevices++;
2358
- // Add the device to the DeviceManager
2359
1605
  this.devices.set(device);
2360
- // Subscribe to the attributes changed event
2361
1606
  await this.subscribeAttributeChanged(plugin, device);
2362
1607
  this.log.info(`Added and registered bridged endpoint (${plugin.registeredDevices}) ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) for plugin ${plg}${pluginName}${nf}`);
2363
1608
  }
2364
- /**
2365
- * Removes a MatterbridgeEndpoint from the specified plugin.
2366
- *
2367
- * @param {string} pluginName - The name of the plugin.
2368
- * @param {MatterbridgeEndpoint} device - The device to remove as a bridged endpoint.
2369
- * @returns {Promise<void>} A promise that resolves when the bridged endpoint has been removed.
2370
- */
2371
1609
  async removeBridgedEndpoint(pluginName, device) {
2372
1610
  this.log.debug(`Removing bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} (${zb}${device.name}${db}) for plugin ${plg}${pluginName}${db}`);
2373
- // Check if the plugin is registered
2374
1611
  const plugin = this.plugins.get(pluginName);
2375
1612
  if (!plugin) {
2376
1613
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: plugin not found`);
2377
1614
  return;
2378
1615
  }
2379
- // Register and add the device to the matterbridge aggregator node
2380
1616
  if (this.bridgeMode === 'bridge') {
2381
1617
  if (!this.aggregatorNode) {
2382
1618
  this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: aggregator node not found`);
@@ -2389,7 +1625,6 @@ export class Matterbridge extends EventEmitter {
2389
1625
  }
2390
1626
  else if (this.bridgeMode === 'childbridge') {
2391
1627
  if (plugin.type === 'AccessoryPlatform') {
2392
- // Nothing to do here since the server node has no aggregator node but only the device itself
2393
1628
  }
2394
1629
  else if (plugin.type === 'DynamicPlatform') {
2395
1630
  if (!plugin.aggregatorNode) {
@@ -2402,21 +1637,8 @@ export class Matterbridge extends EventEmitter {
2402
1637
  if (plugin.registeredDevices !== undefined)
2403
1638
  plugin.registeredDevices--;
2404
1639
  }
2405
- // Remove the device from the DeviceManager
2406
1640
  this.devices.remove(device);
2407
1641
  }
2408
- /**
2409
- * Removes all bridged endpoints from the specified plugin.
2410
- *
2411
- * @param {string} pluginName - The name of the plugin.
2412
- * @param {number} [delay] - The delay in milliseconds between removing each bridged endpoint (default: 0).
2413
- * @returns {Promise<void>} A promise that resolves when all bridged endpoints have been removed.
2414
- *
2415
- * @remarks
2416
- * This method iterates through all devices in the DeviceManager and removes each bridged endpoint associated with the specified plugin.
2417
- * It also applies a delay between each removal if specified.
2418
- * The delay is useful to allow the controllers to receive a single subscription for each device removed.
2419
- */
2420
1642
  async removeAllBridgedEndpoints(pluginName, delay = 0) {
2421
1643
  this.log.debug(`Removing all bridged endpoints for plugin ${plg}${pluginName}${db}${delay > 0 ? ` with delay ${delay} ms` : ''}`);
2422
1644
  for (const device of this.devices.array().filter((device) => device.plugin === pluginName)) {
@@ -2427,24 +1649,13 @@ export class Matterbridge extends EventEmitter {
2427
1649
  if (delay > 0)
2428
1650
  await wait(2000);
2429
1651
  }
2430
- /**
2431
- * Subscribes to the attribute change event for the given device and plugin.
2432
- * Specifically, it listens for changes in the 'reachable' attribute of the
2433
- * BridgedDeviceBasicInformationServer cluster server of the bridged device or BasicInformationServer cluster server of server node.
2434
- *
2435
- * @param {Plugin} plugin - The plugin associated with the device.
2436
- * @param {MatterbridgeEndpoint} device - The device to subscribe to attribute changes for.
2437
- * @returns {Promise<void>} A promise that resolves when the subscription is set up.
2438
- */
2439
1652
  async subscribeAttributeChanged(plugin, device) {
2440
1653
  if (!plugin || !device || !device.plugin || !device.serialNumber || !device.uniqueId || !device.maybeNumber)
2441
1654
  return;
2442
1655
  this.log.info(`Subscribing attributes for endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) plugin ${plg}${plugin.name}${nf}`);
2443
- // Subscribe to the reachable$Changed event of the BasicInformationServer cluster server of the server node in childbridge mode
2444
1656
  if (this.bridgeMode === 'childbridge' && plugin.type === 'AccessoryPlatform' && plugin.serverNode) {
2445
1657
  plugin.serverNode.eventsOf(BasicInformationServer).reachable$Changed?.on((reachable) => {
2446
1658
  this.log.info(`Accessory endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) is ${reachable ? 'reachable' : 'unreachable'}`);
2447
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2448
1659
  this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, device.number, device.id, 'BasicInformation', 'reachable', reachable);
2449
1660
  });
2450
1661
  }
@@ -2494,7 +1705,6 @@ export class Matterbridge extends EventEmitter {
2494
1705
  this.log.debug(`Subscribing to endpoint ${or}${device.id}${db}:${or}${device.number}${db} attribute ${dev}${sub.cluster}${db}.${dev}${sub.attribute}${db} changes...`);
2495
1706
  await device.subscribeAttribute(sub.cluster, sub.attribute, (value) => {
2496
1707
  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}${isValidObject(value) ? debugStringify(value) : value}${db}`);
2497
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2498
1708
  this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, device.number, device.id, sub.cluster, sub.attribute, value);
2499
1709
  });
2500
1710
  }
@@ -2503,19 +1713,12 @@ export class Matterbridge extends EventEmitter {
2503
1713
  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...`);
2504
1714
  await child.subscribeAttribute(sub.cluster, sub.attribute, (value) => {
2505
1715
  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}${isValidObject(value) ? debugStringify(value) : value}${db}`);
2506
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
2507
1716
  this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, child.number, child.id, sub.cluster, sub.attribute, value);
2508
1717
  });
2509
1718
  }
2510
1719
  }
2511
1720
  }
2512
1721
  }
2513
- /**
2514
- * Sanitizes the fabric information by converting bigint properties to strings because `res.json` doesn't support bigint.
2515
- *
2516
- * @param {ExposedFabricInformation[]} fabricInfo - The array of exposed fabric information objects.
2517
- * @returns {SanitizedExposedFabricInformation[]} An array of sanitized exposed fabric information objects.
2518
- */
2519
1722
  sanitizeFabricInformations(fabricInfo) {
2520
1723
  return fabricInfo.map((info) => {
2521
1724
  return {
@@ -2529,12 +1732,6 @@ export class Matterbridge extends EventEmitter {
2529
1732
  };
2530
1733
  });
2531
1734
  }
2532
- /**
2533
- * Sanitizes the session information by converting bigint properties to strings because `res.json` doesn't support bigint.
2534
- *
2535
- * @param {SessionsBehavior.Session[]} sessions - The array of session information objects.
2536
- * @returns {SanitizedSession[]} An array of sanitized session information objects.
2537
- */
2538
1735
  sanitizeSessionInformation(sessions) {
2539
1736
  return sessions
2540
1737
  .filter((session) => session.isPeerActive)
@@ -2561,21 +1758,7 @@ export class Matterbridge extends EventEmitter {
2561
1758
  };
2562
1759
  });
2563
1760
  }
2564
- /**
2565
- * Sets the reachability of the specified aggregator node bridged devices and trigger.
2566
- *
2567
- * @param {Endpoint<AggregatorEndpoint>} aggregatorNode - The aggregator node to set the reachability for.
2568
- * @param {boolean} reachable - A boolean indicating the reachability status to set.
2569
- */
2570
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
2571
1761
  async setAggregatorReachability(aggregatorNode, reachable) {
2572
- /*
2573
- for (const child of aggregatorNode.parts) {
2574
- this.log.debug(`Setting reachability of ${(child as unknown as MatterbridgeEndpoint)?.deviceName} to ${reachable}`);
2575
- await child.setStateOf(BridgedDeviceBasicInformationServer, { reachable });
2576
- child.act((agent) => child.eventsOf(BridgedDeviceBasicInformationServer).reachableChanged.emit({ reachableNewValue: true }, agent.context));
2577
- }
2578
- */
2579
1762
  }
2580
1763
  getVendorIdName = (vendorId) => {
2581
1764
  if (!vendorId)
@@ -2615,11 +1798,10 @@ export class Matterbridge extends EventEmitter {
2615
1798
  case 0x1488:
2616
1799
  vendorName = '(ShortcutLabsFlic)';
2617
1800
  break;
2618
- case 65521: // 0xFFF1
1801
+ case 65521:
2619
1802
  vendorName = '(MatterTest)';
2620
1803
  break;
2621
1804
  }
2622
1805
  return vendorName;
2623
1806
  };
2624
1807
  }
2625
- //# sourceMappingURL=matterbridge.js.map