homebridge 2.0.0-alpha.5 → 2.0.0-alpha.50

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