@matterbridge/core 3.10.10-dev-20260914-784e019 → 3.10.10-dev-20260917-9fdf275

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.
@@ -32,6 +32,15 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
32
32
  });
33
33
  }, DEFERRED_INVOKE_DELAY_MS);
34
34
  }
35
+ async #trickleLocalIceCandidates(requestorEndpoint, webRtcSessionId, webRtcPeer) {
36
+ const iceCandidates = webRtcPeer.localIceCandidates;
37
+ if (iceCandidates.length === 0)
38
+ return;
39
+ await requestorEndpoint.commandsOf(WebRtcTransportRequestorClient).iceCandidates({ webRtcSessionId, iceCandidates });
40
+ this.endpoint
41
+ .stateOf(MatterbridgeServer)
42
+ .log.info(`MatterbridgeWebRtcTransportProviderServer: invoked ICECandidates with ${iceCandidates.length} local candidate(s) for session ${webRtcSessionId} on the peer's WebRtcTransportRequestor`);
43
+ }
35
44
  async #resolvePeerRequestorEndpoint(peerNodeId, fabricIndex, peerEndpointId) {
36
45
  try {
37
46
  const serverNode = Node.forEndpoint(this.endpoint);
@@ -208,6 +217,19 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
208
217
  }
209
218
  return true;
210
219
  }
220
+ #updateStreamReferenceCounts(videoStreams, audioStreams, change) {
221
+ if (!this.endpoint.behaviors.has(MatterbridgeCameraAvStreamManagementServer))
222
+ return;
223
+ const state = this.agent.get(MatterbridgeCameraAvStreamManagementServer).state;
224
+ for (const stream of state.allocatedVideoStreams) {
225
+ if (videoStreams?.includes(stream.videoStreamId))
226
+ stream.referenceCount = Math.max(0, stream.referenceCount + change);
227
+ }
228
+ for (const stream of state.allocatedAudioStreams) {
229
+ if (audioStreams?.includes(stream.audioStreamId))
230
+ stream.referenceCount = Math.max(0, stream.referenceCount + change);
231
+ }
232
+ }
211
233
  async solicitOffer(request) {
212
234
  this.#validateNoConflictingStreamFields(request);
213
235
  let videoStreams;
@@ -252,11 +274,12 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
252
274
  this.endpoint.emitCommand(WebRtcTransportProvider, 'solicitOffer', request, this.context);
253
275
  return { webRtcSessionId, deferredOffer: false, ...this.#echoDeprecatedStreamIds(request, videoStreams, audioStreams) };
254
276
  }
277
+ this.#updateStreamReferenceCounts(videoStreams, audioStreams, 1);
255
278
  const webRtcPeer = new WeriftWebRtcSession(webRtcSessionId, this.state.weriftOfferOptions);
256
279
  this.internal.sessions.set(webRtcSessionId, webRtcPeer);
257
280
  const sdp = await webRtcPeer.createOffer({
258
- video: !!videoStreams?.length,
259
- audio: !!audioStreams?.length,
281
+ offerVideo: !!videoStreams?.length,
282
+ offerAudio: !!audioStreams?.length,
260
283
  videoResolution: this.state.weriftOfferOptions.videoResolution ?? this.#resolveVideoResolution(videoStreams),
261
284
  });
262
285
  if (requestorEndpoint) {
@@ -309,11 +332,11 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
309
332
  fabricIndex,
310
333
  },
311
334
  ];
312
- const requestorEndpointForCapacityCheck = await this.#resolvePeerRequestorEndpoint(peerNodeId, fabricIndex, request.originatingEndpointId ?? EndpointNumber(0));
313
- if (this.#evictIfOverCapacity(webRtcSessionId, requestorEndpointForCapacityCheck)) {
314
- this.endpoint.emitCommand(WebRtcTransportProvider, 'provideOffer', request, this.context);
315
- return { webRtcSessionId, ...this.#echoDeprecatedStreamIds(request, videoStreams, audioStreams) };
335
+ if (this.state.currentSessions.length > MAX_CONCURRENT_SESSIONS) {
336
+ this.state.currentSessions = this.state.currentSessions.filter((session) => session.id !== webRtcSessionId);
337
+ throw new StatusResponseError(`MatterbridgeWebRtcTransportProviderServer.provideOffer: cannot sustain more than MAX_CONCURRENT_SESSIONS (${MAX_CONCURRENT_SESSIONS}) concurrent webRTC sessions (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.ResourceExhausted);
316
338
  }
339
+ this.#updateStreamReferenceCounts(videoStreams, audioStreams, 1);
317
340
  }
318
341
  else if (!this.state.currentSessions.some((session) => session.id === webRtcSessionId)) {
319
342
  throw new StatusResponseError(`MatterbridgeWebRtcTransportProviderServer.provideOffer: webRTC session ${webRtcSessionId} is not present in currentSessions (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.NotFound);
@@ -324,8 +347,8 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
324
347
  const webRtcPeer = this.internal.sessions.get(webRtcSessionId) ?? new WeriftWebRtcSession(webRtcSessionId, this.state.weriftOfferOptions);
325
348
  this.internal.sessions.set(webRtcSessionId, webRtcPeer);
326
349
  const sdp = await webRtcPeer.createAnswer(request.sdp, {
327
- video: !!session.videoStreams?.length,
328
- audio: !!session.audioStreams?.length,
350
+ offerVideo: !!session.videoStreams?.length,
351
+ offerAudio: !!session.audioStreams?.length,
329
352
  videoResolution: this.state.weriftOfferOptions.videoResolution ?? this.#resolveVideoResolution(session.videoStreams),
330
353
  });
331
354
  const requestorEndpoint = await this.#resolvePeerRequestorEndpoint(session.peerNodeId, session.fabricIndex, session.peerEndpointId);
@@ -387,15 +410,27 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
387
410
  `with ${String(error)} (endpoint ${endpointLabel})`);
388
411
  }
389
412
  }));
413
+ const session = this.state.currentSessions.find((candidateSession) => candidateSession.id === request.webRtcSessionId);
414
+ if (session && !this.internal.trickledSessions.has(request.webRtcSessionId)) {
415
+ this.internal.trickledSessions.add(request.webRtcSessionId);
416
+ this.#invokeDeferred(async () => {
417
+ const requestorEndpoint = await this.#resolvePeerRequestorEndpoint(session.peerNodeId, session.fabricIndex, session.peerEndpointId);
418
+ if (requestorEndpoint)
419
+ await this.#trickleLocalIceCandidates(requestorEndpoint, request.webRtcSessionId, webRtcPeer);
420
+ }, `ICECandidates for session ${request.webRtcSessionId}`);
421
+ }
390
422
  }
391
423
  this.endpoint.emitCommand(WebRtcTransportProvider, 'provideIceCandidates', request, this.context);
392
424
  }
393
425
  async endSession(request) {
394
426
  const device = this.endpoint.stateOf(MatterbridgeServer);
395
- if (!this.state.currentSessions.some((session) => session.id === request.webRtcSessionId)) {
427
+ const session = this.state.currentSessions.find((session) => session.id === request.webRtcSessionId);
428
+ if (!session) {
396
429
  throw new StatusResponseError(`MatterbridgeWebRtcTransportProviderServer.endSession: webRTC session ${request.webRtcSessionId} is not present in currentSessions (endpoint ${this.endpoint.maybeId}.${this.endpoint.maybeNumber})`, Status.NotFound);
397
430
  }
431
+ this.#updateStreamReferenceCounts(session.videoStreams, session.audioStreams, -1);
398
432
  this.state.currentSessions = this.state.currentSessions.filter((session) => session.id !== request.webRtcSessionId);
433
+ this.internal.trickledSessions.delete(request.webRtcSessionId);
399
434
  const webRtcPeer = this.internal.sessions.get(request.webRtcSessionId);
400
435
  if (webRtcPeer) {
401
436
  this.internal.sessions.delete(request.webRtcSessionId);
@@ -407,16 +442,17 @@ export class MatterbridgeWebRtcTransportProviderServer extends WebRtcTransportPr
407
442
  }
408
443
  (function (MatterbridgeWebRtcTransportProviderServer) {
409
444
  class State extends WebRtcTransportProviderServer.State {
410
- weriftOfferOptions = { video: true, audio: true, videoSource: 'none', audioSource: 'none' };
445
+ weriftOfferOptions = { offerVideo: true, offerAudio: true, videoSource: 'none', audioSource: 'none' };
411
446
  }
412
447
  MatterbridgeWebRtcTransportProviderServer.State = State;
413
448
  class Internal {
414
449
  nextWebRtcSessionId = 0;
415
450
  sessions = new Map();
451
+ trickledSessions = new Set();
416
452
  }
417
453
  MatterbridgeWebRtcTransportProviderServer.Internal = Internal;
418
454
  })(MatterbridgeWebRtcTransportProviderServer || (MatterbridgeWebRtcTransportProviderServer = {}));
419
- export function createDefaultWebRtcTransportProviderClusterServer(endpoint, weriftOfferOptions = { video: true, audio: true, videoSource: 'none', audioSource: 'none' }) {
455
+ export function createDefaultWebRtcTransportProviderClusterServer(endpoint, weriftOfferOptions = { offerVideo: true, offerAudio: true, videoSource: 'none', audioSource: 'none' }) {
420
456
  endpoint.behaviors.require(MatterbridgeWebRtcTransportProviderServer, { currentSessions: [], weriftOfferOptions });
421
457
  return endpoint;
422
458
  }
@@ -2,8 +2,8 @@ import { RTCPeerConnection } from 'werift';
2
2
  type VideoSource = 'none' | 'test' | 'webcam' | 'rtsp';
3
3
  type AudioSource = 'none' | 'test' | 'microphone' | 'rtsp';
4
4
  export interface WeriftOfferOptions {
5
- video: boolean;
6
- audio: boolean;
5
+ offerVideo: boolean;
6
+ offerAudio: boolean;
7
7
  videoSource: VideoSource;
8
8
  videoSourceDevice?: string;
9
9
  videoResolution?: string;
@@ -29,9 +29,15 @@ export declare class WeriftWebRtcSession {
29
29
  private static readonly DIAGNOSTICS_INTERVAL_MS;
30
30
  private lastDiagnosticsCounters?;
31
31
  private readonly dtlsTransportsWithStateLogging;
32
+ private readonly gatheredIceCandidates;
32
33
  private static parseIcePortRange;
33
34
  private static parseIceAdditionalHostAddresses;
34
35
  constructor(webRtcSessionId: number, options: WeriftOfferOptions);
36
+ get localIceCandidates(): {
37
+ candidate: string;
38
+ sdpMid: string | null;
39
+ sdpmLineIndex: number | null;
40
+ }[];
35
41
  private summarizeSdp;
36
42
  private getFreeUdpPort;
37
43
  private getPreferredInjectableVideoCodec;
@@ -42,10 +48,11 @@ export declare class WeriftWebRtcSession {
42
48
  private getConfiguredVideoResolution;
43
49
  private getConfiguredVideoSource;
44
50
  private buildFfmpegVideoInputArgs;
51
+ private logFfmpegStderr;
45
52
  private generateVideoTrack;
46
53
  private preferVideoCodecOnTransceivers;
47
54
  private preferAudioCodecOnTransceivers;
48
- private static readonly TEST_VOICE_PATH;
55
+ private static readonly TEST_TONE_INPUT;
49
56
  private getConfiguredAudioSource;
50
57
  private buildFfmpegAudioInputArgs;
51
58
  private generateAudioTrack;
@@ -1,5 +1,4 @@
1
1
  import { createSocket } from 'node:dgram';
2
- import { fileURLToPath } from 'node:url';
3
2
  import { fireAndForget, getErrorMessage } from '@matterbridge/utils';
4
3
  import { AnsiLogger, MAGENTA } from 'node-ansi-logger';
5
4
  import { RTCPeerConnection, RTCRtpCodecParameters, useH264, useOPUS, usePCMU, useVP8 } from 'werift';
@@ -22,6 +21,7 @@ export class WeriftWebRtcSession {
22
21
  static DIAGNOSTICS_INTERVAL_MS = 10_000;
23
22
  lastDiagnosticsCounters;
24
23
  dtlsTransportsWithStateLogging = new Set();
24
+ gatheredIceCandidates = [];
25
25
  static parseIcePortRange() {
26
26
  const raw = process.env.MATTERBRIDGE_ICE_PORT_RANGE?.trim();
27
27
  if (!raw)
@@ -56,6 +56,9 @@ export class WeriftWebRtcSession {
56
56
  });
57
57
  this.peerConnection.onIceCandidate.subscribe((candidate) => {
58
58
  this.log.debug(candidate ? `Gathered local ICE candidate: ${candidate.candidate}` : 'ICE candidate gathering completed');
59
+ if (candidate) {
60
+ this.gatheredIceCandidates.push({ candidate: candidate.candidate, sdpMid: candidate.sdpMid ?? null, sdpmLineIndex: candidate.sdpMLineIndex ?? null });
61
+ }
59
62
  });
60
63
  this.peerConnection.iceConnectionStateChange.subscribe((state) => {
61
64
  this.log.info(`ICE connection state: ${state}`);
@@ -90,6 +93,9 @@ export class WeriftWebRtcSession {
90
93
  });
91
94
  }
92
95
  }
96
+ get localIceCandidates() {
97
+ return [...this.gatheredIceCandidates];
98
+ }
93
99
  summarizeSdp(sdp) {
94
100
  const mediaKinds = sdp
95
101
  .split('\n')
@@ -178,19 +184,19 @@ export class WeriftWebRtcSession {
178
184
  }
179
185
  }
180
186
  buildFfmpegVideoInputArgs(videoSource) {
181
- const testPatternInput = {
182
- args: ['-re', '-f', 'lavfi', '-i', 'testsrc=size=640x480:rate=10'],
183
- description: 'synthetic moving test pattern',
184
- bitrateKbps: WeriftWebRtcSession.DEFAULT_BITRATE_KBPS,
185
- };
186
187
  if (videoSource === 'test') {
188
+ const testPatternInput = {
189
+ args: ['-re', '-f', 'lavfi', '-i', 'testsrc=size=640x480:rate=10'],
190
+ description: 'synthetic moving test pattern',
191
+ bitrateKbps: WeriftWebRtcSession.DEFAULT_BITRATE_KBPS,
192
+ };
187
193
  this.log.debug(`Test pattern params: resolution=640x480, description="${testPatternInput.description}", bitrateKbps=${testPatternInput.bitrateKbps}`);
188
194
  return testPatternInput;
189
195
  }
190
196
  const device = this.options.videoSourceDevice;
191
197
  if (!device) {
192
- this.log.warn(`options.videoSource=${videoSource} requires options.videoSourceDevice to be set; falling back to the synthetic test video`);
193
- return testPatternInput;
198
+ this.log.error(`options.videoSource=${videoSource} requires options.videoSourceDevice to be set; not injecting a video track`);
199
+ return undefined;
194
200
  }
195
201
  const resolution = this.getConfiguredVideoResolution();
196
202
  const bitrateKbps = this.getConfiguredVideoBitrate();
@@ -209,10 +215,17 @@ export class WeriftWebRtcSession {
209
215
  case 'win32':
210
216
  return { args: ['-f', 'dshow', '-video_size', resolution, '-framerate', '30', '-i', `video=${device}`], description, bitrateKbps };
211
217
  default:
212
- this.log.warn(`Webcam capture via ffmpeg is not supported on platform "${process.platform}"; falling back to the synthetic test video`);
213
- return testPatternInput;
218
+ this.log.error(`Webcam capture via ffmpeg is not supported on platform "${process.platform}"; not injecting a video track`);
219
+ return undefined;
214
220
  }
215
221
  }
222
+ logFfmpegStderr(generator, kind) {
223
+ generator.stderr?.on('data', (chunk) => {
224
+ const message = chunk.toString().trim();
225
+ if (message)
226
+ this.log.debug(`Ffmpeg ${kind} generator: ${message}`);
227
+ });
228
+ }
216
229
  async generateVideoTrack(codec) {
217
230
  if (this.testVideoAttached)
218
231
  return;
@@ -222,6 +235,8 @@ export class WeriftWebRtcSession {
222
235
  return;
223
236
  }
224
237
  const videoInput = this.buildFfmpegVideoInputArgs(videoSource);
238
+ if (!videoInput)
239
+ return;
225
240
  this.log.debug(`Attempting to attach ${videoInput.description} video track at ${videoInput.bitrateKbps}kbps`);
226
241
  if (!hasFfmpeg()) {
227
242
  this.log.warn('Cannot inject video stream: missing dependency ffmpeg');
@@ -254,6 +269,7 @@ export class WeriftWebRtcSession {
254
269
  `rtp://127.0.0.1:${udpPort}`,
255
270
  ];
256
271
  const generator = runFfmpeg(ffmpegArgs);
272
+ this.logFfmpegStderr(generator, 'video');
257
273
  generator.once('error', (error) => {
258
274
  this.log.warn(`Video generator failed: ${getErrorMessage(error)}`);
259
275
  });
@@ -296,7 +312,7 @@ export class WeriftWebRtcSession {
296
312
  this.log.debug(`Preferred ${mimeType.toUpperCase()} codecs on ${adjustedTransceivers} audio transceiver(s)`);
297
313
  }
298
314
  }
299
- static TEST_VOICE_PATH = fileURLToPath(new URL('../../assets/test-voice.opus', import.meta.url));
315
+ static TEST_TONE_INPUT = 'sine=frequency=440:beep_factor=4:sample_rate=48000,volume=6dB';
300
316
  getConfiguredAudioSource() {
301
317
  const source = this.options.audioSource?.trim().toLowerCase() ?? 'none';
302
318
  switch (source) {
@@ -311,17 +327,13 @@ export class WeriftWebRtcSession {
311
327
  }
312
328
  }
313
329
  buildFfmpegAudioInputArgs(audioSource) {
314
- const testVoiceInput = {
315
- args: ['-re', '-stream_loop', '-1', '-i', WeriftWebRtcSession.TEST_VOICE_PATH],
316
- description: 'recorded test-voice clip',
317
- volumeFilter: 'volume=6dB',
318
- };
319
- if (audioSource === 'test')
320
- return testVoiceInput;
330
+ if (audioSource === 'test') {
331
+ return { args: ['-re', '-f', 'lavfi', '-i', WeriftWebRtcSession.TEST_TONE_INPUT], description: 'synthetic test tone' };
332
+ }
321
333
  const device = this.options.audioSourceDevice;
322
334
  if (!device) {
323
- this.log.warn(`options.audioSource=${audioSource} requires options.audioSourceDevice to be set; falling back to the recorded test-voice clip`);
324
- return testVoiceInput;
335
+ this.log.error(`options.audioSource=${audioSource} requires options.audioSourceDevice to be set; not injecting an audio track`);
336
+ return undefined;
325
337
  }
326
338
  if (audioSource === 'rtsp') {
327
339
  const description = `RTSP camera audio (${device})`;
@@ -338,8 +350,8 @@ export class WeriftWebRtcSession {
338
350
  case 'win32':
339
351
  return { args: ['-f', 'dshow', '-i', `audio=${device}`], description };
340
352
  default:
341
- this.log.warn(`Microphone capture via ffmpeg is not supported on platform "${process.platform}"; falling back to the recorded test-voice clip`);
342
- return testVoiceInput;
353
+ this.log.error(`Microphone capture via ffmpeg is not supported on platform "${process.platform}"; not injecting an audio track`);
354
+ return undefined;
343
355
  }
344
356
  }
345
357
  async generateAudioTrack(codec) {
@@ -351,6 +363,8 @@ export class WeriftWebRtcSession {
351
363
  return;
352
364
  }
353
365
  const audioInput = this.buildFfmpegAudioInputArgs(audioSource);
366
+ if (!audioInput)
367
+ return;
354
368
  this.log.debug(`Attempting to attach ${audioInput.description} audio track`);
355
369
  if (!hasFfmpeg()) {
356
370
  this.log.warn('Cannot inject audio stream: missing dependency ffmpeg');
@@ -373,13 +387,12 @@ export class WeriftWebRtcSession {
373
387
  'error',
374
388
  ...audioInput.args,
375
389
  '-vn',
376
- ...(audioInput.volumeFilter ? ['-af', audioInput.volumeFilter] : []),
377
390
  '-c:a',
378
391
  'libopus',
379
392
  '-b:a',
380
393
  '32k',
381
394
  '-ac',
382
- String(channels),
395
+ '1',
383
396
  '-ar',
384
397
  String(clockRate),
385
398
  '-f',
@@ -389,6 +402,7 @@ export class WeriftWebRtcSession {
389
402
  `rtp://127.0.0.1:${udpPort}`,
390
403
  ];
391
404
  const generator = runFfmpeg(ffmpegArgs);
405
+ this.logFfmpegStderr(generator, 'audio');
392
406
  generator.once('error', (error) => {
393
407
  this.log.warn(`Audio generator failed: ${getErrorMessage(error)}`);
394
408
  });
@@ -427,8 +441,8 @@ export class WeriftWebRtcSession {
427
441
  async createOffer(overrides) {
428
442
  this.applyOptionOverrides(overrides);
429
443
  const options = this.options;
430
- this.log.debug(`CreateOffer requested (video=${options.video}, audio=${options.audio}, videoResolution=${options.videoResolution ?? 'undefined'})`);
431
- if (options.video) {
444
+ this.log.debug(`CreateOffer requested (offerVideo=${options.offerVideo}, offerAudio=${options.offerAudio}, videoResolution=${options.videoResolution ?? 'undefined'})`);
445
+ if (options.offerVideo) {
432
446
  const preferredCodec = this.getPreferredInjectableVideoCodec();
433
447
  if (preferredCodec) {
434
448
  this.preferVideoCodecOnTransceivers(preferredCodec.mimeType.toLowerCase());
@@ -440,7 +454,7 @@ export class WeriftWebRtcSession {
440
454
  if (!this.testVideoAttached)
441
455
  this.peerConnection.addTransceiver('video', { direction: 'sendonly' });
442
456
  }
443
- if (options.audio)
457
+ if (options.offerAudio)
444
458
  this.peerConnection.addTransceiver('audio', { direction: 'sendonly' });
445
459
  const offer = await this.peerConnection.createOffer();
446
460
  await this.peerConnection.setLocalDescription(offer);
@@ -7,4 +7,5 @@ export declare class MatterbridgeGeneralDiagnosticsServer extends GeneralDiagnos
7
7
  testEventTrigger({ eventTrigger, enableKey }: GeneralDiagnostics.TestEventTriggerRequest): Promise<void>;
8
8
  payloadTestRequest(request: GeneralDiagnostics.PayloadTestRequest): ReturnType<GeneralDiagnosticsServer['payloadTestRequest']>;
9
9
  }
10
+ export declare function createChipTestRestartFlag(matterbridge: Matterbridge): void;
10
11
  export declare function createChipTestAppPipe(matterbridge: Matterbridge): void;
package/dist/chipTests.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { closeSync, constants, existsSync, openSync, readSync, unlinkSync } from 'node:fs';
2
+ import { closeSync, constants, existsSync, openSync, readFileSync, readSync, unlinkSync } from 'node:fs';
3
3
  import { Seconds, Time } from '@matter/general';
4
4
  import { BasicInformationServer } from '@matter/node/behaviors/basic-information';
5
5
  import { BridgedDeviceBasicInformationServer } from '@matter/node/behaviors/bridged-device-basic-information';
@@ -21,12 +21,17 @@ import { RefrigeratorAlarm } from '@matter/types/clusters/refrigerator-alarm';
21
21
  import { RvcOperationalState } from '@matter/types/clusters/rvc-operational-state';
22
22
  import { RvcRunMode } from '@matter/types/clusters/rvc-run-mode';
23
23
  import { SmokeCoAlarm } from '@matter/types/clusters/smoke-co-alarm';
24
+ import { Switch } from '@matter/types/clusters/switch';
24
25
  import { TariffPriceType, TariffUnit } from '@matter/types/globals';
26
+ import { wait } from '@matterbridge/utils/wait';
25
27
  import { MatterbridgeOccupancySensingServer } from './behaviors/occupancySensingServer.js';
26
28
  import { cliEmitter } from './cliEmitter.js';
27
29
  import { MatterbridgeRvcOperationalStateServer, MatterbridgeRvcRunModeServer } from './devices/roboticVacuumCleaner.js';
28
30
  import { MatterbridgeEndpoint } from './matterbridgeEndpoint.js';
31
+ import { featuresFor } from './matterbridgeEndpointHelpers.js';
29
32
  const chipTestAppPipePath = '/tmp/matterbridge-chip-test-app-pipe';
33
+ const chipTestRestartFlagPath = '/tmp/matterbridge-chip-test-restart-flag';
34
+ const chipTestRestartFlagText = 'restart';
30
35
  const chipTestValidEventTrigger = 0xfffffffffff10000n;
31
36
  const smokeCoAlarmWarningSmokeAlarmTrigger = 0x005c000000000090n;
32
37
  const smokeCoAlarmCriticalSmokeAlarmTrigger = 0x005c00000000009cn;
@@ -98,6 +103,9 @@ export const chipTestEnableKey = Uint8Array.from({ length: 16 }, (_, index) => i
98
103
  const smokeCoAlarmChipTestEnableKey = Uint8Array.from([0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff]);
99
104
  let chipTestMatterbridge;
100
105
  let closeChipTestAppPipe;
106
+ let chipTestRestartFlagTimer;
107
+ let chipTestRestartPending = false;
108
+ let chipTestRestartFlagWarned = false;
101
109
  let electricalPowerMeasurementFakeLoadTimer;
102
110
  let chipTestActiveEndpointId;
103
111
  export class MatterbridgeGeneralDiagnosticsServer extends GeneralDiagnosticsServer {
@@ -127,6 +135,65 @@ export class MatterbridgeGeneralDiagnosticsServer extends GeneralDiagnosticsServ
127
135
  return super.payloadTestRequest(request);
128
136
  }
129
137
  }
138
+ function removeChipTestRestartFlag(log) {
139
+ try {
140
+ if (existsSync(chipTestRestartFlagPath))
141
+ unlinkSync(chipTestRestartFlagPath);
142
+ }
143
+ catch (error) {
144
+ log.error(`Failed to remove CHIP test restart flag ${chipTestRestartFlagPath}: ${error instanceof Error ? error.message : String(error)}`);
145
+ }
146
+ }
147
+ export function createChipTestRestartFlag(matterbridge) {
148
+ if (chipTestRestartPending) {
149
+ const onOnline = (nodeId) => {
150
+ if (nodeId !== 'Matterbridge')
151
+ return;
152
+ matterbridge.off('online', onOnline);
153
+ removeChipTestRestartFlag(matterbridge.log);
154
+ chipTestRestartPending = false;
155
+ matterbridge.log.notice(`CHIP test restart completed, cleared restart flag ${chipTestRestartFlagPath}`);
156
+ };
157
+ matterbridge.on('online', onOnline);
158
+ }
159
+ if (chipTestRestartFlagTimer)
160
+ return;
161
+ matterbridge.log.notice(`CHIP test restart flag monitor watching ${chipTestRestartFlagPath}`);
162
+ chipTestRestartFlagTimer = setInterval(() => {
163
+ const instance = chipTestMatterbridge;
164
+ if (!instance || chipTestRestartPending || !existsSync(chipTestRestartFlagPath))
165
+ return;
166
+ let flagText;
167
+ try {
168
+ flagText = readFileSync(chipTestRestartFlagPath, 'utf8').trim();
169
+ }
170
+ catch (error) {
171
+ instance.log.error(`Failed to read CHIP test restart flag ${chipTestRestartFlagPath}: ${error instanceof Error ? error.message : String(error)}`);
172
+ return;
173
+ }
174
+ if (flagText !== chipTestRestartFlagText) {
175
+ if (!chipTestRestartFlagWarned) {
176
+ chipTestRestartFlagWarned = true;
177
+ instance.log.warn(`Ignoring unsupported CHIP test restart flag content "${flagText}": only "${chipTestRestartFlagText}" is implemented`);
178
+ }
179
+ return;
180
+ }
181
+ chipTestRestartFlagWarned = false;
182
+ chipTestRestartPending = true;
183
+ instance.log.notice(`CHIP test restart requested via ${chipTestRestartFlagPath}, restarting Matterbridge...`);
184
+ instance.restartProcess().catch((error) => {
185
+ chipTestRestartPending = false;
186
+ instance.log.error(`Failed to restart Matterbridge for the CHIP test restart flag: ${error instanceof Error ? error.message : String(error)}`);
187
+ });
188
+ }, 250);
189
+ chipTestRestartFlagTimer.unref();
190
+ cliEmitter.once('shutdown', () => {
191
+ if (chipTestRestartFlagTimer)
192
+ clearInterval(chipTestRestartFlagTimer);
193
+ chipTestRestartFlagTimer = undefined;
194
+ removeChipTestRestartFlag(matterbridge.log);
195
+ });
196
+ }
130
197
  function isChipTestEnableKey(keyData) {
131
198
  return equalsBytes(keyData, chipTestEnableKey) || equalsBytes(keyData, smokeCoAlarmChipTestEnableKey);
132
199
  }
@@ -1097,10 +1164,87 @@ async function handleChipTestAppPipeCommand(matterbridge, command) {
1097
1164
  }
1098
1165
  matterbridge.log.info(`CHIP test app pipe OperationalStateChange(${command.Operation}${command.Param === undefined ? '' : `, ${command.Param}`}) applied on endpoint ${endpointId}`);
1099
1166
  return;
1167
+ case 'SimulateSwitchIdle':
1168
+ await endpoint.setAttribute(Switch.id, 'currentPosition', 0, matterbridge.log);
1169
+ matterbridge.log.info(`CHIP test app pipe set Switch.CurrentPosition to 0 (idle) on endpoint ${endpointId}`);
1170
+ return;
1171
+ case 'SimulateLongPress':
1172
+ await simulateChipTestSwitchLongPress(matterbridge, endpoint, endpointId, command);
1173
+ return;
1174
+ case 'SimulateLatchPosition': {
1175
+ const newPosition = command.PositionId ?? 0;
1176
+ if (endpoint.getAttribute(Switch.id, 'currentPosition', matterbridge.log) === newPosition) {
1177
+ matterbridge.log.info(`CHIP test app pipe left Switch latched at position ${newPosition} on endpoint ${endpointId}`);
1178
+ return;
1179
+ }
1180
+ await endpoint.setAttribute(Switch.id, 'currentPosition', newPosition, matterbridge.log);
1181
+ await endpoint.triggerEvent(Switch.id, 'switchLatched', { newPosition }, matterbridge.log);
1182
+ matterbridge.log.info(`CHIP test app pipe latched Switch to position ${newPosition} on endpoint ${endpointId}`);
1183
+ return;
1184
+ }
1185
+ case 'SimulateMultiPress':
1186
+ await simulateChipTestSwitchMultiPress(matterbridge, endpoint, endpointId, command);
1187
+ return;
1100
1188
  default:
1101
1189
  matterbridge.log.warn(`Ignoring unsupported CHIP test app pipe command: ${JSON.stringify(command)}`);
1102
1190
  }
1103
1191
  }
1192
+ async function simulateChipTestSwitchLongPress(matterbridge, endpoint, endpointId, command) {
1193
+ if (!endpoint.hasClusterServer(Switch.id)) {
1194
+ matterbridge.log.warn(`Ignoring SimulateLongPress CHIP test app pipe command on endpoint ${endpointId} without a Switch cluster server`);
1195
+ return;
1196
+ }
1197
+ const features = featuresFor(endpoint, Switch.id);
1198
+ const newPosition = command.ButtonId ?? 1;
1199
+ const delayMs = command.LongPressDelayMillis ?? 0;
1200
+ const durationMs = command.LongPressDurationMillis ?? 0;
1201
+ await endpoint.setAttribute(Switch.id, 'currentPosition', newPosition, matterbridge.log);
1202
+ await endpoint.triggerEvent(Switch.id, 'initialPress', { newPosition }, matterbridge.log);
1203
+ matterbridge.log.info(`CHIP test app pipe pressed Switch position ${newPosition} on endpoint ${endpointId} for ${durationMs}ms`);
1204
+ if (features.momentarySwitchLongPress) {
1205
+ await wait(Math.min(delayMs, durationMs));
1206
+ await endpoint.triggerEvent(Switch.id, 'longPress', { newPosition }, matterbridge.log);
1207
+ await wait(Math.max(durationMs - delayMs, 0));
1208
+ }
1209
+ else {
1210
+ await wait(durationMs);
1211
+ }
1212
+ await endpoint.setAttribute(Switch.id, 'currentPosition', 0, matterbridge.log);
1213
+ if (features.momentarySwitchLongPress) {
1214
+ await endpoint.triggerEvent(Switch.id, 'longRelease', { previousPosition: newPosition }, matterbridge.log);
1215
+ }
1216
+ else if (features.momentarySwitchRelease) {
1217
+ await endpoint.triggerEvent(Switch.id, 'shortRelease', { previousPosition: newPosition }, matterbridge.log);
1218
+ }
1219
+ matterbridge.log.info(`CHIP test app pipe released Switch position ${newPosition} on endpoint ${endpointId}`);
1220
+ }
1221
+ async function simulateChipTestSwitchMultiPress(matterbridge, endpoint, endpointId, command) {
1222
+ if (!endpoint.hasClusterServer(Switch.id)) {
1223
+ matterbridge.log.warn(`Ignoring SimulateMultiPress CHIP test app pipe command on endpoint ${endpointId} without a Switch cluster server`);
1224
+ return;
1225
+ }
1226
+ const features = featuresFor(endpoint, Switch.id);
1227
+ const newPosition = command.ButtonId ?? 1;
1228
+ const presses = Math.max(command.MultiPressNumPresses ?? 1, 1);
1229
+ const pressedMs = command.MultiPressPressedTimeMillis ?? 0;
1230
+ const releasedMs = command.MultiPressReleasedTimeMillis ?? 0;
1231
+ const multiPressMax = endpoint.getAttribute(Switch.id, 'multiPressMax', matterbridge.log) ?? command.MultiPressMax ?? presses;
1232
+ for (let press = 1; press <= presses; press++) {
1233
+ await endpoint.setAttribute(Switch.id, 'currentPosition', newPosition, matterbridge.log);
1234
+ await endpoint.triggerEvent(Switch.id, 'initialPress', { newPosition }, matterbridge.log);
1235
+ if (press > 1) {
1236
+ await endpoint.triggerEvent(Switch.id, 'multiPressOngoing', { newPosition, currentNumberOfPressesCounted: Math.min(press, multiPressMax) }, matterbridge.log);
1237
+ }
1238
+ await wait(pressedMs);
1239
+ await endpoint.setAttribute(Switch.id, 'currentPosition', 0, matterbridge.log);
1240
+ if (features.momentarySwitchRelease) {
1241
+ await endpoint.triggerEvent(Switch.id, 'shortRelease', { previousPosition: newPosition }, matterbridge.log);
1242
+ }
1243
+ await wait(releasedMs);
1244
+ }
1245
+ await endpoint.triggerEvent(Switch.id, 'multiPressComplete', { previousPosition: newPosition, totalNumberOfPressesCounted: Math.min(presses, multiPressMax) }, matterbridge.log);
1246
+ matterbridge.log.info(`CHIP test app pipe completed ${presses} press(es) of Switch position ${newPosition} on endpoint ${endpointId}`);
1247
+ }
1104
1248
  function getChipTestEndpoint(matterbridge, endpointId) {
1105
1249
  const aggregatorEndpoint = matterbridge.aggregatorNode;
1106
1250
  if (!aggregatorEndpoint)
@@ -1127,5 +1271,14 @@ function isChipTestAppPipeCommand(value) {
1127
1271
  (!('SoilMoistureValue' in value) || typeof value.SoilMoistureValue === 'number') &&
1128
1272
  (!('Device' in value) || typeof value.Device === 'string') &&
1129
1273
  (!('Operation' in value) || typeof value.Operation === 'string') &&
1130
- (!('Param' in value) || typeof value.Param === 'number'));
1274
+ (!('Param' in value) || typeof value.Param === 'number') &&
1275
+ (!('ButtonId' in value) || typeof value.ButtonId === 'number') &&
1276
+ (!('LongPressDelayMillis' in value) || typeof value.LongPressDelayMillis === 'number') &&
1277
+ (!('LongPressDurationMillis' in value) || typeof value.LongPressDurationMillis === 'number') &&
1278
+ (!('FeatureMap' in value) || typeof value.FeatureMap === 'number') &&
1279
+ (!('PositionId' in value) || typeof value.PositionId === 'number') &&
1280
+ (!('MultiPressPressedTimeMillis' in value) || typeof value.MultiPressPressedTimeMillis === 'number') &&
1281
+ (!('MultiPressReleasedTimeMillis' in value) || typeof value.MultiPressReleasedTimeMillis === 'number') &&
1282
+ (!('MultiPressNumPresses' in value) || typeof value.MultiPressNumPresses === 'number') &&
1283
+ (!('MultiPressMax' in value) || typeof value.MultiPressMax === 'number'));
1131
1284
  }