homebridge 2.0.0-alpha.7 → 2.0.0-alpha.71

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 +1460 -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,1460 @@
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, HomebridgeFanControlServer, 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
+ fanControl: HomebridgeFanControlServer,
839
+ thermostat: HomebridgeThermostatServer,
840
+ // Robotic vacuum cleaners
841
+ rvcOperationalState: HomebridgeRvcOperationalStateServer,
842
+ rvcRunMode: HomebridgeRvcRunModeServer,
843
+ rvcCleanMode: HomebridgeRvcCleanModeServer,
844
+ serviceArea: HomebridgeServiceAreaServer,
845
+ // Identification
846
+ identify: HomebridgeIdentifyServer,
847
+ };
848
+ // Build array of custom behaviors to apply based on what handlers are defined
849
+ const customBehaviors = [];
850
+ // For RoboticVacuumCleaner, add optional clusters if they're defined in accessory.clusters
851
+ // These clusters need to be added to the device type even if there are no handlers
852
+ if (deviceType === devices.RoboticVacuumCleanerDevice || deviceType.name === 'RoboticVacuumCleaner') {
853
+ // Import RVC requirements
854
+ const { RvcCleanModeServer, ServiceAreaServer } = devices.RoboticVacuumCleanerRequirements;
855
+ // Add RvcCleanMode if defined in clusters
856
+ if (accessory.clusters?.rvcCleanMode) {
857
+ // Check if there's a custom behavior with handlers
858
+ if (accessory.handlers?.rvcCleanMode) {
859
+ const behaviorClass = HomebridgeRvcCleanModeServer;
860
+ customBehaviors.push(behaviorClass);
861
+ log.info('Adding custom RvcCleanMode behavior with handlers');
862
+ }
863
+ else {
864
+ // No handlers, use base server
865
+ customBehaviors.push(RvcCleanModeServer);
866
+ log.info('Adding base RvcCleanMode server');
867
+ }
868
+ }
869
+ // Add ServiceArea if defined in clusters
870
+ if (accessory.clusters?.serviceArea) {
871
+ // Check if there's a custom behavior with handlers
872
+ if (accessory.handlers?.serviceArea) {
873
+ let behaviorClass = HomebridgeServiceAreaServer;
874
+ // Apply features if detected
875
+ if (serviceAreaFeatures && serviceAreaFeatures.length > 0) {
876
+ behaviorClass = behaviorClass.with(...serviceAreaFeatures);
877
+ log.info(`ServiceArea custom behavior will have features: ${serviceAreaFeatures.join(', ')}`);
878
+ }
879
+ customBehaviors.push(behaviorClass);
880
+ log.info('Adding custom ServiceArea behavior with handlers');
881
+ }
882
+ else {
883
+ // No handlers, use base server with features
884
+ let behaviorClass = ServiceAreaServer;
885
+ if (serviceAreaFeatures && serviceAreaFeatures.length > 0) {
886
+ behaviorClass = behaviorClass.with(...serviceAreaFeatures);
887
+ log.info(`ServiceArea base server will have features: ${serviceAreaFeatures.join(', ')}`);
888
+ }
889
+ customBehaviors.push(behaviorClass);
890
+ log.info('Adding base ServiceArea server');
891
+ }
892
+ }
893
+ }
894
+ for (const clusterName of Object.keys(accessory.handlers || {})) {
895
+ // Skip windowCovering if we already applied features via base WindowCoveringServer
896
+ if (clusterName === 'windowCovering' && accessory.context?._skipWindowCoveringBehavior) {
897
+ log.debug('Skipping custom WindowCovering behavior (using base server with features instead)');
898
+ continue;
899
+ }
900
+ // Skip RVC clusters - they're handled specially above for RoboticVacuumCleaner
901
+ if (clusterName === 'rvcCleanMode' || clusterName === 'serviceArea') {
902
+ continue;
903
+ }
904
+ let behaviorClass = behaviorMap[clusterName];
905
+ // Apply ColorControl features if we detected them earlier
906
+ if (clusterName === 'colorControl' && behaviorClass && colorControlFeatures && colorControlFeatures.length > 0) {
907
+ behaviorClass = behaviorClass.with(...colorControlFeatures);
908
+ log.info(`ColorControl custom behavior will preserve features: ${colorControlFeatures.join(', ')}`);
909
+ }
910
+ // Apply Thermostat features if we detected them earlier
911
+ if (clusterName === 'thermostat' && behaviorClass && thermostatFeatures && thermostatFeatures.length > 0) {
912
+ behaviorClass = behaviorClass.with(...thermostatFeatures);
913
+ log.info(`Thermostat custom behavior will preserve features: ${thermostatFeatures.join(', ')}`);
914
+ }
915
+ // Apply ServiceArea features if we detected them earlier
916
+ if (clusterName === 'serviceArea' && behaviorClass && serviceAreaFeatures && serviceAreaFeatures.length > 0) {
917
+ behaviorClass = behaviorClass.with(...serviceAreaFeatures);
918
+ log.info(`ServiceArea custom behavior will preserve features: ${serviceAreaFeatures.join(', ')}`);
919
+ }
920
+ // Apply WindowCovering features to custom behavior as well
921
+ // (features were already applied to base device type, but custom behavior needs them too)
922
+ if (clusterName === 'windowCovering') {
923
+ log.warn(`🔍 WindowCovering handler found: behaviorClass=${!!behaviorClass}, windowCoveringFeatures=${windowCoveringFeatures}, length=${windowCoveringFeatures?.length}`);
924
+ if (behaviorClass && windowCoveringFeatures && windowCoveringFeatures.length > 0) {
925
+ behaviorClass = behaviorClass.with(...windowCoveringFeatures);
926
+ log.warn(`🔧 WindowCovering custom behavior will have features: ${windowCoveringFeatures.join(', ')}`);
927
+ }
928
+ else {
929
+ log.warn(`⚠️ Skipping WindowCovering feature application: behaviorClass=${!!behaviorClass}, features=${windowCoveringFeatures}`);
930
+ }
931
+ }
932
+ if (behaviorClass) {
933
+ customBehaviors.push(behaviorClass);
934
+ log.info(`Will use ${behaviorClass.name} for ${accessory.displayName}`);
935
+ }
936
+ else {
937
+ log.warn(`No custom behavior class available for cluster '${clusterName}' - handlers will be registered but may not be called`);
938
+ }
939
+ }
940
+ if (customBehaviors.length > 0) {
941
+ // Cast to any to bypass TypeScript limitations
942
+ deviceType = deviceType.with(...customBehaviors);
943
+ log.info(`Applied ${customBehaviors.length} custom behavior(s) to device type`);
944
+ }
945
+ }
946
+ // Add BridgedDeviceBasicInformationServer for bridged devices
947
+ // This is required by the Matter spec for devices behind an aggregator
948
+ deviceType = deviceType.with(BridgedDeviceBasicInformationServer);
949
+ log.debug(`Added BridgedDeviceBasicInformationServer to ${accessory.displayName}`);
950
+ // Create endpoint with the modified device type AND initial cluster states
951
+ // IMPORTANT: Cluster states must be provided at creation time, before adding to aggregator
952
+ // This ensures mandatory attributes are set before Matter.js validates the endpoint
953
+ const endpointOptions = {
954
+ id: accessory.uuid,
955
+ // Add bridgedDeviceBasicInformation cluster (required for bridged devices)
956
+ bridgedDeviceBasicInformation: {
957
+ nodeLabel: accessory.displayName, // Main end user name for the device
958
+ productName: accessory.model,
959
+ productLabel: accessory.displayName,
960
+ serialNumber: accessory.serialNumber,
961
+ reachable: true,
962
+ },
963
+ ...accessory.clusters, // Spread cluster states as initial values
964
+ };
965
+ const endpoint = new Endpoint(deviceType, endpointOptions);
966
+ if (this.config.debugModeEnabled) {
967
+ log.debug(`Created endpoint for ${accessory.displayName} with initial cluster states`);
968
+ }
969
+ // Add to aggregator (validation happens here - cluster states must already be set)
970
+ await this.aggregator.add(endpoint);
971
+ if (this.config.debugModeEnabled) {
972
+ log.debug(`Added endpoint for ${accessory.displayName} to aggregator`);
973
+ }
974
+ // Set up command handlers if provided
975
+ if (accessory.handlers) {
976
+ log.info(`Setting up handlers for accessory ${accessory.uuid}`);
977
+ // Register handlers with the custom behavior classes
978
+ for (const [clusterName, handlers] of Object.entries(accessory.handlers)) {
979
+ log.info(` Processing cluster: ${clusterName}`);
980
+ for (const [commandName, handler] of Object.entries(handlers)) {
981
+ registerHandler(accessory.uuid, clusterName, commandName, handler);
982
+ }
983
+ }
984
+ }
985
+ // Store accessory
986
+ const internalAccessory = {
987
+ ...accessory,
988
+ _associatedPlugin: pluginIdentifier,
989
+ _associatedPlatform: platformName,
990
+ endpoint,
991
+ registered: true,
992
+ };
993
+ this.accessories.set(accessory.uuid, internalAccessory);
994
+ log.info(`Registered Matter accessory: ${accessory.displayName} (${accessory.uuid})`);
995
+ if (this.config.debugModeEnabled) {
996
+ log.debug(`Total registered accessories: ${this.accessories.size}/${this.MAX_DEVICES}`);
997
+ }
998
+ // Emit accessory-registered event
999
+ this.emit('accessory-registered', accessory);
1000
+ // Notify controllers about the new device (parts list changed)
1001
+ // This allows the Home app to discover new devices without re-pairing
1002
+ await this.notifyPartsListChanged();
1003
+ // Save to cache asynchronously (don't block registration)
1004
+ if (this.accessoryCache) {
1005
+ this.accessoryCache.save(this.accessories).catch((error) => {
1006
+ log.warn('Failed to save accessory cache:', error);
1007
+ });
1008
+ }
1009
+ }
1010
+ catch (error) {
1011
+ log.error(`Failed to register Matter accessory ${accessory.displayName}:`, error);
1012
+ throw new MatterDeviceError(`Failed to register accessory: ${error}`);
1013
+ }
1014
+ }
1015
+ /**
1016
+ * Unregister a Matter accessory (Plugin API)
1017
+ */
1018
+ async unregisterAccessory(uuid) {
1019
+ const accessory = this.accessories.get(uuid);
1020
+ if (!accessory) {
1021
+ // Accessory not in memory, but might be in cache - still remove from cache
1022
+ log.debug(`Accessory ${uuid} not found or not registered`);
1023
+ // Check if it exists in cache and remove it
1024
+ if (this.accessoryCache && this.accessoryCache.getCached(uuid)) {
1025
+ log.debug(`Removing ${uuid} from cache`);
1026
+ this.accessoryCache.removeCached(uuid);
1027
+ this.accessoryCache.save(this.accessories).catch((error) => {
1028
+ log.warn('Failed to save accessory cache:', error);
1029
+ });
1030
+ }
1031
+ return;
1032
+ }
1033
+ try {
1034
+ if (accessory.endpoint && this.aggregator) {
1035
+ await accessory.endpoint.close();
1036
+ log.debug(`Removed endpoint for ${accessory.displayName}`);
1037
+ }
1038
+ this.accessories.delete(uuid);
1039
+ log.info(`Unregistered Matter accessory: ${accessory.displayName} (${uuid})`);
1040
+ // Emit accessory-unregistered event
1041
+ this.emit('accessory-unregistered', uuid);
1042
+ // Notify controllers about the removed device (parts list changed)
1043
+ await this.notifyPartsListChanged();
1044
+ // Update cache (remove the accessory)
1045
+ if (this.accessoryCache) {
1046
+ this.accessoryCache.removeCached(uuid);
1047
+ this.accessoryCache.save(this.accessories).catch((error) => {
1048
+ log.warn('Failed to save accessory cache:', error);
1049
+ });
1050
+ }
1051
+ }
1052
+ catch (error) {
1053
+ log.error(`Failed to unregister Matter accessory ${uuid}:`, error);
1054
+ throw new MatterDeviceError(`Failed to unregister accessory: ${error}`);
1055
+ }
1056
+ }
1057
+ /**
1058
+ * Update a Matter accessory's state (Plugin API)
1059
+ *
1060
+ * This method can be called from anywhere, including from within handlers.
1061
+ * State updates are automatically deferred to avoid transaction conflicts.
1062
+ */
1063
+ async updateAccessoryState(uuid, cluster, attributes) {
1064
+ const accessory = this.accessories.get(uuid);
1065
+ if (!accessory || !accessory.endpoint) {
1066
+ throw new MatterDeviceError(`Accessory ${uuid} not found or not registered`);
1067
+ }
1068
+ // Defer the update to avoid "read-only transaction" errors when called from handlers
1069
+ // Matter.js uses transactions, and we need to wait until the transaction fully completes
1070
+ // Use setTimeout with a delay to ensure we're completely outside the transaction
1071
+ return new Promise((resolve, reject) => {
1072
+ setTimeout(async () => {
1073
+ try {
1074
+ // Use endpoint.set() method which is the proper way to update state
1075
+ // This handles transactions correctly
1076
+ const endpoint = accessory.endpoint;
1077
+ // Construct the update object
1078
+ const updateObject = { [cluster]: attributes };
1079
+ // Use endpoint.set() which properly handles state updates
1080
+ await endpoint.set(updateObject);
1081
+ // CRITICAL: Also update the cached clusters object so state persists across restarts
1082
+ // Merge the new attributes into the existing cluster state
1083
+ if (!accessory.clusters[cluster]) {
1084
+ accessory.clusters[cluster] = {};
1085
+ }
1086
+ accessory.clusters[cluster] = {
1087
+ ...accessory.clusters[cluster],
1088
+ ...attributes,
1089
+ };
1090
+ log.debug(`Updated ${cluster} state for ${accessory.displayName}:`, attributes);
1091
+ resolve();
1092
+ }
1093
+ catch (error) {
1094
+ log.error(`Failed to update state for accessory ${uuid}:`, error);
1095
+ reject(new MatterDeviceError(`Failed to update accessory state: ${error}`));
1096
+ }
1097
+ }, 50); // 50ms delay to ensure we're completely outside the transaction
1098
+ });
1099
+ }
1100
+ /**
1101
+ * Get a Matter accessory's current state (Plugin API)
1102
+ *
1103
+ * Returns the current cluster attribute values that are exposed to Matter controllers.
1104
+ * This is useful for:
1105
+ * - Reading state after plugin restart (when local variables are lost)
1106
+ * - Verifying current state before making changes
1107
+ * - Multiple parts of code that need to read state
1108
+ * - Debugging and logging
1109
+ *
1110
+ * @param uuid - The UUID of the accessory
1111
+ * @param cluster - The cluster name (e.g., 'onOff', 'levelControl')
1112
+ * @returns Current cluster attribute values, or undefined if cluster not found
1113
+ */
1114
+ getAccessoryState(uuid, cluster) {
1115
+ const accessory = this.accessories.get(uuid);
1116
+ if (!accessory || !accessory.endpoint) {
1117
+ log.debug(`Accessory ${uuid} not found or not registered`);
1118
+ return undefined;
1119
+ }
1120
+ try {
1121
+ const endpoint = accessory.endpoint;
1122
+ if (!endpoint.state) {
1123
+ log.debug(`endpoint.state is undefined for ${accessory.displayName}`);
1124
+ return undefined;
1125
+ }
1126
+ if (!endpoint.state[cluster]) {
1127
+ const availableClusters = Object.keys(endpoint.state || {});
1128
+ log.debug(`Cluster '${cluster}' not found on ${accessory.displayName}. Available: ${availableClusters.join(', ')}`);
1129
+ return undefined;
1130
+ }
1131
+ const clusterState = endpoint.state[cluster];
1132
+ // Build result object by reading each property directly
1133
+ const result = {};
1134
+ // Get list of properties to read - use both approaches for maximum compatibility
1135
+ const allKeys = new Set([
1136
+ ...Object.keys(clusterState),
1137
+ ...Object.getOwnPropertyNames(clusterState),
1138
+ ]);
1139
+ for (const key of allKeys) {
1140
+ try {
1141
+ // Skip internal properties, methods, and symbols
1142
+ if (key.startsWith('_') || key.startsWith('$')) {
1143
+ continue;
1144
+ }
1145
+ // Try to read the value directly
1146
+ const value = clusterState[key];
1147
+ // Skip functions and undefined values
1148
+ if (typeof value === 'function' || value === undefined) {
1149
+ continue;
1150
+ }
1151
+ result[key] = value;
1152
+ }
1153
+ catch (propError) {
1154
+ log.debug(`Could not read property ${key} from ${cluster}:`, propError);
1155
+ }
1156
+ }
1157
+ if (Object.keys(result).length === 0) {
1158
+ log.debug(`Cluster ${cluster} found but no readable properties on accessory ${accessory.displayName}`);
1159
+ return undefined;
1160
+ }
1161
+ return result;
1162
+ }
1163
+ catch (error) {
1164
+ log.error(`Failed to get state for accessory ${uuid}:`, error);
1165
+ return undefined;
1166
+ }
1167
+ }
1168
+ /**
1169
+ * Get all cached accessories (Internal - for restore process)
1170
+ * @internal
1171
+ */
1172
+ getAllCachedAccessories() {
1173
+ if (!this.accessoryCache) {
1174
+ log.debug('getAllCachedAccessories: No cache available');
1175
+ return [];
1176
+ }
1177
+ const cached = Array.from(this.accessoryCache.getAllCached().values());
1178
+ log.debug(`getAllCachedAccessories: Returning ${cached.length} accessories`);
1179
+ return cached;
1180
+ }
1181
+ /**
1182
+ * Get all registered accessories (Plugin API)
1183
+ */
1184
+ getAccessories() {
1185
+ return Array.from(this.accessories.values()).map((acc) => {
1186
+ // Return copy without internal fields
1187
+ // eslint-disable-next-line unused-imports/no-unused-vars
1188
+ const { endpoint, registered, ...publicAccessory } = acc;
1189
+ return publicAccessory;
1190
+ });
1191
+ }
1192
+ /**
1193
+ * Get a specific accessory by UUID (Plugin API)
1194
+ */
1195
+ getAccessory(uuid) {
1196
+ const accessory = this.accessories.get(uuid);
1197
+ if (!accessory) {
1198
+ return undefined;
1199
+ }
1200
+ // Return copy without internal fields
1201
+ // eslint-disable-next-line unused-imports/no-unused-vars
1202
+ const { endpoint, registered, ...publicAccessory } = accessory;
1203
+ return publicAccessory;
1204
+ }
1205
+ /**
1206
+ * Stop the Matter server
1207
+ */
1208
+ async stop() {
1209
+ if (!this.isRunning) {
1210
+ log.debug('Matter server is not running');
1211
+ return;
1212
+ }
1213
+ this.isRunning = false;
1214
+ // Stop monitoring
1215
+ this.stopFabricMonitoring();
1216
+ networkMonitor.stopMonitoring();
1217
+ try {
1218
+ // Save accessory cache before shutting down (BEFORE clearing accessories!)
1219
+ if (this.accessoryCache && this.accessories.size > 0) {
1220
+ await this.accessoryCache.save(this.accessories);
1221
+ log.debug('Saved accessory cache before shutdown');
1222
+ }
1223
+ // Clean up all accessories
1224
+ for (const accessory of this.accessories.values()) {
1225
+ try {
1226
+ if (accessory.endpoint) {
1227
+ await accessory.endpoint.close();
1228
+ }
1229
+ }
1230
+ catch (error) {
1231
+ log.error('Failed to clean up accessory:', error);
1232
+ }
1233
+ }
1234
+ this.accessories.clear();
1235
+ // Stop server
1236
+ if (this.serverNode) {
1237
+ await this.serverNode.close();
1238
+ }
1239
+ await this.cleanup();
1240
+ log.info('Matter server stopped');
1241
+ }
1242
+ catch (error) {
1243
+ log.error('Error stopping Matter server:', error);
1244
+ await errorHandler.handleError(error, 'server-stop');
1245
+ throw error;
1246
+ }
1247
+ finally {
1248
+ this.isRunning = false;
1249
+ }
1250
+ }
1251
+ /**
1252
+ * Cleanup resources
1253
+ */
1254
+ async cleanup() {
1255
+ // Remove signal handlers
1256
+ if (this.shutdownHandler) {
1257
+ process.off('SIGINT', this.shutdownHandler);
1258
+ process.off('SIGTERM', this.shutdownHandler);
1259
+ this.shutdownHandler = null;
1260
+ }
1261
+ // Run all cleanup handlers
1262
+ for (const handler of this.cleanupHandlers) {
1263
+ try {
1264
+ await handler();
1265
+ }
1266
+ catch (error) {
1267
+ log.debug('Error during cleanup handler:', error);
1268
+ }
1269
+ }
1270
+ this.cleanupHandlers = [];
1271
+ // Clear references
1272
+ this.serverNode = null;
1273
+ this.aggregator = null;
1274
+ this.isRunning = false;
1275
+ this.commissioningInfo = {};
1276
+ }
1277
+ /**
1278
+ * Get fabric information for commissioned controllers
1279
+ */
1280
+ getFabricInfo() {
1281
+ try {
1282
+ if (!this.serverNode || !this.storageManager) {
1283
+ return [];
1284
+ }
1285
+ // Fabric data is stored in the main storage file (uniqueId namespace)
1286
+ // with the key "fabrics.fabrics"
1287
+ const storage = this.storageManager.getStorage(this.config.uniqueId);
1288
+ const fabricsData = storage.get(['fabrics'], 'fabrics');
1289
+ if (Array.isArray(fabricsData) && fabricsData.length > 0) {
1290
+ // Map the fabric data to our interface
1291
+ return fabricsData.map(fabric => ({
1292
+ fabricIndex: fabric.fabricIndex || 0,
1293
+ fabricId: fabric.fabricId?.value?.toString() || '',
1294
+ nodeId: fabric.nodeId?.value?.toString() || '',
1295
+ rootVendorId: fabric.rootVendorId || 0,
1296
+ label: fabric.label || '',
1297
+ }));
1298
+ }
1299
+ return [];
1300
+ }
1301
+ catch (error) {
1302
+ log.debug('Failed to get fabric info from storage:', error);
1303
+ return [];
1304
+ }
1305
+ }
1306
+ /**
1307
+ * Check if the server is commissioned
1308
+ */
1309
+ isCommissioned() {
1310
+ try {
1311
+ if (!this.storageManager) {
1312
+ return false;
1313
+ }
1314
+ // Commissioned status is stored in the main storage file (uniqueId namespace)
1315
+ // at key "root.commissioning.commissioned"
1316
+ const storage = this.storageManager.getStorage(this.config.uniqueId);
1317
+ const commissioned = storage.get(['root', 'commissioning'], 'commissioned');
1318
+ if (commissioned === true) {
1319
+ return true;
1320
+ }
1321
+ // Fallback to checking fabric count if commissioned flag not found
1322
+ const fabrics = this.getFabricInfo();
1323
+ return fabrics.length > 0;
1324
+ }
1325
+ catch (error) {
1326
+ log.debug('Failed to check commissioned status from storage:', error);
1327
+ return false;
1328
+ }
1329
+ }
1330
+ /**
1331
+ * Get the number of commissioned fabrics
1332
+ */
1333
+ getCommissionedFabricCount() {
1334
+ return this.getFabricInfo().length;
1335
+ }
1336
+ /**
1337
+ * Get server status information
1338
+ */
1339
+ getServerInfo() {
1340
+ return {
1341
+ running: this.isRunning,
1342
+ port: this.config.port || 5540,
1343
+ deviceCount: this.accessories.size,
1344
+ commissioned: this.isCommissioned(),
1345
+ fabricCount: this.getCommissionedFabricCount(),
1346
+ serialNumber: this.serialNumber,
1347
+ };
1348
+ }
1349
+ /**
1350
+ * Get commissioning information
1351
+ */
1352
+ getCommissioningInfo() {
1353
+ return {
1354
+ ...this.commissioningInfo,
1355
+ serialNumber: this.serialNumber,
1356
+ passcode: this.passcode,
1357
+ discriminator: this.discriminator,
1358
+ commissioned: this.isCommissioned(),
1359
+ };
1360
+ }
1361
+ /**
1362
+ * Get storage statistics
1363
+ */
1364
+ getStorageStats() {
1365
+ if (!this.storageManager) {
1366
+ return null;
1367
+ }
1368
+ return this.storageManager.getAllStats();
1369
+ }
1370
+ /**
1371
+ * Check if server is running
1372
+ */
1373
+ isServerRunning() {
1374
+ return this.isRunning;
1375
+ }
1376
+ /**
1377
+ * Get Matter device types available for plugin use
1378
+ */
1379
+ getDeviceTypes() {
1380
+ return deviceTypes;
1381
+ }
1382
+ /**
1383
+ * Get Matter clusters available for plugin use
1384
+ */
1385
+ getClusters() {
1386
+ return clusters;
1387
+ }
1388
+ /**
1389
+ * Remove a specific fabric (controller) from the bridge
1390
+ * This decommissions a single controller while leaving others intact
1391
+ *
1392
+ * @param fabricIndex - The fabric index to remove
1393
+ * @returns Promise that resolves when the fabric is removed
1394
+ */
1395
+ async removeFabric(fabricIndex) {
1396
+ if (!this.serverNode) {
1397
+ throw new MatterDeviceError('Matter server not started');
1398
+ }
1399
+ try {
1400
+ log.info(`Removing fabric ${fabricIndex}...`);
1401
+ const serverState = this.serverNode;
1402
+ const removeFabric = serverState?.state?.commissioning?.removeFabric;
1403
+ if (typeof removeFabric !== 'function') {
1404
+ throw new MatterDeviceError('Fabric removal not supported by Matter.js version');
1405
+ }
1406
+ // Remove the fabric
1407
+ await removeFabric(fabricIndex);
1408
+ log.info(`Fabric ${fabricIndex} removed successfully`);
1409
+ // The fabric monitoring will detect this change and emit the appropriate events
1410
+ }
1411
+ catch (error) {
1412
+ log.error(`Failed to remove fabric ${fabricIndex}:`, error);
1413
+ throw new MatterDeviceError(`Failed to remove fabric: ${error.message}`, error);
1414
+ }
1415
+ }
1416
+ /**
1417
+ * Check if a specific fabric exists
1418
+ */
1419
+ hasFabric(fabricIndex) {
1420
+ const fabrics = this.getFabricInfo();
1421
+ return fabrics.some(f => f.fabricIndex === fabricIndex);
1422
+ }
1423
+ /**
1424
+ * Notify controllers that the parts list has changed
1425
+ * This triggers controllers (like Home app) to re-read the device list
1426
+ * and discover new or removed accessories without needing to re-pair
1427
+ */
1428
+ async notifyPartsListChanged() {
1429
+ if (!this.aggregator || !this.isCommissioned()) {
1430
+ // No controllers connected, skip notification
1431
+ return;
1432
+ }
1433
+ try {
1434
+ // Access the aggregator's descriptor cluster state
1435
+ // The partsList is automatically updated by Matter.js when endpoints are added/removed
1436
+ // We just need to ensure controllers are notified of the change
1437
+ const aggregatorState = this.aggregator;
1438
+ if (aggregatorState.state?.descriptor) {
1439
+ // Get current parts list (endpoint numbers of all children)
1440
+ const partsList = aggregatorState.state.descriptor.partsList || [];
1441
+ if (this.config.debugModeEnabled) {
1442
+ log.debug(`Parts list changed: ${partsList.length} devices (endpoints: ${partsList.join(', ')})`);
1443
+ }
1444
+ // Trigger a state update event to notify subscribed controllers
1445
+ // By setting the partsList to itself, we trigger the change notification
1446
+ await this.aggregator.set({
1447
+ descriptor: {
1448
+ partsList,
1449
+ },
1450
+ });
1451
+ log.info(`Notified controllers of parts list change (${this.accessories.size} devices)`);
1452
+ }
1453
+ }
1454
+ catch (error) {
1455
+ // Non-fatal error - log but don't throw
1456
+ log.warn(`Failed to notify controllers of parts list change: ${error.message}`);
1457
+ }
1458
+ }
1459
+ }
1460
+ //# sourceMappingURL=matterServer.js.map