@matterbridge/core 3.5.3 → 3.5.4-dev-20260211-c4f9359
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.
- package/README.md +1 -1
- package/dist/cli.d.ts +0 -24
- package/dist/cli.js +1 -97
- package/dist/cliEmitter.d.ts +0 -36
- package/dist/cliEmitter.js +0 -37
- package/dist/cliHistory.d.ts +0 -42
- package/dist/cliHistory.js +0 -38
- package/dist/clusters/export.d.ts +0 -1
- package/dist/clusters/export.js +0 -2
- package/dist/deviceManager.d.ts +0 -108
- package/dist/deviceManager.js +1 -114
- package/dist/devices/airConditioner.d.ts +0 -75
- package/dist/devices/airConditioner.js +0 -57
- package/dist/devices/basicVideoPlayer.d.ts +0 -58
- package/dist/devices/basicVideoPlayer.js +1 -56
- package/dist/devices/batteryStorage.d.ts +0 -43
- package/dist/devices/batteryStorage.js +1 -48
- package/dist/devices/castingVideoPlayer.d.ts +0 -63
- package/dist/devices/castingVideoPlayer.js +2 -65
- package/dist/devices/cooktop.d.ts +0 -55
- package/dist/devices/cooktop.js +0 -56
- package/dist/devices/dishwasher.d.ts +0 -55
- package/dist/devices/dishwasher.js +0 -57
- package/dist/devices/evse.d.ts +0 -57
- package/dist/devices/evse.js +10 -74
- package/dist/devices/export.d.ts +0 -1
- package/dist/devices/export.js +0 -5
- package/dist/devices/extractorHood.d.ts +0 -41
- package/dist/devices/extractorHood.js +0 -43
- package/dist/devices/heatPump.d.ts +0 -43
- package/dist/devices/heatPump.js +2 -50
- package/dist/devices/laundryDryer.d.ts +0 -58
- package/dist/devices/laundryDryer.js +3 -62
- package/dist/devices/laundryWasher.d.ts +0 -64
- package/dist/devices/laundryWasher.js +4 -70
- package/dist/devices/microwaveOven.d.ts +1 -77
- package/dist/devices/microwaveOven.js +5 -88
- package/dist/devices/oven.d.ts +0 -82
- package/dist/devices/oven.js +0 -85
- package/dist/devices/refrigerator.d.ts +0 -100
- package/dist/devices/refrigerator.js +0 -102
- package/dist/devices/roboticVacuumCleaner.d.ts +0 -83
- package/dist/devices/roboticVacuumCleaner.js +9 -100
- package/dist/devices/solarPower.d.ts +0 -36
- package/dist/devices/solarPower.js +0 -38
- package/dist/devices/speaker.d.ts +0 -79
- package/dist/devices/speaker.js +0 -84
- package/dist/devices/temperatureControl.d.ts +0 -21
- package/dist/devices/temperatureControl.js +3 -24
- package/dist/devices/waterHeater.d.ts +0 -74
- package/dist/devices/waterHeater.js +2 -82
- package/dist/dgram/export.d.ts +0 -1
- package/dist/dgram/export.js +0 -1
- package/dist/export.d.ts +0 -23
- package/dist/export.js +0 -28
- package/dist/frontend.d.ts +0 -187
- package/dist/frontend.js +38 -539
- package/dist/helpers.d.ts +0 -43
- package/dist/helpers.js +0 -86
- package/dist/jestutils/export.d.ts +0 -1
- package/dist/jestutils/export.js +0 -1
- package/dist/jestutils/jestHelpers.d.ts +0 -259
- package/dist/jestutils/jestHelpers.js +14 -395
- package/dist/matter/behaviors.d.ts +0 -1
- package/dist/matter/behaviors.js +0 -2
- package/dist/matter/clusters.d.ts +0 -1
- package/dist/matter/clusters.js +0 -2
- package/dist/matter/devices.d.ts +0 -1
- package/dist/matter/devices.js +0 -2
- package/dist/matter/endpoints.d.ts +0 -1
- package/dist/matter/endpoints.js +0 -2
- package/dist/matter/export.d.ts +0 -1
- package/dist/matter/export.js +0 -2
- package/dist/matter/types.d.ts +0 -1
- package/dist/matter/types.js +0 -2
- package/dist/matterNode.d.ts +0 -258
- package/dist/matterNode.js +8 -356
- package/dist/matterbridge.d.ts +0 -389
- package/dist/matterbridge.js +48 -878
- package/dist/matterbridgeAccessoryPlatform.d.ts +0 -42
- package/dist/matterbridgeAccessoryPlatform.js +0 -50
- package/dist/matterbridgeBehaviors.d.ts +0 -24
- package/dist/matterbridgeBehaviors.js +5 -65
- package/dist/matterbridgeDeviceTypes.d.ts +0 -649
- package/dist/matterbridgeDeviceTypes.js +6 -673
- package/dist/matterbridgeDynamicPlatform.d.ts +0 -42
- package/dist/matterbridgeDynamicPlatform.js +0 -50
- package/dist/matterbridgeEndpoint.d.ts +0 -1369
- package/dist/matterbridgeEndpoint.js +56 -1514
- package/dist/matterbridgeEndpointHelpers.d.ts +0 -425
- package/dist/matterbridgeEndpointHelpers.js +20 -483
- package/dist/matterbridgeEndpointTypes.d.ts +0 -70
- package/dist/matterbridgeEndpointTypes.js +0 -25
- package/dist/matterbridgePlatform.d.ts +0 -434
- package/dist/matterbridgePlatform.js +1 -473
- package/dist/mb_coap.d.ts +0 -23
- package/dist/mb_coap.js +3 -41
- package/dist/mb_health.d.ts +0 -67
- package/dist/mb_health.js +0 -70
- package/dist/mb_mdns.d.ts +0 -23
- package/dist/mb_mdns.js +36 -94
- package/dist/pluginManager.d.ts +0 -307
- package/dist/pluginManager.js +6 -346
- package/dist/spawn.d.ts +0 -32
- package/dist/spawn.js +1 -71
- package/dist/utils/export.d.ts +0 -1
- package/dist/utils/export.js +0 -1
- package/package.json +27 -6
- package/dist/cli.d.ts.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/cliEmitter.d.ts.map +0 -1
- package/dist/cliEmitter.js.map +0 -1
- package/dist/cliHistory.d.ts.map +0 -1
- package/dist/cliHistory.js.map +0 -1
- package/dist/clusters/export.d.ts.map +0 -1
- package/dist/clusters/export.js.map +0 -1
- package/dist/crypto/attestationDecoder.d.ts +0 -180
- package/dist/crypto/attestationDecoder.d.ts.map +0 -1
- package/dist/crypto/attestationDecoder.js +0 -176
- package/dist/crypto/attestationDecoder.js.map +0 -1
- package/dist/crypto/declarationDecoder.d.ts +0 -72
- package/dist/crypto/declarationDecoder.d.ts.map +0 -1
- package/dist/crypto/declarationDecoder.js +0 -241
- package/dist/crypto/declarationDecoder.js.map +0 -1
- package/dist/crypto/extract/342/200/220cert/342/200/220extensions.d.ts +0 -9
- package/dist/crypto/extract/342/200/220cert/342/200/220extensions.d.ts.map +0 -1
- package/dist/crypto/extract/342/200/220cert/342/200/220extensions.js +0 -120
- package/dist/crypto/extract/342/200/220cert/342/200/220extensions.js.map +0 -1
- package/dist/crypto/read-extensions.d.ts +0 -2
- package/dist/crypto/read-extensions.d.ts.map +0 -1
- package/dist/crypto/read-extensions.js +0 -81
- package/dist/crypto/read-extensions.js.map +0 -1
- package/dist/crypto/testData.d.ts +0 -31
- package/dist/crypto/testData.d.ts.map +0 -1
- package/dist/crypto/testData.js +0 -131
- package/dist/crypto/testData.js.map +0 -1
- package/dist/crypto/walk-der.d.ts +0 -2
- package/dist/crypto/walk-der.d.ts.map +0 -1
- package/dist/crypto/walk-der.js +0 -165
- package/dist/crypto/walk-der.js.map +0 -1
- package/dist/deviceManager.d.ts.map +0 -1
- package/dist/deviceManager.js.map +0 -1
- package/dist/devices/airConditioner.d.ts.map +0 -1
- package/dist/devices/airConditioner.js.map +0 -1
- package/dist/devices/basicVideoPlayer.d.ts.map +0 -1
- package/dist/devices/basicVideoPlayer.js.map +0 -1
- package/dist/devices/batteryStorage.d.ts.map +0 -1
- package/dist/devices/batteryStorage.js.map +0 -1
- package/dist/devices/castingVideoPlayer.d.ts.map +0 -1
- package/dist/devices/castingVideoPlayer.js.map +0 -1
- package/dist/devices/cooktop.d.ts.map +0 -1
- package/dist/devices/cooktop.js.map +0 -1
- package/dist/devices/dishwasher.d.ts.map +0 -1
- package/dist/devices/dishwasher.js.map +0 -1
- package/dist/devices/evse.d.ts.map +0 -1
- package/dist/devices/evse.js.map +0 -1
- package/dist/devices/export.d.ts.map +0 -1
- package/dist/devices/export.js.map +0 -1
- package/dist/devices/extractorHood.d.ts.map +0 -1
- package/dist/devices/extractorHood.js.map +0 -1
- package/dist/devices/heatPump.d.ts.map +0 -1
- package/dist/devices/heatPump.js.map +0 -1
- package/dist/devices/laundryDryer.d.ts.map +0 -1
- package/dist/devices/laundryDryer.js.map +0 -1
- package/dist/devices/laundryWasher.d.ts.map +0 -1
- package/dist/devices/laundryWasher.js.map +0 -1
- package/dist/devices/microwaveOven.d.ts.map +0 -1
- package/dist/devices/microwaveOven.js.map +0 -1
- package/dist/devices/oven.d.ts.map +0 -1
- package/dist/devices/oven.js.map +0 -1
- package/dist/devices/refrigerator.d.ts.map +0 -1
- package/dist/devices/refrigerator.js.map +0 -1
- package/dist/devices/roboticVacuumCleaner.d.ts.map +0 -1
- package/dist/devices/roboticVacuumCleaner.js.map +0 -1
- package/dist/devices/solarPower.d.ts.map +0 -1
- package/dist/devices/solarPower.js.map +0 -1
- package/dist/devices/speaker.d.ts.map +0 -1
- package/dist/devices/speaker.js.map +0 -1
- package/dist/devices/temperatureControl.d.ts.map +0 -1
- package/dist/devices/temperatureControl.js.map +0 -1
- package/dist/devices/waterHeater.d.ts.map +0 -1
- package/dist/devices/waterHeater.js.map +0 -1
- package/dist/dgram/export.d.ts.map +0 -1
- package/dist/dgram/export.js.map +0 -1
- package/dist/export.d.ts.map +0 -1
- package/dist/export.js.map +0 -1
- package/dist/frontend.d.ts.map +0 -1
- package/dist/frontend.js.map +0 -1
- package/dist/helpers.d.ts.map +0 -1
- package/dist/helpers.js.map +0 -1
- package/dist/jestutils/export.d.ts.map +0 -1
- package/dist/jestutils/export.js.map +0 -1
- package/dist/jestutils/jestHelpers.d.ts.map +0 -1
- package/dist/jestutils/jestHelpers.js.map +0 -1
- package/dist/matter/behaviors.d.ts.map +0 -1
- package/dist/matter/behaviors.js.map +0 -1
- package/dist/matter/clusters.d.ts.map +0 -1
- package/dist/matter/clusters.js.map +0 -1
- package/dist/matter/devices.d.ts.map +0 -1
- package/dist/matter/devices.js.map +0 -1
- package/dist/matter/endpoints.d.ts.map +0 -1
- package/dist/matter/endpoints.js.map +0 -1
- package/dist/matter/export.d.ts.map +0 -1
- package/dist/matter/export.js.map +0 -1
- package/dist/matter/types.d.ts.map +0 -1
- package/dist/matter/types.js.map +0 -1
- package/dist/matterNode.d.ts.map +0 -1
- package/dist/matterNode.js.map +0 -1
- package/dist/matterbridge.d.ts.map +0 -1
- package/dist/matterbridge.js.map +0 -1
- package/dist/matterbridgeAccessoryPlatform.d.ts.map +0 -1
- package/dist/matterbridgeAccessoryPlatform.js.map +0 -1
- package/dist/matterbridgeBehaviors.d.ts.map +0 -1
- package/dist/matterbridgeBehaviors.js.map +0 -1
- package/dist/matterbridgeDeviceTypes.d.ts.map +0 -1
- package/dist/matterbridgeDeviceTypes.js.map +0 -1
- package/dist/matterbridgeDynamicPlatform.d.ts.map +0 -1
- package/dist/matterbridgeDynamicPlatform.js.map +0 -1
- package/dist/matterbridgeEndpoint.d.ts.map +0 -1
- package/dist/matterbridgeEndpoint.js.map +0 -1
- package/dist/matterbridgeEndpointHelpers.d.ts.map +0 -1
- package/dist/matterbridgeEndpointHelpers.js.map +0 -1
- package/dist/matterbridgeEndpointTypes.d.ts.map +0 -1
- package/dist/matterbridgeEndpointTypes.js.map +0 -1
- package/dist/matterbridgePlatform.d.ts.map +0 -1
- package/dist/matterbridgePlatform.js.map +0 -1
- package/dist/mb_coap.d.ts.map +0 -1
- package/dist/mb_coap.js.map +0 -1
- package/dist/mb_health.d.ts.map +0 -1
- package/dist/mb_health.js.map +0 -1
- package/dist/mb_mdns.d.ts.map +0 -1
- package/dist/mb_mdns.js.map +0 -1
- package/dist/pluginManager.d.ts.map +0 -1
- package/dist/pluginManager.js.map +0 -1
- package/dist/spawn.d.ts.map +0 -1
- package/dist/spawn.js.map +0 -1
- package/dist/utils/export.d.ts.map +0 -1
- package/dist/utils/export.js.map +0 -1
- package/dist/workers/brand.d.ts +0 -25
- package/dist/workers/brand.d.ts.map +0 -1
- package/dist/workers/brand.extend.d.ts +0 -10
- package/dist/workers/brand.extend.d.ts.map +0 -1
- package/dist/workers/brand.extend.js +0 -15
- package/dist/workers/brand.extend.js.map +0 -1
- package/dist/workers/brand.invalid.d.ts +0 -9
- package/dist/workers/brand.invalid.d.ts.map +0 -1
- package/dist/workers/brand.invalid.js +0 -19
- package/dist/workers/brand.invalid.js.map +0 -1
- package/dist/workers/brand.js +0 -67
- package/dist/workers/brand.js.map +0 -1
- package/dist/workers/clusterTypes.d.ts +0 -47
- package/dist/workers/clusterTypes.d.ts.map +0 -1
- package/dist/workers/clusterTypes.js +0 -57
- package/dist/workers/clusterTypes.js.map +0 -1
- package/dist/workers/frontendWorker.d.ts +0 -2
- package/dist/workers/frontendWorker.d.ts.map +0 -1
- package/dist/workers/frontendWorker.js +0 -90
- package/dist/workers/frontendWorker.js.map +0 -1
- package/dist/workers/helloWorld.d.ts +0 -2
- package/dist/workers/helloWorld.d.ts.map +0 -1
- package/dist/workers/helloWorld.js +0 -135
- package/dist/workers/helloWorld.js.map +0 -1
- package/dist/workers/matterWorker.d.ts +0 -2
- package/dist/workers/matterWorker.d.ts.map +0 -1
- package/dist/workers/matterWorker.js +0 -104
- package/dist/workers/matterWorker.js.map +0 -1
- package/dist/workers/matterbridgeWorker.d.ts +0 -2
- package/dist/workers/matterbridgeWorker.d.ts.map +0 -1
- package/dist/workers/matterbridgeWorker.js +0 -75
- package/dist/workers/matterbridgeWorker.js.map +0 -1
- package/dist/workers/messageLab.d.ts +0 -134
- package/dist/workers/messageLab.d.ts.map +0 -1
- package/dist/workers/messageLab.js +0 -129
- package/dist/workers/messageLab.js.map +0 -1
- package/dist/workers/testWorker.d.ts +0 -2
- package/dist/workers/testWorker.d.ts.map +0 -1
- package/dist/workers/testWorker.js +0 -45
- package/dist/workers/testWorker.js.map +0 -1
- package/dist/workers/usage.d.ts +0 -19
- package/dist/workers/usage.d.ts.map +0 -1
- package/dist/workers/usage.js +0 -140
- package/dist/workers/usage.js.map +0 -1
- package/dist/workers/workerManager.d.ts +0 -115
- package/dist/workers/workerManager.d.ts.map +0 -1
- package/dist/workers/workerManager.js +0 -464
- package/dist/workers/workerManager.js.map +0 -1
- package/dist/workers/workerServer.d.ts +0 -126
- package/dist/workers/workerServer.d.ts.map +0 -1
- package/dist/workers/workerServer.js +0 -340
- package/dist/workers/workerServer.js.map +0 -1
- package/dist/workers/workerTypes.d.ts +0 -23
- package/dist/workers/workerTypes.d.ts.map +0 -1
- package/dist/workers/workerTypes.js +0 -3
- package/dist/workers/workerTypes.js.map +0 -1
package/dist/matterbridge.js
CHANGED
|
@@ -1,80 +1,42 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This file contains the class Matterbridge.
|
|
3
|
-
*
|
|
4
|
-
* @file matterbridge.ts
|
|
5
|
-
* @author Luca Liguori
|
|
6
|
-
* @created 2023-12-29
|
|
7
|
-
* @version 1.6.2
|
|
8
|
-
* @license Apache-2.0
|
|
9
|
-
*
|
|
10
|
-
* Copyright 2023, 2024, 2025, 2026 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 { fileURLToPath } from 'node:url';
|
|
31
6
|
import fs, { unlinkSync } from 'node:fs';
|
|
32
7
|
import EventEmitter from 'node:events';
|
|
33
8
|
import { inspect } from 'node:util';
|
|
34
|
-
// AnsiLogger module
|
|
35
9
|
import { AnsiLogger, UNDERLINE, UNDERLINEOFF, db, debugStringify, BRIGHT, RESET, er, nf, rs, wr, RED, GREEN, zb, CYAN, nt, BLUE, or, } from 'node-ansi-logger';
|
|
36
|
-
// NodeStorage module
|
|
37
10
|
import { NodeStorageManager } from 'node-persist-manager';
|
|
38
|
-
|
|
39
|
-
import '@matter/nodejs'; // Set up Node.js environment for matter.js
|
|
11
|
+
import '@matter/nodejs';
|
|
40
12
|
import { Logger, LogLevel as MatterLogLevel, LogFormat as MatterLogFormat, UINT32_MAX, UINT16_MAX, Crypto, Environment, StorageService, } from '@matter/general';
|
|
41
13
|
import { PaseClient } from '@matter/protocol';
|
|
42
14
|
import { Endpoint, ServerNode } from '@matter/node';
|
|
43
15
|
import { DeviceTypeId, VendorId } from '@matter/types/datatype';
|
|
44
16
|
import { AggregatorEndpoint } from '@matter/node/endpoints';
|
|
45
17
|
import { BasicInformationServer } from '@matter/node/behaviors/basic-information';
|
|
46
|
-
// @matterbridge
|
|
47
18
|
import { copyDirectory, createDirectory, formatBytes, formatPercent, formatUptime, getIntParameter, getParameter, hasParameter, isValidNumber, isValidObject, isValidString, parseVersionString, } from '@matterbridge/utils';
|
|
48
19
|
import { dev, MATTER_LOGGER_FILE, MATTER_STORAGE_NAME, MATTERBRIDGE_LOGGER_FILE, NODE_STORAGE_DIR, plg, typ } from '@matterbridge/types';
|
|
49
20
|
import { BroadcastServer } from '@matterbridge/thread';
|
|
50
|
-
// Matterbridge
|
|
51
21
|
import { PluginManager } from './pluginManager.js';
|
|
52
22
|
import { DeviceManager } from './deviceManager.js';
|
|
53
23
|
import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
|
|
54
24
|
import { bridge } from './matterbridgeDeviceTypes.js';
|
|
55
25
|
import { Frontend } from './frontend.js';
|
|
56
26
|
import { addVirtualDevice, addVirtualDevices } from './helpers.js';
|
|
57
|
-
/**
|
|
58
|
-
* Represents the Matterbridge application.
|
|
59
|
-
*/
|
|
60
27
|
export class Matterbridge extends EventEmitter {
|
|
61
|
-
/** Matterbridge system information */
|
|
62
28
|
systemInformation = {
|
|
63
|
-
// Network properties
|
|
64
29
|
interfaceName: '',
|
|
65
30
|
macAddress: '',
|
|
66
31
|
ipv4Address: '',
|
|
67
32
|
ipv6Address: '',
|
|
68
|
-
// Node.js properties
|
|
69
33
|
nodeVersion: '',
|
|
70
|
-
// Fixed system properties
|
|
71
34
|
hostname: '',
|
|
72
35
|
user: '',
|
|
73
36
|
osType: '',
|
|
74
37
|
osRelease: '',
|
|
75
38
|
osPlatform: '',
|
|
76
39
|
osArch: '',
|
|
77
|
-
// Cpu and memory properties
|
|
78
40
|
totalMemory: '',
|
|
79
41
|
freeMemory: '',
|
|
80
42
|
systemUptime: '',
|
|
@@ -85,71 +47,44 @@ export class Matterbridge extends EventEmitter {
|
|
|
85
47
|
heapTotal: '',
|
|
86
48
|
heapUsed: '',
|
|
87
49
|
};
|
|
88
|
-
// Matterbridge settings
|
|
89
|
-
/** It indicates the home directory of the Matterbridge application. The home directory is the base directory where Matterbridge creates the matterbridge directories (os.homedir() if not overridden). */
|
|
90
50
|
homeDirectory = '';
|
|
91
|
-
/** It indicates the root directory of the Matterbridge application. The root directory is the directory where Matterbridge is executed. */
|
|
92
51
|
rootDirectory = '';
|
|
93
|
-
/** It indicates where the directory .matterbridge is located. */
|
|
94
52
|
matterbridgeDirectory = '';
|
|
95
|
-
/** It indicates where the directory Matterbridge is located. */
|
|
96
53
|
matterbridgePluginDirectory = '';
|
|
97
|
-
/** It indicates where the directory .mattercert is located. */
|
|
98
54
|
matterbridgeCertDirectory = '';
|
|
99
|
-
/** It indicates the global modules directory for npm. */
|
|
100
55
|
globalModulesDirectory = '';
|
|
101
56
|
matterbridgeVersion = '';
|
|
102
57
|
matterbridgeLatestVersion = '';
|
|
103
58
|
matterbridgeDevVersion = '';
|
|
104
59
|
frontendVersion = '';
|
|
105
|
-
/** It indicates the mode of the Matterbridge instance. It can be 'bridge', 'childbridge', 'controller' or ''. */
|
|
106
60
|
bridgeMode = '';
|
|
107
|
-
/** It indicates the restart mode of the Matterbridge instance. It can be 'service', 'docker' or ''. */
|
|
108
61
|
restartMode = '';
|
|
109
|
-
/** It indicates whether virtual mode is enabled and its type. The virtual mode control the creation of "Update matterbridge" and "Restart matterbridge" endpoints. */
|
|
110
62
|
virtualMode = 'outlet';
|
|
111
|
-
/** It indicates the Matterbridge profile in use. */
|
|
112
63
|
profile = getParameter('profile');
|
|
113
|
-
/** Matterbridge logger */
|
|
114
64
|
log = new AnsiLogger({
|
|
115
65
|
logName: 'Matterbridge',
|
|
116
66
|
logNameColor: '\x1b[38;5;115m',
|
|
117
|
-
logTimestampFormat: 4
|
|
118
|
-
logLevel: hasParameter('debug') ? "debug"
|
|
67
|
+
logTimestampFormat: 4,
|
|
68
|
+
logLevel: hasParameter('debug') ? "debug" : "info",
|
|
119
69
|
});
|
|
120
|
-
/** Matterbridge logger level */
|
|
121
70
|
logLevel = this.log.logLevel;
|
|
122
|
-
/** Whether to log to a file */
|
|
123
71
|
fileLogger = false;
|
|
124
|
-
|
|
125
|
-
matterLog = new AnsiLogger({ logName: 'Matter', logNameColor: '\x1b[34m', logTimestampFormat: 4 /* TimestampFormat.TIME_MILLIS */, logLevel: "debug" /* LogLevel.DEBUG */ });
|
|
126
|
-
/** Matter logger level */
|
|
72
|
+
matterLog = new AnsiLogger({ logName: 'Matter', logNameColor: '\x1b[34m', logTimestampFormat: 4, logLevel: "debug" });
|
|
127
73
|
matterLogLevel = this.matterLog.logLevel;
|
|
128
|
-
/** Whether to log Matter to a file */
|
|
129
74
|
matterFileLogger = false;
|
|
130
|
-
// Frontend settings
|
|
131
75
|
readOnly = hasParameter('readonly') || hasParameter('shelly');
|
|
132
76
|
shellyBoard = hasParameter('shelly');
|
|
133
77
|
shellySysUpdate = false;
|
|
134
78
|
shellyMainUpdate = false;
|
|
135
|
-
/** It indicates whether a restart is required. It can be unset in childbridge mode by restarting the plugin that triggered the restart. */
|
|
136
79
|
restartRequired = false;
|
|
137
|
-
/** It indicates whether a fixed restart is required. It cannot be unset once set. */
|
|
138
80
|
fixedRestartRequired = false;
|
|
139
|
-
/** It indicates whether an update is available. */
|
|
140
81
|
updateRequired = false;
|
|
141
|
-
// Managers
|
|
142
82
|
plugins = new PluginManager(this);
|
|
143
83
|
devices = new DeviceManager();
|
|
144
|
-
// Frontend
|
|
145
84
|
frontend = new Frontend(this);
|
|
146
|
-
/** Matterbridge node storage manager created in the directory 'storage' in matterbridgeDirectory */
|
|
147
85
|
nodeStorage;
|
|
148
|
-
/** Matterbridge node context created with name 'matterbridge' */
|
|
149
86
|
nodeContext;
|
|
150
|
-
/** The main instance of the Matterbridge class (singleton) */
|
|
151
87
|
static instance;
|
|
152
|
-
// Instance properties
|
|
153
88
|
shutdown = false;
|
|
154
89
|
failCountLimit = hasParameter('shelly') ? 600 : 120;
|
|
155
90
|
hasCleanupStarted = false;
|
|
@@ -164,32 +99,19 @@ export class Matterbridge extends EventEmitter {
|
|
|
164
99
|
sigtermHandler;
|
|
165
100
|
exceptionHandler;
|
|
166
101
|
rejectionHandler;
|
|
167
|
-
/** Matter environment default */
|
|
168
102
|
environment = Environment.default;
|
|
169
|
-
/** Matter storage service from environment default */
|
|
170
103
|
matterStorageService;
|
|
171
|
-
/** Matter storage manager created with name 'Matterbridge' */
|
|
172
104
|
matterStorageManager;
|
|
173
|
-
/** Matter matterbridge storage context created in the storage manager with name 'persist' */
|
|
174
105
|
matterbridgeContext;
|
|
175
106
|
controllerContext;
|
|
176
|
-
/** Matter mdns interface e.g. 'eth0' or 'wlan0' or 'Wi-Fi' */
|
|
177
107
|
mdnsInterface;
|
|
178
|
-
/** Matter listeningAddressIpv4 address */
|
|
179
108
|
ipv4Address;
|
|
180
|
-
/** Matter listeningAddressIpv6 address */
|
|
181
109
|
ipv6Address;
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
/** Matter commissioning discriminator */
|
|
187
|
-
discriminator; // first server node discriminator
|
|
188
|
-
/** Matter device certification */
|
|
189
|
-
certification; // device certification
|
|
190
|
-
/** Matter server node in bridge mode */
|
|
110
|
+
port;
|
|
111
|
+
passcode;
|
|
112
|
+
discriminator;
|
|
113
|
+
certification;
|
|
191
114
|
serverNode;
|
|
192
|
-
/** Matter aggregator node in bridge mode */
|
|
193
115
|
aggregatorNode;
|
|
194
116
|
aggregatorVendorId = VendorId(getIntParameter('vendorId') ?? 0xfff1);
|
|
195
117
|
aggregatorVendorName = getParameter('vendorName') ?? 'Matterbridge';
|
|
@@ -198,26 +120,17 @@ export class Matterbridge extends EventEmitter {
|
|
|
198
120
|
aggregatorDeviceType = DeviceTypeId(getIntParameter('deviceType') ?? bridge.code);
|
|
199
121
|
aggregatorSerialNumber = getParameter('serialNumber');
|
|
200
122
|
aggregatorUniqueId = getParameter('uniqueId');
|
|
201
|
-
/** Advertising nodes map: time advertising started keyed by storeId */
|
|
202
123
|
advertisingNodes = new Map();
|
|
203
|
-
/** Broadcast server */
|
|
204
124
|
server;
|
|
205
125
|
verbose = hasParameter('verbose');
|
|
206
|
-
/** We load asyncronously so is private */
|
|
207
126
|
constructor() {
|
|
208
127
|
super();
|
|
209
128
|
this.server = new BroadcastServer('matterbridge', this.log);
|
|
210
129
|
this.server.on('broadcast_message', this.msgHandler.bind(this));
|
|
211
130
|
}
|
|
212
|
-
/** Close the broadcast server */
|
|
213
131
|
destroy() {
|
|
214
132
|
this.server.close();
|
|
215
133
|
}
|
|
216
|
-
/**
|
|
217
|
-
* Get a platform matterbridge object
|
|
218
|
-
*
|
|
219
|
-
* @returns {PlatformMatterbridge} The platform matterbridge object.
|
|
220
|
-
*/
|
|
221
134
|
getPlatformMatterbridge() {
|
|
222
135
|
return {
|
|
223
136
|
systemInformation: { ...this.systemInformation },
|
|
@@ -240,11 +153,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
240
153
|
aggregatorProductName: this.aggregatorProductName,
|
|
241
154
|
};
|
|
242
155
|
}
|
|
243
|
-
/**
|
|
244
|
-
* Get a shared matterbridge object
|
|
245
|
-
*
|
|
246
|
-
* @returns {SharedMatterbridge} The shared matterbridge object.
|
|
247
|
-
*/
|
|
248
156
|
getSharedMatterbridge() {
|
|
249
157
|
return {
|
|
250
158
|
systemInformation: { ...this.systemInformation },
|
|
@@ -323,19 +231,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
323
231
|
}
|
|
324
232
|
}
|
|
325
233
|
}
|
|
326
|
-
//* ************************************************************************************************************************************ */
|
|
327
|
-
// loadInstance() and cleanup() methods */
|
|
328
|
-
//* ************************************************************************************************************************************ */
|
|
329
|
-
/**
|
|
330
|
-
* Loads an instance of the Matterbridge class.
|
|
331
|
-
* If an instance already exists, return that instance.
|
|
332
|
-
*
|
|
333
|
-
* @param {boolean} initialize - Whether to initialize the Matterbridge instance after loading. Defaults to false.
|
|
334
|
-
* @returns {Matterbridge} A promise that resolves to the Matterbridge instance.
|
|
335
|
-
*/
|
|
336
234
|
static async loadInstance(initialize = false) {
|
|
337
235
|
if (!Matterbridge.instance) {
|
|
338
|
-
// eslint-disable-next-line no-console
|
|
339
236
|
if (hasParameter('debug'))
|
|
340
237
|
console.log(GREEN + 'Creating a new instance of Matterbridge.', initialize ? 'Initializing...' : 'Not initializing...', rs);
|
|
341
238
|
Matterbridge.instance = new Matterbridge();
|
|
@@ -344,86 +241,57 @@ export class Matterbridge extends EventEmitter {
|
|
|
344
241
|
}
|
|
345
242
|
return Matterbridge.instance;
|
|
346
243
|
}
|
|
347
|
-
/**
|
|
348
|
-
* Initializes the Matterbridge application.
|
|
349
|
-
*
|
|
350
|
-
* @remarks
|
|
351
|
-
* This method performs the necessary setup and initialization steps for the Matterbridge application.
|
|
352
|
-
* It displays the help information if the 'help' parameter is provided, sets up the logger, checks the
|
|
353
|
-
* node version, registers signal handlers, initializes storage, and parses the command line.
|
|
354
|
-
*
|
|
355
|
-
* @returns {Promise<void>} A Promise that resolves when the initialization is complete.
|
|
356
|
-
*/
|
|
357
244
|
async initialize() {
|
|
358
|
-
// for (let i = 1; i <= 255; i++) console.log(`\x1b[38;5;${i}mColor: ${i}`);
|
|
359
|
-
// Emit the initialize_started event
|
|
360
245
|
this.emit('initialize_started');
|
|
361
|
-
// Set the restart mode
|
|
362
246
|
if (hasParameter('service'))
|
|
363
247
|
this.restartMode = 'service';
|
|
364
248
|
if (hasParameter('docker'))
|
|
365
249
|
this.restartMode = 'docker';
|
|
366
|
-
// Set the matterbridge home directory
|
|
367
250
|
this.homeDirectory = getParameter('homedir') ?? os.homedir();
|
|
368
251
|
await createDirectory(this.homeDirectory, 'Matterbridge Home Directory', this.log);
|
|
369
|
-
// Set the matterbridge directory
|
|
370
252
|
this.matterbridgeDirectory = this.profile ? path.join(this.homeDirectory, '.matterbridge', 'profiles', this.profile) : path.join(this.homeDirectory, '.matterbridge');
|
|
371
253
|
await createDirectory(this.matterbridgeDirectory, 'Matterbridge Directory', this.log);
|
|
372
254
|
await createDirectory(path.join(this.matterbridgeDirectory, 'certs'), 'Matterbridge Frontend Certificate Directory', this.log);
|
|
373
255
|
await createDirectory(path.join(this.matterbridgeDirectory, 'uploads'), 'Matterbridge Frontend Uploads Directory', this.log);
|
|
374
|
-
// Set the matterbridge plugin directory
|
|
375
256
|
this.matterbridgePluginDirectory = this.profile ? path.join(this.homeDirectory, 'Matterbridge', 'profiles', this.profile) : path.join(this.homeDirectory, 'Matterbridge');
|
|
376
257
|
await createDirectory(this.matterbridgePluginDirectory, 'Matterbridge Plugin Directory', this.log);
|
|
377
|
-
// Set the matterbridge cert directory
|
|
378
258
|
this.matterbridgeCertDirectory = this.profile ? path.join(this.homeDirectory, '.mattercert', 'profiles', this.profile) : path.join(this.homeDirectory, '.mattercert');
|
|
379
259
|
await createDirectory(this.matterbridgeCertDirectory, 'Matterbridge Matter Certificate Directory', this.log);
|
|
380
|
-
// Set the matterbridge root directory
|
|
381
260
|
const currentFileDirectory = path.dirname(fileURLToPath(import.meta.url));
|
|
382
|
-
// Adjust the path for packages core dist directory or node_modules @matterbridge core dist directory
|
|
383
261
|
this.rootDirectory = currentFileDirectory.includes(path.join('packages', 'core'))
|
|
384
262
|
? path.resolve(currentFileDirectory, '../', '../', '../')
|
|
385
263
|
: path.resolve(currentFileDirectory, '../', '../', '..', '../');
|
|
386
|
-
// Setup the matter environment with default values
|
|
387
264
|
this.environment.vars.set('log.level', MatterLogLevel.INFO);
|
|
388
265
|
this.environment.vars.set('log.format', hasParameter('no-ansi') || process.env.NO_COLOR === '1' ? MatterLogFormat.PLAIN : MatterLogFormat.ANSI);
|
|
389
266
|
this.environment.vars.set('path.root', path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME));
|
|
390
267
|
this.environment.vars.set('runtime.signals', false);
|
|
391
268
|
this.environment.vars.set('runtime.exitcode', false);
|
|
392
|
-
// Register process handlers
|
|
393
269
|
this.registerProcessHandlers();
|
|
394
|
-
// Initialize nodeStorage and nodeContext
|
|
395
270
|
try {
|
|
396
271
|
this.log.debug(`Creating node storage manager: ${CYAN}${NODE_STORAGE_DIR}${db}`);
|
|
397
272
|
this.nodeStorage = new NodeStorageManager({ dir: path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR), writeQueue: false, expiredInterval: undefined, logging: false });
|
|
398
273
|
this.log.debug('Creating node storage context for matterbridge');
|
|
399
274
|
this.nodeContext = await this.nodeStorage.createStorage('matterbridge');
|
|
400
|
-
// TODO: Remove this code when node-persist-manager is updated
|
|
401
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
402
275
|
const keys = (await this.nodeStorage?.storage.keys());
|
|
403
276
|
for (const key of keys) {
|
|
404
277
|
this.log.debug(`Checking node storage manager key: ${CYAN}${key}${db}`);
|
|
405
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
406
278
|
await this.nodeStorage?.storage.get(key);
|
|
407
279
|
}
|
|
408
280
|
const storages = await this.nodeStorage.getStorageNames();
|
|
409
281
|
for (const storage of storages) {
|
|
410
282
|
this.log.debug(`Checking storage: ${CYAN}${storage}${db}`);
|
|
411
283
|
const nodeContext = await this.nodeStorage?.createStorage(storage);
|
|
412
|
-
// TODO: Remove this code when node-persist-manager is updated
|
|
413
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
414
284
|
const keys = (await nodeContext?.storage.keys());
|
|
415
285
|
keys.forEach(async (key) => {
|
|
416
286
|
this.log.debug(`Checking key: ${CYAN}${storage}:${key}${db}`);
|
|
417
287
|
await nodeContext?.get(key);
|
|
418
288
|
});
|
|
419
289
|
}
|
|
420
|
-
// Creating a backup of the node storage since it is not corrupted
|
|
421
290
|
this.log.debug('Creating node storage backup...');
|
|
422
291
|
await copyDirectory(path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR), path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR + '.backup'));
|
|
423
292
|
this.log.debug('Created node storage backup');
|
|
424
293
|
}
|
|
425
294
|
catch (error) {
|
|
426
|
-
// Restoring the backup of the node storage since it is corrupted
|
|
427
295
|
this.log.error(`Error creating node storage manager and context: ${error instanceof Error ? error.message : error}`);
|
|
428
296
|
if (hasParameter('norestore')) {
|
|
429
297
|
this.log.fatal(`The matterbridge storage is corrupted. Found -norestore parameter: exiting...`);
|
|
@@ -437,20 +305,15 @@ export class Matterbridge extends EventEmitter {
|
|
|
437
305
|
if (!this.nodeStorage || !this.nodeContext) {
|
|
438
306
|
throw new Error('Fatal error creating node storage manager and context for matterbridge');
|
|
439
307
|
}
|
|
440
|
-
// Set the first port to use for the commissioning server (will be incremented in childbridge mode)
|
|
441
308
|
this.port = getIntParameter('port') ?? (await this.nodeContext.get('matterport', 5540)) ?? 5540;
|
|
442
|
-
// Set the first passcode to use for the commissioning server (will be incremented in childbridge mode)
|
|
443
309
|
this.passcode = getIntParameter('passcode') ?? (await this.nodeContext.get('matterpasscode')) ?? PaseClient.generateRandomPasscode(this.environment.get(Crypto));
|
|
444
|
-
// Set the first discriminator to use for the commissioning server (will be incremented in childbridge mode)
|
|
445
310
|
this.discriminator =
|
|
446
311
|
getIntParameter('discriminator') ?? (await this.nodeContext.get('matterdiscriminator')) ?? PaseClient.generateRandomDiscriminator(this.environment.get(Crypto));
|
|
447
|
-
// Certificate management
|
|
448
312
|
const pairingFilePath = path.join(this.matterbridgeCertDirectory, 'pairing.json');
|
|
449
313
|
try {
|
|
450
314
|
await fs.promises.access(pairingFilePath, fs.constants.R_OK);
|
|
451
315
|
const pairingFileContent = await fs.promises.readFile(pairingFilePath, 'utf8');
|
|
452
316
|
const pairingFileJson = JSON.parse(pairingFileContent);
|
|
453
|
-
// Set the vendorId, vendorName, productId, productName, deviceType, serialNumber, uniqueId if they are present in the pairing file
|
|
454
317
|
if (isValidNumber(pairingFileJson.vendorId)) {
|
|
455
318
|
this.aggregatorVendorId = VendorId(pairingFileJson.vendorId);
|
|
456
319
|
this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using vendorId ${CYAN}${this.aggregatorVendorId}${nf} from pairing file.`);
|
|
@@ -479,13 +342,11 @@ export class Matterbridge extends EventEmitter {
|
|
|
479
342
|
this.aggregatorUniqueId = pairingFileJson.uniqueId;
|
|
480
343
|
this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using uniqueId ${CYAN}${this.aggregatorUniqueId}${nf} from pairing file.`);
|
|
481
344
|
}
|
|
482
|
-
// Override the passcode and discriminator if they are present in the pairing file
|
|
483
345
|
if (isValidNumber(pairingFileJson.passcode) && isValidNumber(pairingFileJson.discriminator)) {
|
|
484
346
|
this.passcode = pairingFileJson.passcode;
|
|
485
347
|
this.discriminator = pairingFileJson.discriminator;
|
|
486
348
|
this.log.info(`Pairing file ${CYAN}${pairingFilePath}${nf} found. Using passcode ${CYAN}${this.passcode}${nf} and discriminator ${CYAN}${this.discriminator}${nf} from pairing file.`);
|
|
487
349
|
}
|
|
488
|
-
// Set the certification for matter.js if it is present in the pairing file
|
|
489
350
|
if (pairingFileJson.privateKey && pairingFileJson.certificate && pairingFileJson.intermediateCertificate && pairingFileJson.declaration) {
|
|
490
351
|
const { hexToBuffer } = await import('@matterbridge/utils');
|
|
491
352
|
this.certification = {
|
|
@@ -500,44 +361,41 @@ export class Matterbridge extends EventEmitter {
|
|
|
500
361
|
catch (error) {
|
|
501
362
|
this.log.debug(`Pairing file ${CYAN}${pairingFilePath}${db} not found: ${error instanceof Error ? error.message : error}`);
|
|
502
363
|
}
|
|
503
|
-
// Store the passcode, discriminator and port in the node context
|
|
504
364
|
await this.nodeContext.set('matterport', this.port);
|
|
505
365
|
await this.nodeContext.set('matterpasscode', this.passcode);
|
|
506
366
|
await this.nodeContext.set('matterdiscriminator', this.discriminator);
|
|
507
367
|
this.log.debug(`Initializing server node for Matterbridge on port ${this.port} with passcode ${this.passcode} and discriminator ${this.discriminator}`);
|
|
508
|
-
// Set matterbridge logger level (context: matterbridgeLogLevel)
|
|
509
368
|
if (hasParameter('logger')) {
|
|
510
369
|
const level = getParameter('logger');
|
|
511
370
|
if (level === 'debug') {
|
|
512
|
-
this.log.logLevel = "debug"
|
|
371
|
+
this.log.logLevel = "debug";
|
|
513
372
|
}
|
|
514
373
|
else if (level === 'info') {
|
|
515
|
-
this.log.logLevel = "info"
|
|
374
|
+
this.log.logLevel = "info";
|
|
516
375
|
}
|
|
517
376
|
else if (level === 'notice') {
|
|
518
|
-
this.log.logLevel = "notice"
|
|
377
|
+
this.log.logLevel = "notice";
|
|
519
378
|
}
|
|
520
379
|
else if (level === 'warn') {
|
|
521
|
-
this.log.logLevel = "warn"
|
|
380
|
+
this.log.logLevel = "warn";
|
|
522
381
|
}
|
|
523
382
|
else if (level === 'error') {
|
|
524
|
-
this.log.logLevel = "error"
|
|
383
|
+
this.log.logLevel = "error";
|
|
525
384
|
}
|
|
526
385
|
else if (level === 'fatal') {
|
|
527
|
-
this.log.logLevel = "fatal"
|
|
386
|
+
this.log.logLevel = "fatal";
|
|
528
387
|
}
|
|
529
388
|
else {
|
|
530
389
|
this.log.warn(`Invalid matterbridge logger level: ${level}. Using default level "info".`);
|
|
531
|
-
this.log.logLevel = "info"
|
|
390
|
+
this.log.logLevel = "info";
|
|
532
391
|
}
|
|
533
392
|
}
|
|
534
393
|
else {
|
|
535
|
-
this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.shellyBoard ? "notice"
|
|
394
|
+
this.log.logLevel = await this.nodeContext.get('matterbridgeLogLevel', this.shellyBoard ? "notice" : "info");
|
|
536
395
|
}
|
|
537
396
|
this.logLevel = this.log.logLevel;
|
|
538
397
|
this.frontend.logLevel = this.log.logLevel;
|
|
539
398
|
MatterbridgeEndpoint.logLevel = this.log.logLevel;
|
|
540
|
-
// Create the file logger for matterbridge (context: matterbridgeFileLog)
|
|
541
399
|
if (hasParameter('filelogger') || (await this.nodeContext.get('matterbridgeFileLog', false))) {
|
|
542
400
|
AnsiLogger.setGlobalLogfile(path.join(this.matterbridgeDirectory, MATTERBRIDGE_LOGGER_FILE), this.log.logLevel, true);
|
|
543
401
|
this.fileLogger = true;
|
|
@@ -546,7 +404,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
546
404
|
this.log.debug(`Matterbridge logLevel: ${this.log.logLevel} fileLoger: ${this.fileLogger}.`);
|
|
547
405
|
if (this.profile !== undefined)
|
|
548
406
|
this.log.debug(`Matterbridge profile: ${this.profile}.`);
|
|
549
|
-
// Set matter.js logger level, format and logger (context: matterLogLevel)
|
|
550
407
|
if (hasParameter('matterlogger')) {
|
|
551
408
|
const level = getParameter('matterlogger');
|
|
552
409
|
if (level === 'debug') {
|
|
@@ -577,13 +434,11 @@ export class Matterbridge extends EventEmitter {
|
|
|
577
434
|
}
|
|
578
435
|
Logger.format = MatterLogFormat.ANSI;
|
|
579
436
|
this.matterLogLevel = MatterLogLevel.names[Logger.level];
|
|
580
|
-
// Create the logger for matter.js with file logging (context: matterFileLog)
|
|
581
437
|
if (hasParameter('matterfilelogger') || (await this.nodeContext.get('matterFileLog', false))) {
|
|
582
438
|
this.matterFileLogger = true;
|
|
583
439
|
}
|
|
584
440
|
Logger.destinations.default.write = this.createDestinationMatterLogger(this.matterFileLogger);
|
|
585
441
|
this.log.debug(`Matter logLevel: ${this.matterLogLevel} fileLoger: ${this.matterFileLogger}.`);
|
|
586
|
-
// Log network interfaces
|
|
587
442
|
const networkInterfaces = os.networkInterfaces();
|
|
588
443
|
const availableAddresses = Object.entries(networkInterfaces);
|
|
589
444
|
const availableInterfaceNames = Object.keys(networkInterfaces);
|
|
@@ -596,7 +451,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
596
451
|
});
|
|
597
452
|
}
|
|
598
453
|
}
|
|
599
|
-
// Set the interface to use for matter server node mdnsInterface
|
|
600
454
|
if (hasParameter('mdnsinterface')) {
|
|
601
455
|
this.mdnsInterface = getParameter('mdnsinterface');
|
|
602
456
|
}
|
|
@@ -605,7 +459,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
605
459
|
if (this.mdnsInterface === '')
|
|
606
460
|
this.mdnsInterface = undefined;
|
|
607
461
|
}
|
|
608
|
-
// Validate mdnsInterface
|
|
609
462
|
if (this.mdnsInterface) {
|
|
610
463
|
if (!availableInterfaceNames.includes(this.mdnsInterface)) {
|
|
611
464
|
this.log.error(`Invalid mdnsinterface: ${this.mdnsInterface}. Available interfaces are: ${availableInterfaceNames.join(', ')}. Using all available interfaces.`);
|
|
@@ -618,7 +471,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
618
471
|
}
|
|
619
472
|
if (this.mdnsInterface)
|
|
620
473
|
this.environment.vars.set('mdns.networkInterface', this.mdnsInterface);
|
|
621
|
-
// Set the listeningAddressIpv4 for the matter commissioning server
|
|
622
474
|
if (hasParameter('ipv4address')) {
|
|
623
475
|
this.ipv4Address = getParameter('ipv4address');
|
|
624
476
|
}
|
|
@@ -627,7 +479,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
627
479
|
if (this.ipv4Address === '')
|
|
628
480
|
this.ipv4Address = undefined;
|
|
629
481
|
}
|
|
630
|
-
// Validate ipv4address
|
|
631
482
|
if (this.ipv4Address) {
|
|
632
483
|
let isValid = false;
|
|
633
484
|
for (const [ifaceName, ifaces] of availableAddresses) {
|
|
@@ -643,7 +494,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
643
494
|
await this.nodeContext.remove('matteripv4address');
|
|
644
495
|
}
|
|
645
496
|
}
|
|
646
|
-
// Set the listeningAddressIpv6 for the matter commissioning server
|
|
647
497
|
if (hasParameter('ipv6address')) {
|
|
648
498
|
this.ipv6Address = getParameter('ipv6address');
|
|
649
499
|
}
|
|
@@ -652,7 +502,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
652
502
|
if (this.ipv6Address === '')
|
|
653
503
|
this.ipv6Address = undefined;
|
|
654
504
|
}
|
|
655
|
-
// Validate ipv6address
|
|
656
505
|
if (this.ipv6Address) {
|
|
657
506
|
let isValid = false;
|
|
658
507
|
for (const [ifaceName, ifaces] of availableAddresses) {
|
|
@@ -661,7 +510,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
661
510
|
isValid = true;
|
|
662
511
|
break;
|
|
663
512
|
}
|
|
664
|
-
/* istanbul ignore next */
|
|
665
513
|
if (ifaces &&
|
|
666
514
|
ifaces.find((iface) => iface.scopeid && iface.scopeid > 0 && iface.address + '%' + (process.platform === 'win32' ? iface.scopeid : ifaceName) === this.ipv6Address)) {
|
|
667
515
|
this.log.info(`Using ipv6address ${CYAN}${this.ipv6Address}${nf} on interface ${CYAN}${ifaceName}${nf} for the Matter server node.`);
|
|
@@ -675,7 +523,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
675
523
|
await this.nodeContext.remove('matteripv6address');
|
|
676
524
|
}
|
|
677
525
|
}
|
|
678
|
-
// Initialize the virtual mode
|
|
679
526
|
if (hasParameter('novirtual')) {
|
|
680
527
|
this.virtualMode = 'disabled';
|
|
681
528
|
await this.nodeContext.set('virtualmode', 'disabled');
|
|
@@ -684,15 +531,10 @@ export class Matterbridge extends EventEmitter {
|
|
|
684
531
|
this.virtualMode = (await this.nodeContext.get('virtualmode', 'outlet'));
|
|
685
532
|
}
|
|
686
533
|
this.log.debug(`Virtual mode ${this.virtualMode}.`);
|
|
687
|
-
// Initialize PluginManager
|
|
688
534
|
this.plugins.logLevel = this.log.logLevel;
|
|
689
535
|
await this.plugins.loadFromStorage();
|
|
690
|
-
// Initialize DeviceManager
|
|
691
536
|
this.devices.logLevel = this.log.logLevel;
|
|
692
|
-
// Get the plugins from node storage and create the plugins node storage contexts
|
|
693
537
|
for (const plugin of this.plugins) {
|
|
694
|
-
// Try to reinstall the plugin from npm (for Docker pull and external plugins)
|
|
695
|
-
// We don't do this when the add and other shutdown parameters are set because we shut down the process after adding the plugin
|
|
696
538
|
if (!fs.existsSync(plugin.path) &&
|
|
697
539
|
!hasParameter('add') &&
|
|
698
540
|
!hasParameter('remove') &&
|
|
@@ -728,7 +570,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
728
570
|
await plugin.nodeContext.set('description', plugin.description);
|
|
729
571
|
await plugin.nodeContext.set('author', plugin.author);
|
|
730
572
|
}
|
|
731
|
-
// Log system info and create .matterbridge directory
|
|
732
573
|
await this.logNodeAndSystemInfo();
|
|
733
574
|
this.log.notice(`Matterbridge version ${this.matterbridgeVersion} ` +
|
|
734
575
|
`${hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge') ? 'mode bridge ' : ''}` +
|
|
@@ -736,7 +577,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
736
577
|
`${hasParameter('controller') ? 'mode controller ' : ''}` +
|
|
737
578
|
`${this.restartMode !== '' ? 'restart mode ' + this.restartMode + ' ' : ''}` +
|
|
738
579
|
`running on ${this.systemInformation.osType} (v.${this.systemInformation.osRelease}) platform ${this.systemInformation.osPlatform} arch ${this.systemInformation.osArch}`);
|
|
739
|
-
// Check node version and throw error
|
|
740
580
|
const minNodeVersion = 20;
|
|
741
581
|
const nodeVersion = process.versions.node;
|
|
742
582
|
const versionMajor = parseInt(nodeVersion.split('.')[0]);
|
|
@@ -744,35 +584,16 @@ export class Matterbridge extends EventEmitter {
|
|
|
744
584
|
this.log.error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
|
|
745
585
|
throw new Error(`Node version ${versionMajor} is not supported. Please upgrade to ${minNodeVersion} or above.`);
|
|
746
586
|
}
|
|
747
|
-
// Parse command line
|
|
748
587
|
await this.parseCommandLine();
|
|
749
|
-
// Emit the initialize_completed event
|
|
750
588
|
this.emit('initialize_completed');
|
|
751
589
|
this.initialized = true;
|
|
752
590
|
}
|
|
753
|
-
/**
|
|
754
|
-
* Resolve a file path located in the `@matterbridge/core` distribution directory.
|
|
755
|
-
*
|
|
756
|
-
* @remarks
|
|
757
|
-
* Matterbridge spawns ESM workers from built JavaScript files (e.g. `workerCheckUpdates.js`).
|
|
758
|
-
* Depending on how the code is executed:
|
|
759
|
-
* - **Production**: `import.meta.url` points inside `.../node_modules/@matterbridge/core/dist/...`
|
|
760
|
-
* and the worker file is usually alongside the current module.
|
|
761
|
-
* - **Development / tests**: `import.meta.url` may point inside `.../packages/core/src/...`
|
|
762
|
-
* while the worker file exists in `.../packages/core/dist/...`.
|
|
763
|
-
*
|
|
764
|
-
* This helper tries both locations and returns the first existing candidate.
|
|
765
|
-
*
|
|
766
|
-
* @param {string} fileName - Worker/build artifact file name, e.g. `workerGlobalPrefix.js`.
|
|
767
|
-
* @returns {string} Absolute path to the resolved file. If none exists, returns the first candidate (best effort).
|
|
768
|
-
*/
|
|
769
591
|
resolveWorkerDistFilePath(fileName) {
|
|
770
592
|
const currentModuleDirectory = path.dirname(fileURLToPath(import.meta.url));
|
|
771
|
-
// This core package's src or dist directory or the global installation dist directory for thread package
|
|
772
593
|
const candidates = [
|
|
773
|
-
path.join(currentModuleDirectory, fileName),
|
|
774
|
-
path.join(currentModuleDirectory, '..', 'dist', fileName),
|
|
775
|
-
path.join(this.rootDirectory, 'node_modules', '@matterbridge', 'thread', 'dist', fileName),
|
|
594
|
+
path.join(currentModuleDirectory, fileName),
|
|
595
|
+
path.join(currentModuleDirectory, '..', 'dist', fileName),
|
|
596
|
+
path.join(this.rootDirectory, 'node_modules', '@matterbridge', 'thread', 'dist', fileName),
|
|
776
597
|
];
|
|
777
598
|
for (const candidate of candidates) {
|
|
778
599
|
if (fs.existsSync(candidate))
|
|
@@ -780,12 +601,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
780
601
|
}
|
|
781
602
|
return candidates[0];
|
|
782
603
|
}
|
|
783
|
-
/**
|
|
784
|
-
* Parses the command line arguments and performs the corresponding actions.
|
|
785
|
-
*
|
|
786
|
-
* @private
|
|
787
|
-
* @returns {Promise<void>} A promise that resolves when the command line arguments have been processed, or the process exits.
|
|
788
|
-
*/
|
|
789
604
|
async parseCommandLine() {
|
|
790
605
|
if (hasParameter('list')) {
|
|
791
606
|
this.log.info(`│ Registered plugins (${this.plugins.length})`);
|
|
@@ -801,19 +616,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
801
616
|
}
|
|
802
617
|
index++;
|
|
803
618
|
}
|
|
804
|
-
/*
|
|
805
|
-
const serializedRegisteredDevices = await this.nodeContext?.get<SerializedMatterbridgeEndpoint[]>('devices', []);
|
|
806
|
-
this.log.info(`│ Registered devices (${serializedRegisteredDevices?.length})`);
|
|
807
|
-
serializedRegisteredDevices?.forEach((device, index) => {
|
|
808
|
-
if (index !== serializedRegisteredDevices.length - 1) {
|
|
809
|
-
this.log.info(`├─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
|
|
810
|
-
this.log.info(`│ └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
|
|
811
|
-
} else {
|
|
812
|
-
this.log.info(`└─┬─ plugin ${plg}${device.pluginName}${nf} device: ${dev}${device.deviceName}${nf} uniqueId: ${YELLOW}${device.uniqueId}${nf}`);
|
|
813
|
-
this.log.info(` └─ endpoint ${RED}${device.endpoint}${nf} ${typ}${device.endpointName}${nf} ${debugStringify(device.clusterServersId)}`);
|
|
814
|
-
}
|
|
815
|
-
});
|
|
816
|
-
*/
|
|
817
619
|
this.shutdown = true;
|
|
818
620
|
return;
|
|
819
621
|
}
|
|
@@ -863,10 +665,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
863
665
|
this.shutdown = true;
|
|
864
666
|
return;
|
|
865
667
|
}
|
|
866
|
-
// Initialize frontend
|
|
867
668
|
if (getIntParameter('frontend') !== 0 || getIntParameter('frontend') === undefined)
|
|
868
669
|
await this.frontend.start(getIntParameter('frontend'));
|
|
869
|
-
// Start the matter storage and create the matterbridge context
|
|
870
670
|
try {
|
|
871
671
|
await this.startMatterStorage();
|
|
872
672
|
if (this.aggregatorSerialNumber && this.aggregatorUniqueId && this.matterStorageService) {
|
|
@@ -880,21 +680,18 @@ export class Matterbridge extends EventEmitter {
|
|
|
880
680
|
this.log.fatal(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
|
|
881
681
|
throw new Error(`Fatal error creating matter storage: ${error instanceof Error ? error.message : error}`);
|
|
882
682
|
}
|
|
883
|
-
// Clear the matterbridge context if the reset parameter is set (bridge mode)
|
|
884
683
|
if (hasParameter('reset') && getParameter('reset') === undefined) {
|
|
885
684
|
this.initialized = true;
|
|
886
685
|
await this.shutdownProcessAndReset();
|
|
887
686
|
this.shutdown = true;
|
|
888
687
|
return;
|
|
889
688
|
}
|
|
890
|
-
// Clear matterbridge plugin context if the reset parameter is set (childbridge mode)
|
|
891
689
|
if (hasParameter('reset') && getParameter('reset') !== undefined) {
|
|
892
690
|
this.log.debug(`Reset plugin ${getParameter('reset')}`);
|
|
893
691
|
const plugin = this.plugins.get(getParameter('reset'));
|
|
894
692
|
if (plugin) {
|
|
895
693
|
const matterStorageManager = await this.matterStorageService?.open(plugin.name);
|
|
896
694
|
if (!matterStorageManager) {
|
|
897
|
-
/* istanbul ignore next */
|
|
898
695
|
this.log.error(`Plugin ${plg}${plugin.name}${er} storageManager not found`);
|
|
899
696
|
}
|
|
900
697
|
else {
|
|
@@ -913,60 +710,47 @@ export class Matterbridge extends EventEmitter {
|
|
|
913
710
|
this.shutdown = true;
|
|
914
711
|
return;
|
|
915
712
|
}
|
|
916
|
-
// Check in 5 minutes the latest and dev versions of matterbridge and the plugins
|
|
917
713
|
clearTimeout(this.checkUpdateTimeout);
|
|
918
714
|
this.checkUpdateTimeout = setTimeout(async () => {
|
|
919
|
-
// const { checkUpdates } = await import('./checkUpdates.js');
|
|
920
|
-
// checkUpdates(this);
|
|
921
715
|
const { createESMWorker } = await import('@matterbridge/thread');
|
|
922
716
|
createESMWorker('CheckUpdates', this.resolveWorkerDistFilePath('workerCheckUpdates.js'));
|
|
923
717
|
}, 300 * 1000).unref();
|
|
924
|
-
// Check each 12 hours the latest and dev versions of matterbridge and the plugins
|
|
925
718
|
clearInterval(this.checkUpdateInterval);
|
|
926
719
|
this.checkUpdateInterval = setInterval(async () => {
|
|
927
|
-
// const { checkUpdates } = await import('./checkUpdates.js');
|
|
928
|
-
// checkUpdates(this);
|
|
929
720
|
const { createESMWorker } = await import('@matterbridge/thread');
|
|
930
721
|
createESMWorker('CheckUpdates', this.resolveWorkerDistFilePath('workerCheckUpdates.js'));
|
|
931
722
|
}, 12 * 60 * 60 * 1000).unref();
|
|
932
|
-
// Start the matterbridge in mode test
|
|
933
723
|
if (hasParameter('test')) {
|
|
934
724
|
this.bridgeMode = 'bridge';
|
|
935
725
|
return;
|
|
936
726
|
}
|
|
937
|
-
// Start the matterbridge in mode controller
|
|
938
727
|
if (hasParameter('controller')) {
|
|
939
728
|
this.bridgeMode = 'controller';
|
|
940
729
|
await this.startController();
|
|
941
730
|
return;
|
|
942
731
|
}
|
|
943
|
-
// Check if the bridge mode is set and start matterbridge in bridge mode if not set
|
|
944
732
|
if (!hasParameter('bridge') && !hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === '') {
|
|
945
733
|
this.log.info('Setting default matterbridge start mode to bridge');
|
|
946
734
|
await this.nodeContext?.set('bridgeMode', 'bridge');
|
|
947
735
|
}
|
|
948
|
-
// Wait delay if specified (default 2 minutes) and the system uptime is less than 5 minutes. It solves race conditions on system startup.
|
|
949
736
|
if (hasParameter('delay') && os.uptime() <= 60 * 5) {
|
|
950
737
|
const { wait } = await import('@matterbridge/utils');
|
|
951
738
|
const delay = getIntParameter('delay') || 120;
|
|
952
739
|
this.log.warn('Delay switch found with system uptime less then 5 minutes. Waiting for ' + delay + ' seconds before starting matterbridge...');
|
|
953
740
|
await wait(delay * 1000, 'Race condition delay', true);
|
|
954
741
|
}
|
|
955
|
-
// Wait delay if specified (default 2 minutes). It solves race conditions on docker compose startup.
|
|
956
742
|
if (hasParameter('fixed_delay')) {
|
|
957
743
|
const { wait } = await import('@matterbridge/utils');
|
|
958
744
|
const delay = getIntParameter('fixed_delay') || 120;
|
|
959
745
|
this.log.warn('Fixed delay switch found. Waiting for ' + delay + ' seconds before starting matterbridge...');
|
|
960
746
|
await wait(delay * 1000, 'Fixed race condition delay', true);
|
|
961
747
|
}
|
|
962
|
-
// Start matterbridge in bridge mode
|
|
963
748
|
if (hasParameter('bridge') || (!hasParameter('childbridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'bridge')) {
|
|
964
749
|
this.bridgeMode = 'bridge';
|
|
965
750
|
this.log.debug(`Starting matterbridge in mode ${this.bridgeMode}`);
|
|
966
751
|
await this.startBridge();
|
|
967
752
|
return;
|
|
968
753
|
}
|
|
969
|
-
// Start matterbridge in childbridge mode
|
|
970
754
|
if (hasParameter('childbridge') || (!hasParameter('bridge') && (await this.nodeContext?.get('bridgeMode', '')) === 'childbridge')) {
|
|
971
755
|
this.bridgeMode = 'childbridge';
|
|
972
756
|
this.log.debug(`Starting matterbridge in mode ${this.bridgeMode}`);
|
|
@@ -974,22 +758,10 @@ export class Matterbridge extends EventEmitter {
|
|
|
974
758
|
return;
|
|
975
759
|
}
|
|
976
760
|
}
|
|
977
|
-
/**
|
|
978
|
-
* Asynchronously loads and starts the registered plugins.
|
|
979
|
-
*
|
|
980
|
-
* This method is responsible for initializing and starting all enabled plugins.
|
|
981
|
-
* It ensures that each plugin is properly loaded and started before the bridge starts.
|
|
982
|
-
*
|
|
983
|
-
* @param {boolean} [wait] - If true, the method will wait for all plugins to be fully loaded and started before resolving. Defaults to false.
|
|
984
|
-
* @param {boolean} [start] - If true, the method will start the plugins after loading them. Defaults to true.
|
|
985
|
-
* @returns {Promise<void>} A promise that resolves when all plugins have been loaded and started.
|
|
986
|
-
*/
|
|
987
761
|
async startPlugins(wait = false, start = true) {
|
|
988
|
-
// Check, load and start the plugins
|
|
989
762
|
for (const plugin of this.plugins) {
|
|
990
763
|
plugin.configJson = await this.plugins.loadConfig(plugin);
|
|
991
764
|
plugin.schemaJson = await this.plugins.loadSchema(plugin);
|
|
992
|
-
// Check if the plugin is available
|
|
993
765
|
if (!(await this.plugins.resolve(plugin.path))) {
|
|
994
766
|
this.log.error(`Plugin ${plg}${plugin.name}${er} not found or not validated. Disabling it.`);
|
|
995
767
|
plugin.enabled = false;
|
|
@@ -1009,16 +781,10 @@ export class Matterbridge extends EventEmitter {
|
|
|
1009
781
|
if (wait)
|
|
1010
782
|
await this.plugins.load(plugin, start, 'Matterbridge is starting');
|
|
1011
783
|
else
|
|
1012
|
-
this.plugins.load(plugin, start, 'Matterbridge is starting');
|
|
784
|
+
this.plugins.load(plugin, start, 'Matterbridge is starting');
|
|
1013
785
|
}
|
|
1014
786
|
this.frontend.wssSendRefreshRequired('plugins');
|
|
1015
787
|
}
|
|
1016
|
-
/**
|
|
1017
|
-
* Registers the process handlers for uncaughtException, unhandledRejection, SIGINT and SIGTERM.
|
|
1018
|
-
* - When an uncaught exception occurs, the exceptionHandler logs the error message and stack trace.
|
|
1019
|
-
* - When an unhandled promise rejection occurs, the rejectionHandler logs the reason and stack trace.
|
|
1020
|
-
* - When either of SIGINT and SIGTERM signals are received, the cleanup method is called with an appropriate message.
|
|
1021
|
-
*/
|
|
1022
788
|
registerProcessHandlers() {
|
|
1023
789
|
this.log.debug(`Registering uncaughtException and unhandledRejection handlers...`);
|
|
1024
790
|
process.removeAllListeners('uncaughtException');
|
|
@@ -1045,9 +811,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1045
811
|
};
|
|
1046
812
|
process.on('SIGTERM', this.sigtermHandler);
|
|
1047
813
|
}
|
|
1048
|
-
/**
|
|
1049
|
-
* Deregisters the process uncaughtException, unhandledRejection, SIGINT and SIGTERM signal handlers.
|
|
1050
|
-
*/
|
|
1051
814
|
deregisterProcessHandlers() {
|
|
1052
815
|
this.log.debug(`Deregistering uncaughtException and unhandledRejection handlers...`);
|
|
1053
816
|
if (this.exceptionHandler)
|
|
@@ -1064,20 +827,7 @@ export class Matterbridge extends EventEmitter {
|
|
|
1064
827
|
process.off('SIGTERM', this.sigtermHandler);
|
|
1065
828
|
this.sigtermHandler = undefined;
|
|
1066
829
|
}
|
|
1067
|
-
/**
|
|
1068
|
-
* Logs the node and system information.
|
|
1069
|
-
*
|
|
1070
|
-
* @remarks
|
|
1071
|
-
* This method retrieves and logs various details about the host system, including:
|
|
1072
|
-
* - IP address information (IPv4, IPv6, MAC address)
|
|
1073
|
-
* - Node.js version
|
|
1074
|
-
* - Hostname and user information
|
|
1075
|
-
* - Operating system details (type, release, platform, architecture)
|
|
1076
|
-
* - Memory usage statistics
|
|
1077
|
-
* - Uptime information for both the system and the process
|
|
1078
|
-
*/
|
|
1079
830
|
async logNodeAndSystemInfo() {
|
|
1080
|
-
// IP address information
|
|
1081
831
|
const excludedInterfaceNamePattern = /(tailscale|wireguard|openvpn|zerotier|hamachi|\bwg\d+\b|\btun\d+\b|\btap\d+\b|\butun\d+\b|docker|podman|\bveth[a-z0-9]*\b|\bbr-[a-z0-9]+\b|cni|kube|flannel|calico|virbr\d*\b|vmware|vmnet\d*\b|virtualbox|vboxnet\d*\b|teredo|isatap)/i;
|
|
1082
832
|
const networkInterfaces = os.networkInterfaces();
|
|
1083
833
|
this.systemInformation.interfaceName = '';
|
|
@@ -1111,18 +861,16 @@ export class Matterbridge extends EventEmitter {
|
|
|
1111
861
|
break;
|
|
1112
862
|
}
|
|
1113
863
|
}
|
|
1114
|
-
// Node information
|
|
1115
864
|
this.systemInformation.nodeVersion = process.versions.node;
|
|
1116
865
|
const versionMajor = parseInt(this.systemInformation.nodeVersion.split('.')[0]);
|
|
1117
866
|
const versionMinor = parseInt(this.systemInformation.nodeVersion.split('.')[1]);
|
|
1118
867
|
const versionPatch = parseInt(this.systemInformation.nodeVersion.split('.')[2]);
|
|
1119
|
-
// Host system information
|
|
1120
868
|
this.systemInformation.hostname = os.hostname();
|
|
1121
869
|
this.systemInformation.user = os.userInfo().username;
|
|
1122
|
-
this.systemInformation.osType = os.type();
|
|
1123
|
-
this.systemInformation.osRelease = os.release();
|
|
1124
|
-
this.systemInformation.osPlatform = os.platform();
|
|
1125
|
-
this.systemInformation.osArch = os.arch();
|
|
870
|
+
this.systemInformation.osType = os.type();
|
|
871
|
+
this.systemInformation.osRelease = os.release();
|
|
872
|
+
this.systemInformation.osPlatform = os.platform();
|
|
873
|
+
this.systemInformation.osArch = os.arch();
|
|
1126
874
|
this.systemInformation.totalMemory = formatBytes(os.totalmem());
|
|
1127
875
|
this.systemInformation.freeMemory = formatBytes(os.freemem());
|
|
1128
876
|
this.systemInformation.systemUptime = formatUptime(os.uptime());
|
|
@@ -1132,7 +880,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1132
880
|
this.systemInformation.rss = formatBytes(process.memoryUsage().rss);
|
|
1133
881
|
this.systemInformation.heapTotal = formatBytes(process.memoryUsage().heapTotal);
|
|
1134
882
|
this.systemInformation.heapUsed = formatBytes(process.memoryUsage().heapUsed);
|
|
1135
|
-
// Log the system information
|
|
1136
883
|
this.log.debug('Host System Information:');
|
|
1137
884
|
this.log.debug(`- Hostname: ${this.systemInformation.hostname}`);
|
|
1138
885
|
this.log.debug(`- User: ${this.systemInformation.user}`);
|
|
@@ -1152,17 +899,14 @@ export class Matterbridge extends EventEmitter {
|
|
|
1152
899
|
this.log.debug(`- RSS: ${this.systemInformation.rss}`);
|
|
1153
900
|
this.log.debug(`- Heap Total: ${this.systemInformation.heapTotal}`);
|
|
1154
901
|
this.log.debug(`- Heap Used: ${this.systemInformation.heapUsed}`);
|
|
1155
|
-
// Log directories
|
|
1156
902
|
this.log.debug(`Root Directory: ${this.rootDirectory}`);
|
|
1157
903
|
this.log.debug(`Home Directory: ${this.homeDirectory}`);
|
|
1158
904
|
this.log.debug(`Matterbridge Directory: ${this.matterbridgeDirectory}`);
|
|
1159
905
|
this.log.debug(`Matterbridge Plugin Directory: ${this.matterbridgePluginDirectory}`);
|
|
1160
906
|
this.log.debug(`Matterbridge Matter Certificate Directory: ${this.matterbridgeCertDirectory}`);
|
|
1161
|
-
// Global node_modules directory
|
|
1162
907
|
if (this.nodeContext)
|
|
1163
908
|
this.globalModulesDirectory = await this.nodeContext.get('globalModulesDirectory', '');
|
|
1164
909
|
if (this.globalModulesDirectory === '') {
|
|
1165
|
-
// First run of Matterbridge so the node storage is empty
|
|
1166
910
|
this.log.debug(`Getting global node_modules directory...`);
|
|
1167
911
|
try {
|
|
1168
912
|
const { getGlobalNodeModules } = await import('@matterbridge/utils');
|
|
@@ -1175,42 +919,29 @@ export class Matterbridge extends EventEmitter {
|
|
|
1175
919
|
}
|
|
1176
920
|
}
|
|
1177
921
|
else {
|
|
1178
|
-
// The global node_modules directory is already set in the node storage and we check if it is still valid
|
|
1179
922
|
this.log.debug(`Global node_modules Directory: ${this.globalModulesDirectory}`);
|
|
1180
923
|
const { createESMWorker } = await import('@matterbridge/thread');
|
|
1181
924
|
createESMWorker('NpmGlobalPrefix', this.resolveWorkerDistFilePath('workerGlobalPrefix.js'));
|
|
1182
925
|
}
|
|
1183
|
-
// Matterbridge version
|
|
1184
926
|
this.log.debug(`Reading matterbridge package.json...`);
|
|
1185
927
|
const packageJson = JSON.parse(await fs.promises.readFile(path.join(this.rootDirectory, 'package.json'), 'utf-8'));
|
|
1186
928
|
this.matterbridgeVersion = this.matterbridgeLatestVersion = this.matterbridgeDevVersion = packageJson.version;
|
|
1187
929
|
this.log.debug(`Matterbridge Version: ${this.matterbridgeVersion}`);
|
|
1188
|
-
// Matterbridge latest version (will be set in the checkUpdate function)
|
|
1189
930
|
if (this.nodeContext)
|
|
1190
931
|
this.matterbridgeLatestVersion = await this.nodeContext.get('matterbridgeLatestVersion', this.matterbridgeVersion);
|
|
1191
932
|
this.log.debug(`Matterbridge Latest Version: ${this.matterbridgeLatestVersion}`);
|
|
1192
|
-
// Matterbridge dev version (will be set in the checkUpdate function)
|
|
1193
933
|
if (this.nodeContext)
|
|
1194
934
|
this.matterbridgeDevVersion = await this.nodeContext.get('matterbridgeDevVersion', this.matterbridgeVersion);
|
|
1195
935
|
this.log.debug(`Matterbridge Dev Version: ${this.matterbridgeDevVersion}`);
|
|
1196
|
-
// Frontend version
|
|
1197
936
|
this.log.debug(`Reading frontend package.json...`);
|
|
1198
937
|
const frontendPackageJson = JSON.parse(await fs.promises.readFile(path.join(this.rootDirectory, 'apps', 'frontend', 'package.json'), 'utf8'));
|
|
1199
938
|
this.frontendVersion = frontendPackageJson.version;
|
|
1200
939
|
this.log.debug(`Frontend version ${CYAN}${this.frontendVersion}${db}`);
|
|
1201
|
-
// Current working directory
|
|
1202
940
|
const currentDir = process.cwd();
|
|
1203
941
|
this.log.debug(`Current Working Directory: ${currentDir}`);
|
|
1204
|
-
// Command line arguments (excluding 'node' and the script name)
|
|
1205
942
|
const cmdArgs = process.argv.slice(2).join(' ');
|
|
1206
943
|
this.log.debug(`Command Line Arguments: ${cmdArgs}`);
|
|
1207
944
|
}
|
|
1208
|
-
/**
|
|
1209
|
-
* Set the logger logLevel for the Matterbridge classes and call onChangeLoggerLevel() for each plugin.
|
|
1210
|
-
*
|
|
1211
|
-
* @param {LogLevel} logLevel The logger logLevel to set.
|
|
1212
|
-
* @returns {Promise<LogLevel>} A promise that resolves when the logLevel has been set.
|
|
1213
|
-
*/
|
|
1214
945
|
async setLogLevel(logLevel) {
|
|
1215
946
|
this.logLevel = logLevel;
|
|
1216
947
|
this.log.logLevel = logLevel;
|
|
@@ -1224,86 +955,57 @@ export class Matterbridge extends EventEmitter {
|
|
|
1224
955
|
continue;
|
|
1225
956
|
if (plugin.platform.config.debug === true)
|
|
1226
957
|
pluginDebug = true;
|
|
1227
|
-
plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug"
|
|
1228
|
-
await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug"
|
|
1229
|
-
}
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
callbackLogLevel = "debug" /* LogLevel.DEBUG */;
|
|
958
|
+
plugin.platform.log.logLevel = plugin.platform.config.debug === true ? "debug" : logLevel;
|
|
959
|
+
await plugin.platform.onChangeLoggerLevel(plugin.platform.config.debug === true ? "debug" : logLevel);
|
|
960
|
+
}
|
|
961
|
+
let callbackLogLevel = "notice";
|
|
962
|
+
if (logLevel === "info" || Logger.level === MatterLogLevel.INFO)
|
|
963
|
+
callbackLogLevel = "info";
|
|
964
|
+
if (logLevel === "debug" || Logger.level === MatterLogLevel.DEBUG || pluginDebug)
|
|
965
|
+
callbackLogLevel = "debug";
|
|
1236
966
|
AnsiLogger.setGlobalCallbackLevel(callbackLogLevel);
|
|
1237
967
|
this.log.debug(`WebSocketServer logger global callback set to ${callbackLogLevel}`);
|
|
1238
968
|
return logLevel;
|
|
1239
969
|
}
|
|
1240
|
-
/**
|
|
1241
|
-
* Get the current logger logLevel.
|
|
1242
|
-
*
|
|
1243
|
-
* @returns {LogLevel} The current logger logLevel.
|
|
1244
|
-
*/
|
|
1245
970
|
getLogLevel() {
|
|
1246
971
|
return this.log.logLevel;
|
|
1247
972
|
}
|
|
1248
|
-
/**
|
|
1249
|
-
* Creates a MatterLogger function to show the matter.js log messages in AnsiLogger (for the frontend).
|
|
1250
|
-
* It also logs to file (matter.log) if fileLogger is true.
|
|
1251
|
-
*
|
|
1252
|
-
* @param {boolean} fileLogger - Whether to log to file or not.
|
|
1253
|
-
* @returns {(text: string, message: Diagnostic.Message) => void} The MatterLogger function. \x1b[35m for violet \x1b[34m is blue
|
|
1254
|
-
*/
|
|
1255
973
|
createDestinationMatterLogger(fileLogger) {
|
|
1256
974
|
if (fileLogger) {
|
|
1257
975
|
this.matterLog.logFilePath = path.join(this.matterbridgeDirectory, MATTER_LOGGER_FILE);
|
|
1258
976
|
}
|
|
1259
977
|
return (text, message) => {
|
|
1260
|
-
// 2024-08-21 08:55:19.488 DEBUG InteractionMessenger Sending DataReport chunk with 28 attributes and 0 events: 1004 bytes
|
|
1261
978
|
const logger = text.slice(44, 44 + 20).trim();
|
|
1262
979
|
const msg = text.slice(65);
|
|
1263
980
|
this.matterLog.logName = logger;
|
|
1264
981
|
switch (message.level) {
|
|
1265
982
|
case MatterLogLevel.DEBUG:
|
|
1266
|
-
this.matterLog.log("debug"
|
|
983
|
+
this.matterLog.log("debug", msg);
|
|
1267
984
|
break;
|
|
1268
985
|
case MatterLogLevel.INFO:
|
|
1269
|
-
this.matterLog.log("info"
|
|
986
|
+
this.matterLog.log("info", msg);
|
|
1270
987
|
break;
|
|
1271
988
|
case MatterLogLevel.NOTICE:
|
|
1272
|
-
this.matterLog.log("notice"
|
|
989
|
+
this.matterLog.log("notice", msg);
|
|
1273
990
|
break;
|
|
1274
991
|
case MatterLogLevel.WARN:
|
|
1275
|
-
this.matterLog.log("warn"
|
|
992
|
+
this.matterLog.log("warn", msg);
|
|
1276
993
|
break;
|
|
1277
994
|
case MatterLogLevel.ERROR:
|
|
1278
|
-
this.matterLog.log("error"
|
|
995
|
+
this.matterLog.log("error", msg);
|
|
1279
996
|
break;
|
|
1280
997
|
case MatterLogLevel.FATAL:
|
|
1281
|
-
this.matterLog.log("fatal"
|
|
998
|
+
this.matterLog.log("fatal", msg);
|
|
1282
999
|
break;
|
|
1283
1000
|
}
|
|
1284
1001
|
};
|
|
1285
1002
|
}
|
|
1286
|
-
/**
|
|
1287
|
-
* Restarts the process by exiting the current instance and loading a new instance (/api/restart).
|
|
1288
|
-
*
|
|
1289
|
-
* @returns {Promise<void>} A promise that resolves when the restart is completed.
|
|
1290
|
-
*/
|
|
1291
1003
|
async restartProcess() {
|
|
1292
1004
|
await this.cleanup('restarting...', true);
|
|
1293
1005
|
}
|
|
1294
|
-
/**
|
|
1295
|
-
* Shut down the process (/api/shutdown).
|
|
1296
|
-
*
|
|
1297
|
-
* @returns {Promise<void>} A promise that resolves when the shutdown is completed.
|
|
1298
|
-
*/
|
|
1299
1006
|
async shutdownProcess() {
|
|
1300
1007
|
await this.cleanup('shutting down...', false);
|
|
1301
1008
|
}
|
|
1302
|
-
/**
|
|
1303
|
-
* Update matterbridge and shut down the process (virtual device 'Update Matterbridge').
|
|
1304
|
-
*
|
|
1305
|
-
* @returns {Promise<void>} A promise that resolves when the update is completed.
|
|
1306
|
-
*/
|
|
1307
1009
|
async updateProcess() {
|
|
1308
1010
|
this.log.info('Updating matterbridge...');
|
|
1309
1011
|
const { spawnCommand } = await import('./spawn.js');
|
|
@@ -1316,13 +1018,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1316
1018
|
this.frontend.wssSendRestartRequired();
|
|
1317
1019
|
await this.cleanup('updating...', false);
|
|
1318
1020
|
}
|
|
1319
|
-
/**
|
|
1320
|
-
* Unregister all devices and shut down the process (/api/unregister).
|
|
1321
|
-
*
|
|
1322
|
-
* @param {number} [timeout] - The timeout duration to wait for the message exchange to complete in milliseconds. Default is 1000.
|
|
1323
|
-
*
|
|
1324
|
-
* @returns {Promise<void>} A promise that resolves when the cleanup is completed.
|
|
1325
|
-
*/
|
|
1326
1021
|
async unregisterAndShutdownProcess(timeout = 1000) {
|
|
1327
1022
|
const { wait } = await import('@matterbridge/utils');
|
|
1328
1023
|
this.log.info('Unregistering all devices and shutting down...');
|
|
@@ -1335,71 +1030,46 @@ export class Matterbridge extends EventEmitter {
|
|
|
1335
1030
|
await this.removeAllBridgedEndpoints(plugin.name, 100);
|
|
1336
1031
|
}
|
|
1337
1032
|
this.log.debug('Waiting for the MessageExchange to finish...');
|
|
1338
|
-
await wait(timeout);
|
|
1033
|
+
await wait(timeout);
|
|
1339
1034
|
this.log.debug('Cleaning up and shutting down...');
|
|
1340
1035
|
await this.cleanup('unregistered all devices and shutting down...', false, timeout);
|
|
1341
1036
|
}
|
|
1342
|
-
/**
|
|
1343
|
-
* Reset commissioning and shut down the process (/api/reset).
|
|
1344
|
-
*
|
|
1345
|
-
* @returns {Promise<void>} A promise that resolves when the cleanup is completed.
|
|
1346
|
-
*/
|
|
1347
1037
|
async shutdownProcessAndReset() {
|
|
1348
1038
|
await this.cleanup('shutting down with reset...', false);
|
|
1349
1039
|
}
|
|
1350
|
-
/**
|
|
1351
|
-
* Factory reset and shut down the process (/api/factory-reset).
|
|
1352
|
-
*
|
|
1353
|
-
* @returns {Promise<void>} A promise that resolves when the cleanup is completed.
|
|
1354
|
-
*/
|
|
1355
1040
|
async shutdownProcessAndFactoryReset() {
|
|
1356
1041
|
await this.cleanup('shutting down with factory reset...', false);
|
|
1357
1042
|
}
|
|
1358
|
-
/**
|
|
1359
|
-
* Cleans up the Matterbridge instance.
|
|
1360
|
-
*
|
|
1361
|
-
* @param {string} message - The cleanup message.
|
|
1362
|
-
* @param {boolean} [restart] - Indicates whether to restart the instance after cleanup. Default is `false`.
|
|
1363
|
-
* @param {number} [pause] - The pause in ms to wait for the message exchange to complete in milliseconds. Default is 1000.
|
|
1364
|
-
*
|
|
1365
|
-
* @returns {Promise<void>} A promise that resolves when the cleanup is completed.
|
|
1366
|
-
*/
|
|
1367
1043
|
async cleanup(message, restart = false, pause = 1000) {
|
|
1368
1044
|
if (this.initialized && !this.hasCleanupStarted) {
|
|
1369
1045
|
this.emit('cleanup_started');
|
|
1370
1046
|
this.hasCleanupStarted = true;
|
|
1371
1047
|
this.log.info(message);
|
|
1372
|
-
// Clear the start matter interval
|
|
1373
1048
|
if (this.startMatterInterval) {
|
|
1374
1049
|
clearInterval(this.startMatterInterval);
|
|
1375
1050
|
this.startMatterInterval = undefined;
|
|
1376
1051
|
this.log.debug('Start matter interval cleared');
|
|
1377
1052
|
}
|
|
1378
|
-
// Clear the check update timeout
|
|
1379
1053
|
if (this.checkUpdateTimeout) {
|
|
1380
1054
|
clearTimeout(this.checkUpdateTimeout);
|
|
1381
1055
|
this.checkUpdateTimeout = undefined;
|
|
1382
1056
|
this.log.debug('Check update timeout cleared');
|
|
1383
1057
|
}
|
|
1384
|
-
// Clear the check update interval
|
|
1385
1058
|
if (this.checkUpdateInterval) {
|
|
1386
1059
|
clearInterval(this.checkUpdateInterval);
|
|
1387
1060
|
this.checkUpdateInterval = undefined;
|
|
1388
1061
|
this.log.debug('Check update interval cleared');
|
|
1389
1062
|
}
|
|
1390
|
-
// Clear the configure timeout
|
|
1391
1063
|
if (this.configureTimeout) {
|
|
1392
1064
|
clearTimeout(this.configureTimeout);
|
|
1393
1065
|
this.configureTimeout = undefined;
|
|
1394
1066
|
this.log.debug('Matterbridge configure timeout cleared');
|
|
1395
1067
|
}
|
|
1396
|
-
// Clear the reachability timeout
|
|
1397
1068
|
if (this.reachabilityTimeout) {
|
|
1398
1069
|
clearTimeout(this.reachabilityTimeout);
|
|
1399
1070
|
this.reachabilityTimeout = undefined;
|
|
1400
1071
|
this.log.debug('Matterbridge reachability timeout cleared');
|
|
1401
1072
|
}
|
|
1402
|
-
// Call the shutdown method of each plugin and clear the plugins reachability timeout
|
|
1403
1073
|
for (const plugin of this.plugins) {
|
|
1404
1074
|
if (!plugin.enabled || plugin.error)
|
|
1405
1075
|
continue;
|
|
@@ -1410,7 +1080,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1410
1080
|
this.log.debug(`Plugin ${plg}${plugin.name}${db} reachability timeout cleared`);
|
|
1411
1081
|
}
|
|
1412
1082
|
}
|
|
1413
|
-
// Stop matter server nodes
|
|
1414
1083
|
this.log.notice(`Stopping matter server nodes in ${this.bridgeMode} mode...`);
|
|
1415
1084
|
if (pause > 0) {
|
|
1416
1085
|
const { wait } = await import('@matterbridge/utils');
|
|
@@ -1438,7 +1107,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1438
1107
|
}
|
|
1439
1108
|
}
|
|
1440
1109
|
this.log.notice('Stopped matter server nodes');
|
|
1441
|
-
// Matter commisioning reset
|
|
1442
1110
|
if (message === 'shutting down with reset...') {
|
|
1443
1111
|
this.log.info('Resetting Matterbridge commissioning information...');
|
|
1444
1112
|
await this.matterStorageManager?.createContext('events')?.clearAll();
|
|
@@ -1448,7 +1116,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1448
1116
|
await this.matterbridgeContext?.clearAll();
|
|
1449
1117
|
this.log.info('Matter storage reset done! Remove the bridge from the controller.');
|
|
1450
1118
|
}
|
|
1451
|
-
// Unregister all devices
|
|
1452
1119
|
if (message === 'unregistered all devices and shutting down...') {
|
|
1453
1120
|
if (this.bridgeMode === 'bridge') {
|
|
1454
1121
|
await this.matterStorageManager?.createContext('root')?.createContext('parts')?.createContext('Matterbridge')?.createContext('parts')?.clearAll();
|
|
@@ -1466,14 +1133,7 @@ export class Matterbridge extends EventEmitter {
|
|
|
1466
1133
|
}
|
|
1467
1134
|
this.log.info('Matter storage reset done!');
|
|
1468
1135
|
}
|
|
1469
|
-
// Stop matter storage
|
|
1470
1136
|
await this.stopMatterStorage();
|
|
1471
|
-
/**
|
|
1472
|
-
* Unlink a file safely, ignoring errors.
|
|
1473
|
-
*
|
|
1474
|
-
* @param {string} path - The path to the file to unlink.
|
|
1475
|
-
* @param {AnsiLogger} log - The logger to use for logging.
|
|
1476
|
-
*/
|
|
1477
1137
|
function unlinkSafe(path, log) {
|
|
1478
1138
|
try {
|
|
1479
1139
|
log.debug(`Removing ${path}...`);
|
|
@@ -1481,15 +1141,12 @@ export class Matterbridge extends EventEmitter {
|
|
|
1481
1141
|
log.debug(`Removed ${path}`);
|
|
1482
1142
|
}
|
|
1483
1143
|
catch {
|
|
1484
|
-
// Ignore errors if the file does not exist
|
|
1485
1144
|
}
|
|
1486
1145
|
}
|
|
1487
|
-
// Remove the resumption records for Matterbridge (bridge mode)
|
|
1488
1146
|
this.log.debug(`Cleaning matter storage context for ${GREEN}Matterbridge${db}...`);
|
|
1489
1147
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, 'Matterbridge', 'sessions.resumptionRecords'), this.log);
|
|
1490
1148
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, 'Matterbridge', 'root.subscriptions.subscriptions'), this.log);
|
|
1491
1149
|
for (const plugin of this.plugins.array()) {
|
|
1492
|
-
// Remove the resumption records for the plugins (childbridge mode)
|
|
1493
1150
|
this.log.debug(`Cleaning matter storage context for plugin ${plg}${plugin.name}${db}...`);
|
|
1494
1151
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, plugin.name, 'sessions.resumptionRecords'), this.log);
|
|
1495
1152
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, plugin.name, 'root.subscriptions.subscriptions'), this.log);
|
|
@@ -1497,38 +1154,19 @@ export class Matterbridge extends EventEmitter {
|
|
|
1497
1154
|
for (const device of this.devices.array().filter((d) => d.mode === 'server')) {
|
|
1498
1155
|
if (!device.deviceName)
|
|
1499
1156
|
continue;
|
|
1500
|
-
// Remove the resumption records for the server mode devices
|
|
1501
1157
|
this.log.debug(`Cleaning matter storage context for server node device ${dev}${device.deviceName}${db}...`);
|
|
1502
1158
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, device.deviceName.replace(/[ .]/g, ''), 'sessions.resumptionRecords'), this.log);
|
|
1503
1159
|
unlinkSafe(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME, device.deviceName.replace(/[ .]/g, ''), 'root.subscriptions.subscriptions'), this.log);
|
|
1504
1160
|
}
|
|
1505
|
-
// Stop the frontend
|
|
1506
1161
|
await this.frontend.stop();
|
|
1507
1162
|
this.frontend.destroy();
|
|
1508
|
-
// Close PluginManager and DeviceManager
|
|
1509
1163
|
this.plugins.destroy();
|
|
1510
1164
|
this.devices.destroy();
|
|
1511
|
-
// Stop thread messaging server
|
|
1512
1165
|
this.server.close();
|
|
1513
|
-
// Close the matterbridge node storage and context
|
|
1514
1166
|
if (this.nodeStorage && this.nodeContext) {
|
|
1515
|
-
/*
|
|
1516
|
-
TODO: Implement serialization of registered devices
|
|
1517
|
-
this.log.info('Saving registered devices...');
|
|
1518
|
-
const serializedRegisteredDevices: SerializedMatterbridgeEndpoint[] = [];
|
|
1519
|
-
this.devices.forEach(async (device) => {
|
|
1520
|
-
const serializedMatterbridgeDevice = MatterbridgeEndpoint.serialize(device);
|
|
1521
|
-
this.log.info(`- ${serializedMatterbridgeDevice.deviceName}${rs}\n`, serializedMatterbridgeDevice);
|
|
1522
|
-
if (serializedMatterbridgeDevice) serializedRegisteredDevices.push(serializedMatterbridgeDevice);
|
|
1523
|
-
});
|
|
1524
|
-
await this.nodeContext.set<SerializedMatterbridgeEndpoint[]>('devices', serializedRegisteredDevices);
|
|
1525
|
-
this.log.info(`Saved registered devices (${serializedRegisteredDevices?.length})`);
|
|
1526
|
-
*/
|
|
1527
|
-
// Clear nodeContext and nodeStorage (they just need 1000ms to write the data to disk)
|
|
1528
1167
|
this.log.debug(`Closing node storage context for ${plg}Matterbridge${db}...`);
|
|
1529
1168
|
await this.nodeContext.close();
|
|
1530
1169
|
this.nodeContext = undefined;
|
|
1531
|
-
// Clear nodeContext for each plugin (they just need 1000ms to write the data to disk)
|
|
1532
1170
|
for (const plugin of this.plugins) {
|
|
1533
1171
|
if (plugin.nodeContext) {
|
|
1534
1172
|
this.log.debug(`Closing node storage context for plugin ${plg}${plugin.name}${db}...`);
|
|
@@ -1545,10 +1183,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
1545
1183
|
}
|
|
1546
1184
|
this.plugins.clear();
|
|
1547
1185
|
this.devices.clear();
|
|
1548
|
-
// Factory reset
|
|
1549
1186
|
if (message === 'shutting down with factory reset...') {
|
|
1550
1187
|
try {
|
|
1551
|
-
// Delete matter storage directory with its subdirectories and backup
|
|
1552
1188
|
const dir = path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME);
|
|
1553
1189
|
this.log.info(`Removing matter storage directory: ${dir}`);
|
|
1554
1190
|
await fs.promises.rm(dir, { recursive: true });
|
|
@@ -1557,13 +1193,11 @@ export class Matterbridge extends EventEmitter {
|
|
|
1557
1193
|
await fs.promises.rm(backup, { recursive: true });
|
|
1558
1194
|
}
|
|
1559
1195
|
catch (error) {
|
|
1560
|
-
// istanbul ignore next if
|
|
1561
1196
|
if (error instanceof Error && error.code !== 'ENOENT') {
|
|
1562
1197
|
this.log.error(`Error removing matter storage directory: ${error}`);
|
|
1563
1198
|
}
|
|
1564
1199
|
}
|
|
1565
1200
|
try {
|
|
1566
|
-
// Delete matterbridge storage directory with its subdirectories and backup
|
|
1567
1201
|
const dir = path.join(this.matterbridgeDirectory, NODE_STORAGE_DIR);
|
|
1568
1202
|
this.log.info(`Removing matterbridge storage directory: ${dir}`);
|
|
1569
1203
|
await fs.promises.rm(dir, { recursive: true });
|
|
@@ -1572,20 +1206,18 @@ export class Matterbridge extends EventEmitter {
|
|
|
1572
1206
|
await fs.promises.rm(backup, { recursive: true });
|
|
1573
1207
|
}
|
|
1574
1208
|
catch (error) {
|
|
1575
|
-
// istanbul ignore next if
|
|
1576
1209
|
if (error instanceof Error && error.code !== 'ENOENT') {
|
|
1577
1210
|
this.log.error(`Error removing matterbridge storage directory: ${error}`);
|
|
1578
1211
|
}
|
|
1579
1212
|
}
|
|
1580
1213
|
this.log.info('Factory reset done! Remove all paired fabrics from the controllers.');
|
|
1581
1214
|
}
|
|
1582
|
-
// Deregisters the process handlers
|
|
1583
1215
|
this.deregisterProcessHandlers();
|
|
1584
1216
|
if (restart) {
|
|
1585
1217
|
if (message === 'updating...') {
|
|
1586
1218
|
this.log.info('Cleanup completed. Updating...');
|
|
1587
1219
|
Matterbridge.instance = undefined;
|
|
1588
|
-
this.emit('update');
|
|
1220
|
+
this.emit('update');
|
|
1589
1221
|
}
|
|
1590
1222
|
else if (message === 'restarting...') {
|
|
1591
1223
|
this.log.info('Cleanup completed. Restarting...');
|
|
@@ -1614,14 +1246,7 @@ export class Matterbridge extends EventEmitter {
|
|
|
1614
1246
|
this.log.debug('Cleanup already started...');
|
|
1615
1247
|
}
|
|
1616
1248
|
}
|
|
1617
|
-
/**
|
|
1618
|
-
* Starts the Matterbridge in bridge mode.
|
|
1619
|
-
*
|
|
1620
|
-
* @private
|
|
1621
|
-
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
|
|
1622
|
-
*/
|
|
1623
1249
|
async startBridge() {
|
|
1624
|
-
// Plugins are configured by a timer when matter server is started and plugin.configured is set to true
|
|
1625
1250
|
if (!this.matterStorageManager)
|
|
1626
1251
|
throw new Error('No storage manager initialized');
|
|
1627
1252
|
if (!this.matterbridgeContext)
|
|
@@ -1635,7 +1260,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1635
1260
|
this.frontend.wssSendSnackbarMessage(`The bridge is starting...`, 0, 'info');
|
|
1636
1261
|
let failCount = 0;
|
|
1637
1262
|
this.startMatterInterval = setInterval(async () => {
|
|
1638
|
-
// istanbul ignore if cause is just a logging statement
|
|
1639
1263
|
if (failCount && failCount % 10 === 0) {
|
|
1640
1264
|
this.frontend.wssSendSnackbarMessage(`The bridge is still starting...`, 10, 'info');
|
|
1641
1265
|
this.frontend.wssSendRefreshRequired('plugins');
|
|
@@ -1669,16 +1293,13 @@ export class Matterbridge extends EventEmitter {
|
|
|
1669
1293
|
clearInterval(this.startMatterInterval);
|
|
1670
1294
|
this.startMatterInterval = undefined;
|
|
1671
1295
|
this.log.debug('Cleared startMatterInterval interval in bridge mode');
|
|
1672
|
-
|
|
1673
|
-
this.startServerNode(this.serverNode); // We don't await this, because the server node is started in the background
|
|
1674
|
-
// Start the Matter server node of single devices in mode 'server'
|
|
1296
|
+
this.startServerNode(this.serverNode);
|
|
1675
1297
|
for (const device of this.devices.array()) {
|
|
1676
1298
|
if (device.mode === 'server' && device.serverNode) {
|
|
1677
1299
|
this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
|
|
1678
|
-
this.startServerNode(device.serverNode);
|
|
1300
|
+
this.startServerNode(device.serverNode);
|
|
1679
1301
|
}
|
|
1680
1302
|
}
|
|
1681
|
-
// Configure the plugins
|
|
1682
1303
|
this.configureTimeout = setTimeout(async () => {
|
|
1683
1304
|
for (const plugin of this.plugins.array()) {
|
|
1684
1305
|
if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
|
|
@@ -1696,13 +1317,11 @@ export class Matterbridge extends EventEmitter {
|
|
|
1696
1317
|
}
|
|
1697
1318
|
this.frontend.wssSendRefreshRequired('plugins');
|
|
1698
1319
|
}, 30 * 1000).unref();
|
|
1699
|
-
// Setting reachability to true
|
|
1700
1320
|
this.reachabilityTimeout = setTimeout(() => {
|
|
1701
1321
|
this.log.info(`Setting reachability to true for ${plg}Matterbridge${db}`);
|
|
1702
1322
|
if (this.aggregatorNode)
|
|
1703
1323
|
this.setAggregatorReachability(this.aggregatorNode, true);
|
|
1704
1324
|
}, 60 * 1000).unref();
|
|
1705
|
-
// Logger.get('LogServerNode').info(this.serverNode);
|
|
1706
1325
|
this.emit('bridge_started');
|
|
1707
1326
|
this.log.notice('Matterbridge bridge started successfully');
|
|
1708
1327
|
this.frontend.wssSendRefreshRequired('settings');
|
|
@@ -1710,33 +1329,22 @@ export class Matterbridge extends EventEmitter {
|
|
|
1710
1329
|
this.frontend.wssSendCloseSnackbarMessage(`The bridge is starting...`);
|
|
1711
1330
|
}, Number(process.env['MATTERBRIDGE_START_MATTER_INTERVAL_MS']) || this.startMatterIntervalMs);
|
|
1712
1331
|
}
|
|
1713
|
-
/**
|
|
1714
|
-
* Starts the Matterbridge in childbridge mode.
|
|
1715
|
-
*
|
|
1716
|
-
* @param {number} [delay] - The delay before starting the childbridge. Default is 1000 milliseconds.
|
|
1717
|
-
*
|
|
1718
|
-
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
|
|
1719
|
-
*/
|
|
1720
1332
|
async startChildbridge(delay = 1000) {
|
|
1721
1333
|
if (!this.matterStorageManager)
|
|
1722
1334
|
throw new Error('No storage manager initialized');
|
|
1723
1335
|
const { wait } = await import('@matterbridge/utils');
|
|
1724
|
-
// Load with await all plugins but don't start them. We get the platform.type to pre-create server nodes for DynamicPlatform plugins
|
|
1725
1336
|
this.log.debug('Loading all plugins in childbridge mode...');
|
|
1726
1337
|
await this.startPlugins(true, false);
|
|
1727
|
-
// Create server nodes for DynamicPlatform plugins and start all plugins in the background
|
|
1728
1338
|
this.log.debug('Creating server nodes for DynamicPlatform plugins and starting all plugins in childbridge mode...');
|
|
1729
1339
|
for (const plugin of this.plugins.array().filter((p) => p.enabled && !p.error)) {
|
|
1730
1340
|
if (plugin.type === 'DynamicPlatform')
|
|
1731
1341
|
await this.createDynamicPlugin(plugin);
|
|
1732
|
-
this.plugins.start(plugin, 'Matterbridge is starting');
|
|
1342
|
+
this.plugins.start(plugin, 'Matterbridge is starting');
|
|
1733
1343
|
}
|
|
1734
|
-
// Start the Matterbridge in childbridge mode when all plugins are loaded and started
|
|
1735
1344
|
this.log.debug('Starting start matter interval in childbridge mode...');
|
|
1736
1345
|
this.frontend.wssSendSnackbarMessage(`The bridge is starting...`, 0, 'info');
|
|
1737
1346
|
let failCount = 0;
|
|
1738
1347
|
this.startMatterInterval = setInterval(async () => {
|
|
1739
|
-
// istanbul ignore if cause is just a logging statement
|
|
1740
1348
|
if (failCount && failCount % 10 === 0) {
|
|
1741
1349
|
this.frontend.wssSendSnackbarMessage(`The bridge is still starting...`, 10, 'info');
|
|
1742
1350
|
this.frontend.wssSendRefreshRequired('plugins');
|
|
@@ -1774,9 +1382,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
1774
1382
|
clearInterval(this.startMatterInterval);
|
|
1775
1383
|
this.startMatterInterval = undefined;
|
|
1776
1384
|
if (delay > 0)
|
|
1777
|
-
await wait(Number(process.env['MATTERBRIDGE_PAUSE_MATTER_INTERVAL_MS']) || delay);
|
|
1385
|
+
await wait(Number(process.env['MATTERBRIDGE_PAUSE_MATTER_INTERVAL_MS']) || delay);
|
|
1778
1386
|
this.log.debug('Cleared startMatterInterval interval in childbridge mode');
|
|
1779
|
-
// Configure the plugins
|
|
1780
1387
|
this.configureTimeout = setTimeout(async () => {
|
|
1781
1388
|
for (const plugin of this.plugins.array()) {
|
|
1782
1389
|
if (!plugin.enabled || !plugin.loaded || !plugin.started || plugin.error)
|
|
@@ -1801,7 +1408,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
1801
1408
|
this.log.error(`Plugin ${plg}${plugin.name}${er} didn't register any devices to Matterbridge. Verify the plugin configuration.`);
|
|
1802
1409
|
continue;
|
|
1803
1410
|
}
|
|
1804
|
-
// istanbul ignore next if cause is just a safety check
|
|
1805
1411
|
if (!plugin.serverNode) {
|
|
1806
1412
|
this.log.error(`Server node not found for plugin ${plg}${plugin.name}${er}`);
|
|
1807
1413
|
continue;
|
|
@@ -1814,23 +1420,19 @@ export class Matterbridge extends EventEmitter {
|
|
|
1814
1420
|
this.log.error(`Node storage context not found for plugin ${plg}${plugin.name}${er}`);
|
|
1815
1421
|
continue;
|
|
1816
1422
|
}
|
|
1817
|
-
|
|
1818
|
-
this.startServerNode(plugin.serverNode); // We don't await this, because the server node is started in the background
|
|
1819
|
-
// Setting reachability to true
|
|
1423
|
+
this.startServerNode(plugin.serverNode);
|
|
1820
1424
|
plugin.reachabilityTimeout = setTimeout(() => {
|
|
1821
1425
|
this.log.info(`Setting reachability to true for ${plg}${plugin.name}${nf}`);
|
|
1822
1426
|
if (plugin.type === 'DynamicPlatform' && plugin.aggregatorNode)
|
|
1823
1427
|
this.setAggregatorReachability(plugin.aggregatorNode, true);
|
|
1824
1428
|
}, 60 * 1000).unref();
|
|
1825
1429
|
}
|
|
1826
|
-
// Start the Matter server node of single devices in mode 'server'
|
|
1827
1430
|
for (const device of this.devices.array()) {
|
|
1828
1431
|
if (device.mode === 'server' && device.serverNode) {
|
|
1829
1432
|
this.log.debug(`Starting server node for device ${dev}${device.deviceName}${db} in server mode...`);
|
|
1830
|
-
this.startServerNode(device.serverNode);
|
|
1433
|
+
this.startServerNode(device.serverNode);
|
|
1831
1434
|
}
|
|
1832
1435
|
}
|
|
1833
|
-
// Logger.get('LogServerNode').info(this.serverNode);
|
|
1834
1436
|
this.emit('childbridge_started');
|
|
1835
1437
|
this.log.notice('Matterbridge childbridge started successfully');
|
|
1836
1438
|
this.frontend.wssSendRefreshRequired('settings');
|
|
@@ -1838,229 +1440,9 @@ export class Matterbridge extends EventEmitter {
|
|
|
1838
1440
|
this.frontend.wssSendCloseSnackbarMessage(`The bridge is starting...`);
|
|
1839
1441
|
}, Number(process.env['MATTERBRIDGE_START_MATTER_INTERVAL_MS']) || this.startMatterIntervalMs);
|
|
1840
1442
|
}
|
|
1841
|
-
/**
|
|
1842
|
-
* Starts the Matterbridge controller.
|
|
1843
|
-
*
|
|
1844
|
-
* @private
|
|
1845
|
-
* @returns {Promise<void>} A promise that resolves when the Matterbridge is started.
|
|
1846
|
-
*/
|
|
1847
1443
|
async startController() {
|
|
1848
|
-
/*
|
|
1849
|
-
if (!this.matterStorageManager) {
|
|
1850
|
-
this.log.error('No storage manager initialized');
|
|
1851
|
-
await this.cleanup('No storage manager initialized');
|
|
1852
|
-
return;
|
|
1853
|
-
}
|
|
1854
|
-
this.log.info('Creating context: mattercontrollerContext');
|
|
1855
|
-
this.controllerContext = this.matterStorageManager.createContext('mattercontrollerContext');
|
|
1856
|
-
if (!this.controllerContext) {
|
|
1857
|
-
this.log.error('No storage context mattercontrollerContext initialized');
|
|
1858
|
-
await this.cleanup('No storage context mattercontrollerContext initialized');
|
|
1859
|
-
return;
|
|
1860
|
-
}
|
|
1861
|
-
|
|
1862
|
-
this.log.debug('Starting matterbridge in mode', this.bridgeMode);
|
|
1863
|
-
this.matterServer = await this.createMatterServer(this.storageManager);
|
|
1864
|
-
this.log.info('Creating matter commissioning controller');
|
|
1865
|
-
this.commissioningController = new CommissioningController({
|
|
1866
|
-
autoConnect: false,
|
|
1867
|
-
});
|
|
1868
|
-
this.log.info('Adding matter commissioning controller to matter server');
|
|
1869
|
-
await this.matterServer.addCommissioningController(this.commissioningController);
|
|
1870
|
-
|
|
1871
|
-
this.log.info('Starting matter server');
|
|
1872
|
-
await this.matterServer.start();
|
|
1873
|
-
this.log.info('Matter server started');
|
|
1874
|
-
const commissioningOptions: ControllerCommissioningFlowOptions = {
|
|
1875
|
-
regulatoryLocation: GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor,
|
|
1876
|
-
regulatoryCountryCode: 'XX',
|
|
1877
|
-
};
|
|
1878
|
-
const commissioningController = new CommissioningController({
|
|
1879
|
-
environment: {
|
|
1880
|
-
environment,
|
|
1881
|
-
id: uniqueId,
|
|
1882
|
-
},
|
|
1883
|
-
autoConnect: false, // Do not auto connect to the commissioned nodes
|
|
1884
|
-
adminFabricLabel,
|
|
1885
|
-
});
|
|
1886
|
-
|
|
1887
|
-
if (hasParameter('pairingcode')) {
|
|
1888
|
-
this.log.info('Pairing device with pairingcode:', getParameter('pairingcode'));
|
|
1889
|
-
const pairingCode = getParameter('pairingcode');
|
|
1890
|
-
const ip = this.controllerContext.has('ip') ? this.controllerContext.get<string>('ip') : undefined;
|
|
1891
|
-
const port = this.controllerContext.has('port') ? this.controllerContext.get<number>('port') : undefined;
|
|
1892
|
-
|
|
1893
|
-
let longDiscriminator, setupPin, shortDiscriminator;
|
|
1894
|
-
if (pairingCode !== undefined) {
|
|
1895
|
-
const pairingCodeCodec = ManualPairingCodeCodec.decode(pairingCode);
|
|
1896
|
-
shortDiscriminator = pairingCodeCodec.shortDiscriminator;
|
|
1897
|
-
longDiscriminator = undefined;
|
|
1898
|
-
setupPin = pairingCodeCodec.passcode;
|
|
1899
|
-
this.log.info(`Data extracted from pairing code: ${Logger.toJSON(pairingCodeCodec)}`);
|
|
1900
|
-
} else {
|
|
1901
|
-
longDiscriminator = await this.controllerContext.get('longDiscriminator', 3840);
|
|
1902
|
-
if (longDiscriminator > 4095) throw new Error('Discriminator value must be less than 4096');
|
|
1903
|
-
setupPin = this.controllerContext.get('pin', 20202021);
|
|
1904
|
-
}
|
|
1905
|
-
if ((shortDiscriminator === undefined && longDiscriminator === undefined) || setupPin === undefined) {
|
|
1906
|
-
throw new Error('Please specify the longDiscriminator of the device to commission with -longDiscriminator or provide a valid passcode with -passcode');
|
|
1907
|
-
}
|
|
1908
|
-
|
|
1909
|
-
const options = {
|
|
1910
|
-
commissioning: commissioningOptions,
|
|
1911
|
-
discovery: {
|
|
1912
|
-
knownAddress: ip !== undefined && port !== undefined ? { ip, port, type: 'udp' } : undefined,
|
|
1913
|
-
identifierData: longDiscriminator !== undefined ? { longDiscriminator } : shortDiscriminator !== undefined ? { shortDiscriminator } : {},
|
|
1914
|
-
},
|
|
1915
|
-
passcode: setupPin,
|
|
1916
|
-
} as NodeCommissioningOptions;
|
|
1917
|
-
this.log.info('Commissioning with options:', options);
|
|
1918
|
-
const nodeId = await this.commissioningController.commissionNode(options);
|
|
1919
|
-
this.log.info(`Commissioning successfully done with nodeId: ${nodeId}`);
|
|
1920
|
-
this.log.info('ActiveSessionInformation:', this.commissioningController.getActiveSessionInformation());
|
|
1921
|
-
} // (hasParameter('pairingcode'))
|
|
1922
|
-
|
|
1923
|
-
if (hasParameter('unpairall')) {
|
|
1924
|
-
this.log.info('***Commissioning controller unpairing all nodes...');
|
|
1925
|
-
const nodeIds = this.commissioningController.getCommissionedNodes();
|
|
1926
|
-
for (const nodeId of nodeIds) {
|
|
1927
|
-
this.log.info('***Commissioning controller unpairing node:', nodeId);
|
|
1928
|
-
await this.commissioningController.removeNode(nodeId);
|
|
1929
|
-
}
|
|
1930
|
-
return;
|
|
1931
|
-
}
|
|
1932
|
-
|
|
1933
|
-
if (hasParameter('discover')) {
|
|
1934
|
-
// const discover = await this.commissioningController.discoverCommissionableDevices({ productId: 0x8000, deviceType: 0xfff1 });
|
|
1935
|
-
// console.log(discover);
|
|
1936
|
-
}
|
|
1937
|
-
|
|
1938
|
-
if (!this.commissioningController.isCommissioned()) {
|
|
1939
|
-
this.log.info('***Commissioning controller is not commissioned: use matterbridge -controller -pairingcode [pairingcode] to commission a device');
|
|
1940
|
-
return;
|
|
1941
|
-
}
|
|
1942
|
-
|
|
1943
|
-
const nodeIds = this.commissioningController.getCommissionedNodes();
|
|
1944
|
-
this.log.info(`***Commissioning controller is commissioned ${this.commissioningController.isCommissioned()} and has ${nodeIds.length} nodes commisioned: `);
|
|
1945
|
-
for (const nodeId of nodeIds) {
|
|
1946
|
-
this.log.info(`***Connecting to commissioned node: ${nodeId}`);
|
|
1947
|
-
|
|
1948
|
-
const node = await this.commissioningController.connectNode(nodeId, {
|
|
1949
|
-
autoSubscribe: false,
|
|
1950
|
-
attributeChangedCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, attributeName }, value }) =>
|
|
1951
|
-
this.log.info(`***Commissioning controller attributeChangedCallback ${peerNodeId}: attribute ${nodeId}/${endpointId}/${clusterId}/${attributeName} changed to ${Logger.toJSON(value)}`),
|
|
1952
|
-
eventTriggeredCallback: (peerNodeId, { path: { nodeId, clusterId, endpointId, eventName }, events }) =>
|
|
1953
|
-
this.log.info(`***Commissioning controller eventTriggeredCallback ${peerNodeId}: Event ${nodeId}/${endpointId}/${clusterId}/${eventName} triggered with ${Logger.toJSON(events)}`),
|
|
1954
|
-
stateInformationCallback: (peerNodeId, info) => {
|
|
1955
|
-
switch (info) {
|
|
1956
|
-
case NodeStateInformation.Connected:
|
|
1957
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} connected`);
|
|
1958
|
-
break;
|
|
1959
|
-
case NodeStateInformation.Disconnected:
|
|
1960
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} disconnected`);
|
|
1961
|
-
break;
|
|
1962
|
-
case NodeStateInformation.Reconnecting:
|
|
1963
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} reconnecting`);
|
|
1964
|
-
break;
|
|
1965
|
-
case NodeStateInformation.WaitingForDeviceDiscovery:
|
|
1966
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} waiting for device discovery`);
|
|
1967
|
-
break;
|
|
1968
|
-
case NodeStateInformation.StructureChanged:
|
|
1969
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} structure changed`);
|
|
1970
|
-
break;
|
|
1971
|
-
case NodeStateInformation.Decommissioned:
|
|
1972
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} decommissioned`);
|
|
1973
|
-
break;
|
|
1974
|
-
default:
|
|
1975
|
-
this.log.info(`***Commissioning controller stateInformationCallback ${peerNodeId}: Node ${nodeId} NodeStateInformation.${info}`);
|
|
1976
|
-
break;
|
|
1977
|
-
}
|
|
1978
|
-
},
|
|
1979
|
-
});
|
|
1980
|
-
|
|
1981
|
-
node.logStructure();
|
|
1982
|
-
|
|
1983
|
-
// Get the interaction client
|
|
1984
|
-
this.log.info('Getting the interaction client');
|
|
1985
|
-
const interactionClient = await node.getInteractionClient();
|
|
1986
|
-
let cluster;
|
|
1987
|
-
let attributes;
|
|
1988
|
-
|
|
1989
|
-
// Log BasicInformationCluster
|
|
1990
|
-
cluster = BasicInformationCluster;
|
|
1991
|
-
attributes = await interactionClient.getMultipleAttributes({
|
|
1992
|
-
attributes: [{ clusterId: cluster.id }],
|
|
1993
|
-
});
|
|
1994
|
-
if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
|
|
1995
|
-
attributes.forEach((attribute) => {
|
|
1996
|
-
this.log.info(
|
|
1997
|
-
`- 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}`,
|
|
1998
|
-
);
|
|
1999
|
-
});
|
|
2000
|
-
|
|
2001
|
-
// Log PowerSourceCluster
|
|
2002
|
-
cluster = PowerSourceCluster;
|
|
2003
|
-
attributes = await interactionClient.getMultipleAttributes({
|
|
2004
|
-
attributes: [{ clusterId: cluster.id }],
|
|
2005
|
-
});
|
|
2006
|
-
if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
|
|
2007
|
-
attributes.forEach((attribute) => {
|
|
2008
|
-
this.log.info(
|
|
2009
|
-
`- 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}`,
|
|
2010
|
-
);
|
|
2011
|
-
});
|
|
2012
|
-
|
|
2013
|
-
// Log ThreadNetworkDiagnostics
|
|
2014
|
-
cluster = ThreadNetworkDiagnosticsCluster;
|
|
2015
|
-
attributes = await interactionClient.getMultipleAttributes({
|
|
2016
|
-
attributes: [{ clusterId: cluster.id }],
|
|
2017
|
-
});
|
|
2018
|
-
if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
|
|
2019
|
-
attributes.forEach((attribute) => {
|
|
2020
|
-
this.log.info(
|
|
2021
|
-
`- 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}`,
|
|
2022
|
-
);
|
|
2023
|
-
});
|
|
2024
|
-
|
|
2025
|
-
// Log SwitchCluster
|
|
2026
|
-
cluster = SwitchCluster;
|
|
2027
|
-
attributes = await interactionClient.getMultipleAttributes({
|
|
2028
|
-
attributes: [{ clusterId: cluster.id }],
|
|
2029
|
-
});
|
|
2030
|
-
if (attributes.length > 0) this.log.info(`Cluster: ${idn}${cluster.name}${rs}${nf} attributes:`);
|
|
2031
|
-
attributes.forEach((attribute) => {
|
|
2032
|
-
this.log.info(
|
|
2033
|
-
`- 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}`,
|
|
2034
|
-
);
|
|
2035
|
-
});
|
|
2036
|
-
|
|
2037
|
-
this.log.info('Subscribing to all attributes and events');
|
|
2038
|
-
await node.subscribeAllAttributesAndEvents({
|
|
2039
|
-
ignoreInitialTriggers: false,
|
|
2040
|
-
attributeChangedCallback: ({ path: { nodeId, clusterId, endpointId, attributeName }, version, value }) =>
|
|
2041
|
-
this.log.info(
|
|
2042
|
-
`***${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}`,
|
|
2043
|
-
),
|
|
2044
|
-
eventTriggeredCallback: ({ path: { nodeId, clusterId, endpointId, eventName }, events }) => {
|
|
2045
|
-
this.log.info(
|
|
2046
|
-
`***${db}Commissioning controller eventTriggeredCallback: event ${BLUE}${nodeId}${db}/${or}${endpointId}${db}/${hk}${getClusterNameById(clusterId)}${db}/${zb}${eventName}${db} triggered with ${debugStringify(events ?? { none: true })}`,
|
|
2047
|
-
);
|
|
2048
|
-
},
|
|
2049
|
-
});
|
|
2050
|
-
this.log.info('Subscribed to all attributes and events');
|
|
2051
|
-
}
|
|
2052
|
-
*/
|
|
2053
1444
|
}
|
|
2054
|
-
/** */
|
|
2055
|
-
/** Matter.js methods */
|
|
2056
|
-
/** */
|
|
2057
|
-
/**
|
|
2058
|
-
* Starts the matter storage with name Matterbridge, create the matterbridge context and performs a backup.
|
|
2059
|
-
*
|
|
2060
|
-
* @returns {Promise<void>} - A promise that resolves when the storage is started.
|
|
2061
|
-
*/
|
|
2062
1445
|
async startMatterStorage() {
|
|
2063
|
-
// Setup Matter storage
|
|
2064
1446
|
this.log.info(`Starting matter node storage...`);
|
|
2065
1447
|
this.matterStorageService = this.environment.get(StorageService);
|
|
2066
1448
|
this.log.info(`Matter node storage service created: ${this.matterStorageService.location}`);
|
|
@@ -2068,17 +1450,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
2068
1450
|
this.log.info('Matter node storage manager "Matterbridge" created');
|
|
2069
1451
|
this.matterbridgeContext = await this.createServerNodeContext('Matterbridge', 'Matterbridge', this.aggregatorDeviceType, this.aggregatorVendorId, this.aggregatorVendorName, this.aggregatorProductId, this.aggregatorProductName, this.aggregatorSerialNumber, this.aggregatorUniqueId);
|
|
2070
1452
|
this.log.info('Matter node storage started');
|
|
2071
|
-
// Backup matter storage since it is created/opened correctly
|
|
2072
1453
|
await this.backupMatterStorage(path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME), path.join(this.matterbridgeDirectory, MATTER_STORAGE_NAME + '.backup'));
|
|
2073
1454
|
}
|
|
2074
|
-
/**
|
|
2075
|
-
* Makes a backup copy of the specified matter storage directory.
|
|
2076
|
-
*
|
|
2077
|
-
* @param {string} storageName - The name of the storage directory to be backed up.
|
|
2078
|
-
* @param {string} backupName - The name of the backup directory to be created.
|
|
2079
|
-
* @private
|
|
2080
|
-
* @returns {Promise<void>} A promise that resolves when the has been done.
|
|
2081
|
-
*/
|
|
2082
1455
|
async backupMatterStorage(storageName, backupName) {
|
|
2083
1456
|
this.log.info('Creating matter node storage backup...');
|
|
2084
1457
|
try {
|
|
@@ -2089,11 +1462,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2089
1462
|
this.log.error(`Error creating matter node storage backup from ${storageName} to ${backupName}:`, error);
|
|
2090
1463
|
}
|
|
2091
1464
|
}
|
|
2092
|
-
/**
|
|
2093
|
-
* Stops the matter storage.
|
|
2094
|
-
*
|
|
2095
|
-
* @returns {Promise<void>} A promise that resolves when the storage is stopped.
|
|
2096
|
-
*/
|
|
2097
1465
|
async stopMatterStorage() {
|
|
2098
1466
|
this.log.info('Closing matter node storage...');
|
|
2099
1467
|
await this.matterStorageManager?.close();
|
|
@@ -2102,20 +1470,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2102
1470
|
this.matterbridgeContext = undefined;
|
|
2103
1471
|
this.log.info('Matter node storage closed');
|
|
2104
1472
|
}
|
|
2105
|
-
/**
|
|
2106
|
-
* Creates a server node storage context.
|
|
2107
|
-
*
|
|
2108
|
-
* @param {string} storeId - The storeId.
|
|
2109
|
-
* @param {string} deviceName - The name of the device.
|
|
2110
|
-
* @param {DeviceTypeId} deviceType - The device type of the device.
|
|
2111
|
-
* @param {number} vendorId - The vendor ID.
|
|
2112
|
-
* @param {string} vendorName - The vendor name.
|
|
2113
|
-
* @param {number} productId - The product ID.
|
|
2114
|
-
* @param {string} productName - The product name.
|
|
2115
|
-
* @param {string} [serialNumber] - The serial number of the device (optional).
|
|
2116
|
-
* @param {string} [uniqueId] - The unique ID of the device (optional).
|
|
2117
|
-
* @returns {Promise<StorageContext>} The storage context for the commissioning server.
|
|
2118
|
-
*/
|
|
2119
1473
|
async createServerNodeContext(storeId, deviceName, deviceType, vendorId, vendorName, productId, productName, serialNumber, uniqueId) {
|
|
2120
1474
|
const { randomBytes } = await import('node:crypto');
|
|
2121
1475
|
if (!this.matterStorageService)
|
|
@@ -2157,15 +1511,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2157
1511
|
this.log.debug(`- hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
|
|
2158
1512
|
return storageContext;
|
|
2159
1513
|
}
|
|
2160
|
-
/**
|
|
2161
|
-
* Creates a server node.
|
|
2162
|
-
*
|
|
2163
|
-
* @param {StorageContext} storageContext - The storage context for the server node.
|
|
2164
|
-
* @param {number} [port] - The port number for the server node. Defaults to 5540.
|
|
2165
|
-
* @param {number} [passcode] - The passcode for the server node. Defaults to 20242025.
|
|
2166
|
-
* @param {number} [discriminator] - The discriminator for the server node. Defaults to 3850.
|
|
2167
|
-
* @returns {Promise<ServerNode<ServerNode.RootEndpoint>>} A promise that resolves to the created server node.
|
|
2168
|
-
*/
|
|
2169
1514
|
async createServerNode(storageContext, port = 5540, passcode = 20242025, discriminator = 3850) {
|
|
2170
1515
|
const storeId = await storageContext.get('storeId');
|
|
2171
1516
|
this.log.notice(`Creating server node for ${storeId} on port ${port} with passcode ${passcode} and discriminator ${discriminator}...`);
|
|
@@ -2184,35 +1529,25 @@ export class Matterbridge extends EventEmitter {
|
|
|
2184
1529
|
this.log.debug(`- softwareVersionString: ${await storageContext.get('softwareVersionString')}`);
|
|
2185
1530
|
this.log.debug(`- hardwareVersion: ${await storageContext.get('hardwareVersion')}`);
|
|
2186
1531
|
this.log.debug(`- hardwareVersionString: ${await storageContext.get('hardwareVersionString')}`);
|
|
2187
|
-
/**
|
|
2188
|
-
* Create a Matter ServerNode, which contains the Root Endpoint and all relevant data and configuration
|
|
2189
|
-
*/
|
|
2190
1532
|
const serverNode = await ServerNode.create({
|
|
2191
|
-
// Required: Give the Node a unique ID which is used to store the state of this node
|
|
2192
1533
|
id: storeId,
|
|
2193
|
-
// Environment to run the server node in
|
|
2194
1534
|
environment: this.environment,
|
|
2195
|
-
// Provide Network relevant configuration like the port
|
|
2196
1535
|
network: {
|
|
2197
1536
|
listeningAddressIpv4: this.ipv4Address,
|
|
2198
1537
|
listeningAddressIpv6: this.ipv6Address,
|
|
2199
1538
|
port,
|
|
2200
1539
|
},
|
|
2201
|
-
// Provide the certificate for the device
|
|
2202
1540
|
operationalCredentials: {
|
|
2203
1541
|
certification: this.certification,
|
|
2204
1542
|
},
|
|
2205
|
-
// Provide Commissioning relevant settings
|
|
2206
1543
|
commissioning: {
|
|
2207
1544
|
passcode,
|
|
2208
1545
|
discriminator,
|
|
2209
1546
|
},
|
|
2210
|
-
// Provide Node announcement settings
|
|
2211
1547
|
productDescription: {
|
|
2212
1548
|
name: await storageContext.get('deviceName'),
|
|
2213
1549
|
deviceType: DeviceTypeId(await storageContext.get('deviceType')),
|
|
2214
1550
|
},
|
|
2215
|
-
// Provide defaults for the BasicInformation cluster on the Root endpoint
|
|
2216
1551
|
basicInformation: {
|
|
2217
1552
|
nodeLabel: await storageContext.get('nodeLabel'),
|
|
2218
1553
|
vendorId: VendorId(await storageContext.get('vendorId')),
|
|
@@ -2229,23 +1564,17 @@ export class Matterbridge extends EventEmitter {
|
|
|
2229
1564
|
reachable: true,
|
|
2230
1565
|
},
|
|
2231
1566
|
});
|
|
2232
|
-
/**
|
|
2233
|
-
* This event is triggered when the device is initially commissioned successfully.
|
|
2234
|
-
* This means: It is added to the first fabric.
|
|
2235
|
-
*/
|
|
2236
1567
|
serverNode.lifecycle.commissioned.on(() => {
|
|
2237
1568
|
this.log.notice(`Server node for ${storeId} was initially commissioned successfully!`);
|
|
2238
1569
|
this.advertisingNodes.delete(storeId);
|
|
2239
1570
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2240
1571
|
});
|
|
2241
|
-
/** This event is triggered when all fabrics are removed from the device, usually it also does a factory reset then. */
|
|
2242
1572
|
serverNode.lifecycle.decommissioned.on(() => {
|
|
2243
1573
|
this.log.notice(`Server node for ${storeId} was fully decommissioned successfully!`);
|
|
2244
1574
|
this.advertisingNodes.delete(storeId);
|
|
2245
1575
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2246
1576
|
this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
|
|
2247
1577
|
});
|
|
2248
|
-
/** This event is triggered when the device went online. This means that it is discoverable in the network. */
|
|
2249
1578
|
serverNode.lifecycle.online.on(async () => {
|
|
2250
1579
|
this.log.notice(`Server node for ${storeId} is online`);
|
|
2251
1580
|
if (!serverNode.lifecycle.isCommissioned) {
|
|
@@ -2256,16 +1585,13 @@ export class Matterbridge extends EventEmitter {
|
|
|
2256
1585
|
this.log.notice(`Manual pairing code: ${manualPairingCode}`);
|
|
2257
1586
|
}
|
|
2258
1587
|
else {
|
|
2259
|
-
// istanbul ignore next
|
|
2260
1588
|
this.log.notice(`Server node for ${storeId} is already commissioned. Waiting for controllers to connect ...`);
|
|
2261
|
-
// istanbul ignore next
|
|
2262
1589
|
this.advertisingNodes.delete(storeId);
|
|
2263
1590
|
}
|
|
2264
1591
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2265
1592
|
this.frontend.wssSendSnackbarMessage(`${storeId} is online`, 5, 'success');
|
|
2266
1593
|
this.emit('online', storeId);
|
|
2267
1594
|
});
|
|
2268
|
-
/** This event is triggered when the device went offline. it is not longer discoverable or connectable in the network. */
|
|
2269
1595
|
serverNode.lifecycle.offline.on(() => {
|
|
2270
1596
|
this.log.notice(`Server node for ${storeId} is offline`);
|
|
2271
1597
|
this.advertisingNodes.delete(storeId);
|
|
@@ -2273,15 +1599,11 @@ export class Matterbridge extends EventEmitter {
|
|
|
2273
1599
|
this.frontend.wssSendSnackbarMessage(`${storeId} is offline`, 5, 'warning');
|
|
2274
1600
|
this.emit('offline', storeId);
|
|
2275
1601
|
});
|
|
2276
|
-
/**
|
|
2277
|
-
* This event is triggered when a fabric is added, removed or updated on the device. Use this if more granular
|
|
2278
|
-
* information is needed.
|
|
2279
|
-
*/
|
|
2280
1602
|
serverNode.events.commissioning.fabricsChanged.on((fabricIndex, fabricAction) => {
|
|
2281
1603
|
let action = '';
|
|
2282
1604
|
switch (fabricAction) {
|
|
2283
1605
|
case 'added':
|
|
2284
|
-
this.advertisingNodes.delete(storeId);
|
|
1606
|
+
this.advertisingNodes.delete(storeId);
|
|
2285
1607
|
action = 'added';
|
|
2286
1608
|
break;
|
|
2287
1609
|
case 'deleted':
|
|
@@ -2294,22 +1616,14 @@ export class Matterbridge extends EventEmitter {
|
|
|
2294
1616
|
this.log.notice(`Commissioned fabric index ${fabricIndex} ${action} on server node for ${storeId}: ${debugStringify(serverNode.state.commissioning.fabrics[fabricIndex])}`);
|
|
2295
1617
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2296
1618
|
});
|
|
2297
|
-
/**
|
|
2298
|
-
* This event is triggered when an operative new session was opened by a Controller.
|
|
2299
|
-
* It is not triggered for the initial commissioning process, just afterwards for real connections.
|
|
2300
|
-
*/
|
|
2301
1619
|
serverNode.events.sessions.opened.on((session) => {
|
|
2302
1620
|
this.log.notice(`Session opened on server node for ${storeId}: ${debugStringify(session)}`);
|
|
2303
1621
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2304
1622
|
});
|
|
2305
|
-
/**
|
|
2306
|
-
* This event is triggered when an operative session is closed by a Controller or because the Device goes offline.
|
|
2307
|
-
*/
|
|
2308
1623
|
serverNode.events.sessions.closed.on((session) => {
|
|
2309
1624
|
this.log.notice(`Session closed on server node for ${storeId}: ${debugStringify(session)}`);
|
|
2310
1625
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
2311
1626
|
});
|
|
2312
|
-
/** This event is triggered when a subscription gets added or removed on an operative session. */
|
|
2313
1627
|
serverNode.events.sessions.subscriptionsChanged.on((session) => {
|
|
2314
1628
|
this.log.notice(`Session subscriptions changed on server node for ${storeId}: ${debugStringify(session)}`);
|
|
2315
1629
|
this.frontend.wssSendRefreshRequired('matter', { matter: { ...this.getServerNodeData(serverNode) } });
|
|
@@ -2317,12 +1631,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2317
1631
|
this.log.info(`Created server node for ${storeId}`);
|
|
2318
1632
|
return serverNode;
|
|
2319
1633
|
}
|
|
2320
|
-
/**
|
|
2321
|
-
* Gets the matter sanitized data of the specified server node.
|
|
2322
|
-
*
|
|
2323
|
-
* @param {ServerNode} [serverNode] - The server node to start.
|
|
2324
|
-
* @returns {ApiMatter} The sanitized data of the server node.
|
|
2325
|
-
*/
|
|
2326
1634
|
getServerNodeData(serverNode) {
|
|
2327
1635
|
const advertiseTime = this.advertisingNodes.get(serverNode.id) || 0;
|
|
2328
1636
|
return {
|
|
@@ -2339,25 +1647,12 @@ export class Matterbridge extends EventEmitter {
|
|
|
2339
1647
|
serialNumber: serverNode.state.basicInformation.serialNumber,
|
|
2340
1648
|
};
|
|
2341
1649
|
}
|
|
2342
|
-
/**
|
|
2343
|
-
* Starts the specified server node.
|
|
2344
|
-
*
|
|
2345
|
-
* @param {ServerNode} [matterServerNode] - The server node to start.
|
|
2346
|
-
* @returns {Promise<void>} A promise that resolves when the server node has started.
|
|
2347
|
-
*/
|
|
2348
1650
|
async startServerNode(matterServerNode) {
|
|
2349
1651
|
if (!matterServerNode)
|
|
2350
1652
|
return;
|
|
2351
1653
|
this.log.notice(`Starting ${matterServerNode.id} server node`);
|
|
2352
1654
|
await matterServerNode.start();
|
|
2353
1655
|
}
|
|
2354
|
-
/**
|
|
2355
|
-
* Stops the specified server node.
|
|
2356
|
-
*
|
|
2357
|
-
* @param {ServerNode} matterServerNode - The server node to stop.
|
|
2358
|
-
* @param {number} [timeout] - The timeout in milliseconds for stopping the server node. Defaults to 10 seconds.
|
|
2359
|
-
* @returns {Promise<void>} A promise that resolves when the server node has stopped.
|
|
2360
|
-
*/
|
|
2361
1656
|
async stopServerNode(matterServerNode, timeout = 10000) {
|
|
2362
1657
|
const { withTimeout } = await import('@matterbridge/utils');
|
|
2363
1658
|
if (!matterServerNode)
|
|
@@ -2371,25 +1666,12 @@ export class Matterbridge extends EventEmitter {
|
|
|
2371
1666
|
this.log.error(`Failed to close ${matterServerNode.id} server node: ${error instanceof Error ? error.message : error}`);
|
|
2372
1667
|
}
|
|
2373
1668
|
}
|
|
2374
|
-
/**
|
|
2375
|
-
* Creates an aggregator node with the specified storage context.
|
|
2376
|
-
*
|
|
2377
|
-
* @param {StorageContext} storageContext - The storage context for the aggregator node.
|
|
2378
|
-
* @returns {Promise<Endpoint<AggregatorEndpoint>>} A promise that resolves to the created aggregator node.
|
|
2379
|
-
*/
|
|
2380
1669
|
async createAggregatorNode(storageContext) {
|
|
2381
1670
|
this.log.notice(`Creating ${await storageContext.get('storeId')} aggregator...`);
|
|
2382
1671
|
const aggregatorNode = new Endpoint(AggregatorEndpoint, { id: `${await storageContext.get('storeId')}` });
|
|
2383
1672
|
this.log.info(`Created ${await storageContext.get('storeId')} aggregator`);
|
|
2384
1673
|
return aggregatorNode;
|
|
2385
1674
|
}
|
|
2386
|
-
/**
|
|
2387
|
-
* Creates and configures the server node for an accessory plugin for a given device.
|
|
2388
|
-
*
|
|
2389
|
-
* @param {Plugin} plugin - The plugin to configure.
|
|
2390
|
-
* @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
|
|
2391
|
-
* @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
|
|
2392
|
-
*/
|
|
2393
1675
|
async createAccessoryPlugin(plugin, device) {
|
|
2394
1676
|
if (!plugin.locked && device.deviceType && device.deviceName && device.vendorId && device.productId && device.vendorName && device.productName) {
|
|
2395
1677
|
plugin.locked = true;
|
|
@@ -2401,12 +1683,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2401
1683
|
await plugin.serverNode.add(device);
|
|
2402
1684
|
}
|
|
2403
1685
|
}
|
|
2404
|
-
/**
|
|
2405
|
-
* Creates and configures the server node and the aggregator node for a dynamic plugin.
|
|
2406
|
-
*
|
|
2407
|
-
* @param {Plugin} plugin - The plugin to configure.
|
|
2408
|
-
* @returns {Promise<void>} A promise that resolves when the server node and the aggregator node for the dynamic plugin is created and configured.
|
|
2409
|
-
*/
|
|
2410
1686
|
async createDynamicPlugin(plugin) {
|
|
2411
1687
|
if (!plugin.locked) {
|
|
2412
1688
|
plugin.locked = true;
|
|
@@ -2419,13 +1695,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2419
1695
|
await plugin.serverNode.add(plugin.aggregatorNode);
|
|
2420
1696
|
}
|
|
2421
1697
|
}
|
|
2422
|
-
/**
|
|
2423
|
-
* Creates and configures the server node for a single not bridged device.
|
|
2424
|
-
*
|
|
2425
|
-
* @param {Plugin} plugin - The plugin to configure.
|
|
2426
|
-
* @param {MatterbridgeEndpoint} device - The device to associate with the plugin.
|
|
2427
|
-
* @returns {Promise<void>} A promise that resolves when the server node for the accessory plugin is created and configured.
|
|
2428
|
-
*/
|
|
2429
1698
|
async createDeviceServerNode(plugin, device) {
|
|
2430
1699
|
if (device.mode === 'server' &&
|
|
2431
1700
|
!device.serverNode &&
|
|
@@ -2443,16 +1712,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
2443
1712
|
this.log.debug(`Added ${plg}${plugin.name}${db}:${dev}${device.deviceName}${db} to server node`);
|
|
2444
1713
|
}
|
|
2445
1714
|
}
|
|
2446
|
-
/**
|
|
2447
|
-
* Adds a MatterbridgeEndpoint to the specified plugin.
|
|
2448
|
-
*
|
|
2449
|
-
* @param {string} pluginName - The name of the plugin.
|
|
2450
|
-
* @param {MatterbridgeEndpoint} device - The device to add as a bridged endpoint.
|
|
2451
|
-
* @returns {Promise<void>} A promise that resolves when the bridged endpoint has been added.
|
|
2452
|
-
*/
|
|
2453
1715
|
async addBridgedEndpoint(pluginName, device) {
|
|
2454
1716
|
const { waiter } = await import('@matterbridge/utils');
|
|
2455
|
-
// Check if the plugin is registered
|
|
2456
1717
|
const plugin = this.plugins.get(pluginName);
|
|
2457
1718
|
if (!plugin) {
|
|
2458
1719
|
this.log.error(`Error adding bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.id}${er}) plugin ${plg}${pluginName}${er} not found`);
|
|
@@ -2472,7 +1733,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2472
1733
|
}
|
|
2473
1734
|
else if (this.bridgeMode === 'bridge') {
|
|
2474
1735
|
if (device.mode === 'matter') {
|
|
2475
|
-
// Register and add the device to the matterbridge server node
|
|
2476
1736
|
this.log.debug(`Adding matter endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge server node...`);
|
|
2477
1737
|
if (!this.serverNode) {
|
|
2478
1738
|
this.log.error('Server node not found for Matterbridge');
|
|
@@ -2489,7 +1749,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2489
1749
|
}
|
|
2490
1750
|
}
|
|
2491
1751
|
else {
|
|
2492
|
-
// Register and add the device to the matterbridge aggregator node
|
|
2493
1752
|
this.log.debug(`Adding bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} to Matterbridge aggregator node`);
|
|
2494
1753
|
if (!this.aggregatorNode) {
|
|
2495
1754
|
this.log.error('Aggregator node not found for Matterbridge');
|
|
@@ -2507,7 +1766,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2507
1766
|
}
|
|
2508
1767
|
}
|
|
2509
1768
|
else if (this.bridgeMode === 'childbridge') {
|
|
2510
|
-
// Register and add the device to the plugin server node
|
|
2511
1769
|
if (plugin.type === 'AccessoryPlatform') {
|
|
2512
1770
|
try {
|
|
2513
1771
|
this.log.debug(`Creating endpoint ${dev}${device.deviceName}${db} for AccessoryPlatform plugin ${plg}${plugin.name}${db} server node`);
|
|
@@ -2531,12 +1789,10 @@ export class Matterbridge extends EventEmitter {
|
|
|
2531
1789
|
return;
|
|
2532
1790
|
}
|
|
2533
1791
|
}
|
|
2534
|
-
// Register and add the device to the plugin aggregator node
|
|
2535
1792
|
if (plugin.type === 'DynamicPlatform') {
|
|
2536
1793
|
try {
|
|
2537
1794
|
this.log.debug(`Adding bridged endpoint ${dev}${device.deviceName}${db} for DynamicPlatform plugin ${plg}${plugin.name}${db} aggregator node`);
|
|
2538
1795
|
await this.createDynamicPlugin(plugin);
|
|
2539
|
-
// Fast plugins can add another device before the server node is ready, so we wait for the server node to be ready
|
|
2540
1796
|
await waiter(`createDynamicPlugin(${plugin.name})`, () => plugin.serverNode?.hasParts === true);
|
|
2541
1797
|
if (!plugin.aggregatorNode) {
|
|
2542
1798
|
this.log.error(`Aggregator node not found for plugin ${plg}${plugin.name}${er}`);
|
|
@@ -2557,22 +1813,12 @@ export class Matterbridge extends EventEmitter {
|
|
|
2557
1813
|
}
|
|
2558
1814
|
if (plugin.registeredDevices !== undefined)
|
|
2559
1815
|
plugin.registeredDevices++;
|
|
2560
|
-
// Add the device to the DeviceManager
|
|
2561
1816
|
this.devices.set(device);
|
|
2562
|
-
// Subscribe to the attributes changed event
|
|
2563
1817
|
await this.subscribeAttributeChanged(plugin, device);
|
|
2564
1818
|
this.log.info(`Added and registered bridged endpoint (${plugin.registeredDevices}) ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) for plugin ${plg}${pluginName}${nf}`);
|
|
2565
1819
|
}
|
|
2566
|
-
/**
|
|
2567
|
-
* Removes a MatterbridgeEndpoint from the specified plugin.
|
|
2568
|
-
*
|
|
2569
|
-
* @param {string} pluginName - The name of the plugin.
|
|
2570
|
-
* @param {MatterbridgeEndpoint} device - The device to remove as a bridged endpoint.
|
|
2571
|
-
* @returns {Promise<void>} A promise that resolves when the bridged endpoint has been removed.
|
|
2572
|
-
*/
|
|
2573
1820
|
async removeBridgedEndpoint(pluginName, device) {
|
|
2574
1821
|
this.log.debug(`Removing bridged endpoint ${plg}${pluginName}${db}:${dev}${device.deviceName}${db} (${zb}${device.name}${db}) for plugin ${plg}${pluginName}${db}`);
|
|
2575
|
-
// Check if the plugin is registered
|
|
2576
1822
|
const plugin = this.plugins.get(pluginName);
|
|
2577
1823
|
if (!plugin) {
|
|
2578
1824
|
this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: plugin not found`);
|
|
@@ -2582,7 +1828,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2582
1828
|
this.log.info(`Removed mode server bridged endpoint(${plugin.registeredDevices}) ${dev}${device.deviceName}${nf} (${zb}${device.name}${nf}) for plugin ${plg}${pluginName}${nf}`);
|
|
2583
1829
|
}
|
|
2584
1830
|
else if (this.bridgeMode === 'bridge') {
|
|
2585
|
-
// Unregister and remove the device from the matterbridge aggregator node
|
|
2586
1831
|
if (!this.aggregatorNode) {
|
|
2587
1832
|
this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: aggregator node not found`);
|
|
2588
1833
|
return;
|
|
@@ -2594,10 +1839,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
2594
1839
|
}
|
|
2595
1840
|
else if (this.bridgeMode === 'childbridge') {
|
|
2596
1841
|
if (plugin.type === 'AccessoryPlatform') {
|
|
2597
|
-
// Nothing to do here since the server node has no aggregator node but only the device itself
|
|
2598
1842
|
}
|
|
2599
1843
|
else if (plugin.type === 'DynamicPlatform') {
|
|
2600
|
-
// Unregister and remove the device from the plugin aggregator node
|
|
2601
1844
|
if (!plugin.aggregatorNode) {
|
|
2602
1845
|
this.log.error(`Error removing bridged endpoint ${dev}${device.deviceName}${er} (${zb}${device.name}${er}) for plugin ${plg}${pluginName}${er}: aggregator node not found`);
|
|
2603
1846
|
return;
|
|
@@ -2608,21 +1851,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
2608
1851
|
if (plugin.registeredDevices !== undefined)
|
|
2609
1852
|
plugin.registeredDevices--;
|
|
2610
1853
|
}
|
|
2611
|
-
// Remove the device from the DeviceManager
|
|
2612
1854
|
this.devices.remove(device);
|
|
2613
1855
|
}
|
|
2614
|
-
/**
|
|
2615
|
-
* Removes all bridged endpoints from the specified plugin.
|
|
2616
|
-
*
|
|
2617
|
-
* @param {string} pluginName - The name of the plugin.
|
|
2618
|
-
* @param {number} [delay] - The delay in milliseconds between removing each bridged endpoint (default: 0).
|
|
2619
|
-
* @returns {Promise<void>} A promise that resolves when all bridged endpoints have been removed.
|
|
2620
|
-
*
|
|
2621
|
-
* @remarks
|
|
2622
|
-
* This method iterates through all devices in the DeviceManager and removes each bridged endpoint associated with the specified plugin.
|
|
2623
|
-
* It also applies a delay between each removal if specified.
|
|
2624
|
-
* The delay is useful to allow the controllers to receive a single subscription for each device removed.
|
|
2625
|
-
*/
|
|
2626
1856
|
async removeAllBridgedEndpoints(pluginName, delay = 0) {
|
|
2627
1857
|
const { wait } = await import('@matterbridge/utils');
|
|
2628
1858
|
this.log.debug(`Removing all bridged endpoints for plugin ${plg}${pluginName}${db}${delay > 0 ? ` with delay ${delay} ms` : ''}`);
|
|
@@ -2634,28 +1864,8 @@ export class Matterbridge extends EventEmitter {
|
|
|
2634
1864
|
if (delay > 0)
|
|
2635
1865
|
await wait(2000);
|
|
2636
1866
|
}
|
|
2637
|
-
/**
|
|
2638
|
-
* Registers a virtual device.
|
|
2639
|
-
* Virtual devices are only supported in bridge mode and childbridge mode with a DynamicPlatform.
|
|
2640
|
-
*
|
|
2641
|
-
* The virtual device is created as an instance of `Endpoint` with the provided device type.
|
|
2642
|
-
* When the virtual device is turned on, the provided callback function is executed.
|
|
2643
|
-
* The onOff state of the virtual device always reverts to false when the device is turned on.
|
|
2644
|
-
*
|
|
2645
|
-
* @param { string } pluginName - The name of the plugin to register the virtual device under.
|
|
2646
|
-
* @param { string } name - The name of the virtual device.
|
|
2647
|
-
* @param { 'light' | 'outlet' | 'switch' | 'mounted_switch' } type - The type of the virtual device.
|
|
2648
|
-
* @param { () => Promise<void> } callback - The callback to call when the virtual device is turned on.
|
|
2649
|
-
*
|
|
2650
|
-
* @returns {Promise<boolean>} A promise that resolves to true if the virtual device was successfully registered, false otherwise.
|
|
2651
|
-
*
|
|
2652
|
-
* @remarks
|
|
2653
|
-
* The virtual devices don't show up in the device list of the frontend.
|
|
2654
|
-
* Type 'switch' is not supported by Alexa and 'mounted_switch' is not supported by Apple Home.
|
|
2655
|
-
*/
|
|
2656
1867
|
async addVirtualEndpoint(pluginName, name, type, callback) {
|
|
2657
1868
|
this.log.debug(`Adding virtual endpoint ${plg}${pluginName}${db}:${dev}${name}${db}...`);
|
|
2658
|
-
// Check if the plugin is registered
|
|
2659
1869
|
const plugin = this.plugins.get(pluginName);
|
|
2660
1870
|
if (!plugin) {
|
|
2661
1871
|
this.log.error(`Error adding virtual endpoint ${dev}${name}${er} for plugin ${plg}${pluginName}${er}: plugin not found`);
|
|
@@ -2682,24 +1892,13 @@ export class Matterbridge extends EventEmitter {
|
|
|
2682
1892
|
this.log.error(`Virtual endpoint ${dev}${name}${er} for plugin ${plg}${pluginName}${er} not created. Virtual endpoints are only supported in bridge mode and childbridge mode with a DynamicPlatform.`);
|
|
2683
1893
|
return false;
|
|
2684
1894
|
}
|
|
2685
|
-
/**
|
|
2686
|
-
* Subscribes to the attribute change event for the given device and plugin.
|
|
2687
|
-
* Specifically, it listens for changes in the 'reachable' attribute of the
|
|
2688
|
-
* BridgedDeviceBasicInformationServer cluster server of the bridged device or BasicInformationServer cluster server of server node.
|
|
2689
|
-
*
|
|
2690
|
-
* @param {Plugin} plugin - The plugin associated with the device.
|
|
2691
|
-
* @param {MatterbridgeEndpoint} device - The device to subscribe to attribute changes for.
|
|
2692
|
-
* @returns {Promise<void>} A promise that resolves when the subscription is set up.
|
|
2693
|
-
*/
|
|
2694
1895
|
async subscribeAttributeChanged(plugin, device) {
|
|
2695
1896
|
if (!plugin || !device || !device.plugin || !device.serialNumber || !device.uniqueId || !device.maybeNumber)
|
|
2696
1897
|
return;
|
|
2697
1898
|
this.log.info(`Subscribing attributes for endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) plugin ${plg}${plugin.name}${nf}`);
|
|
2698
|
-
// Subscribe to the reachable$Changed event of the BasicInformationServer cluster server of the server node in childbridge mode
|
|
2699
1899
|
if (this.bridgeMode === 'childbridge' && plugin.type === 'AccessoryPlatform' && plugin.serverNode) {
|
|
2700
1900
|
plugin.serverNode.eventsOf(BasicInformationServer).reachable$Changed?.on((reachable) => {
|
|
2701
1901
|
this.log.info(`Accessory endpoint ${dev}${device.deviceName}${nf} (${dev}${device.id}${nf}) is ${reachable ? 'reachable' : 'unreachable'}`);
|
|
2702
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
2703
1902
|
this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, device.number, device.id, 'BasicInformation', 'reachable', reachable);
|
|
2704
1903
|
});
|
|
2705
1904
|
}
|
|
@@ -2749,7 +1948,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2749
1948
|
this.log.debug(`Subscribing to endpoint ${or}${device.id}${db}:${or}${device.number}${db} attribute ${dev}${sub.cluster}${db}.${dev}${sub.attribute}${db} changes...`);
|
|
2750
1949
|
await device.subscribeAttribute(sub.cluster, sub.attribute, (value) => {
|
|
2751
1950
|
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}`);
|
|
2752
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
2753
1951
|
this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, device.number, device.id, sub.cluster, sub.attribute, value);
|
|
2754
1952
|
});
|
|
2755
1953
|
}
|
|
@@ -2758,19 +1956,12 @@ export class Matterbridge extends EventEmitter {
|
|
|
2758
1956
|
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...`);
|
|
2759
1957
|
await child.subscribeAttribute(sub.cluster, sub.attribute, (value) => {
|
|
2760
1958
|
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}`);
|
|
2761
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
2762
1959
|
this.frontend.wssSendAttributeChangedMessage(device.plugin, device.serialNumber, device.uniqueId, child.number, child.id, sub.cluster, sub.attribute, value);
|
|
2763
1960
|
});
|
|
2764
1961
|
}
|
|
2765
1962
|
}
|
|
2766
1963
|
}
|
|
2767
1964
|
}
|
|
2768
|
-
/**
|
|
2769
|
-
* Sanitizes the fabric information by converting bigint properties to strings because `res.json` doesn't support bigint.
|
|
2770
|
-
*
|
|
2771
|
-
* @param {ExposedFabricInformation[]} fabricInfo - The array of exposed fabric information objects.
|
|
2772
|
-
* @returns {SanitizedExposedFabricInformation[]} An array of sanitized exposed fabric information objects.
|
|
2773
|
-
*/
|
|
2774
1965
|
sanitizeFabricInformations(fabricInfo) {
|
|
2775
1966
|
return fabricInfo.map((info) => {
|
|
2776
1967
|
return {
|
|
@@ -2784,12 +1975,6 @@ export class Matterbridge extends EventEmitter {
|
|
|
2784
1975
|
};
|
|
2785
1976
|
});
|
|
2786
1977
|
}
|
|
2787
|
-
/**
|
|
2788
|
-
* Sanitizes the session information by converting bigint properties to strings because `res.json` doesn't support bigint.
|
|
2789
|
-
*
|
|
2790
|
-
* @param {SessionsBehavior.Session[]} sessions - The array of session information objects.
|
|
2791
|
-
* @returns {SanitizedSession[]} An array of sanitized session information objects.
|
|
2792
|
-
*/
|
|
2793
1978
|
sanitizeSessionInformation(sessions) {
|
|
2794
1979
|
return sessions
|
|
2795
1980
|
.filter((session) => session.isPeerActive)
|
|
@@ -2816,21 +2001,7 @@ export class Matterbridge extends EventEmitter {
|
|
|
2816
2001
|
};
|
|
2817
2002
|
});
|
|
2818
2003
|
}
|
|
2819
|
-
/**
|
|
2820
|
-
* Sets the reachability of the specified aggregator node bridged devices and trigger.
|
|
2821
|
-
*
|
|
2822
|
-
* @param {Endpoint<AggregatorEndpoint>} aggregatorNode - The aggregator node to set the reachability for.
|
|
2823
|
-
* @param {boolean} reachable - A boolean indicating the reachability status to set.
|
|
2824
|
-
*/
|
|
2825
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
2826
2004
|
async setAggregatorReachability(aggregatorNode, reachable) {
|
|
2827
|
-
/*
|
|
2828
|
-
for (const child of aggregatorNode.parts) {
|
|
2829
|
-
this.log.debug(`Setting reachability of ${(child as unknown as MatterbridgeEndpoint)?.deviceName} to ${reachable}`);
|
|
2830
|
-
await child.setStateOf(BridgedDeviceBasicInformationServer, { reachable });
|
|
2831
|
-
child.act((agent) => child.eventsOf(BridgedDeviceBasicInformationServer).reachableChanged.emit({ reachableNewValue: true }, agent.context));
|
|
2832
|
-
}
|
|
2833
|
-
*/
|
|
2834
2005
|
}
|
|
2835
2006
|
getVendorIdName = (vendorId) => {
|
|
2836
2007
|
if (!vendorId)
|
|
@@ -2870,11 +2041,10 @@ export class Matterbridge extends EventEmitter {
|
|
|
2870
2041
|
case 0x1488:
|
|
2871
2042
|
vendorName = '(ShortcutLabsFlic)';
|
|
2872
2043
|
break;
|
|
2873
|
-
case 65521:
|
|
2044
|
+
case 65521:
|
|
2874
2045
|
vendorName = '(MatterTest)';
|
|
2875
2046
|
break;
|
|
2876
2047
|
}
|
|
2877
2048
|
return vendorName;
|
|
2878
2049
|
};
|
|
2879
2050
|
}
|
|
2880
|
-
//# sourceMappingURL=matterbridge.js.map
|