homebridge 2.0.0-alpha.6 → 2.0.0-alpha.60
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/bin/homebridge.js +22 -0
- package/dist/api.d.ts +235 -3
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +91 -0
- package/dist/api.js.map +1 -1
- package/dist/bridgeService.d.ts +11 -3
- package/dist/bridgeService.d.ts.map +1 -1
- package/dist/bridgeService.js +9 -5
- package/dist/bridgeService.js.map +1 -1
- package/dist/childBridgeFork.d.ts +30 -3
- package/dist/childBridgeFork.d.ts.map +1 -1
- package/dist/childBridgeFork.js +270 -5
- package/dist/childBridgeFork.js.map +1 -1
- package/dist/childBridgeService.d.ts +22 -0
- package/dist/childBridgeService.d.ts.map +1 -1
- package/dist/childBridgeService.js +85 -26
- package/dist/childBridgeService.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +3 -2
- package/dist/cli.js.map +1 -1
- package/dist/externalPortService.d.ts +27 -6
- package/dist/externalPortService.d.ts.map +1 -1
- package/dist/externalPortService.js +73 -7
- package/dist/externalPortService.js.map +1 -1
- package/dist/index.d.ts +48 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +36 -0
- package/dist/index.js.map +1 -1
- package/dist/ipcService.d.ts +20 -0
- package/dist/ipcService.d.ts.map +1 -1
- package/dist/ipcService.js.map +1 -1
- package/dist/logger.d.ts +6 -0
- package/dist/logger.d.ts.map +1 -1
- package/dist/logger.js +8 -0
- package/dist/logger.js.map +1 -1
- package/dist/matter/index.d.ts +59 -0
- package/dist/matter/index.d.ts.map +1 -0
- package/dist/matter/index.js +19 -0
- package/dist/matter/index.js.map +1 -0
- package/dist/matter/matterAccessoryCache.d.ts +77 -0
- package/dist/matter/matterAccessoryCache.d.ts.map +1 -0
- package/dist/matter/matterAccessoryCache.js +176 -0
- package/dist/matter/matterAccessoryCache.js.map +1 -0
- package/dist/matter/matterBehaviors.d.ts +158 -0
- package/dist/matter/matterBehaviors.d.ts.map +1 -0
- package/dist/matter/matterBehaviors.js +740 -0
- package/dist/matter/matterBehaviors.js.map +1 -0
- package/dist/matter/matterConfigValidator.d.ts +81 -0
- package/dist/matter/matterConfigValidator.d.ts.map +1 -0
- package/dist/matter/matterConfigValidator.js +240 -0
- package/dist/matter/matterConfigValidator.js.map +1 -0
- package/dist/matter/matterErrorHandler.d.ts +94 -0
- package/dist/matter/matterErrorHandler.d.ts.map +1 -0
- package/dist/matter/matterErrorHandler.js +485 -0
- package/dist/matter/matterErrorHandler.js.map +1 -0
- package/dist/matter/matterLogFormatter.d.ts +19 -0
- package/dist/matter/matterLogFormatter.d.ts.map +1 -0
- package/dist/matter/matterLogFormatter.js +126 -0
- package/dist/matter/matterLogFormatter.js.map +1 -0
- package/dist/matter/matterNetworkMonitor.d.ts +68 -0
- package/dist/matter/matterNetworkMonitor.d.ts.map +1 -0
- package/dist/matter/matterNetworkMonitor.js +249 -0
- package/dist/matter/matterNetworkMonitor.js.map +1 -0
- package/dist/matter/matterServer.d.ts +643 -0
- package/dist/matter/matterServer.d.ts.map +1 -0
- package/dist/matter/matterServer.js +1623 -0
- package/dist/matter/matterServer.js.map +1 -0
- package/dist/matter/matterSharedTypes.d.ts +165 -0
- package/dist/matter/matterSharedTypes.d.ts.map +1 -0
- package/dist/matter/matterSharedTypes.js +51 -0
- package/dist/matter/matterSharedTypes.js.map +1 -0
- package/dist/matter/matterStorage.d.ts +126 -0
- package/dist/matter/matterStorage.d.ts.map +1 -0
- package/dist/matter/matterStorage.js +419 -0
- package/dist/matter/matterStorage.js.map +1 -0
- package/dist/matter/matterTypes.d.ts +612 -0
- package/dist/matter/matterTypes.d.ts.map +1 -0
- package/dist/matter/matterTypes.js +150 -0
- package/dist/matter/matterTypes.js.map +1 -0
- package/dist/platformAccessory.d.ts +1 -0
- package/dist/platformAccessory.d.ts.map +1 -1
- package/dist/platformAccessory.js +8 -1
- package/dist/platformAccessory.js.map +1 -1
- package/dist/plugin.d.ts +0 -1
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +8 -11
- package/dist/plugin.js.map +1 -1
- package/dist/pluginManager.d.ts.map +1 -1
- package/dist/pluginManager.js +22 -21
- package/dist/pluginManager.js.map +1 -1
- package/dist/server.d.ts +23 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +374 -10
- package/dist/server.js.map +1 -1
- package/dist/storageService.js +8 -8
- package/dist/storageService.js.map +1 -1
- package/dist/user.d.ts +1 -0
- package/dist/user.d.ts.map +1 -1
- package/dist/user.js +10 -7
- package/dist/user.js.map +1 -1
- package/dist/util/mac.d.ts.map +1 -1
- package/dist/util/mac.js +2 -2
- package/dist/util/mac.js.map +1 -1
- package/dist/version.js +2 -2
- package/dist/version.js.map +1 -1
- package/package.json +25 -26
- package/bin/homebridge +0 -19
|
@@ -0,0 +1,1623 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matter.js Server Implementation for Homebridge Plugin API
|
|
3
|
+
*
|
|
4
|
+
* This provides a Matter bridge that plugins can use to register
|
|
5
|
+
* Matter accessories via the Homebridge API.
|
|
6
|
+
*/
|
|
7
|
+
import { randomBytes } from 'node:crypto';
|
|
8
|
+
import { EventEmitter } from 'node:events';
|
|
9
|
+
import { constants, existsSync } from 'node:fs';
|
|
10
|
+
import { access, writeFile } from 'node:fs/promises';
|
|
11
|
+
import { homedir, release } from 'node:os';
|
|
12
|
+
import { join, normalize, resolve } from 'node:path';
|
|
13
|
+
import process from 'node:process';
|
|
14
|
+
import { Endpoint, Environment, Logger as MatterLogger, LogLevel as MatterLogLevel, ServerNode, StorageService, VendorId, } from '@matter/main';
|
|
15
|
+
import { WindowCoveringServer } from '@matter/main/behaviors';
|
|
16
|
+
import * as devices from '@matter/main/devices';
|
|
17
|
+
import { AggregatorEndpoint } from '@matter/main/endpoints';
|
|
18
|
+
import { ManualPairingCodeCodec, QrPairingCodeCodec } from '@matter/types/schema';
|
|
19
|
+
import fse from 'fs-extra';
|
|
20
|
+
import QRCode from 'qrcode-terminal';
|
|
21
|
+
import { Logger } from '../logger.js';
|
|
22
|
+
import getVersion from '../version.js';
|
|
23
|
+
import { MatterAccessoryCache } from './matterAccessoryCache.js';
|
|
24
|
+
import { HomebridgeColorControlServer, HomebridgeDoorLockServer, HomebridgeIdentifyServer, HomebridgeLevelControlServer, HomebridgeOnOffServer, HomebridgeRvcCleanModeServer, HomebridgeRvcOperationalStateServer, HomebridgeRvcRunModeServer, HomebridgeServiceAreaServer, HomebridgeThermostatServer, HomebridgeWindowCoveringServer, registerHandler, setAccessoriesMap, } from './matterBehaviors.js';
|
|
25
|
+
import { sanitizeUniqueId, truncateString, validatePort } from './matterConfigValidator.js';
|
|
26
|
+
import { errorHandler } from './matterErrorHandler.js';
|
|
27
|
+
import { createHomebridgeLogFormatter } from './matterLogFormatter.js';
|
|
28
|
+
import { networkMonitor } from './matterNetworkMonitor.js';
|
|
29
|
+
import { MatterStorageManager } from './matterStorage.js';
|
|
30
|
+
import { clusters, deviceTypes, MatterDeviceError, } from './matterTypes.js';
|
|
31
|
+
const log = Logger.withPrefix('Matter/Server');
|
|
32
|
+
// Constants for Matter server configuration
|
|
33
|
+
const DEFAULT_MATTER_PORT = 5540;
|
|
34
|
+
const DEFAULT_VENDOR_ID = 0xFFF1; // Test vendor ID from Matter spec
|
|
35
|
+
const DEFAULT_PRODUCT_ID = 0x8001; // Test product ID
|
|
36
|
+
const MAX_DEVICES_PER_BRIDGE = 1000; // Matter spec maximum devices per aggregator
|
|
37
|
+
const SERVER_READY_TIMEOUT_MS = 5000;
|
|
38
|
+
const SERVER_READY_POLL_INTERVAL_MS = 100;
|
|
39
|
+
const SERVER_INIT_DELAY_MS = 200;
|
|
40
|
+
const MAX_PASSCODE_ATTEMPTS = 100;
|
|
41
|
+
const FABRIC_MONITOR_INTERVAL_MS = 2000; // Check for fabric changes every 2 seconds
|
|
42
|
+
/**
|
|
43
|
+
* Matter Server for Homebridge Plugin API
|
|
44
|
+
* Allows plugins to register Matter accessories explicitly
|
|
45
|
+
*
|
|
46
|
+
* Extends EventEmitter to provide commissioning lifecycle events
|
|
47
|
+
*/
|
|
48
|
+
export class MatterServer extends EventEmitter {
|
|
49
|
+
config;
|
|
50
|
+
serverNode = null;
|
|
51
|
+
aggregator = null;
|
|
52
|
+
accessories = new Map();
|
|
53
|
+
isRunning = false;
|
|
54
|
+
MAX_DEVICES = MAX_DEVICES_PER_BRIDGE;
|
|
55
|
+
shutdownHandler = null;
|
|
56
|
+
// Internal commissioning values (generated, not user-configurable)
|
|
57
|
+
passcode = 0;
|
|
58
|
+
discriminator = 0;
|
|
59
|
+
vendorId;
|
|
60
|
+
productId;
|
|
61
|
+
commissioningInfo = {};
|
|
62
|
+
serialNumber;
|
|
63
|
+
cleanupHandlers = [];
|
|
64
|
+
storageManager = null;
|
|
65
|
+
matterStoragePath;
|
|
66
|
+
accessoryCache = null;
|
|
67
|
+
// Fabric monitoring
|
|
68
|
+
fabricMonitorInterval = null;
|
|
69
|
+
previousFabrics = new Map();
|
|
70
|
+
constructor(config) {
|
|
71
|
+
super();
|
|
72
|
+
// Store the validated config
|
|
73
|
+
this.config = this.validateAndSanitizeConfig(config);
|
|
74
|
+
// Configure Matter.js library logging
|
|
75
|
+
// Suppress DEBUG/INFO logs from Matter.js library unless debug mode is explicitly enabled
|
|
76
|
+
if (this.config.debugModeEnabled) {
|
|
77
|
+
log.info('Matter debug mode enabled - verbose logging active');
|
|
78
|
+
MatterLogger.level = MatterLogLevel.DEBUG;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
MatterLogger.level = MatterLogLevel.NOTICE;
|
|
82
|
+
}
|
|
83
|
+
// Set custom log format to match homebridge format:
|
|
84
|
+
// [DD/MM/YYYY, HH:MM:SS] [Matter/Facility] message
|
|
85
|
+
MatterLogger.format = createHomebridgeLogFormatter();
|
|
86
|
+
// Redirect all Matter.js logs to console.log to prevent console.debug() suppression
|
|
87
|
+
// Matter.js uses console.debug() for DEBUG level logs, which is silently ignored in many Node.js environments
|
|
88
|
+
MatterLogger.destinations.default.write = (text) => {
|
|
89
|
+
console.log(text); // eslint-disable-line no-console
|
|
90
|
+
};
|
|
91
|
+
// Initialize commissioning values (will be loaded from storage in start())
|
|
92
|
+
this.vendorId = DEFAULT_VENDOR_ID;
|
|
93
|
+
this.productId = DEFAULT_PRODUCT_ID;
|
|
94
|
+
// Provide accessories map reference to behaviors for cache syncing
|
|
95
|
+
setAccessoriesMap(this.accessories);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Validate and sanitize Matter server configuration
|
|
99
|
+
* Throws descriptive errors if configuration is invalid
|
|
100
|
+
*/
|
|
101
|
+
validateAndSanitizeConfig(config) {
|
|
102
|
+
const errors = [];
|
|
103
|
+
// Validate port
|
|
104
|
+
const port = config.port || DEFAULT_MATTER_PORT;
|
|
105
|
+
const portValidation = validatePort(port, false);
|
|
106
|
+
if (!portValidation.valid) {
|
|
107
|
+
errors.push(`Invalid port: ${portValidation.error}`);
|
|
108
|
+
}
|
|
109
|
+
// Validate and sanitize uniqueId (REQUIRED)
|
|
110
|
+
if (!config.uniqueId) {
|
|
111
|
+
errors.push('uniqueId is required for Matter server configuration');
|
|
112
|
+
}
|
|
113
|
+
const rawUniqueId = config.uniqueId || '';
|
|
114
|
+
const uniqueIdResult = sanitizeUniqueId(rawUniqueId);
|
|
115
|
+
const uniqueId = uniqueIdResult.value;
|
|
116
|
+
if (uniqueId.length === 0) {
|
|
117
|
+
errors.push('Invalid uniqueId: must be a non-empty string');
|
|
118
|
+
}
|
|
119
|
+
// Validate storagePath (if provided)
|
|
120
|
+
let storagePath = config.storagePath;
|
|
121
|
+
if (storagePath !== undefined) {
|
|
122
|
+
storagePath = resolve(storagePath); // Resolve to absolute path
|
|
123
|
+
}
|
|
124
|
+
// Validate and sanitize manufacturer
|
|
125
|
+
let manufacturer = config.manufacturer;
|
|
126
|
+
if (manufacturer !== undefined) {
|
|
127
|
+
manufacturer = truncateString(manufacturer, 32, 'Manufacturer name').value;
|
|
128
|
+
}
|
|
129
|
+
// Validate and sanitize model
|
|
130
|
+
let model = config.model;
|
|
131
|
+
if (model !== undefined) {
|
|
132
|
+
model = truncateString(model, 32, 'Model name').value;
|
|
133
|
+
}
|
|
134
|
+
// Validate firmwareRevision
|
|
135
|
+
let firmwareRevision = config.firmwareRevision;
|
|
136
|
+
if (firmwareRevision !== undefined) {
|
|
137
|
+
firmwareRevision = truncateString(firmwareRevision, 64, 'Firmware revision').value;
|
|
138
|
+
}
|
|
139
|
+
// Validate serialNumber
|
|
140
|
+
let serialNumber = config.serialNumber;
|
|
141
|
+
if (serialNumber !== undefined) {
|
|
142
|
+
serialNumber = truncateString(serialNumber, 32, 'Serial number').value;
|
|
143
|
+
}
|
|
144
|
+
// Validate debugModeEnabled
|
|
145
|
+
const debugModeEnabled = config.debugModeEnabled || false;
|
|
146
|
+
// Throw if there are validation errors
|
|
147
|
+
if (errors.length > 0) {
|
|
148
|
+
throw new MatterDeviceError(`Matter configuration validation failed:\n${errors.map(e => ` - ${e}`).join('\n')}`);
|
|
149
|
+
}
|
|
150
|
+
return {
|
|
151
|
+
port,
|
|
152
|
+
uniqueId,
|
|
153
|
+
storagePath,
|
|
154
|
+
manufacturer,
|
|
155
|
+
model,
|
|
156
|
+
firmwareRevision,
|
|
157
|
+
serialNumber,
|
|
158
|
+
debugModeEnabled,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Generate a secure random passcode
|
|
163
|
+
* According to Matter spec, passcode must be:
|
|
164
|
+
* - 8 digits (00000001 to 99999998)
|
|
165
|
+
* - Not in the invalid list
|
|
166
|
+
* - Not sequential or repeating patterns
|
|
167
|
+
*/
|
|
168
|
+
generateSecurePasscode() {
|
|
169
|
+
let passcode;
|
|
170
|
+
const maxAttempts = MAX_PASSCODE_ATTEMPTS;
|
|
171
|
+
let attempts = 0;
|
|
172
|
+
const invalidPasscodes = [
|
|
173
|
+
0,
|
|
174
|
+
11111111,
|
|
175
|
+
22222222,
|
|
176
|
+
33333333,
|
|
177
|
+
44444444,
|
|
178
|
+
55555555,
|
|
179
|
+
66666666,
|
|
180
|
+
77777777,
|
|
181
|
+
88888888,
|
|
182
|
+
99999999,
|
|
183
|
+
12345678,
|
|
184
|
+
87654321,
|
|
185
|
+
];
|
|
186
|
+
do {
|
|
187
|
+
// Use cryptographically secure random number generation
|
|
188
|
+
const randomValue = randomBytes(4).readUInt32BE(0);
|
|
189
|
+
// Generate a value between 1 and 99999998
|
|
190
|
+
passcode = (randomValue % 99999998) + 1;
|
|
191
|
+
attempts++;
|
|
192
|
+
if (attempts > maxAttempts) {
|
|
193
|
+
throw new Error('Failed to generate secure passcode after maximum attempts');
|
|
194
|
+
}
|
|
195
|
+
} while (invalidPasscodes.includes(passcode)
|
|
196
|
+
|| !this.isValidPasscode(passcode));
|
|
197
|
+
return passcode;
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Validate a passcode according to Matter specifications
|
|
201
|
+
*/
|
|
202
|
+
isValidPasscode(passcode) {
|
|
203
|
+
// Must be between 1 and 99999998
|
|
204
|
+
if (passcode < 1 || passcode > 99999998) {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
// Convert to 8-digit string
|
|
208
|
+
const passcodeStr = passcode.toString().padStart(8, '0');
|
|
209
|
+
// Check for sequential patterns (12345678, 23456789, etc.)
|
|
210
|
+
let isSequential = true;
|
|
211
|
+
for (let i = 1; i < passcodeStr.length; i++) {
|
|
212
|
+
if (Number.parseInt(passcodeStr[i]) !== Number.parseInt(passcodeStr[i - 1]) + 1) {
|
|
213
|
+
isSequential = false;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (isSequential) {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
// Check for reverse sequential (87654321, 76543210, etc.)
|
|
221
|
+
let isReverseSequential = true;
|
|
222
|
+
for (let i = 1; i < passcodeStr.length; i++) {
|
|
223
|
+
if (Number.parseInt(passcodeStr[i]) !== Number.parseInt(passcodeStr[i - 1]) - 1) {
|
|
224
|
+
isReverseSequential = false;
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (isReverseSequential) {
|
|
229
|
+
return false;
|
|
230
|
+
}
|
|
231
|
+
// Check for too many repeating digits (more than 3 of same digit)
|
|
232
|
+
const digitCounts = new Map();
|
|
233
|
+
for (const digit of passcodeStr) {
|
|
234
|
+
digitCounts.set(digit, (digitCounts.get(digit) || 0) + 1);
|
|
235
|
+
if (digitCounts.get(digit) > 3) {
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Generate a random discriminator
|
|
243
|
+
* According to Matter spec, discriminator must be:
|
|
244
|
+
* - 12 bits (0-4095)
|
|
245
|
+
* - Should be random for security
|
|
246
|
+
*/
|
|
247
|
+
generateRandomDiscriminator() {
|
|
248
|
+
// Generate cryptographically secure random 12-bit discriminator (0-4095)
|
|
249
|
+
const discriminator = randomBytes(2).readUInt16BE(0) & 0x0FFF; // Mask to 12 bits
|
|
250
|
+
// Validate discriminator range
|
|
251
|
+
if (discriminator < 0 || discriminator > 4095) {
|
|
252
|
+
throw new Error(`Invalid discriminator generated: ${discriminator}`);
|
|
253
|
+
}
|
|
254
|
+
return discriminator;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Create ServerNode with automatic recovery from corrupted storage
|
|
258
|
+
*
|
|
259
|
+
* Matter.js can fail to start if fabric data is corrupted (common after
|
|
260
|
+
* hard shutdowns or disk errors). This method implements automatic recovery by:
|
|
261
|
+
*
|
|
262
|
+
* 1. Attempting normal ServerNode creation
|
|
263
|
+
* 2. If it fails with storage errors, identifying and removing corrupted files
|
|
264
|
+
* 3. Retrying ServerNode creation with fresh storage
|
|
265
|
+
*
|
|
266
|
+
* This prevents the need for manual intervention while preserving data
|
|
267
|
+
* safety by only removing storage on confirmed corruption errors.
|
|
268
|
+
*
|
|
269
|
+
* @param nodeOptions - Matter.js ServerNode configuration
|
|
270
|
+
* @param sanitizedId - Filesystem-safe bridge identifier
|
|
271
|
+
* @returns Initialized ServerNode instance
|
|
272
|
+
* @throws Error if recovery fails or error is not storage-related
|
|
273
|
+
*/
|
|
274
|
+
async createServerNodeWithRecovery(nodeOptions, sanitizedId) {
|
|
275
|
+
try {
|
|
276
|
+
// First attempt to create ServerNode
|
|
277
|
+
return await ServerNode.create(nodeOptions);
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
// Check if this is a storage corruption error
|
|
281
|
+
const isStorageError = error?.message?.includes('Invalid public key encoding')
|
|
282
|
+
|| error?.message?.includes('FabricManager unavailable')
|
|
283
|
+
|| error?.message?.includes('key-input')
|
|
284
|
+
|| error?.cause?.message?.includes('Invalid public key encoding');
|
|
285
|
+
if (!isStorageError) {
|
|
286
|
+
// Not a storage error, rethrow
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
// Storage is corrupted - clean up and retry
|
|
290
|
+
log.warn('Detected corrupted Matter storage, attempting automatic recovery...');
|
|
291
|
+
// The ServerNodeStore directory is inside our storage path with the same name as the bridge ID
|
|
292
|
+
const environment = Environment.default;
|
|
293
|
+
const storageService = environment.get(StorageService);
|
|
294
|
+
const storageLocation = storageService.location;
|
|
295
|
+
if (!storageLocation) {
|
|
296
|
+
throw new Error('Storage location not set, cannot recover from corrupted storage');
|
|
297
|
+
}
|
|
298
|
+
const serverNodeStorePath = join(storageLocation, sanitizedId);
|
|
299
|
+
const serverNodeStoreJsonFile = `${serverNodeStorePath}.json`;
|
|
300
|
+
try {
|
|
301
|
+
let removedSomething = false;
|
|
302
|
+
// Delete the ServerNodeStore subdirectory
|
|
303
|
+
if (existsSync(serverNodeStorePath)) {
|
|
304
|
+
log.info(`Removing corrupted ServerNodeStore directory: ${serverNodeStorePath}`);
|
|
305
|
+
await fse.remove(serverNodeStorePath);
|
|
306
|
+
removedSomething = true;
|
|
307
|
+
}
|
|
308
|
+
// Delete the ServerNodeStore JSON file (contains fabric data)
|
|
309
|
+
if (existsSync(serverNodeStoreJsonFile)) {
|
|
310
|
+
log.info(`Removing corrupted ServerNodeStore JSON file: ${serverNodeStoreJsonFile}`);
|
|
311
|
+
await fse.remove(serverNodeStoreJsonFile);
|
|
312
|
+
removedSomething = true;
|
|
313
|
+
}
|
|
314
|
+
if (removedSomething) {
|
|
315
|
+
log.info('Corrupted storage removed, retrying ServerNode creation...');
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
log.warn('No corrupted storage files found, corruption may be elsewhere');
|
|
319
|
+
}
|
|
320
|
+
// Retry ServerNode creation
|
|
321
|
+
const serverNode = await ServerNode.create(nodeOptions);
|
|
322
|
+
log.info('Successfully recovered from corrupted Matter storage');
|
|
323
|
+
return serverNode;
|
|
324
|
+
}
|
|
325
|
+
catch (retryError) {
|
|
326
|
+
log.error('Failed to recover from corrupted storage:', retryError);
|
|
327
|
+
log.error('Original error:', error);
|
|
328
|
+
throw new Error('Matter storage is corrupted and automatic recovery failed. '
|
|
329
|
+
+ `Please manually delete: ${serverNodeStorePath}`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Start the Matter server
|
|
335
|
+
*/
|
|
336
|
+
async start() {
|
|
337
|
+
if (this.isRunning) {
|
|
338
|
+
log.warn('Matter server is already running');
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
try {
|
|
342
|
+
log.info('Starting Matter.js server...');
|
|
343
|
+
// IMPORTANT: Storage must be configured BEFORE any Matter.js operations
|
|
344
|
+
// This ensures persistent fabric data across restarts
|
|
345
|
+
await this.setupStorage();
|
|
346
|
+
// Load or generate commissioning credentials
|
|
347
|
+
await this.loadOrGenerateCredentials();
|
|
348
|
+
log.info(`Configuration: Port=${this.config.port}, Passcode=${this.passcode}, Discriminator=${this.discriminator}`);
|
|
349
|
+
// Start network monitoring
|
|
350
|
+
networkMonitor.startMonitoring();
|
|
351
|
+
this.cleanupHandlers.push(() => networkMonitor.stopMonitoring());
|
|
352
|
+
// Create commissioning options
|
|
353
|
+
const commissioningOptions = {
|
|
354
|
+
passcode: this.passcode,
|
|
355
|
+
discriminator: this.discriminator,
|
|
356
|
+
};
|
|
357
|
+
log.info(`Using commissioning credentials: passcode=${this.passcode}, discriminator=${this.discriminator}`);
|
|
358
|
+
// Use default name for the Matter bridge
|
|
359
|
+
const bridgeName = 'Homebridge Matter Bridge';
|
|
360
|
+
// uniqueId is already sanitized in validateAndSanitizeConfig()
|
|
361
|
+
const sanitizedId = this.config.uniqueId;
|
|
362
|
+
// Create node options with proper typing
|
|
363
|
+
const nodeOptions = {
|
|
364
|
+
id: sanitizedId,
|
|
365
|
+
network: {
|
|
366
|
+
port: this.config.port,
|
|
367
|
+
ipv4: true, // Always enable IPv4 for Matter
|
|
368
|
+
},
|
|
369
|
+
commissioning: commissioningOptions,
|
|
370
|
+
productDescription: {
|
|
371
|
+
name: bridgeName,
|
|
372
|
+
deviceType: AggregatorEndpoint.deviceType,
|
|
373
|
+
},
|
|
374
|
+
basicInformation: {
|
|
375
|
+
nodeLabel: bridgeName.slice(0, 32), // Maximum 32 characters
|
|
376
|
+
vendorId: VendorId(this.vendorId),
|
|
377
|
+
vendorName: (this.config.manufacturer || 'Homebridge').slice(0, 32),
|
|
378
|
+
productId: this.productId,
|
|
379
|
+
productName: (this.config.model || 'Homebridge Matter Bridge').slice(0, 32),
|
|
380
|
+
productLabel: bridgeName.slice(0, 64), // Maximum 64 characters
|
|
381
|
+
serialNumber: this.serialNumber = this.config.serialNumber || this.config.uniqueId,
|
|
382
|
+
hardwareVersion: 1,
|
|
383
|
+
hardwareVersionString: release(),
|
|
384
|
+
softwareVersion: 1,
|
|
385
|
+
softwareVersionString: this.config.firmwareRevision || getVersion(),
|
|
386
|
+
reachable: true,
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
// Create server node with automatic recovery from corrupted storage
|
|
390
|
+
this.serverNode = await this.createServerNodeWithRecovery(nodeOptions, sanitizedId);
|
|
391
|
+
// Create aggregator endpoint for bridge pattern
|
|
392
|
+
this.aggregator = new Endpoint(AggregatorEndpoint, {
|
|
393
|
+
id: 'homebridge-aggregator',
|
|
394
|
+
});
|
|
395
|
+
// Add aggregator to server
|
|
396
|
+
await this.serverNode.add(this.aggregator);
|
|
397
|
+
// Generate and display commissioning information
|
|
398
|
+
await this.generateCommissioningInfo();
|
|
399
|
+
// Set up graceful shutdown handler
|
|
400
|
+
this.shutdownHandler = async () => {
|
|
401
|
+
log.info('Shutting down Matter server...');
|
|
402
|
+
await this.stop();
|
|
403
|
+
};
|
|
404
|
+
// Register shutdown handlers
|
|
405
|
+
process.on('SIGINT', this.shutdownHandler);
|
|
406
|
+
process.on('SIGTERM', this.shutdownHandler);
|
|
407
|
+
// Start the server in a non-blocking way
|
|
408
|
+
this.serverNode.run().then(() => {
|
|
409
|
+
log.info('Matter server stopped normally');
|
|
410
|
+
}, (error) => {
|
|
411
|
+
log.error('Matter server stopped with error:', error);
|
|
412
|
+
errorHandler.handleError(error, 'server-runtime');
|
|
413
|
+
});
|
|
414
|
+
// Wait for server to be ready
|
|
415
|
+
await this.waitForServerReady();
|
|
416
|
+
// Load cached accessories (don't restore them yet - wait for plugins to re-register)
|
|
417
|
+
if (this.accessoryCache) {
|
|
418
|
+
const loaded = await this.accessoryCache.load();
|
|
419
|
+
log.debug(`Matter cache loaded: ${loaded.size} accessories`);
|
|
420
|
+
}
|
|
421
|
+
else {
|
|
422
|
+
log.debug('No accessory cache available');
|
|
423
|
+
}
|
|
424
|
+
// Start fabric monitoring to emit commissioning events
|
|
425
|
+
this.startFabricMonitoring();
|
|
426
|
+
this.isRunning = true;
|
|
427
|
+
log.info(`Matter server started successfully on port ${this.config.port}`);
|
|
428
|
+
log.info('Plugins can now register Matter accessories via the API');
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
log.error('Failed to start Matter server:', error);
|
|
432
|
+
await this.cleanup();
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Set up and validate storage
|
|
438
|
+
*/
|
|
439
|
+
async setupStorage() {
|
|
440
|
+
if (!this.config.storagePath) {
|
|
441
|
+
throw new Error('Storage path is required for Matter server');
|
|
442
|
+
}
|
|
443
|
+
// Resolve to absolute path and validate
|
|
444
|
+
const storagePath = resolve(this.config.storagePath);
|
|
445
|
+
const normalizedPath = normalize(storagePath);
|
|
446
|
+
// Ensure path is within allowed directories
|
|
447
|
+
const allowedBasePaths = [
|
|
448
|
+
resolve(homedir(), '.homebridge'),
|
|
449
|
+
resolve(process.cwd()),
|
|
450
|
+
'/var/lib/homebridge', // Common system location
|
|
451
|
+
];
|
|
452
|
+
const isAllowed = allowedBasePaths.some(basePath => normalizedPath.startsWith(basePath));
|
|
453
|
+
if (!isAllowed || normalizedPath.includes('..')) {
|
|
454
|
+
throw new Error(`Storage path not allowed: ${normalizedPath}. Must be within homebridge directories.`);
|
|
455
|
+
}
|
|
456
|
+
// Ensure the storage directory exists with proper permissions
|
|
457
|
+
try {
|
|
458
|
+
await fse.ensureDir(normalizedPath);
|
|
459
|
+
await access(normalizedPath, constants.R_OK | constants.W_OK);
|
|
460
|
+
}
|
|
461
|
+
catch (error) {
|
|
462
|
+
throw new Error(`Storage path not accessible: ${error}`);
|
|
463
|
+
}
|
|
464
|
+
// Create bridge-specific storage directory
|
|
465
|
+
// uniqueId is already sanitized in validateAndSanitizeConfig()
|
|
466
|
+
const bridgeId = this.config.uniqueId || 'default';
|
|
467
|
+
this.matterStoragePath = join(normalizedPath, bridgeId);
|
|
468
|
+
await fse.ensureDir(this.matterStoragePath);
|
|
469
|
+
// Create storage manager
|
|
470
|
+
this.storageManager = new MatterStorageManager(this.matterStoragePath);
|
|
471
|
+
// Create accessory cache
|
|
472
|
+
this.accessoryCache = new MatterAccessoryCache(normalizedPath, bridgeId);
|
|
473
|
+
// Configure environment to use our custom storage
|
|
474
|
+
const environment = Environment.default;
|
|
475
|
+
const storageService = environment.get(StorageService);
|
|
476
|
+
storageService.location = this.matterStoragePath;
|
|
477
|
+
// CRITICAL: Override storage factory with custom implementation
|
|
478
|
+
// This ensures fabric data is properly persisted
|
|
479
|
+
storageService.factory = (namespace) => {
|
|
480
|
+
if (!this.storageManager) {
|
|
481
|
+
throw new Error('Storage manager not initialized');
|
|
482
|
+
}
|
|
483
|
+
const storage = this.storageManager.getStorage(namespace);
|
|
484
|
+
// Initialize asynchronously - Matter.js handles async storage properly
|
|
485
|
+
storage.initialize().catch((error) => {
|
|
486
|
+
log.error(`Failed to initialize storage namespace ${namespace}:`, error);
|
|
487
|
+
});
|
|
488
|
+
// Note: Cast to unknown first to satisfy TypeScript - our storage implements the required interface
|
|
489
|
+
return storage;
|
|
490
|
+
};
|
|
491
|
+
// Add cleanup handler for storage
|
|
492
|
+
this.cleanupHandlers.push(async () => {
|
|
493
|
+
if (this.storageManager) {
|
|
494
|
+
await this.storageManager.closeAll();
|
|
495
|
+
}
|
|
496
|
+
});
|
|
497
|
+
log.info(`Matter storage initialized at: ${this.matterStoragePath}`);
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Load or generate commissioning credentials (passcode and discriminator)
|
|
501
|
+
* These must be persistent across restarts to maintain the same QR code
|
|
502
|
+
*/
|
|
503
|
+
async loadOrGenerateCredentials() {
|
|
504
|
+
if (!this.storageManager) {
|
|
505
|
+
throw new Error('Storage manager not initialized');
|
|
506
|
+
}
|
|
507
|
+
// Use 'credentials' namespace
|
|
508
|
+
const storage = this.storageManager.getStorage('credentials');
|
|
509
|
+
// CRITICAL: Initialize storage before reading to avoid race condition
|
|
510
|
+
await storage.initialize();
|
|
511
|
+
// Try to load existing credentials
|
|
512
|
+
const storedPasscode = storage.get([], 'passcode');
|
|
513
|
+
const storedDiscriminator = storage.get([], 'discriminator');
|
|
514
|
+
if (storedPasscode && storedDiscriminator) {
|
|
515
|
+
// Use stored credentials
|
|
516
|
+
log.info('Loading existing commissioning credentials from storage');
|
|
517
|
+
this.passcode = storedPasscode;
|
|
518
|
+
this.discriminator = storedDiscriminator;
|
|
519
|
+
}
|
|
520
|
+
else {
|
|
521
|
+
// Generate new credentials and store them
|
|
522
|
+
log.info('Generating new commissioning credentials');
|
|
523
|
+
this.passcode = this.generateSecurePasscode();
|
|
524
|
+
this.discriminator = this.generateRandomDiscriminator();
|
|
525
|
+
// Store for future use
|
|
526
|
+
storage.set([], 'passcode', this.passcode);
|
|
527
|
+
storage.set([], 'discriminator', this.discriminator);
|
|
528
|
+
log.info('Commissioning credentials saved to storage');
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Generate and display commissioning information
|
|
533
|
+
*/
|
|
534
|
+
async generateCommissioningInfo() {
|
|
535
|
+
const passcode = this.passcode.toString().padStart(8, '0');
|
|
536
|
+
const discriminator = this.discriminator;
|
|
537
|
+
const vendorId = this.vendorId;
|
|
538
|
+
const productId = this.productId;
|
|
539
|
+
// Use Matter.js library to generate pairing codes properly
|
|
540
|
+
const manualCode = ManualPairingCodeCodec.encode({
|
|
541
|
+
discriminator,
|
|
542
|
+
passcode: this.passcode,
|
|
543
|
+
});
|
|
544
|
+
// Format as XXXX-XXX-XXXX for display
|
|
545
|
+
const manualPairingCode = `${manualCode.slice(0, 4)}-${manualCode.slice(4, 7)}-${manualCode.slice(7, 11)}`;
|
|
546
|
+
log.info(`Encoding QR code with: passcode=${this.passcode}, discriminator=${discriminator}, vendorId=${vendorId}, productId=${productId}`);
|
|
547
|
+
const qrCodePayload = QrPairingCodeCodec.encode([{
|
|
548
|
+
version: 0,
|
|
549
|
+
vendorId,
|
|
550
|
+
productId,
|
|
551
|
+
flowType: 0, // Standard commissioning flow
|
|
552
|
+
discoveryCapabilities: 4, // OnNetwork=4
|
|
553
|
+
discriminator,
|
|
554
|
+
passcode: this.passcode,
|
|
555
|
+
}]);
|
|
556
|
+
log.info(`Generated QR code: ${qrCodePayload}`);
|
|
557
|
+
log.info(`Generated manual code: ${manualPairingCode}`);
|
|
558
|
+
// Store commissioning info
|
|
559
|
+
this.commissioningInfo = {
|
|
560
|
+
qrCode: qrCodePayload,
|
|
561
|
+
manualPairingCode,
|
|
562
|
+
};
|
|
563
|
+
// Save commissioning info to disk for UI access
|
|
564
|
+
try {
|
|
565
|
+
if (!this.matterStoragePath) {
|
|
566
|
+
throw new Error('Matter storage path not initialized');
|
|
567
|
+
}
|
|
568
|
+
const commissioningFilePath = join(this.matterStoragePath, 'commissioning.json');
|
|
569
|
+
const commissioningData = {
|
|
570
|
+
qrCode: qrCodePayload,
|
|
571
|
+
manualPairingCode,
|
|
572
|
+
serialNumber: this.serialNumber,
|
|
573
|
+
passcode: this.passcode,
|
|
574
|
+
discriminator: this.discriminator,
|
|
575
|
+
commissioned: this.isCommissioned(),
|
|
576
|
+
};
|
|
577
|
+
await writeFile(commissioningFilePath, JSON.stringify(commissioningData, null, 2), 'utf-8');
|
|
578
|
+
log.debug(`Saved commissioning info to ${commissioningFilePath}`);
|
|
579
|
+
}
|
|
580
|
+
catch (error) {
|
|
581
|
+
log.warn(`Failed to save commissioning info to disk: ${error.message}`);
|
|
582
|
+
}
|
|
583
|
+
// Display commissioning information
|
|
584
|
+
log.info(`\n${'='.repeat(60)}`);
|
|
585
|
+
log.info('📱 MATTER COMMISSIONING INFORMATION');
|
|
586
|
+
log.info('='.repeat(60));
|
|
587
|
+
log.info(`Manual Pairing Code: ${manualPairingCode}`);
|
|
588
|
+
log.info(`Passcode: ${passcode}`);
|
|
589
|
+
log.info(`Discriminator: ${discriminator}`);
|
|
590
|
+
log.info('\nQR Code for commissioning:');
|
|
591
|
+
// Generate and display QR code in terminal
|
|
592
|
+
QRCode.generate(qrCodePayload, { small: true }, (qrcode) => {
|
|
593
|
+
// eslint-disable-next-line no-console
|
|
594
|
+
console.log(qrcode);
|
|
595
|
+
});
|
|
596
|
+
log.info(`${'='.repeat(60)}\n`);
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* Wait for the server to be ready
|
|
600
|
+
*/
|
|
601
|
+
async waitForServerReady(maxWaitTime = SERVER_READY_TIMEOUT_MS) {
|
|
602
|
+
const startTime = Date.now();
|
|
603
|
+
while (!this.serverNode || !this.aggregator) {
|
|
604
|
+
if (Date.now() - startTime > maxWaitTime) {
|
|
605
|
+
throw new Error('Server failed to become ready within timeout');
|
|
606
|
+
}
|
|
607
|
+
await new Promise(resolve => setTimeout(resolve, SERVER_READY_POLL_INTERVAL_MS));
|
|
608
|
+
}
|
|
609
|
+
// Additional small delay to ensure everything is initialized
|
|
610
|
+
await new Promise(resolve => setTimeout(resolve, SERVER_INIT_DELAY_MS));
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Start monitoring fabric changes to emit commissioning events
|
|
614
|
+
*/
|
|
615
|
+
startFabricMonitoring() {
|
|
616
|
+
// Stop any existing monitor
|
|
617
|
+
this.stopFabricMonitoring();
|
|
618
|
+
// Initialize with current fabrics
|
|
619
|
+
const initialFabrics = this.getFabricInfo();
|
|
620
|
+
for (const fabric of initialFabrics) {
|
|
621
|
+
this.previousFabrics.set(fabric.fabricIndex, fabric);
|
|
622
|
+
}
|
|
623
|
+
log.debug('Starting fabric monitoring for commissioning events');
|
|
624
|
+
// Set up periodic monitoring
|
|
625
|
+
this.fabricMonitorInterval = setInterval(() => {
|
|
626
|
+
this.checkFabricChanges();
|
|
627
|
+
}, FABRIC_MONITOR_INTERVAL_MS);
|
|
628
|
+
// Add to clean up handlers
|
|
629
|
+
this.cleanupHandlers.push(() => this.stopFabricMonitoring());
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* Stop fabric monitoring
|
|
633
|
+
*/
|
|
634
|
+
stopFabricMonitoring() {
|
|
635
|
+
if (this.fabricMonitorInterval) {
|
|
636
|
+
clearInterval(this.fabricMonitorInterval);
|
|
637
|
+
this.fabricMonitorInterval = null;
|
|
638
|
+
log.debug('Stopped fabric monitoring');
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Check for fabric changes and emit appropriate events
|
|
643
|
+
*/
|
|
644
|
+
checkFabricChanges() {
|
|
645
|
+
try {
|
|
646
|
+
const currentFabrics = this.getFabricInfo();
|
|
647
|
+
const currentFabricMap = new Map();
|
|
648
|
+
// Build map of current fabrics
|
|
649
|
+
for (const fabric of currentFabrics) {
|
|
650
|
+
currentFabricMap.set(fabric.fabricIndex, fabric);
|
|
651
|
+
}
|
|
652
|
+
const previousCount = this.previousFabrics.size;
|
|
653
|
+
const currentCount = currentFabricMap.size;
|
|
654
|
+
// Check for added fabrics
|
|
655
|
+
for (const [fabricIndex, fabric] of currentFabricMap) {
|
|
656
|
+
if (!this.previousFabrics.has(fabricIndex)) {
|
|
657
|
+
log.info(`Fabric added: ${fabric.fabricId} (index: ${fabricIndex})`);
|
|
658
|
+
this.emit('fabric-added', fabric);
|
|
659
|
+
// If this is the first fabric, emit 'commissioned' event
|
|
660
|
+
if (previousCount === 0 && currentCount === 1) {
|
|
661
|
+
log.info('Bridge commissioned for the first time');
|
|
662
|
+
this.emit('commissioned', fabric);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
// Check for removed fabrics
|
|
667
|
+
for (const [fabricIndex, fabric] of this.previousFabrics) {
|
|
668
|
+
if (!currentFabricMap.has(fabricIndex)) {
|
|
669
|
+
log.info(`Fabric removed: ${fabric.fabricId} (index: ${fabricIndex})`);
|
|
670
|
+
this.emit('fabric-removed', fabric);
|
|
671
|
+
// If this was the last fabric, emit 'decommissioned' event
|
|
672
|
+
if (previousCount === 1 && currentCount === 0) {
|
|
673
|
+
log.info('Bridge decommissioned (last fabric removed)');
|
|
674
|
+
this.emit('decommissioned');
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
// Emit general commissioning-changed event if count changed
|
|
679
|
+
if (previousCount !== currentCount) {
|
|
680
|
+
const commissioned = currentCount > 0;
|
|
681
|
+
log.debug(`Commissioning state changed: commissioned=${commissioned}, fabricCount=${currentCount}`);
|
|
682
|
+
this.emit('commissioning-changed', commissioned, currentCount);
|
|
683
|
+
// Update commissioning info file
|
|
684
|
+
this.updateCommissioningFile().catch((error) => {
|
|
685
|
+
log.warn('Failed to update commissioning file:', error);
|
|
686
|
+
});
|
|
687
|
+
}
|
|
688
|
+
// Update previous fabrics map
|
|
689
|
+
this.previousFabrics = currentFabricMap;
|
|
690
|
+
}
|
|
691
|
+
catch (error) {
|
|
692
|
+
log.error('Error checking fabric changes:', error);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Update commissioning info file when commissioning state changes
|
|
697
|
+
*/
|
|
698
|
+
async updateCommissioningFile() {
|
|
699
|
+
try {
|
|
700
|
+
if (!this.matterStoragePath) {
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
const commissioningFilePath = join(this.matterStoragePath, 'commissioning.json');
|
|
704
|
+
const commissioningData = {
|
|
705
|
+
qrCode: this.commissioningInfo.qrCode,
|
|
706
|
+
manualPairingCode: this.commissioningInfo.manualPairingCode,
|
|
707
|
+
serialNumber: this.serialNumber,
|
|
708
|
+
passcode: this.passcode,
|
|
709
|
+
discriminator: this.discriminator,
|
|
710
|
+
commissioned: this.isCommissioned(),
|
|
711
|
+
fabricCount: this.getCommissionedFabricCount(),
|
|
712
|
+
fabrics: this.getFabricInfo(),
|
|
713
|
+
};
|
|
714
|
+
await writeFile(commissioningFilePath, JSON.stringify(commissioningData, null, 2), 'utf-8');
|
|
715
|
+
log.debug('Updated commissioning info file');
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
log.debug(`Failed to update commissioning info file: ${error.message}`);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Register Matter platform accessories (Plugin API - matches HAP pattern)
|
|
723
|
+
*/
|
|
724
|
+
async registerPlatformAccessories(pluginIdentifier, platformName, accessories) {
|
|
725
|
+
for (const accessory of accessories) {
|
|
726
|
+
await this.registerAccessory(pluginIdentifier, platformName, accessory);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* Unregister Matter platform accessories (Plugin API - matches HAP pattern)
|
|
731
|
+
*/
|
|
732
|
+
async unregisterPlatformAccessories(pluginIdentifier, platformName, accessories) {
|
|
733
|
+
for (const accessory of accessories) {
|
|
734
|
+
await this.unregisterAccessory(accessory.uuid);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
/**
|
|
738
|
+
* Register a single Matter accessory (internal method)
|
|
739
|
+
*/
|
|
740
|
+
async registerAccessory(pluginIdentifier, platformName, accessory) {
|
|
741
|
+
if (!this.serverNode || !this.aggregator) {
|
|
742
|
+
throw new MatterDeviceError('Matter server not started');
|
|
743
|
+
}
|
|
744
|
+
// Validate required fields with helpful error messages
|
|
745
|
+
if (!accessory.deviceType) {
|
|
746
|
+
throw new MatterDeviceError(`Matter accessory "${accessory.displayName || 'unknown'}" is missing required field 'deviceType'. `
|
|
747
|
+
+ 'Example: deviceType: api.matterDeviceTypes.OnOffLight\n'
|
|
748
|
+
+ 'Available device types: OnOffLight, DimmableLight, TemperatureSensor, etc.\n'
|
|
749
|
+
+ 'See the Matter types documentation for the full list.');
|
|
750
|
+
}
|
|
751
|
+
if (!accessory.uuid) {
|
|
752
|
+
throw new MatterDeviceError('Matter accessory is missing required field \'uuid\'.\n'
|
|
753
|
+
+ 'Generate a unique UUID for your accessory:\n'
|
|
754
|
+
+ ' const uuid = api.hap.uuid.generate(\'my-unique-id\')');
|
|
755
|
+
}
|
|
756
|
+
if (!accessory.displayName) {
|
|
757
|
+
throw new MatterDeviceError(`Matter accessory (${accessory.uuid}) is missing required field 'displayName'.\n`
|
|
758
|
+
+ 'Example: displayName: \'Living Room Light\'');
|
|
759
|
+
}
|
|
760
|
+
if (!accessory.serialNumber) {
|
|
761
|
+
throw new MatterDeviceError(`Matter accessory "${accessory.displayName}" is missing required field 'serialNumber'.\n`
|
|
762
|
+
+ 'Example: serialNumber: \'ABC123\' or serialNumber: accessory.UUID');
|
|
763
|
+
}
|
|
764
|
+
if (!accessory.manufacturer) {
|
|
765
|
+
throw new MatterDeviceError(`Matter accessory "${accessory.displayName}" is missing required field 'manufacturer'.\n`
|
|
766
|
+
+ 'Example: manufacturer: \'Homebridge\' or manufacturer: \'My Plugin Name\'');
|
|
767
|
+
}
|
|
768
|
+
if (!accessory.model) {
|
|
769
|
+
throw new MatterDeviceError(`Matter accessory "${accessory.displayName}" is missing required field 'model'.\n`
|
|
770
|
+
+ 'Example: model: \'v1.0\' or model: \'Smart Light\'');
|
|
771
|
+
}
|
|
772
|
+
if (!accessory.clusters || typeof accessory.clusters !== 'object') {
|
|
773
|
+
throw new MatterDeviceError(`Matter accessory "${accessory.displayName}" is missing or has invalid 'clusters' field.\n`
|
|
774
|
+
+ 'Clusters define the functionality of your device. Example:\n'
|
|
775
|
+
+ ' clusters: {\n'
|
|
776
|
+
+ ' onOff: { onOff: false },\n'
|
|
777
|
+
+ ' levelControl: { currentLevel: 0, minLevel: 0, maxLevel: 254 }\n'
|
|
778
|
+
+ ' }');
|
|
779
|
+
}
|
|
780
|
+
// Check if already registered (during this session)
|
|
781
|
+
if (this.accessories.has(accessory.uuid)) {
|
|
782
|
+
const existing = this.accessories.get(accessory.uuid);
|
|
783
|
+
throw new MatterDeviceError(`Matter accessory with UUID "${accessory.uuid}" is already registered.\n`
|
|
784
|
+
+ `Existing accessory: "${existing?.displayName}"\n`
|
|
785
|
+
+ `New accessory: "${accessory.displayName}"\n`
|
|
786
|
+
+ 'Each accessory must have a unique UUID. Use api.hap.uuid.generate() with a unique string.');
|
|
787
|
+
}
|
|
788
|
+
// Check if there's a cached version - merge cached cluster states with new registration
|
|
789
|
+
if (this.accessoryCache && this.accessoryCache.hasCached(accessory.uuid)) {
|
|
790
|
+
const cached = this.accessoryCache.getCached(accessory.uuid);
|
|
791
|
+
if (cached && cached.clusters) {
|
|
792
|
+
// Merge cached cluster states with new ones (prefer cached state to persist values across restarts)
|
|
793
|
+
for (const [clusterName, cachedAttrs] of Object.entries(cached.clusters)) {
|
|
794
|
+
if (!accessory.clusters[clusterName]) {
|
|
795
|
+
// Cluster exists in cache but not in new registration - preserve it
|
|
796
|
+
accessory.clusters[clusterName] = cachedAttrs;
|
|
797
|
+
}
|
|
798
|
+
else {
|
|
799
|
+
// Cluster exists in both - merge (prefer cached state over initial values)
|
|
800
|
+
accessory.clusters[clusterName] = {
|
|
801
|
+
...accessory.clusters[clusterName],
|
|
802
|
+
...cachedAttrs,
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
// Restore context if available
|
|
807
|
+
if (cached.context) {
|
|
808
|
+
accessory.context = cached.context;
|
|
809
|
+
}
|
|
810
|
+
log.info(`Restored cached state for Matter accessory: ${accessory.displayName}`);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
// Check device limit
|
|
814
|
+
if (this.accessories.size >= this.MAX_DEVICES) {
|
|
815
|
+
throw new MatterDeviceError(`Cannot register Matter accessory "${accessory.displayName}": `
|
|
816
|
+
+ `Maximum device limit reached (${this.MAX_DEVICES} devices).\n`
|
|
817
|
+
+ `Current registered devices: ${this.accessories.size}`);
|
|
818
|
+
}
|
|
819
|
+
try {
|
|
820
|
+
// Modify device type with custom behaviors if handlers are defined
|
|
821
|
+
let deviceType = accessory.deviceType;
|
|
822
|
+
// IMPORTANT: Detect WindowCovering features based on accessory attributes
|
|
823
|
+
// This must run BEFORE any other device type modifications
|
|
824
|
+
let windowCoveringFeatures = null;
|
|
825
|
+
if (accessory.clusters.windowCovering) {
|
|
826
|
+
windowCoveringFeatures = [];
|
|
827
|
+
const wcCluster = accessory.clusters.windowCovering;
|
|
828
|
+
// Check for lift attributes
|
|
829
|
+
const hasLiftAttrs = 'targetPositionLiftPercent100ths' in wcCluster || 'currentPositionLiftPercent100ths' in wcCluster;
|
|
830
|
+
const hasConfigLift = wcCluster.configStatus?.liftPositionAware === true;
|
|
831
|
+
// Check for tilt attributes
|
|
832
|
+
const hasTiltAttrs = 'targetPositionTiltPercent100ths' in wcCluster || 'currentPositionTiltPercent100ths' in wcCluster;
|
|
833
|
+
const hasConfigTilt = wcCluster.configStatus?.tiltPositionAware === true;
|
|
834
|
+
log.debug(`[${accessory.displayName}] WindowCovering detection: hasLiftAttrs=${hasLiftAttrs}, hasConfigLift=${hasConfigLift}, hasTiltAttrs=${hasTiltAttrs}, hasConfigTilt=${hasConfigTilt}`);
|
|
835
|
+
// Add Lift features if lift attributes are present
|
|
836
|
+
if (hasLiftAttrs) {
|
|
837
|
+
windowCoveringFeatures.push('Lift');
|
|
838
|
+
if (hasConfigLift) {
|
|
839
|
+
windowCoveringFeatures.push('PositionAwareLift');
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
// Add Tilt features if tilt attributes are present
|
|
843
|
+
if (hasTiltAttrs) {
|
|
844
|
+
windowCoveringFeatures.push('Tilt');
|
|
845
|
+
if (hasConfigTilt) {
|
|
846
|
+
windowCoveringFeatures.push('PositionAwareTilt');
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
if (windowCoveringFeatures.length > 0) {
|
|
850
|
+
log.info(`Auto-detected WindowCovering features for ${accessory.displayName}: ${windowCoveringFeatures.join(', ')}`);
|
|
851
|
+
// Apply WindowCovering features to base device type using ONLY base WindowCoveringServer
|
|
852
|
+
// Don't use custom behavior for WindowCovering to avoid conflicts
|
|
853
|
+
deviceType = deviceType.with(WindowCoveringServer.with(...windowCoveringFeatures));
|
|
854
|
+
// Set type attribute ONLY for devices with Tilt features
|
|
855
|
+
// Type 8 (TiltBlindLift) supports lift+tilt
|
|
856
|
+
// Default Rollershade (0) works fine for lift-only devices
|
|
857
|
+
const hasTiltFeatures = windowCoveringFeatures.includes('Tilt');
|
|
858
|
+
if (hasTiltFeatures) {
|
|
859
|
+
const wcCluster = accessory.clusters.windowCovering;
|
|
860
|
+
wcCluster.type = 8; // TiltBlindLift
|
|
861
|
+
log.debug('Set WindowCovering type to 8 (TiltBlindLift) for tilt-capable device');
|
|
862
|
+
}
|
|
863
|
+
// Mark that we should skip custom behavior for windowCovering
|
|
864
|
+
if (!accessory.context) {
|
|
865
|
+
accessory.context = {};
|
|
866
|
+
}
|
|
867
|
+
accessory.context._skipWindowCoveringBehavior = true;
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
log.warn(`⚠️ No WindowCovering features detected for ${accessory.displayName}!`);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
if (accessory.handlers) {
|
|
874
|
+
log.warn(`📝 [${accessory.displayName}] Has handlers: ${Object.keys(accessory.handlers).join(', ')}`);
|
|
875
|
+
// IMPORTANT: Detect ServiceArea features BEFORE modifying device type
|
|
876
|
+
let serviceAreaFeatures = null;
|
|
877
|
+
if (accessory.clusters?.serviceArea) {
|
|
878
|
+
const features = [];
|
|
879
|
+
// Check if Maps feature should be enabled (when supportedMaps is defined)
|
|
880
|
+
if (accessory.clusters.serviceArea.supportedMaps) {
|
|
881
|
+
features.push('Maps');
|
|
882
|
+
}
|
|
883
|
+
// Check if ProgressReporting feature should be enabled (when progress is defined)
|
|
884
|
+
if (accessory.clusters.serviceArea.progress !== undefined) {
|
|
885
|
+
features.push('ProgressReporting');
|
|
886
|
+
}
|
|
887
|
+
if (features.length > 0) {
|
|
888
|
+
serviceAreaFeatures = features;
|
|
889
|
+
log.info(`ServiceArea features will be enabled for ${accessory.displayName}: ${features.join(', ')}`);
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
// IMPORTANT: Detect ColorControl features BEFORE modifying device type
|
|
893
|
+
// Once we start applying custom behaviors, the original structure is lost
|
|
894
|
+
let colorControlFeatures = null;
|
|
895
|
+
if (accessory.handlers.colorControl) {
|
|
896
|
+
const deviceTypeDef = deviceType;
|
|
897
|
+
const existingBehaviors = deviceTypeDef.behaviors;
|
|
898
|
+
if (existingBehaviors) {
|
|
899
|
+
// Behaviors can be an array, Set, or object - handle all cases
|
|
900
|
+
let behaviorsArray;
|
|
901
|
+
if (Array.isArray(existingBehaviors)) {
|
|
902
|
+
behaviorsArray = existingBehaviors;
|
|
903
|
+
}
|
|
904
|
+
else if (typeof existingBehaviors === 'object') {
|
|
905
|
+
// It's an object - get the values
|
|
906
|
+
behaviorsArray = Object.values(existingBehaviors);
|
|
907
|
+
}
|
|
908
|
+
else {
|
|
909
|
+
// Try Array.from as fallback for Sets, Maps, etc.
|
|
910
|
+
behaviorsArray = Array.from(existingBehaviors);
|
|
911
|
+
}
|
|
912
|
+
for (const behavior of behaviorsArray) {
|
|
913
|
+
if (behavior.id === 'colorControl' || behavior.cluster?.id === 0x0300) {
|
|
914
|
+
if (behavior.cluster?.supportedFeatures) {
|
|
915
|
+
const features = behavior.cluster.supportedFeatures;
|
|
916
|
+
colorControlFeatures = [];
|
|
917
|
+
// supportedFeatures is an object with boolean properties, not a bitmap
|
|
918
|
+
if (features.hueSaturation) {
|
|
919
|
+
colorControlFeatures.push('HueSaturation');
|
|
920
|
+
}
|
|
921
|
+
if (features.xy) {
|
|
922
|
+
colorControlFeatures.push('Xy');
|
|
923
|
+
}
|
|
924
|
+
if (features.colorTemperature) {
|
|
925
|
+
colorControlFeatures.push('ColorTemperature');
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
// IMPORTANT: Adjust features based on provided handlers
|
|
929
|
+
// Add missing features and remove features without handlers
|
|
930
|
+
if (accessory.handlers.colorControl) {
|
|
931
|
+
if (!colorControlFeatures) {
|
|
932
|
+
colorControlFeatures = [];
|
|
933
|
+
}
|
|
934
|
+
const handlers = accessory.handlers.colorControl;
|
|
935
|
+
const finalFeatures = [];
|
|
936
|
+
// Check each possible feature and only include it if the handler is provided
|
|
937
|
+
// HueSaturation feature
|
|
938
|
+
if ('moveToHueAndSaturationLogic' in handlers) {
|
|
939
|
+
finalFeatures.push('HueSaturation');
|
|
940
|
+
}
|
|
941
|
+
// Xy feature
|
|
942
|
+
if ('moveToColorLogic' in handlers) {
|
|
943
|
+
finalFeatures.push('Xy');
|
|
944
|
+
}
|
|
945
|
+
// ColorTemperature feature
|
|
946
|
+
if ('moveToColorTemperatureLogic' in handlers) {
|
|
947
|
+
finalFeatures.push('ColorTemperature');
|
|
948
|
+
}
|
|
949
|
+
colorControlFeatures = finalFeatures;
|
|
950
|
+
}
|
|
951
|
+
break;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
else {
|
|
956
|
+
log.warn(`No behaviors found on device type for ${accessory.displayName}`);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
// IMPORTANT: Detect Thermostat features BEFORE modifying device type
|
|
960
|
+
let thermostatFeatures = null;
|
|
961
|
+
if (accessory.handlers.thermostat) {
|
|
962
|
+
const deviceTypeDef = deviceType;
|
|
963
|
+
const existingBehaviors = deviceTypeDef.behaviors;
|
|
964
|
+
if (existingBehaviors) {
|
|
965
|
+
// Behaviors can be an array, Set, or object - handle all cases
|
|
966
|
+
let behaviorsArray;
|
|
967
|
+
if (Array.isArray(existingBehaviors)) {
|
|
968
|
+
behaviorsArray = existingBehaviors;
|
|
969
|
+
}
|
|
970
|
+
else if (typeof existingBehaviors === 'object') {
|
|
971
|
+
// It's an object - get the values
|
|
972
|
+
behaviorsArray = Object.values(existingBehaviors);
|
|
973
|
+
}
|
|
974
|
+
else {
|
|
975
|
+
// Try Array.from as fallback for Sets, Maps, etc.
|
|
976
|
+
behaviorsArray = Array.from(existingBehaviors);
|
|
977
|
+
}
|
|
978
|
+
for (const behavior of behaviorsArray) {
|
|
979
|
+
if (behavior.id === 'thermostat' || behavior.cluster?.id === 0x0201) {
|
|
980
|
+
if (behavior.cluster?.supportedFeatures) {
|
|
981
|
+
const features = behavior.cluster.supportedFeatures;
|
|
982
|
+
thermostatFeatures = [];
|
|
983
|
+
// supportedFeatures is an object with boolean properties
|
|
984
|
+
if (features.heating) {
|
|
985
|
+
thermostatFeatures.push('Heating');
|
|
986
|
+
}
|
|
987
|
+
if (features.cooling) {
|
|
988
|
+
thermostatFeatures.push('Cooling');
|
|
989
|
+
}
|
|
990
|
+
if (features.occupancy) {
|
|
991
|
+
thermostatFeatures.push('Occupancy');
|
|
992
|
+
}
|
|
993
|
+
if (features.autoMode) {
|
|
994
|
+
thermostatFeatures.push('AutoMode');
|
|
995
|
+
}
|
|
996
|
+
log.info(`Detected Thermostat features: ${thermostatFeatures.join(', ')}`);
|
|
997
|
+
}
|
|
998
|
+
break;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
// Map cluster names to custom behavior classes
|
|
1004
|
+
// Only clusters with user-triggered commands need custom behaviors
|
|
1005
|
+
const behaviorMap = {
|
|
1006
|
+
// Core controls
|
|
1007
|
+
onOff: HomebridgeOnOffServer,
|
|
1008
|
+
levelControl: HomebridgeLevelControlServer,
|
|
1009
|
+
colorControl: HomebridgeColorControlServer,
|
|
1010
|
+
// Coverings & locks
|
|
1011
|
+
windowCovering: HomebridgeWindowCoveringServer,
|
|
1012
|
+
doorLock: HomebridgeDoorLockServer,
|
|
1013
|
+
// Climate control
|
|
1014
|
+
thermostat: HomebridgeThermostatServer,
|
|
1015
|
+
// Robotic vacuum cleaners
|
|
1016
|
+
rvcOperationalState: HomebridgeRvcOperationalStateServer,
|
|
1017
|
+
rvcRunMode: HomebridgeRvcRunModeServer,
|
|
1018
|
+
rvcCleanMode: HomebridgeRvcCleanModeServer,
|
|
1019
|
+
serviceArea: HomebridgeServiceAreaServer,
|
|
1020
|
+
// Identification
|
|
1021
|
+
identify: HomebridgeIdentifyServer,
|
|
1022
|
+
};
|
|
1023
|
+
// Build array of custom behaviors to apply based on what handlers are defined
|
|
1024
|
+
const customBehaviors = [];
|
|
1025
|
+
// For RoboticVacuumCleaner, add optional clusters if they're defined in accessory.clusters
|
|
1026
|
+
// These clusters need to be added to the device type even if there are no handlers
|
|
1027
|
+
if (deviceType === devices.RoboticVacuumCleanerDevice || deviceType.name === 'RoboticVacuumCleaner') {
|
|
1028
|
+
// Import RVC requirements
|
|
1029
|
+
const { RvcCleanModeServer, ServiceAreaServer } = devices.RoboticVacuumCleanerRequirements;
|
|
1030
|
+
// Add RvcCleanMode if defined in clusters
|
|
1031
|
+
if (accessory.clusters?.rvcCleanMode) {
|
|
1032
|
+
// Check if there's a custom behavior with handlers
|
|
1033
|
+
if (accessory.handlers?.rvcCleanMode) {
|
|
1034
|
+
const behaviorClass = HomebridgeRvcCleanModeServer;
|
|
1035
|
+
customBehaviors.push(behaviorClass);
|
|
1036
|
+
log.info('Adding custom RvcCleanMode behavior with handlers');
|
|
1037
|
+
}
|
|
1038
|
+
else {
|
|
1039
|
+
// No handlers, use base server
|
|
1040
|
+
customBehaviors.push(RvcCleanModeServer);
|
|
1041
|
+
log.info('Adding base RvcCleanMode server');
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
// Add ServiceArea if defined in clusters
|
|
1045
|
+
if (accessory.clusters?.serviceArea) {
|
|
1046
|
+
// Check if there's a custom behavior with handlers
|
|
1047
|
+
if (accessory.handlers?.serviceArea) {
|
|
1048
|
+
let behaviorClass = HomebridgeServiceAreaServer;
|
|
1049
|
+
// Apply features if detected
|
|
1050
|
+
if (serviceAreaFeatures && serviceAreaFeatures.length > 0) {
|
|
1051
|
+
behaviorClass = behaviorClass.with(...serviceAreaFeatures);
|
|
1052
|
+
log.info(`ServiceArea custom behavior will have features: ${serviceAreaFeatures.join(', ')}`);
|
|
1053
|
+
}
|
|
1054
|
+
customBehaviors.push(behaviorClass);
|
|
1055
|
+
log.info('Adding custom ServiceArea behavior with handlers');
|
|
1056
|
+
}
|
|
1057
|
+
else {
|
|
1058
|
+
// No handlers, use base server with features
|
|
1059
|
+
let behaviorClass = ServiceAreaServer;
|
|
1060
|
+
if (serviceAreaFeatures && serviceAreaFeatures.length > 0) {
|
|
1061
|
+
behaviorClass = behaviorClass.with(...serviceAreaFeatures);
|
|
1062
|
+
log.info(`ServiceArea base server will have features: ${serviceAreaFeatures.join(', ')}`);
|
|
1063
|
+
}
|
|
1064
|
+
customBehaviors.push(behaviorClass);
|
|
1065
|
+
log.info('Adding base ServiceArea server');
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
for (const clusterName of Object.keys(accessory.handlers || {})) {
|
|
1070
|
+
// Skip windowCovering if we already applied features via base WindowCoveringServer
|
|
1071
|
+
if (clusterName === 'windowCovering' && accessory.context?._skipWindowCoveringBehavior) {
|
|
1072
|
+
log.debug('Skipping custom WindowCovering behavior (using base server with features instead)');
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
// Skip RVC clusters - they're handled specially above for RoboticVacuumCleaner
|
|
1076
|
+
if (clusterName === 'rvcCleanMode' || clusterName === 'serviceArea') {
|
|
1077
|
+
continue;
|
|
1078
|
+
}
|
|
1079
|
+
let behaviorClass = behaviorMap[clusterName];
|
|
1080
|
+
// Apply ColorControl features if we detected them earlier
|
|
1081
|
+
if (clusterName === 'colorControl' && behaviorClass && colorControlFeatures && colorControlFeatures.length > 0) {
|
|
1082
|
+
behaviorClass = behaviorClass.with(...colorControlFeatures);
|
|
1083
|
+
log.info(`ColorControl custom behavior will preserve features: ${colorControlFeatures.join(', ')}`);
|
|
1084
|
+
}
|
|
1085
|
+
// Apply Thermostat features if we detected them earlier
|
|
1086
|
+
if (clusterName === 'thermostat' && behaviorClass && thermostatFeatures && thermostatFeatures.length > 0) {
|
|
1087
|
+
behaviorClass = behaviorClass.with(...thermostatFeatures);
|
|
1088
|
+
log.info(`Thermostat custom behavior will preserve features: ${thermostatFeatures.join(', ')}`);
|
|
1089
|
+
}
|
|
1090
|
+
// Apply ServiceArea features if we detected them earlier
|
|
1091
|
+
if (clusterName === 'serviceArea' && behaviorClass && serviceAreaFeatures && serviceAreaFeatures.length > 0) {
|
|
1092
|
+
behaviorClass = behaviorClass.with(...serviceAreaFeatures);
|
|
1093
|
+
log.info(`ServiceArea custom behavior will preserve features: ${serviceAreaFeatures.join(', ')}`);
|
|
1094
|
+
}
|
|
1095
|
+
// Apply WindowCovering features to custom behavior as well
|
|
1096
|
+
// (features were already applied to base device type, but custom behavior needs them too)
|
|
1097
|
+
if (clusterName === 'windowCovering') {
|
|
1098
|
+
log.warn(`🔍 WindowCovering handler found: behaviorClass=${!!behaviorClass}, windowCoveringFeatures=${windowCoveringFeatures}, length=${windowCoveringFeatures?.length}`);
|
|
1099
|
+
if (behaviorClass && windowCoveringFeatures && windowCoveringFeatures.length > 0) {
|
|
1100
|
+
behaviorClass = behaviorClass.with(...windowCoveringFeatures);
|
|
1101
|
+
log.warn(`🔧 WindowCovering custom behavior will have features: ${windowCoveringFeatures.join(', ')}`);
|
|
1102
|
+
}
|
|
1103
|
+
else {
|
|
1104
|
+
log.warn(`⚠️ Skipping WindowCovering feature application: behaviorClass=${!!behaviorClass}, features=${windowCoveringFeatures}`);
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (behaviorClass) {
|
|
1108
|
+
customBehaviors.push(behaviorClass);
|
|
1109
|
+
log.info(`Will use ${behaviorClass.name} for ${accessory.displayName}`);
|
|
1110
|
+
}
|
|
1111
|
+
else {
|
|
1112
|
+
log.warn(`No custom behavior class available for cluster '${clusterName}' - handlers will be registered but may not be called`);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
if (customBehaviors.length > 0) {
|
|
1116
|
+
// Cast to any to bypass TypeScript limitations
|
|
1117
|
+
deviceType = deviceType.with(...customBehaviors);
|
|
1118
|
+
log.info(`Applied ${customBehaviors.length} custom behavior(s) to device type`);
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
// Create endpoint with the modified device type AND initial cluster states
|
|
1122
|
+
// IMPORTANT: Cluster states must be provided at creation time, before adding to aggregator
|
|
1123
|
+
// This ensures mandatory attributes are set before Matter.js validates the endpoint
|
|
1124
|
+
const endpointOptions = {
|
|
1125
|
+
id: accessory.uuid,
|
|
1126
|
+
...accessory.clusters, // Spread cluster states as initial values
|
|
1127
|
+
};
|
|
1128
|
+
const endpoint = new Endpoint(deviceType, endpointOptions);
|
|
1129
|
+
if (this.config.debugModeEnabled) {
|
|
1130
|
+
log.debug(`Created endpoint for ${accessory.displayName} with initial cluster states`);
|
|
1131
|
+
}
|
|
1132
|
+
// Add to aggregator (validation happens here - cluster states must already be set)
|
|
1133
|
+
await this.aggregator.add(endpoint);
|
|
1134
|
+
if (this.config.debugModeEnabled) {
|
|
1135
|
+
log.debug(`Added endpoint for ${accessory.displayName} to aggregator`);
|
|
1136
|
+
}
|
|
1137
|
+
// Set up command handlers if provided
|
|
1138
|
+
if (accessory.handlers) {
|
|
1139
|
+
log.info(`Setting up handlers for accessory ${accessory.uuid}`);
|
|
1140
|
+
// Register handlers with the custom behavior classes
|
|
1141
|
+
for (const [clusterName, handlers] of Object.entries(accessory.handlers)) {
|
|
1142
|
+
log.info(` Processing cluster: ${clusterName}`);
|
|
1143
|
+
for (const [commandName, handler] of Object.entries(handlers)) {
|
|
1144
|
+
registerHandler(accessory.uuid, clusterName, commandName, handler);
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
// Store accessory
|
|
1149
|
+
const internalAccessory = {
|
|
1150
|
+
...accessory,
|
|
1151
|
+
_associatedPlugin: pluginIdentifier,
|
|
1152
|
+
_associatedPlatform: platformName,
|
|
1153
|
+
endpoint,
|
|
1154
|
+
registered: true,
|
|
1155
|
+
};
|
|
1156
|
+
this.accessories.set(accessory.uuid, internalAccessory);
|
|
1157
|
+
log.info(`Registered Matter accessory: ${accessory.displayName} (${accessory.uuid})`);
|
|
1158
|
+
if (this.config.debugModeEnabled) {
|
|
1159
|
+
log.debug(`Total registered accessories: ${this.accessories.size}/${this.MAX_DEVICES}`);
|
|
1160
|
+
}
|
|
1161
|
+
// Emit accessory-registered event
|
|
1162
|
+
this.emit('accessory-registered', accessory);
|
|
1163
|
+
// Notify controllers about the new device (parts list changed)
|
|
1164
|
+
// This allows the Home app to discover new devices without re-pairing
|
|
1165
|
+
await this.notifyPartsListChanged();
|
|
1166
|
+
// Save to cache asynchronously (don't block registration)
|
|
1167
|
+
if (this.accessoryCache) {
|
|
1168
|
+
this.accessoryCache.save(this.accessories).catch((error) => {
|
|
1169
|
+
log.warn('Failed to save accessory cache:', error);
|
|
1170
|
+
});
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
catch (error) {
|
|
1174
|
+
log.error(`Failed to register Matter accessory ${accessory.displayName}:`, error);
|
|
1175
|
+
throw new MatterDeviceError(`Failed to register accessory: ${error}`);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
/**
|
|
1179
|
+
* Unregister a Matter accessory (Plugin API)
|
|
1180
|
+
*/
|
|
1181
|
+
async unregisterAccessory(uuid) {
|
|
1182
|
+
const accessory = this.accessories.get(uuid);
|
|
1183
|
+
if (!accessory) {
|
|
1184
|
+
// Accessory not in memory, but might be in cache - still remove from cache
|
|
1185
|
+
log.debug(`Accessory ${uuid} not found or not registered`);
|
|
1186
|
+
// Check if it exists in cache and remove it
|
|
1187
|
+
if (this.accessoryCache && this.accessoryCache.getCached(uuid)) {
|
|
1188
|
+
log.debug(`Removing ${uuid} from cache`);
|
|
1189
|
+
this.accessoryCache.removeCached(uuid);
|
|
1190
|
+
this.accessoryCache.save(this.accessories).catch((error) => {
|
|
1191
|
+
log.warn('Failed to save accessory cache:', error);
|
|
1192
|
+
});
|
|
1193
|
+
}
|
|
1194
|
+
return;
|
|
1195
|
+
}
|
|
1196
|
+
try {
|
|
1197
|
+
if (accessory.endpoint && this.aggregator) {
|
|
1198
|
+
await accessory.endpoint.close();
|
|
1199
|
+
log.debug(`Removed endpoint for ${accessory.displayName}`);
|
|
1200
|
+
}
|
|
1201
|
+
this.accessories.delete(uuid);
|
|
1202
|
+
log.info(`Unregistered Matter accessory: ${accessory.displayName} (${uuid})`);
|
|
1203
|
+
// Emit accessory-unregistered event
|
|
1204
|
+
this.emit('accessory-unregistered', uuid);
|
|
1205
|
+
// Notify controllers about the removed device (parts list changed)
|
|
1206
|
+
await this.notifyPartsListChanged();
|
|
1207
|
+
// Update cache (remove the accessory)
|
|
1208
|
+
if (this.accessoryCache) {
|
|
1209
|
+
this.accessoryCache.removeCached(uuid);
|
|
1210
|
+
this.accessoryCache.save(this.accessories).catch((error) => {
|
|
1211
|
+
log.warn('Failed to save accessory cache:', error);
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
catch (error) {
|
|
1216
|
+
log.error(`Failed to unregister Matter accessory ${uuid}:`, error);
|
|
1217
|
+
throw new MatterDeviceError(`Failed to unregister accessory: ${error}`);
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Update a Matter accessory's state (Plugin API)
|
|
1222
|
+
*
|
|
1223
|
+
* This method can be called from anywhere, including from within handlers.
|
|
1224
|
+
* State updates are automatically deferred to avoid transaction conflicts.
|
|
1225
|
+
*/
|
|
1226
|
+
async updateAccessoryState(uuid, cluster, attributes) {
|
|
1227
|
+
const accessory = this.accessories.get(uuid);
|
|
1228
|
+
if (!accessory || !accessory.endpoint) {
|
|
1229
|
+
throw new MatterDeviceError(`Accessory ${uuid} not found or not registered`);
|
|
1230
|
+
}
|
|
1231
|
+
// Defer the update to avoid "read-only transaction" errors when called from handlers
|
|
1232
|
+
// Matter.js uses transactions, and we need to wait until the transaction fully completes
|
|
1233
|
+
// Use setTimeout with a delay to ensure we're completely outside the transaction
|
|
1234
|
+
return new Promise((resolve, reject) => {
|
|
1235
|
+
setTimeout(async () => {
|
|
1236
|
+
try {
|
|
1237
|
+
// Use endpoint.set() method which is the proper way to update state
|
|
1238
|
+
// This handles transactions correctly
|
|
1239
|
+
const endpoint = accessory.endpoint;
|
|
1240
|
+
// Construct the update object
|
|
1241
|
+
const updateObject = { [cluster]: attributes };
|
|
1242
|
+
// Use endpoint.set() which properly handles state updates
|
|
1243
|
+
await endpoint.set(updateObject);
|
|
1244
|
+
// CRITICAL: Also update the cached clusters object so state persists across restarts
|
|
1245
|
+
// Merge the new attributes into the existing cluster state
|
|
1246
|
+
if (!accessory.clusters[cluster]) {
|
|
1247
|
+
accessory.clusters[cluster] = {};
|
|
1248
|
+
}
|
|
1249
|
+
accessory.clusters[cluster] = {
|
|
1250
|
+
...accessory.clusters[cluster],
|
|
1251
|
+
...attributes,
|
|
1252
|
+
};
|
|
1253
|
+
log.debug(`Updated ${cluster} state for ${accessory.displayName}:`, attributes);
|
|
1254
|
+
resolve();
|
|
1255
|
+
}
|
|
1256
|
+
catch (error) {
|
|
1257
|
+
log.error(`Failed to update state for accessory ${uuid}:`, error);
|
|
1258
|
+
reject(new MatterDeviceError(`Failed to update accessory state: ${error}`));
|
|
1259
|
+
}
|
|
1260
|
+
}, 50); // 50ms delay to ensure we're completely outside the transaction
|
|
1261
|
+
});
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Get a Matter accessory's current state (Plugin API)
|
|
1265
|
+
*
|
|
1266
|
+
* Returns the current cluster attribute values that are exposed to Matter controllers.
|
|
1267
|
+
* This is useful for:
|
|
1268
|
+
* - Reading state after plugin restart (when local variables are lost)
|
|
1269
|
+
* - Verifying current state before making changes
|
|
1270
|
+
* - Multiple parts of code that need to read state
|
|
1271
|
+
* - Debugging and logging
|
|
1272
|
+
*
|
|
1273
|
+
* @param uuid - The UUID of the accessory
|
|
1274
|
+
* @param cluster - The cluster name (e.g., 'onOff', 'levelControl')
|
|
1275
|
+
* @returns Current cluster attribute values, or undefined if cluster not found
|
|
1276
|
+
*/
|
|
1277
|
+
getAccessoryState(uuid, cluster) {
|
|
1278
|
+
const accessory = this.accessories.get(uuid);
|
|
1279
|
+
if (!accessory || !accessory.endpoint) {
|
|
1280
|
+
log.debug(`Accessory ${uuid} not found or not registered`);
|
|
1281
|
+
return undefined;
|
|
1282
|
+
}
|
|
1283
|
+
try {
|
|
1284
|
+
const endpoint = accessory.endpoint;
|
|
1285
|
+
if (!endpoint.state) {
|
|
1286
|
+
log.debug(`endpoint.state is undefined for ${accessory.displayName}`);
|
|
1287
|
+
return undefined;
|
|
1288
|
+
}
|
|
1289
|
+
if (!endpoint.state[cluster]) {
|
|
1290
|
+
const availableClusters = Object.keys(endpoint.state || {});
|
|
1291
|
+
log.debug(`Cluster '${cluster}' not found on ${accessory.displayName}. Available: ${availableClusters.join(', ')}`);
|
|
1292
|
+
return undefined;
|
|
1293
|
+
}
|
|
1294
|
+
const clusterState = endpoint.state[cluster];
|
|
1295
|
+
// Build result object by reading each property directly
|
|
1296
|
+
const result = {};
|
|
1297
|
+
// Get list of properties to read - use both approaches for maximum compatibility
|
|
1298
|
+
const allKeys = new Set([
|
|
1299
|
+
...Object.keys(clusterState),
|
|
1300
|
+
...Object.getOwnPropertyNames(clusterState),
|
|
1301
|
+
]);
|
|
1302
|
+
for (const key of allKeys) {
|
|
1303
|
+
try {
|
|
1304
|
+
// Skip internal properties, methods, and symbols
|
|
1305
|
+
if (key.startsWith('_') || key.startsWith('$')) {
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
// Try to read the value directly
|
|
1309
|
+
const value = clusterState[key];
|
|
1310
|
+
// Skip functions and undefined values
|
|
1311
|
+
if (typeof value === 'function' || value === undefined) {
|
|
1312
|
+
continue;
|
|
1313
|
+
}
|
|
1314
|
+
result[key] = value;
|
|
1315
|
+
}
|
|
1316
|
+
catch (propError) {
|
|
1317
|
+
log.debug(`Could not read property ${key} from ${cluster}:`, propError);
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
if (Object.keys(result).length === 0) {
|
|
1321
|
+
log.debug(`Cluster ${cluster} found but no readable properties on accessory ${accessory.displayName}`);
|
|
1322
|
+
return undefined;
|
|
1323
|
+
}
|
|
1324
|
+
return result;
|
|
1325
|
+
}
|
|
1326
|
+
catch (error) {
|
|
1327
|
+
log.error(`Failed to get state for accessory ${uuid}:`, error);
|
|
1328
|
+
return undefined;
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1331
|
+
/**
|
|
1332
|
+
* Get all cached accessories (Internal - for restore process)
|
|
1333
|
+
* @internal
|
|
1334
|
+
*/
|
|
1335
|
+
getAllCachedAccessories() {
|
|
1336
|
+
if (!this.accessoryCache) {
|
|
1337
|
+
log.debug('getAllCachedAccessories: No cache available');
|
|
1338
|
+
return [];
|
|
1339
|
+
}
|
|
1340
|
+
const cached = Array.from(this.accessoryCache.getAllCached().values());
|
|
1341
|
+
log.debug(`getAllCachedAccessories: Returning ${cached.length} accessories`);
|
|
1342
|
+
return cached;
|
|
1343
|
+
}
|
|
1344
|
+
/**
|
|
1345
|
+
* Get all registered accessories (Plugin API)
|
|
1346
|
+
*/
|
|
1347
|
+
getAccessories() {
|
|
1348
|
+
return Array.from(this.accessories.values()).map((acc) => {
|
|
1349
|
+
// Return copy without internal fields
|
|
1350
|
+
// eslint-disable-next-line unused-imports/no-unused-vars
|
|
1351
|
+
const { endpoint, registered, ...publicAccessory } = acc;
|
|
1352
|
+
return publicAccessory;
|
|
1353
|
+
});
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* Get a specific accessory by UUID (Plugin API)
|
|
1357
|
+
*/
|
|
1358
|
+
getAccessory(uuid) {
|
|
1359
|
+
const accessory = this.accessories.get(uuid);
|
|
1360
|
+
if (!accessory) {
|
|
1361
|
+
return undefined;
|
|
1362
|
+
}
|
|
1363
|
+
// Return copy without internal fields
|
|
1364
|
+
// eslint-disable-next-line unused-imports/no-unused-vars
|
|
1365
|
+
const { endpoint, registered, ...publicAccessory } = accessory;
|
|
1366
|
+
return publicAccessory;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Stop the Matter server
|
|
1370
|
+
*/
|
|
1371
|
+
async stop() {
|
|
1372
|
+
if (!this.isRunning) {
|
|
1373
|
+
log.debug('Matter server is not running');
|
|
1374
|
+
return;
|
|
1375
|
+
}
|
|
1376
|
+
this.isRunning = false;
|
|
1377
|
+
// Stop monitoring
|
|
1378
|
+
this.stopFabricMonitoring();
|
|
1379
|
+
networkMonitor.stopMonitoring();
|
|
1380
|
+
try {
|
|
1381
|
+
// Save accessory cache before shutting down (BEFORE clearing accessories!)
|
|
1382
|
+
if (this.accessoryCache && this.accessories.size > 0) {
|
|
1383
|
+
await this.accessoryCache.save(this.accessories);
|
|
1384
|
+
log.debug('Saved accessory cache before shutdown');
|
|
1385
|
+
}
|
|
1386
|
+
// Clean up all accessories
|
|
1387
|
+
for (const accessory of this.accessories.values()) {
|
|
1388
|
+
try {
|
|
1389
|
+
if (accessory.endpoint) {
|
|
1390
|
+
await accessory.endpoint.close();
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
catch (error) {
|
|
1394
|
+
log.error('Failed to clean up accessory:', error);
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
this.accessories.clear();
|
|
1398
|
+
// Stop server
|
|
1399
|
+
if (this.serverNode) {
|
|
1400
|
+
await this.serverNode.close();
|
|
1401
|
+
}
|
|
1402
|
+
await this.cleanup();
|
|
1403
|
+
log.info('Matter server stopped');
|
|
1404
|
+
}
|
|
1405
|
+
catch (error) {
|
|
1406
|
+
log.error('Error stopping Matter server:', error);
|
|
1407
|
+
await errorHandler.handleError(error, 'server-stop');
|
|
1408
|
+
throw error;
|
|
1409
|
+
}
|
|
1410
|
+
finally {
|
|
1411
|
+
this.isRunning = false;
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Cleanup resources
|
|
1416
|
+
*/
|
|
1417
|
+
async cleanup() {
|
|
1418
|
+
// Remove signal handlers
|
|
1419
|
+
if (this.shutdownHandler) {
|
|
1420
|
+
process.off('SIGINT', this.shutdownHandler);
|
|
1421
|
+
process.off('SIGTERM', this.shutdownHandler);
|
|
1422
|
+
this.shutdownHandler = null;
|
|
1423
|
+
}
|
|
1424
|
+
// Run all cleanup handlers
|
|
1425
|
+
for (const handler of this.cleanupHandlers) {
|
|
1426
|
+
try {
|
|
1427
|
+
await handler();
|
|
1428
|
+
}
|
|
1429
|
+
catch (error) {
|
|
1430
|
+
log.debug('Error during cleanup handler:', error);
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
this.cleanupHandlers = [];
|
|
1434
|
+
// Clear references
|
|
1435
|
+
this.serverNode = null;
|
|
1436
|
+
this.aggregator = null;
|
|
1437
|
+
this.isRunning = false;
|
|
1438
|
+
this.commissioningInfo = {};
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Get fabric information for commissioned controllers
|
|
1442
|
+
*/
|
|
1443
|
+
getFabricInfo() {
|
|
1444
|
+
try {
|
|
1445
|
+
if (!this.serverNode || !this.storageManager) {
|
|
1446
|
+
return [];
|
|
1447
|
+
}
|
|
1448
|
+
// Fabric data is stored in the main storage file (uniqueId namespace)
|
|
1449
|
+
// with the key "fabrics.fabrics"
|
|
1450
|
+
const storage = this.storageManager.getStorage(this.config.uniqueId);
|
|
1451
|
+
const fabricsData = storage.get(['fabrics'], 'fabrics');
|
|
1452
|
+
if (Array.isArray(fabricsData) && fabricsData.length > 0) {
|
|
1453
|
+
// Map the fabric data to our interface
|
|
1454
|
+
return fabricsData.map(fabric => ({
|
|
1455
|
+
fabricIndex: fabric.fabricIndex || 0,
|
|
1456
|
+
fabricId: fabric.fabricId?.value?.toString() || '',
|
|
1457
|
+
nodeId: fabric.nodeId?.value?.toString() || '',
|
|
1458
|
+
rootVendorId: fabric.rootVendorId || 0,
|
|
1459
|
+
label: fabric.label || '',
|
|
1460
|
+
}));
|
|
1461
|
+
}
|
|
1462
|
+
return [];
|
|
1463
|
+
}
|
|
1464
|
+
catch (error) {
|
|
1465
|
+
log.debug('Failed to get fabric info from storage:', error);
|
|
1466
|
+
return [];
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Check if the server is commissioned
|
|
1471
|
+
*/
|
|
1472
|
+
isCommissioned() {
|
|
1473
|
+
try {
|
|
1474
|
+
if (!this.storageManager) {
|
|
1475
|
+
return false;
|
|
1476
|
+
}
|
|
1477
|
+
// Commissioned status is stored in the main storage file (uniqueId namespace)
|
|
1478
|
+
// at key "root.commissioning.commissioned"
|
|
1479
|
+
const storage = this.storageManager.getStorage(this.config.uniqueId);
|
|
1480
|
+
const commissioned = storage.get(['root', 'commissioning'], 'commissioned');
|
|
1481
|
+
if (commissioned === true) {
|
|
1482
|
+
return true;
|
|
1483
|
+
}
|
|
1484
|
+
// Fallback to checking fabric count if commissioned flag not found
|
|
1485
|
+
const fabrics = this.getFabricInfo();
|
|
1486
|
+
return fabrics.length > 0;
|
|
1487
|
+
}
|
|
1488
|
+
catch (error) {
|
|
1489
|
+
log.debug('Failed to check commissioned status from storage:', error);
|
|
1490
|
+
return false;
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
/**
|
|
1494
|
+
* Get the number of commissioned fabrics
|
|
1495
|
+
*/
|
|
1496
|
+
getCommissionedFabricCount() {
|
|
1497
|
+
return this.getFabricInfo().length;
|
|
1498
|
+
}
|
|
1499
|
+
/**
|
|
1500
|
+
* Get server status information
|
|
1501
|
+
*/
|
|
1502
|
+
getServerInfo() {
|
|
1503
|
+
return {
|
|
1504
|
+
running: this.isRunning,
|
|
1505
|
+
port: this.config.port || 5540,
|
|
1506
|
+
deviceCount: this.accessories.size,
|
|
1507
|
+
commissioned: this.isCommissioned(),
|
|
1508
|
+
fabricCount: this.getCommissionedFabricCount(),
|
|
1509
|
+
serialNumber: this.serialNumber,
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Get commissioning information
|
|
1514
|
+
*/
|
|
1515
|
+
getCommissioningInfo() {
|
|
1516
|
+
return {
|
|
1517
|
+
...this.commissioningInfo,
|
|
1518
|
+
serialNumber: this.serialNumber,
|
|
1519
|
+
passcode: this.passcode,
|
|
1520
|
+
discriminator: this.discriminator,
|
|
1521
|
+
commissioned: this.isCommissioned(),
|
|
1522
|
+
};
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* Get storage statistics
|
|
1526
|
+
*/
|
|
1527
|
+
getStorageStats() {
|
|
1528
|
+
if (!this.storageManager) {
|
|
1529
|
+
return null;
|
|
1530
|
+
}
|
|
1531
|
+
return this.storageManager.getAllStats();
|
|
1532
|
+
}
|
|
1533
|
+
/**
|
|
1534
|
+
* Check if server is running
|
|
1535
|
+
*/
|
|
1536
|
+
isServerRunning() {
|
|
1537
|
+
return this.isRunning;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Get Matter device types available for plugin use
|
|
1541
|
+
*/
|
|
1542
|
+
getDeviceTypes() {
|
|
1543
|
+
return deviceTypes;
|
|
1544
|
+
}
|
|
1545
|
+
/**
|
|
1546
|
+
* Get Matter clusters available for plugin use
|
|
1547
|
+
*/
|
|
1548
|
+
getClusters() {
|
|
1549
|
+
return clusters;
|
|
1550
|
+
}
|
|
1551
|
+
/**
|
|
1552
|
+
* Remove a specific fabric (controller) from the bridge
|
|
1553
|
+
* This decommissions a single controller while leaving others intact
|
|
1554
|
+
*
|
|
1555
|
+
* @param fabricIndex - The fabric index to remove
|
|
1556
|
+
* @returns Promise that resolves when the fabric is removed
|
|
1557
|
+
*/
|
|
1558
|
+
async removeFabric(fabricIndex) {
|
|
1559
|
+
if (!this.serverNode) {
|
|
1560
|
+
throw new MatterDeviceError('Matter server not started');
|
|
1561
|
+
}
|
|
1562
|
+
try {
|
|
1563
|
+
log.info(`Removing fabric ${fabricIndex}...`);
|
|
1564
|
+
const serverState = this.serverNode;
|
|
1565
|
+
const removeFabric = serverState?.state?.commissioning?.removeFabric;
|
|
1566
|
+
if (typeof removeFabric !== 'function') {
|
|
1567
|
+
throw new MatterDeviceError('Fabric removal not supported by Matter.js version');
|
|
1568
|
+
}
|
|
1569
|
+
// Remove the fabric
|
|
1570
|
+
await removeFabric(fabricIndex);
|
|
1571
|
+
log.info(`Fabric ${fabricIndex} removed successfully`);
|
|
1572
|
+
// The fabric monitoring will detect this change and emit the appropriate events
|
|
1573
|
+
}
|
|
1574
|
+
catch (error) {
|
|
1575
|
+
log.error(`Failed to remove fabric ${fabricIndex}:`, error);
|
|
1576
|
+
throw new MatterDeviceError(`Failed to remove fabric: ${error.message}`, error);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Check if a specific fabric exists
|
|
1581
|
+
*/
|
|
1582
|
+
hasFabric(fabricIndex) {
|
|
1583
|
+
const fabrics = this.getFabricInfo();
|
|
1584
|
+
return fabrics.some(f => f.fabricIndex === fabricIndex);
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Notify controllers that the parts list has changed
|
|
1588
|
+
* This triggers controllers (like Home app) to re-read the device list
|
|
1589
|
+
* and discover new or removed accessories without needing to re-pair
|
|
1590
|
+
*/
|
|
1591
|
+
async notifyPartsListChanged() {
|
|
1592
|
+
if (!this.aggregator || !this.isCommissioned()) {
|
|
1593
|
+
// No controllers connected, skip notification
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
try {
|
|
1597
|
+
// Access the aggregator's descriptor cluster state
|
|
1598
|
+
// The partsList is automatically updated by Matter.js when endpoints are added/removed
|
|
1599
|
+
// We just need to ensure controllers are notified of the change
|
|
1600
|
+
const aggregatorState = this.aggregator;
|
|
1601
|
+
if (aggregatorState.state?.descriptor) {
|
|
1602
|
+
// Get current parts list (endpoint numbers of all children)
|
|
1603
|
+
const partsList = aggregatorState.state.descriptor.partsList || [];
|
|
1604
|
+
if (this.config.debugModeEnabled) {
|
|
1605
|
+
log.debug(`Parts list changed: ${partsList.length} devices (endpoints: ${partsList.join(', ')})`);
|
|
1606
|
+
}
|
|
1607
|
+
// Trigger a state update event to notify subscribed controllers
|
|
1608
|
+
// By setting the partsList to itself, we trigger the change notification
|
|
1609
|
+
await this.aggregator.set({
|
|
1610
|
+
descriptor: {
|
|
1611
|
+
partsList,
|
|
1612
|
+
},
|
|
1613
|
+
});
|
|
1614
|
+
log.info(`Notified controllers of parts list change (${this.accessories.size} devices)`);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
catch (error) {
|
|
1618
|
+
// Non-fatal error - log but don't throw
|
|
1619
|
+
log.warn(`Failed to notify controllers of parts list change: ${error.message}`);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
//# sourceMappingURL=matterServer.js.map
|