diff --git a/plugins/homekit/src/camera-mixin.ts b/plugins/homekit/src/camera-mixin.ts index a3aae3fa8d..94c4223e64 100644 --- a/plugins/homekit/src/camera-mixin.ts +++ b/plugins/homekit/src/camera-mixin.ts @@ -160,6 +160,17 @@ ${this.storageSettings.values.qrCode} }); } + if (this.interfaces.includes(ScryptedInterface.PrivacyMode) + && (this.interfaces.includes(ScryptedInterface.MotionSensor) || this.cameraStorageSettings.values.secureVideo3)) { + settings.push({ + title: 'Camera Privacy Mode', + description: 'Link the camera\'s on/off in the Home app to the camera\'s privacy mode. Turning the camera off in the Home app, or a Home/Away mode set to Off, turns the camera itself off for every client. Home hubs reapply the Home app\'s camera mode when they reconnect, so a change made elsewhere (the camera\'s own app) lasts until then. Requires HomeKit Secure Video recording.', + key: 'privacyMode', + value: this.storage.getItem('privacyMode') === 'true', + type: 'boolean', + }); + } + return [...await super.getMixinSettings(), ...settings, ...await this.cameraStorageSettings.getSettings()]; } @@ -171,6 +182,7 @@ ${this.storageSettings.values.qrCode} return this.cameraStorageSettings.putSetting(key, value); } + const oldValue = this.storage.getItem(key); if (key === 'debugMode') { this.storage.setItem(key, JSON.stringify(value)); } @@ -178,6 +190,10 @@ ${this.storageSettings.values.qrCode} this.storage.setItem(key, value?.toString() || ''); } + // privacy mode is bound when the accessory is created. + if (key === 'privacyMode' && oldValue !== this.storage.getItem(key)) + this.alertReload(); + deviceManager.onMixinEvent(this.id, this, ScryptedInterface.Settings, undefined); } } diff --git a/plugins/homekit/src/types/camera.ts b/plugins/homekit/src/types/camera.ts index 3ec6ff4ae2..47015a17f7 100644 --- a/plugins/homekit/src/types/camera.ts +++ b/plugins/homekit/src/types/camera.ts @@ -1,8 +1,8 @@ import type { Resolution, RTCSignalingChannel } from '@scrypted/sdk'; -import sdk, { AudioSensor, Camera, DeviceProvider, Intercom, MotionSensor, OnOff, ScryptedDevice, ScryptedDeviceType, ScryptedInterface, VideoCamera, VideoCameraConfiguration } from '@scrypted/sdk'; +import sdk, { AudioSensor, Camera, DeviceProvider, Intercom, MotionSensor, OnOff, PrivacyMode, ScryptedDevice, ScryptedDeviceType, ScryptedInterface, VideoCamera, VideoCameraConfiguration } from '@scrypted/sdk'; import { createCameraStorageSettings } from '../camera-mixin'; import { DummyDevice, addSupportedType, bindCharacteristic } from '../common'; -import { AudioRecordingCodec, AudioRecordingCodecType, AudioRecordingSamplerate, AudioStreamingCodec, AudioStreamingCodecType, AudioStreamingSamplerate, CameraController, CameraRecordingConfiguration, CameraRecordingDelegate, CameraRecordingOptions, CameraStreamingOptions, Characteristic, CharacteristicEventTypes, H264Level, H264Profile, MediaContainerType, RecordingPacket, SRTPCryptoSuites, SecureVideoController, Service, VideoCodecType, WithUUID } from '../hap'; +import { AudioRecordingCodec, AudioRecordingCodecType, AudioRecordingSamplerate, AudioStreamingCodec, AudioStreamingCodecType, AudioStreamingSamplerate, CameraController, CameraRecordingConfiguration, CameraRecordingDelegate, CameraRecordingOptions, CameraStreamingOptions, ChangeReason, Characteristic, CharacteristicEventTypes, H264Level, H264Profile, MediaContainerType, RecordingPacket, SRTPCryptoSuites, SecureVideoController, Service, VideoCodecType, WithUUID } from '../hap'; import type { HomeKitPlugin } from '../main'; import { setServiceName } from '../service-names'; import { createMultiTierRtpDelegate } from './camera/camera-multitier-rtp'; @@ -22,7 +22,7 @@ addSupportedType({ probe(device: DummyDevice) { return device.interfaces.includes(ScryptedInterface.VideoCamera); }, - async getAccessory(device: ScryptedDevice & VideoCamera & VideoCameraConfiguration & Camera & MotionSensor & AudioSensor & Intercom & OnOff & Resolution, homekitPlugin: HomeKitPlugin) { + async getAccessory(device: ScryptedDevice & VideoCamera & VideoCameraConfiguration & Camera & MotionSensor & AudioSensor & Intercom & OnOff & PrivacyMode & Resolution, homekitPlugin: HomeKitPlugin) { const console = deviceManager.getMixinConsole(device.id, undefined); const storage = deviceManager.getMixinStorage(device.id, undefined); const cameraStorage = createCameraStorageSettings({ storage, onDeviceEvent: undefined }); @@ -280,6 +280,15 @@ addSupportedType({ } } + // HSV3 gates streaming on its global operating mode and snapshots/recording on the recording + // one, and configures recording without a motion sensor, so bind every one that exists. + const operatingModeServices = [ + controller instanceof SecureVideoController ? controller.globalOperatingModeService : undefined, + controller.recordingManagement?.operatingModeService, + ].filter((service): service is Service => !!service); + if (operatingModeServices.length && device.interfaces.includes(ScryptedInterface.PrivacyMode) && storage.getItem('privacyMode') === 'true') + bindPrivacyMode(device, operatingModeServices, console); + // if the camera is a device provider, merge in child devices and // ensure the devices are skipped by the rest of homekit by // reporting that they've been merged @@ -298,3 +307,96 @@ addSupportedType({ return accessory; } }); + +/** + * Bind HomeKitCameraActive (the camera's own on/off in the Home app, also driven by + * the Home/Away camera modes) to the camera's privacy mode: privacy mode on means inactive. + */ +function bindPrivacyMode(device: ScryptedDevice & PrivacyMode, operatingModeServices: Service[], console: Console) { + const characteristics = operatingModeServices.map(service => service.getCharacteristic(Characteristic.HomeKitCameraActive)); + + // The value last applied, shown until the camera reports it, since its state event can trail + // the call. Bounded in time, so a lost event can't hide later changes made elsewhere. + let pending: boolean | undefined; + let target: boolean | undefined; + let pendingTimeout: NodeJS.Timeout | undefined; + // Show the newest intended state: a queued write, then one awaiting its event, then the device. + const isActive = () => !(target ?? pending ?? device.privacyMode); + // Only on a real change: every update persists HAP controller state and, under HSV3, re-runs the + // operating mode listeners. + const sync = () => characteristics.forEach(c => { + if (!!c.value !== isActive()) + c.updateValue(isActive()); + }); + const setPending = (value: boolean | undefined) => { + pending = value; + clearTimeout(pendingTimeout); + if (value !== undefined) + pendingTimeout = setTimeout(() => setPending(undefined), 30000); + sync(); + }; + + // Switching can be slow (a round trip to the camera), so answer HAP right away and apply in + // the background, one change at a time, ending on the latest write. Every write is applied, + // including the mode hubs re-send on each connection: skipping writes that look redundant + // against the camera's possibly lagging state can drop a real change. + let applying = false; + let events = 0; + const apply = async () => { + applying = true; + while (target !== undefined) { + const privacyMode = target; + target = undefined; + const eventsBefore = events; + const previous = pending; + setPending(privacyMode); + const start = Date.now(); + try { + await device.setPrivacyMode(privacyMode); + console.log(`privacy mode ${privacyMode ? 'on' : 'off'} (${Date.now() - start} ms)`); + // Confirmed only by an event during the call; a cached value that matches may be stale. + const confirmed = events !== eventsBefore && device.privacyMode === privacyMode; + setPending(confirmed ? undefined : privacyMode); + } + catch (e) { + console.error('failed to set privacy mode', e); + // Fall back to any earlier applied value still awaiting its event. + setPending(previous); + } + } + applying = false; + }; + + for (const active of characteristics) { + active.on(CharacteristicEventTypes.SET, (value, callback) => { + callback(); + target = !value; + if (!applying) + apply(); + else + // Mirror a queued write onto the other operating mode now; HSV3 gates streaming + // and recording separately and the in-flight call may take a while. + sync(); + }); + + // HAP restores its persisted value when controller storage loads; the camera is the source + // of truth. Re-sync once the restore finishes, since it sets the sensors' StatusActive last. + // The characteristic is a uint8, so compare as booleans. + active.on(CharacteristicEventTypes.CHANGE, change => { + if (change.reason !== ChangeReason.WRITE && !!change.newValue !== isActive()) + setImmediate(() => { + if (!!active.value !== isActive()) + sync(); + }); + }); + } + + device.listen(ScryptedInterface.PrivacyMode, () => { + events++; + if (device.privacyMode === pending) + setPending(undefined); + else + sync(); + }); + sync(); +} diff --git a/sdk/types/scrypted_python/scrypted_sdk/types.py b/sdk/types/scrypted_python/scrypted_sdk/types.py index a2825fe966..886aa318a7 100644 --- a/sdk/types/scrypted_python/scrypted_sdk/types.py +++ b/sdk/types/scrypted_python/scrypted_sdk/types.py @@ -177,6 +177,7 @@ class ScryptedInterface(str, Enum): PositionSensor = "PositionSensor" PowerSensor = "PowerSensor" PressButtons = "PressButtons" + PrivacyMode = "PrivacyMode" Program = "Program" PushHandler = "PushHandler" Readme = "Readme" @@ -1584,6 +1585,14 @@ async def pressButton(self, button: str) -> None: pass +class PrivacyMode: + """PrivacyMode turns the camera itself off: it stops capturing and streaming video for every client, as opposed to a client choosing not to view or record it.""" + + privacyMode: bool # True when the camera is turned off. + async def setPrivacyMode(self, privacyMode: bool) -> None: + pass + + class Program: async def run(self, variables: Any = None) -> Any: @@ -2115,6 +2124,7 @@ class ScryptedInterfaceProperty(str, Enum): audioVolumes = "audioVolumes" recordingActive = "recordingActive" ptzCapabilities = "ptzCapabilities" + privacyMode = "privacyMode" lockState = "lockState" entryOpen = "entryOpen" batteryLevel = "batteryLevel" @@ -2195,6 +2205,7 @@ class ScryptedInterfaceMethods(str, Enum): deleteRecordingStream = "deleteRecordingStream" setRecordingActive = "setRecordingActive" ptzCommand = "ptzCommand" + setPrivacyMode = "setPrivacyMode" getRecordedEvents = "getRecordedEvents" getVideoClip = "getVideoClip" getVideoClips = "getVideoClips" @@ -2533,6 +2544,14 @@ def ptzCapabilities(self) -> PanTiltZoomCapabilities: def ptzCapabilities(self, value: PanTiltZoomCapabilities): self.setScryptedProperty("ptzCapabilities", value) + @property + def privacyMode(self) -> bool: + return self.getScryptedProperty("privacyMode") + + @privacyMode.setter + def privacyMode(self, value: bool): + self.setScryptedProperty("privacyMode", value) + @property def lockState(self) -> LockState: return self.getScryptedProperty("lockState") @@ -3078,6 +3097,15 @@ def systemDevice(self, value: ScryptedSystemDeviceInfo): "ptzCapabilities" ] }, + "PrivacyMode": { + "name": "PrivacyMode", + "methods": [ + "setPrivacyMode" + ], + "properties": [ + "privacyMode" + ] + }, "EventRecorder": { "name": "EventRecorder", "methods": [ diff --git a/sdk/types/src/types.input.ts b/sdk/types/src/types.input.ts index 5ba766d77f..fa07a04fb6 100644 --- a/sdk/types/src/types.input.ts +++ b/sdk/types/src/types.input.ts @@ -1129,6 +1129,19 @@ export interface PanTiltZoom { ptzCommand(command: PanTiltZoomCommand): Promise; } +/** + * PrivacyMode turns the camera itself off: it stops capturing and streaming video for every client, + * as opposed to a client choosing not to view or record it. + */ +export interface PrivacyMode { + /** + * True when the camera is turned off. + */ + privacyMode?: boolean; + + setPrivacyMode(privacyMode: boolean): Promise; +} + /** * Display devices can play back audio and video. */ @@ -2409,6 +2422,7 @@ export enum ScryptedInterface { VideoRecorder = "VideoRecorder", VideoRecorderManagement = "VideoRecorderManagement", PanTiltZoom = "PanTiltZoom", + PrivacyMode = "PrivacyMode", EventRecorder = "EventRecorder", VideoClips = "VideoClips", VideoCameraConfiguration = "VideoCameraConfiguration",