homebridge 2.0.0-alpha.7 → 2.0.0-alpha.70

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