• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

homebridge / HAP-NodeJS / 17775229178

16 Sep 2025 06:21PM UTC coverage: 63.437%. Remained the same
17775229178

push

github

bwp91
v2.0.2

1743 of 3286 branches covered (53.04%)

Branch coverage included in aggregate %.

6250 of 9314 relevant lines covered (67.1%)

312.83 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

43.96
/src/lib/controller/CameraController.ts
1
import crypto from "crypto";
18✔
2
import createDebug from "debug";
18✔
3
import { EventEmitter } from "events";
18✔
4
import { CharacteristicValue, SessionIdentifier } from "../../types";
5
import {
18✔
6
  CameraRecordingConfiguration,
7
  CameraRecordingOptions,
8
  CameraStreamingOptions,
9
  EventTriggerOption,
10
  PrepareStreamRequest,
11
  PrepareStreamResponse,
12
  RecordingManagement,
13
  RecordingManagementState,
14
  RecordingPacket,
15
  RTPStreamManagement,
16
  RTPStreamManagementState,
17
  SnapshotRequest,
18
  StreamingRequest,
19
} from "../camera";
20
import { Characteristic, CharacteristicEventTypes, CharacteristicGetCallback, CharacteristicSetCallback } from "../Characteristic";
18✔
21
import { DataStreamManagement, HDSProtocolSpecificErrorReason } from "../datastream";
18✔
22
import {
23
  CameraOperatingMode,
24
  CameraRecordingManagement,
25
  DataStreamTransportManagement,
26
  Doorbell,
27
  Microphone,
28
  MotionSensor,
29
  OccupancySensor,
30
  Speaker,
31
} from "../definitions";
32
import { HAPStatus } from "../HAPServer";
33
import { Service } from "../Service";
18✔
34
import { HapStatusError } from "../util/hapStatusError";
18✔
35
import { ControllerIdentifier, ControllerServiceMap, DefaultControllerType, SerializableController, StateChangeDelegate } from "./Controller";
36

37
const debug = createDebug("HAP-NodeJS:Camera:Controller");
18✔
38

39
/**
40
 * @group Camera
41
 */
42
export interface CameraControllerOptions {
43
  /**
44
   * Amount of parallel camera streams the accessory is capable of running.
45
   * As of the official HAP specification non SecureVideo cameras have a minimum required amount of 2 (but 1 is also fine).
46
   * Secure Video cameras just expose 1 stream.
47
   *
48
   * Default value: 1
49
   */
50
  cameraStreamCount?: number,
51

52
  /**
53
   * Delegate which handles the actual RTP/RTCP video/audio streaming and Snapshot requests.
54
   */
55
  delegate: CameraStreamingDelegate,
56

57
  /**
58
   * Options regarding video/audio streaming
59
   */
60
  streamingOptions: CameraStreamingOptions,
61

62
  /**
63
   * When supplying this option, it will enable support for HomeKit Secure Video.
64
   * This will create the {@link Service.CameraRecordingManagement}, {@link Service.CameraOperatingMode}
65
   * and {@link Service.DataStreamTransportManagement} services.
66
   *
67
   * NOTE: The controller only initializes the required characteristics for the {@link Service.CameraOperatingMode}.
68
   *   You may add optional characteristics, if required, by accessing the service directly `CameraController.recordingManagement.operatingModeService`.
69
   */
70
  recording?: {
71
    /**
72
     * Options regarding Recordings (Secure Video)
73
     */
74
    options: CameraRecordingOptions,
75

76
    /**
77
      * Delegate which handles the audio/video recording data streaming on motion.
78
      */
79
    delegate: CameraRecordingDelegate,
80
  }
81

82
  /**
83
   * This config section configures optional sensors for the camera.
84
   * It e.g. may be used to set up a {@link EventTriggerOption.MOTION} trigger when configuring Secure Video.
85
   *
86
   * You may either specify and provide the desired {@link Service}s or specify their creation and maintenance using a `boolean` flag.
87
   * In this case the controller will create and maintain the service for you.
88
   * Otherwise, when you supply an already created instance of the {@link Service}, you are responsible yourself to manage the service
89
   * (e.g. creating, restoring, adding to the accessory, ...).
90
   *
91
   * The services can be accessed through the documented property after the call to {@link Accessory.configureController} has returned.
92
   */
93
  sensors?: {
94
    /**
95
     * Define if a {@link Service.MotionSensor} should be created/associated with the controller.
96
     *
97
     * You may access the created service via the {@link CameraController.motionService} property to configure listeners.
98
     *
99
     * ## HomeKit Secure Video:
100
     *
101
     * If supplied, this sensor will be used as a {@link EventTriggerOption.MOTION} trigger.
102
     * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor.
103
     */
104
    motion?: Service | boolean;
105
    /**
106
     * Define if a {@link Service.OccupancySensor} should be created/associated with the controller.
107
     *
108
     * You may access the created service via the {@link CameraController.occupancyService} property to configure listeners.
109
     *
110
     * ## HomeKit Secure Video:
111
     *
112
     * The characteristic {@link Characteristic.StatusActive} will be added, which is used to enable or disable the sensor.
113
     */
114
    occupancy?: Service | boolean;
115
  }
116
}
117

118
/**
119
 * @group Camera
120
 */
121
export type SnapshotRequestCallback = (error?: Error | HAPStatus, buffer?: Buffer) => void;
122
/**
123
 * @group Camera
124
 */
125
export type PrepareStreamCallback = (error?: Error, response?: PrepareStreamResponse) => void;
126
/**
127
 * @group Camera
128
 */
129
export type StreamRequestCallback = (error?: Error) => void;
130

131
/**
132
 * @group Camera
133
 */
134
export const enum ResourceRequestReason {
18✔
135
  /**
136
   * The reason describes periodic resource requests.
137
   * In the example of camera image snapshots those are the typical preview images every 10 seconds.
138
   */
139
  PERIODIC = 0,
18✔
140
  /**
141
   * The resource request is the result of some event.
142
   * In the example of camera image snapshots, requests are made due to e.g. a motion event or similar.
143
   */
144
  EVENT = 1
18✔
145
}
146

147
/**
148
 * @group Camera
149
 */
150
export interface CameraStreamingDelegate {
151

152
  /**
153
   * This method is called when a HomeKit controller requests a snapshot image for the given camera.
154
   * The handler must respect the desired image height and width given in the {@link SnapshotRequest}.
155
   * The returned Buffer (via the callback) must be encoded in jpeg.
156
   *
157
   * HAP-NodeJS will complain about slow running handlers after 5 seconds and terminate the request after 15 seconds.
158
   *
159
   * @param request - Request containing image size.
160
   * @param callback - Callback supplied with the resulting Buffer
161
   */
162
  handleSnapshotRequest(request: SnapshotRequest, callback: SnapshotRequestCallback): void;
163

164
  prepareStream(request: PrepareStreamRequest, callback: PrepareStreamCallback): void;
165
  handleStreamRequest(request: StreamingRequest, callback: StreamRequestCallback): void;
166

167
}
168

169
/**
170
 * A `CameraRecordingDelegate` is responsible for handling recordings of a HomeKit Secure Video camera.
171
 *
172
 * It is responsible for maintaining the prebuffer (see {@link CameraRecordingOptions.prebufferLength},
173
 * once recording was activated (see {@link updateRecordingActive}).
174
 *
175
 * Before recording is considered enabled two things must happen:
176
 * - Recording must be enabled by the user. Signaled through {@link updateRecordingActive}.
177
 * - Recording configurations must be selected by a HomeKit controller through {@link updateRecordingConfiguration}.
178
 *
179
 * A typical recording event scenario happens as follows:
180
 * - The camera is in idle mode, maintaining the prebuffer (the duration of the prebuffer depends on the selected {@link CameraRecordingConfiguration}).
181
 * - A recording event is triggered (e.g. motion or doorbell button press) and the camera signals it through
182
 *   the respective characteristics (e.g. {@link Characteristic.MotionDetected} or {@link Characteristic.ProgrammableSwitchEvent}).
183
 *   Further, the camera saves the content of the prebuffer and starts recording the video.
184
 *   The camera should continue to store the recording until it runs out of space.
185
 *   In any case the camera should preserve recordings which are nearest to the triggered event.
186
 *   A stored recording might be completely deleted if a stream request wasn't initiated for eight seconds.
187
 * - A HomeKit Controller will open a new recording session to download the next recording.
188
 *   This results in a call to {@link handleRecordingStreamRequest}.
189
 * - Once the recording event is finished the camera will reset the state accordingly
190
 *   (e.g. in the {@link Service.MotionSensor} or {@link Service.Doorbell} service).
191
 *   It will continue to send the remaining fragments of the currently ongoing recording stream request.
192
 * - The camera will either reach the end of the recording (and signal this via {@link RecordingPacket.isLast}. Also see {@link acknowledgeStream})
193
 *   or it will continue to stream til the HomeKit Controller closes
194
 *   the stream {@link closeRecordingStream} with reason {@link HDSProtocolSpecificErrorReason.NORMAL}.
195
 * - The camera goes back into idle mode.
196
 *
197
 * @group Camera
198
 */
199
export interface CameraRecordingDelegate {
200
  /**
201
   * A call to this method notifies the `CameraRecordingDelegate` about a change to the
202
   * `CameraRecordingManagement.Active` characteristic. This characteristic controls
203
   * if the camera should react to recording events.
204
   *
205
   * If recording is disabled the camera can stop maintaining its prebuffer.
206
   * If recording is enabled the camera should start recording into its prebuffer.
207
   *
208
   * A `CameraRecordingDelegate` should assume active to be `false` on startup.
209
   * HAP-NodeJS will persist the state of the `Active` characteristic across reboots
210
   * and will call {@link updateRecordingActive} accordingly on startup, if recording was previously enabled.
211
   *
212
   * NOTE: HAP-NodeJS cannot guarantee that a {@link CameraRecordingConfiguration} is present
213
   * when recording is activated (e.g. the selected configuration might be erased due to changes
214
   * in the supplied {@link CameraRecordingOptions}, but the camera is still `active`; or we can't otherwise
215
   * influence the order which a HomeKit Controller might call those characteristics).
216
   * However, HAP-NodeJS guarantees that if there is a valid {@link CameraRecordingConfiguration},
217
   * {@link updateRecordingConfiguration} is called before {@link updateRecordingActive} (when enabling)
218
   * to avoid any unnecessary and potentially expensive reconfigurations.
219
   *
220
   * @param active - Specifies if recording is active or not.
221
   */
222
  updateRecordingActive(active: boolean): void;
223

224
  /**
225
   * A call to this method signals that the selected (by the HomeKit Controller)
226
   * recording configuration of the camera has changed.
227
   *
228
   * On startup the delegate should assume `configuration = undefined`.
229
   * HAP-NodeJS will persist the state of both across reboots and will call
230
   * {@link updateRecordingConfiguration} on startup if there is a **selected configuration** present.
231
   *
232
   * NOTE: An update to the recording configuration might happen while there is still a running
233
   * recording stream. The camera MUST continue to use the previous configuration for the
234
   * currently running stream and only apply the updated configuration to the next stream.
235
   *
236
   * @param configuration - The {@link CameraRecordingConfiguration}. Reconfigure your recording pipeline accordingly.
237
   *  The parameter might be `undefined` when the selected configuration became invalid. This typically ony happens
238
   *  e.g. due to a factory reset (when all pairings are removed). Disable the recording pipeline in such a case
239
   *  even if recording is still enabled for the camera.
240
   */
241
  updateRecordingConfiguration(configuration: CameraRecordingConfiguration | undefined): void;
242

243
  /**
244
   * This method is called to stream the next recording event.
245
   * It is guaranteed that there is only ever one ongoing recording stream request at a time.
246
   *
247
   * When this method is called return the currently ongoing (or next in case of a potentially queued)
248
   * recording via a `AsyncGenerator`. Every `yield` of the generator represents a complete recording `packet`.
249
   * The first packet MUST always be the {@link PacketDataType.MEDIA_INITIALIZATION} packet.
250
   * Any following packet will transport the actual mp4 fragments in {@link PacketDataType.MEDIA_FRAGMENT} packets,
251
   * starting with the content of the prebuffer. Every {@link PacketDataType.MEDIA_FRAGMENT} starts with a key frame
252
   * and must not be longer than the specified duration set via the `CameraRecordingConfiguration.mediaContainerConfiguration.fragmentLength`
253
   * **selected** by the HomeKit Controller in {@link updateRecordingConfiguration}.
254
   *
255
   * NOTE: You MUST respect the value of {@link Characteristic.RecordingAudioActive} characteristic of the {@link Service.CameraOperatingMode}
256
   *   service. When the characteristic is set to false you MUST NOT include audio in the mp4 fragments. You can access the characteristic via
257
   *   the `CameraController.recordingManagement.operatingModeService` property.
258
   *
259
   * You might throw an error in this method if encountering a non-recoverable state.
260
   * You may throw a {@link HDSProtocolError} to manually define the {@link HDSProtocolSpecificErrorReason} for the `DATA_SEND` `CLOSE` event.
261
   *
262
   * There are three ways an ongoing recording stream can be closed:
263
   * - Closed by the Accessory: There are no further fragments to transmit. The delegate MUST signal this by setting {@link RecordingPacket.isLast}
264
   *   to `true`. Once the HomeKit Controller receives this last fragment it will call {@link acknowledgeStream} to notify the accessory about
265
   *   the successful transmission.
266
   * - Closed by the HomeKit Controller (expectedly): After the event trigger has been reset, the accessory continues to stream fragments.
267
   *   At some point the HomeKit Controller will decide to shut down the stream by calling {@link closeRecordingStream} with a reason
268
   *   of {@link HDSProtocolSpecificErrorReason.NORMAL}.
269
   * - Closed by the HomeKit Controller (unexpectedly): A HomeKit Controller might at any point decide to close a recording stream
270
   *   if it encounters erroneous state. This is signaled by a call to {@link closeRecordingStream} with the respective reason.
271
   *
272
   * Once a close of stream is signaled, the `AsyncGenerator` function must return gracefully.
273
   *
274
   * For more information about `AsyncGenerator`s you might have a look at:
275
   * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of
276
   *
277
   * NOTE: HAP-NodeJS guarantees that this method is only called with a valid selected {@link CameraRecordingConfiguration}.
278
   *
279
   * NOTE: Don't rely on the streamId for unique identification. Two {@link DataStreamConnection}s might share the same identifier space.
280
   *
281
   * @param streamId - The streamId of the currently ongoing stream.
282
   */
283
  handleRecordingStreamRequest(streamId: number): AsyncGenerator<RecordingPacket>;
284

285
  /**
286
   * This method is called once the HomeKit Controller acknowledges the `endOfStream`.
287
   * A `endOfStream` is sent by the accessory by setting {@link RecordingPacket.isLast} to `true` in the last packet yielded
288
   * by the {@link handleRecordingStreamRequest} `AsyncGenerator`.
289
   *
290
   * @param streamId - The streamId of the acknowledged stream.
291
   */
292
  acknowledgeStream?(streamId: number): void;
293

294
  /**
295
   * This method is called to notify the delegate that a recording stream started via {@link handleRecordingStreamRequest} was closed.
296
   *
297
   * The method is also called if an ongoing recording stream is closed gracefully (using {@link HDSProtocolSpecificErrorReason.NORMAL}).
298
   * In either case, the delegate should stop supplying further fragments to the recording stream.
299
   * The `AsyncGenerator` function must return without yielding any further {@link RecordingPacket}s.
300
   * HAP-NodeJS won't send out any fragments from this point onwards.
301
   *
302
   * @param streamId - The streamId for which the close event was sent.
303
   * @param reason - The reason with which the stream was closed.
304
   *  NOTE: This method is also called in case of a closed connection. This is encoded by setting the `reason` to undefined.
305
   */
306
  closeRecordingStream(streamId: number, reason: HDSProtocolSpecificErrorReason | undefined): void;
307
}
308

309
/**
310
 * @group Camera
311
 */
312
export interface CameraControllerServiceMap extends ControllerServiceMap {
313
  // "streamManagement%d": CameraRTPStreamManagement, // format to map all stream management services; indexed by zero
314

315
  microphone?: Microphone,
316
  speaker?: Speaker,
317

318
  cameraEventRecordingManagement?: CameraRecordingManagement,
319
  cameraOperatingMode?: CameraOperatingMode,
320
  dataStreamTransportManagement?: DataStreamTransportManagement,
321

322
  motionService?: MotionSensor,
323
  occupancyService?: OccupancySensor,
324

325
  // this ServiceMap is also used by the DoorbellController; there is no necessity to declare it,
326
  // but I think its good practice to reserve the namespace
327
  doorbell?: Doorbell;
328
}
329

330
/**
331
 * @group Camera
332
 */
333
export interface CameraControllerState {
334
  streamManagements: RTPStreamManagementState[];
335
  recordingManagement?: RecordingManagementState;
336
}
337

338
/**
339
 * @group Camera
340
 */
341
export const enum CameraControllerEvents {
18✔
342
  /**
343
   *  Emitted when the mute state or the volume changed. The Apple Home App typically does not set those values
344
   *  except the mute state. When you adjust the volume in the Camera view it will reset the muted state if it was set previously.
345
   *  The value of volume has nothing to do with the volume slider in the Camera view of the Home app.
346
   */
347
  MICROPHONE_PROPERTIES_CHANGED = "microphone-change",
18✔
348
  /**
349
   * Emitted when the mute state or the volume changed. The Apple Home App typically does not set those values
350
   * except the mute state. When you unmute the device microphone it will reset the mute state if it was set previously.
351
   */
352
  SPEAKER_PROPERTIES_CHANGED = "speaker-change",
18✔
353
}
354

355
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
356
export declare interface CameraController {
357
  on(event: "microphone-change", listener: (muted: boolean, volume: number) => void): this;
358
  on(event: "speaker-change", listener: (muted: boolean, volume: number) => void): this;
359

360
  emit(event: "microphone-change", muted: boolean, volume: number): boolean;
361
  emit(event: "speaker-change", muted: boolean, volume: number): boolean;
362
}
363

364
/**
365
 * Everything needed to expose a HomeKit Camera.
366
 *
367
 * @group Camera
368
 */
369
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
370
export class CameraController extends EventEmitter implements SerializableController<CameraControllerServiceMap, CameraControllerState> {
18✔
371
  private static readonly STREAM_MANAGEMENT = "streamManagement"; // key to index all RTPStreamManagement services
18✔
372

373
  private stateChangeDelegate?: StateChangeDelegate;
374

375
  private readonly streamCount: number;
376
  private readonly delegate: CameraStreamingDelegate;
377
  private readonly streamingOptions: CameraStreamingOptions;
378
  /**
379
   * **Temporary** storage for {@link CameraRecordingOptions} and {@link CameraRecordingDelegate}.
380
   * This property is reset to `undefined` after the CameraController was fully initialized.
381
   * You can still access those values via the {@link CameraController.recordingManagement}.
382
   */
383
  private recording?: {
384
    options: CameraRecordingOptions,
385
    delegate: CameraRecordingDelegate,
386
  };
387
  /**
388
   * Temporary storage for the sensor option.
389
   */
390
  private sensorOptions?: {
391
    motion?: Service | boolean;
392
    occupancy?: Service | boolean;
393
  };
394
  private readonly legacyMode: boolean = false;
213✔
395

396
  /**
397
   * @private
398
   */
399
  streamManagements: RTPStreamManagement[] = [];
213✔
400
  /**
401
   * The {@link RecordingManagement} which is responsible for handling HomeKit Secure Video.
402
   * This property is only present if recording was configured.
403
   */
404
  recordingManagement?: RecordingManagement;
405

406
  private microphoneService?: Microphone;
407
  private speakerService?: Speaker;
408

409
  private microphoneMuted = false;
213✔
410
  private microphoneVolume = 100;
213✔
411
  private speakerMuted = false;
213✔
412
  private speakerVolume = 100;
213✔
413

414
  motionService?: MotionSensor;
415
  private motionServiceExternallySupplied = false;
213✔
416
  occupancyService?: OccupancySensor;
417
  private occupancyServiceExternallySupplied = false;
213✔
418

419
  constructor(options: CameraControllerOptions, legacyMode = false) {
213✔
420
    super();
213✔
421
    this.streamCount = Math.max(1, options.cameraStreamCount || 1);
213!
422
    this.delegate = options.delegate;
213✔
423
    this.streamingOptions = options.streamingOptions;
213✔
424
    this.recording = options.recording;
213✔
425
    this.sensorOptions = options.sensors;
213✔
426

427
    this.legacyMode = legacyMode; // legacy mode will prevent from Microphone and Speaker services to get created to avoid collisions
213✔
428
  }
429

430
  /**
431
   * @private
432
   */
433
  controllerId(): ControllerIdentifier {
434
    return DefaultControllerType.CAMERA;
57✔
435
  }
436

437
  // ----------------------------------- STREAM API ------------------------------------
438

439
  /**
440
   * Call this method if you want to forcefully suspend an ongoing streaming session.
441
   * This would be adequate if the rtp server or media encoding encountered an unexpected error.
442
   *
443
   * @param sessionId - id of the current ongoing streaming session
444
   */
445
  public forceStopStreamingSession(sessionId: SessionIdentifier): void {
446
    this.streamManagements.forEach(management => {
×
447
      if (management.sessionIdentifier === sessionId) {
×
448
        management.forceStop();
×
449
      }
450
    });
451
  }
452

453
  public static generateSynchronisationSource(): number {
454
    const ssrc = crypto.randomBytes(4); // range [-2.14748e+09 - 2.14748e+09]
×
455
    ssrc[0] = 0;
×
456
    return ssrc.readInt32BE(0);
×
457
  }
458

459
  // ----------------------------- MICROPHONE/SPEAKER API ------------------------------
460

461
  public setMicrophoneMuted(muted = true): void {
×
462
    if (!this.microphoneService) {
×
463
      return;
×
464
    }
465

466
    this.microphoneMuted = muted;
×
467
    this.microphoneService.updateCharacteristic(Characteristic.Mute, muted);
×
468
  }
469

470
  public setMicrophoneVolume(volume: number): void {
471
    if (!this.microphoneService) {
×
472
      return;
×
473
    }
474

475
    this.microphoneVolume = volume;
×
476
    this.microphoneService.updateCharacteristic(Characteristic.Volume, volume);
×
477
  }
478

479
  public setSpeakerMuted(muted = true): void {
×
480
    if (!this.speakerService) {
×
481
      return;
×
482
    }
483

484
    this.speakerMuted = muted;
×
485
    this.speakerService.updateCharacteristic(Characteristic.Mute, muted);
×
486
  }
487

488
  public setSpeakerVolume(volume: number): void {
489
    if (!this.speakerService) {
×
490
      return;
×
491
    }
492

493
    this.speakerVolume = volume;
×
494
    this.speakerService.updateCharacteristic(Characteristic.Volume, volume);
×
495
  }
496

497
  private emitMicrophoneChange() {
498
    this.emit(CameraControllerEvents.MICROPHONE_PROPERTIES_CHANGED, this.microphoneMuted, this.microphoneVolume);
×
499
  }
500

501
  private emitSpeakerChange() {
502
    this.emit(CameraControllerEvents.SPEAKER_PROPERTIES_CHANGED, this.speakerMuted, this.speakerVolume);
×
503
  }
504

505
  // -----------------------------------------------------------------------------------
506
  /**
507
   * @private
508
   */
509
  constructServices(): CameraControllerServiceMap {
510
    for (let i = 0; i < this.streamCount; i++) {
216✔
511
      const rtp = new RTPStreamManagement(i, this.streamingOptions, this.delegate, undefined, this.rtpStreamManagementDisabledThroughOperatingMode.bind(this));
432✔
512
      this.streamManagements.push(rtp);
432✔
513
    }
514

515
    if (!this.legacyMode && this.streamingOptions.audio) {
216!
516
      // In theory the Microphone Service is a necessity. In practice, it's not. lol.
517
      // So we just add it if the user wants to support audio
518
      this.microphoneService = new Service.Microphone("", "");
216✔
519
      this.microphoneService.setCharacteristic(Characteristic.Volume, this.microphoneVolume);
216✔
520

521
      if (this.streamingOptions.audio.twoWayAudio) {
216!
522
        this.speakerService = new Service.Speaker("", "");
216✔
523
        this.speakerService.setCharacteristic(Characteristic.Volume, this.speakerVolume);
216✔
524
      }
525
    }
526

527
    if (this.recording) {
216✔
528
      this.recordingManagement = new RecordingManagement(this.recording.options, this.recording.delegate, this.retrieveEventTriggerOptions());
213✔
529
    }
530

531

532
    if (this.sensorOptions?.motion) {
216✔
533
      if (typeof this.sensorOptions.motion === "boolean") {
213!
534
        this.motionService = new Service.MotionSensor("", "");
213✔
535
      } else {
536
        this.motionService = this.sensorOptions.motion;
×
537
        this.motionServiceExternallySupplied = true;
×
538
      }
539

540
      this.motionService.setCharacteristic(Characteristic.StatusActive, true);
213✔
541
      this.recordingManagement?.recordingManagementService.addLinkedService(this.motionService);
213✔
542
    }
543

544
    if (this.sensorOptions?.occupancy) {
216✔
545
      if (typeof this.sensorOptions.occupancy === "boolean") {
213!
546
        this.occupancyService = new Service.OccupancySensor("", "");
213✔
547
      } else {
548
        this.occupancyService = this.sensorOptions.occupancy;
×
549
        this.occupancyServiceExternallySupplied = true;
×
550
      }
551

552
      this.occupancyService.setCharacteristic(Characteristic.StatusActive, true);
213✔
553
      this.recordingManagement?.recordingManagementService.addLinkedService(this.occupancyService);
213✔
554
    }
555

556

557
    const serviceMap: CameraControllerServiceMap = {
216✔
558
      microphone: this.microphoneService,
559
      speaker: this.speakerService,
560
      motionService: !this.motionServiceExternallySupplied ? this.motionService : undefined,
216!
561
      occupancyService: !this.occupancyServiceExternallySupplied ? this.occupancyService : undefined,
216!
562
    };
563

564
    if (this.recordingManagement) {
216✔
565
      serviceMap.cameraEventRecordingManagement = this.recordingManagement.recordingManagementService;
213✔
566
      serviceMap.cameraOperatingMode = this.recordingManagement.operatingModeService;
213✔
567
      serviceMap.dataStreamTransportManagement = this.recordingManagement.dataStreamManagement.getService();
213✔
568
    }
569

570
    this.streamManagements.forEach((management, index) => {
216✔
571
      serviceMap[CameraController.STREAM_MANAGEMENT + index] = management.getService();
432✔
572
    });
573

574
    this.recording = undefined;
216✔
575
    this.sensorOptions = undefined;
216✔
576

577
    return serviceMap;
216✔
578
  }
579

580
  /**
581
   * @private
582
   */
583
  initWithServices(serviceMap: CameraControllerServiceMap): void | CameraControllerServiceMap {
584
    const result = this._initWithServices(serviceMap);
×
585

586
    if (result.updated) { // serviceMap must only be returned if anything actually changed
×
587
      return result.serviceMap;
×
588
    }
589
  }
590

591
  protected _initWithServices(serviceMap: CameraControllerServiceMap): { serviceMap: CameraControllerServiceMap, updated: boolean } {
592
    let modifiedServiceMap = false;
×
593

594
    // eslint-disable-next-line no-constant-condition
595
    for (let i = 0; true; i++) {
×
596
      const streamManagementService = serviceMap[CameraController.STREAM_MANAGEMENT + i];
×
597

598
      if (i < this.streamCount) {
×
599
        const operatingModeClosure = this.rtpStreamManagementDisabledThroughOperatingMode.bind(this);
×
600

601
        if (streamManagementService) { // normal init
×
602
          this.streamManagements.push(new RTPStreamManagement(i, this.streamingOptions, this.delegate, streamManagementService, operatingModeClosure));
×
603
        } else { // stream count got bigger, we need to create a new service
604
          const management = new RTPStreamManagement(i, this.streamingOptions, this.delegate, undefined, operatingModeClosure);
×
605

606
          this.streamManagements.push(management);
×
607
          serviceMap[CameraController.STREAM_MANAGEMENT + i] = management.getService();
×
608

609
          modifiedServiceMap = true;
×
610
        }
611
      } else {
612
        if (streamManagementService) { // stream count got reduced, we need to remove old service
×
613
          delete serviceMap[CameraController.STREAM_MANAGEMENT + i];
×
614
          modifiedServiceMap = true;
×
615
        } else {
616
          break; // we finished counting, and we got no saved service; we are finished
×
617
        }
618
      }
619
    }
620

621
    // MICROPHONE
622
    if (!this.legacyMode && this.streamingOptions.audio) { // microphone should be present
×
623
      if (serviceMap.microphone) {
×
624
        this.microphoneService = serviceMap.microphone;
×
625
      } else {
626
        // microphone wasn't created yet => create a new one
627
        this.microphoneService = new Service.Microphone("", "");
×
628
        this.microphoneService.setCharacteristic(Characteristic.Volume, this.microphoneVolume);
×
629

630
        serviceMap.microphone = this.microphoneService;
×
631
        modifiedServiceMap = true;
×
632
      }
633
    } else if (serviceMap.microphone) { // microphone service supplied, though settings seemed to have changed
×
634
      // we need to remove it
635
      delete serviceMap.microphone;
×
636
      modifiedServiceMap = true;
×
637
    }
638

639
    // SPEAKER
640
    if (!this.legacyMode && this.streamingOptions.audio?.twoWayAudio) { // speaker should be present
×
641
      if (serviceMap.speaker) {
×
642
        this.speakerService = serviceMap.speaker;
×
643
      } else {
644
        // speaker wasn't created yet => create a new one
645
        this.speakerService = new Service.Speaker("", "");
×
646
        this.speakerService.setCharacteristic(Characteristic.Volume, this.speakerVolume);
×
647

648
        serviceMap.speaker = this.speakerService;
×
649
        modifiedServiceMap = true;
×
650
      }
651
    } else if (serviceMap.speaker) { // speaker service supplied, though settings seemed to have changed
×
652
      // we need to remove it
653
      delete serviceMap.speaker;
×
654
      modifiedServiceMap = true;
×
655
    }
656

657
    // RECORDING
658
    if (this.recording) {
×
659
      const eventTriggers = this.retrieveEventTriggerOptions();
×
660

661
      // RECORDING MANAGEMENT
662
      if (serviceMap.cameraEventRecordingManagement && serviceMap.cameraOperatingMode && serviceMap.dataStreamTransportManagement) {
×
663
        this.recordingManagement = new RecordingManagement(
×
664
          this.recording.options,
665
          this.recording.delegate,
666
          eventTriggers,
667
          {
668
            recordingManagement: serviceMap.cameraEventRecordingManagement,
669
            operatingMode: serviceMap.cameraOperatingMode,
670
            dataStreamManagement: new DataStreamManagement(serviceMap.dataStreamTransportManagement),
671
          },
672
        );
673
      } else {
674
        this.recordingManagement = new RecordingManagement(
×
675
          this.recording.options,
676
          this.recording.delegate,
677
          eventTriggers,
678
        );
679

680
        serviceMap.cameraEventRecordingManagement = this.recordingManagement.recordingManagementService;
×
681
        serviceMap.cameraOperatingMode = this.recordingManagement.operatingModeService;
×
682
        serviceMap.dataStreamTransportManagement = this.recordingManagement.dataStreamManagement.getService();
×
683
        modifiedServiceMap = true;
×
684
      }
685
    } else {
686
      if (serviceMap.cameraEventRecordingManagement) {
×
687
        delete serviceMap.cameraEventRecordingManagement;
×
688
        modifiedServiceMap = true;
×
689
      }
690
      if (serviceMap.cameraOperatingMode) {
×
691
        delete serviceMap.cameraOperatingMode;
×
692
        modifiedServiceMap = true;
×
693
      }
694
      if (serviceMap.dataStreamTransportManagement) {
×
695
        delete serviceMap.dataStreamTransportManagement;
×
696
        modifiedServiceMap = true;
×
697
      }
698
    }
699

700
    // MOTION SENSOR
701
    if (this.sensorOptions?.motion) {
×
702
      if (typeof this.sensorOptions.motion === "boolean") {
×
703
        if (serviceMap.motionService) {
×
704
          this.motionService = serviceMap.motionService;
×
705
        } else {
706
          // it could be the case that we previously had a manually supplied motion service
707
          // at this point we can't remove the iid from the list of linked services from the recording management!
708
          this.motionService = new Service.MotionSensor("", "");
×
709
        }
710
      } else {
711
        this.motionService = this.sensorOptions.motion;
×
712
        this.motionServiceExternallySupplied = true;
×
713

714
        if (serviceMap.motionService) { // motion service previously supplied as bool option
×
715
          this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.motionService);
×
716
          delete serviceMap.motionService;
×
717
          modifiedServiceMap = true;
×
718
        }
719
      }
720

721
      this.motionService.setCharacteristic(Characteristic.StatusActive, true);
×
722
      this.recordingManagement?.recordingManagementService.addLinkedService(this.motionService);
×
723
    } else {
724
      if (serviceMap.motionService) {
×
725
        this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.motionService);
×
726
        delete serviceMap.motionService;
×
727
        modifiedServiceMap = true;
×
728
      }
729
    }
730

731
    // OCCUPANCY SENSOR
732
    if (this.sensorOptions?.occupancy) {
×
733
      if (typeof this.sensorOptions.occupancy === "boolean") {
×
734
        if (serviceMap.occupancyService) {
×
735
          this.occupancyService = serviceMap.occupancyService;
×
736
        } else {
737
          // it could be the case that we previously had a manually supplied occupancy service
738
          // at this point we can't remove the iid from the list of linked services from the recording management!
739
          this.occupancyService = new Service.OccupancySensor("", "");
×
740
        }
741
      } else {
742
        this.occupancyService = this.sensorOptions.occupancy;
×
743
        this.occupancyServiceExternallySupplied = true;
×
744

745
        if (serviceMap.occupancyService) { // occupancy service previously supplied as bool option
×
746
          this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.occupancyService);
×
747
          delete serviceMap.occupancyService;
×
748
          modifiedServiceMap = true;
×
749
        }
750
      }
751

752
      this.occupancyService.setCharacteristic(Characteristic.StatusActive, true);
×
753
      this.recordingManagement?.recordingManagementService.addLinkedService(this.occupancyService);
×
754
    } else {
755
      if (serviceMap.occupancyService) {
×
756
        this.recordingManagement?.recordingManagementService.removeLinkedService(serviceMap.occupancyService);
×
757
        delete serviceMap.occupancyService;
×
758
        modifiedServiceMap = true;
×
759
      }
760
    }
761

762
    if (this.migrateFromDoorbell(serviceMap)) {
×
763
      modifiedServiceMap = true;
×
764
    }
765

766
    this.recording = undefined;
×
767
    this.sensorOptions = undefined;
×
768

769
    return {
×
770
      serviceMap: serviceMap,
771
      updated: modifiedServiceMap,
772
    };
773
  }
774

775
  // overwritten in DoorbellController (to avoid cyclic dependencies, I hate typescript for that)
776
  protected migrateFromDoorbell(serviceMap: ControllerServiceMap): boolean {
777
    if (serviceMap.doorbell) { // See NOTICE in DoorbellController
×
778
      delete serviceMap.doorbell;
×
779
      return true;
×
780
    }
781

782
    return false;
×
783
  }
784

785
  protected retrieveEventTriggerOptions(): Set<EventTriggerOption> {
786
    if (!this.recording) {
216!
787
      return new Set();
×
788
    }
789

790
    const triggerOptions = new Set<EventTriggerOption>();
216✔
791

792
    if (this.recording.options.overrideEventTriggerOptions) {
216✔
793
      for (const option of this.recording.options.overrideEventTriggerOptions) {
156✔
794
        triggerOptions.add(option);
156✔
795
      }
796
    }
797

798
    if (this.sensorOptions?.motion) {
216!
799
      triggerOptions.add(EventTriggerOption.MOTION);
216✔
800
    }
801

802
    // this method is overwritten by the `DoorbellController` to automatically configure EventTriggerOption.DOORBELL
803

804
    return triggerOptions;
216✔
805
  }
806

807
  /**
808
   * @private
809
   */
810
  configureServices(): void {
811
    if (this.microphoneService) {
216!
812
      this.microphoneService.getCharacteristic(Characteristic.Mute)!
216✔
813
        .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
814
          callback(undefined, this.microphoneMuted);
×
815
        })
816
        .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
817
          this.microphoneMuted = value as boolean;
×
818
          callback();
×
819
          this.emitMicrophoneChange();
×
820
        });
821
      this.microphoneService.getCharacteristic(Characteristic.Volume)!
216✔
822
        .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
823
          callback(undefined, this.microphoneVolume);
×
824
        })
825
        .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
826
          this.microphoneVolume = value as number;
×
827
          callback();
×
828
          this.emitMicrophoneChange();
×
829
        });
830
    }
831

832
    if (this.speakerService) {
216!
833
      this.speakerService.getCharacteristic(Characteristic.Mute)!
216✔
834
        .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
835
          callback(undefined, this.speakerMuted);
×
836
        })
837
        .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
838
          this.speakerMuted = value as boolean;
×
839
          callback();
×
840
          this.emitSpeakerChange();
×
841
        });
842
      this.speakerService.getCharacteristic(Characteristic.Volume)!
216✔
843
        .on(CharacteristicEventTypes.GET, (callback: CharacteristicGetCallback) => {
844
          callback(undefined, this.speakerVolume);
×
845
        })
846
        .on(CharacteristicEventTypes.SET, (value: CharacteristicValue, callback: CharacteristicSetCallback) => {
847
          this.speakerVolume = value as number;
×
848
          callback();
×
849
          this.emitSpeakerChange();
×
850
        });
851
    }
852

853
    // make the sensor services available to the RecordingManagement.
854
    if (this.motionService) {
216!
855
      this.recordingManagement?.sensorServices.push(this.motionService);
216✔
856
    }
857
    if (this.occupancyService) {
216!
858
      this.recordingManagement?.sensorServices.push(this.occupancyService);
216✔
859
    }
860
  }
861

862
  private rtpStreamManagementDisabledThroughOperatingMode(): boolean {
863
    return this.recordingManagement
×
864
      ? !this.recordingManagement.operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value
865
      : false;
866
  }
867

868

869
  /**
870
   * @private
871
   */
872
  handleControllerRemoved(): void {
873
    this.handleFactoryReset();
6✔
874

875
    for (const management of this.streamManagements) {
6✔
876
      management.destroy();
12✔
877
    }
878
    this.streamManagements.splice(0, this.streamManagements.length);
6✔
879

880
    this.microphoneService = undefined;
6✔
881
    this.speakerService = undefined;
6✔
882

883
    this.recordingManagement?.destroy();
6✔
884
    this.recordingManagement = undefined;
6✔
885

886
    this.removeAllListeners();
6✔
887
  }
888

889
  /**
890
   * @private
891
   */
892
  handleFactoryReset(): void {
893
    this.streamManagements.forEach(management => management.handleFactoryReset());
48✔
894
    this.recordingManagement?.handleFactoryReset();
24✔
895

896
    this.microphoneMuted = false;
24✔
897
    this.microphoneVolume = 100;
24✔
898
    this.speakerMuted = false;
24✔
899
    this.speakerVolume = 100;
24✔
900
  }
901

902
  /**
903
   * @private
904
   */
905
  serialize(): CameraControllerState | undefined {
906
    const streamManagementStates: RTPStreamManagementState[] = [];
48✔
907

908
    for (const management of this.streamManagements) {
48✔
909
      const serializedState = management.serialize();
96✔
910
      if (serializedState) {
96!
911
        streamManagementStates.push(serializedState);
96✔
912
      }
913
    }
914

915
    return {
48✔
916
      streamManagements: streamManagementStates,
917
      recordingManagement: this.recordingManagement?.serialize(),
918
    };
919
  }
920

921
  /**
922
   * @private
923
   */
924
  deserialize(serialized: CameraControllerState): void {
925
    for (const streamManagementState of serialized.streamManagements) {
24✔
926
      const streamManagement = this.streamManagements[streamManagementState.id];
36✔
927
      if (streamManagement) {
36!
928
        streamManagement.deserialize(streamManagementState);
36✔
929
      }
930
    }
931

932
    if (serialized.recordingManagement) {
24!
933
      if (this.recordingManagement) {
24!
934
        this.recordingManagement.deserialize(serialized.recordingManagement);
24✔
935
      } else {
936
        // Active characteristic cannot be controlled if removing HSV, ensure they are all active!
937
        for (const streamManagement of this.streamManagements) {
×
938
          streamManagement.service.updateCharacteristic(Characteristic.Active, true);
×
939
        }
940

941
        this.stateChangeDelegate?.();
×
942
      }
943
    }
944
  }
945

946
  /**
947
   * @private
948
   */
949
  setupStateChangeDelegate(delegate?: StateChangeDelegate): void {
950
    this.stateChangeDelegate = delegate;
27✔
951

952
    for (const streamManagement of this.streamManagements) {
27✔
953
      streamManagement.setupStateChangeDelegate(delegate);
54✔
954
    }
955

956
    this.recordingManagement?.setupStateChangeDelegate(delegate);
27✔
957
  }
958

959
  /**
960
   * @private
961
   */
962
  handleSnapshotRequest(height: number, width: number, accessoryName?: string, reason?: ResourceRequestReason): Promise<Buffer> {
963
    // first step is to verify that the reason is applicable to our current policy
964
    const streamingDisabled = this.streamManagements
174✔
965
      .map(management => !management.getService().getCharacteristic(Characteristic.Active).value)
348✔
966
      .reduce((previousValue, currentValue) => previousValue && currentValue);
174✔
967
    if (streamingDisabled) {
174✔
968
      debug("[%s] Rejecting snapshot as streaming is disabled.", accessoryName);
36✔
969
      return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE);
36✔
970
    }
971

972
    if (this.recordingManagement) {
138✔
973
      const operatingModeService = this.recordingManagement.operatingModeService;
135✔
974
      if (!operatingModeService.getCharacteristic(Characteristic.HomeKitCameraActive).value) {
135✔
975
        debug("[%s] Rejecting snapshot as HomeKit camera is disabled.", accessoryName);
39✔
976
        return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE);
39✔
977
      }
978

979
      const eventSnapshotsActive = operatingModeService
96✔
980
        .getCharacteristic(Characteristic.EventSnapshotsActive)
981
        .value;
982
      if (!eventSnapshotsActive) {
96✔
983
        if (reason == null) {
36✔
984
          debug("[%s] Rejecting snapshot as reason is required due to disabled event snapshots.", accessoryName);
12✔
985
          return Promise.reject(HAPStatus.INSUFFICIENT_PRIVILEGES);
12✔
986
        } else if (reason === ResourceRequestReason.EVENT) {
24✔
987
          debug("[%s] Rejecting snapshot as even snapshots are disabled.", accessoryName);
12✔
988
          return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE);
12✔
989
        }
990
      }
991

992
      const periodicSnapshotsActive = operatingModeService
72✔
993
        .getCharacteristic(Characteristic.PeriodicSnapshotsActive)
994
        .value;
995
      if (!periodicSnapshotsActive) {
72✔
996
        if (reason == null) {
36✔
997
          debug("[%s] Rejecting snapshot as reason is required due to disabled periodic snapshots.", accessoryName);
12✔
998
          return Promise.reject(HAPStatus.INSUFFICIENT_PRIVILEGES);
12✔
999
        } else if (reason === ResourceRequestReason.PERIODIC) {
24✔
1000
          debug("[%s] Rejecting snapshot as periodic snapshots are disabled.", accessoryName);
12✔
1001
          return Promise.reject(HAPStatus.NOT_ALLOWED_IN_CURRENT_STATE);
12✔
1002
        }
1003
      }
1004
    }
1005

1006
    // now do the actual snapshot request.
1007
    return new Promise((resolve, reject) => {
51✔
1008
      // TODO test and make timeouts configurable!
1009
      let timeout: NodeJS.Timeout | undefined = setTimeout(() => {
51✔
1010
        console.warn(
×
1011
          `[${accessoryName}] The image snapshot handler for the given accessory is slow to respond! See https://homebridge.io/w/JtMGR for more info.`,
1012
        );
1013

1014
        timeout = setTimeout(() => {
×
1015
          timeout = undefined;
×
1016

1017
          console.warn(
×
1018
            `[${accessoryName}] The image snapshot handler for the given accessory didn't respond at all! See https://homebridge.io/w/JtMGR for more info.`,
1019
          );
1020

1021
          reject(HAPStatus.OPERATION_TIMED_OUT);
×
1022
        }, 17000);
1023
        timeout.unref();
×
1024
      }, 8000);
1025
      timeout.unref();
51✔
1026

1027
      try {
51✔
1028
        this.delegate.handleSnapshotRequest({
51✔
1029
          height: height,
1030
          width: width,
1031
          reason: reason,
1032
        }, (error, buffer) => {
1033
          if (!timeout) {
51!
1034
            return;
×
1035
          } else {
1036
            clearTimeout(timeout);
51✔
1037
            timeout = undefined;
51✔
1038
          }
1039

1040
          if (error) {
51!
1041
            if (typeof error === "number") {
×
1042
              reject(error);
×
1043
            } else {
1044
              debug("[%s] Error getting snapshot: %s", accessoryName, error.stack);
×
1045
              reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
×
1046
            }
1047
            return;
×
1048
          }
1049

1050
          if (!buffer || buffer.length === 0) {
51!
1051
            console.warn(`[${accessoryName}] Snapshot request handler provided empty image buffer!`);
×
1052
            reject(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
×
1053
          } else {
1054
            resolve(buffer);
51✔
1055
          }
1056
        });
1057
      } catch (error) {
1058
        if (!timeout) {
×
1059
          return;
×
1060
        } else {
1061
          clearTimeout(timeout);
×
1062
          timeout = undefined;
×
1063
        }
1064

1065
        console.warn(`[${accessoryName}] Unhandled error thrown inside snapshot request handler: ${error.stack}`);
×
1066
        reject(error instanceof HapStatusError ? error.hapStatus : HAPStatus.SERVICE_COMMUNICATION_FAILURE);
×
1067
      }
1068
    });
1069
  }
1070
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc