Use custom websocket to avoid needing admin privileges.
This commit is contained in:
@@ -2,19 +2,23 @@ import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { localize } from '../../localize/localize';
|
||||
import { EntityRegistryManager } from '../../utils/ha/entity-registry';
|
||||
import { Entity } from '../../utils/ha/entity-registry/types';
|
||||
import { Camera } from '../camera';
|
||||
import { Camera, CameraInitializationOptions } from '../camera';
|
||||
import { CameraInitializationError } from '../error';
|
||||
|
||||
interface BrowseMediaCameraInitializationOptions extends CameraInitializationOptions {
|
||||
entityRegistryManager: EntityRegistryManager;
|
||||
hass: HomeAssistant;
|
||||
}
|
||||
|
||||
export class BrowseMediaCamera extends Camera {
|
||||
protected _entity: Entity | null = null;
|
||||
|
||||
public async initialize(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
options: BrowseMediaCameraInitializationOptions,
|
||||
): Promise<Camera> {
|
||||
const config = this.getConfig();
|
||||
const entity = config.camera_entity
|
||||
? await entityRegistryManager.getEntity(hass, config.camera_entity)
|
||||
? await options.entityRegistryManager.getEntity(options.hass, config.camera_entity)
|
||||
: null;
|
||||
|
||||
if (!entity || !config.camera_entity) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { StateWatcherSubscriptionInterface } from '../../card-controller/hass/state-watcher';
|
||||
import { CameraConfig } from '../../config/types';
|
||||
import { ExtendedHomeAssistant } from '../../types';
|
||||
import { canonicalizeHAURL } from '../../utils/ha';
|
||||
@@ -28,10 +29,10 @@ import {
|
||||
PartialEventQuery,
|
||||
QueryType,
|
||||
} from '../types';
|
||||
import { getPTZCapabilitiesFromCameraConfig } from '../utils/ptz';
|
||||
import { BrowseMediaCamera } from './camera';
|
||||
import { BrowseMediaViewMediaFactory } from './media';
|
||||
import { BrowseMediaMetadata } from './types';
|
||||
import { getPTZCapabilitiesFromCameraConfig } from '../utils/ptz';
|
||||
|
||||
/**
|
||||
* A utility method to determine if a browse media object matches against a
|
||||
@@ -123,16 +124,20 @@ export class BrowseMediaCameraManagerEngine
|
||||
implements CameraManagerEngine
|
||||
{
|
||||
protected _browseMediaManager: BrowseMediaManager<BrowseMediaMetadata>;
|
||||
protected _entityRegistryManager: EntityRegistryManager;
|
||||
protected _resolvedMediaCache: ResolvedMediaCache;
|
||||
protected _requestCache: RequestCache;
|
||||
|
||||
public constructor(
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
stateWatcher: StateWatcherSubscriptionInterface,
|
||||
browseMediaManager: BrowseMediaManager<BrowseMediaMetadata>,
|
||||
resolvedMediaCache: ResolvedMediaCache,
|
||||
requestCache: RequestCache,
|
||||
eventCallback?: CameraEventCallback,
|
||||
) {
|
||||
super(eventCallback);
|
||||
super(stateWatcher, eventCallback);
|
||||
this._entityRegistryManager = entityRegistryManager;
|
||||
this._browseMediaManager = browseMediaManager;
|
||||
this._resolvedMediaCache = resolvedMediaCache;
|
||||
this._requestCache = requestCache;
|
||||
@@ -140,7 +145,6 @@ export class BrowseMediaCameraManagerEngine
|
||||
|
||||
public async createCamera(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
cameraConfig: CameraConfig,
|
||||
): Promise<Camera> {
|
||||
const camera = new BrowseMediaCamera(cameraConfig, this, {
|
||||
@@ -164,7 +168,11 @@ export class BrowseMediaCameraManagerEngine
|
||||
),
|
||||
eventCallback: this._eventCallback,
|
||||
});
|
||||
return await camera.initialize(hass, entityRegistryManager);
|
||||
return await camera.initialize({
|
||||
entityRegistryManager: this._entityRegistryManager,
|
||||
hass,
|
||||
stateWatcher: this._stateWatcher,
|
||||
});
|
||||
}
|
||||
|
||||
public generateDefaultEventQuery(
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { StateWatcherSubscriptionInterface } from '../card-controller/hass/state-watcher';
|
||||
import { CameraConfig } from '../config/types';
|
||||
import { localize } from '../localize/localize';
|
||||
import { allPromises } from '../utils/basic';
|
||||
import {
|
||||
DestroyCallback,
|
||||
isTriggeredState,
|
||||
parseStateChangeTrigger,
|
||||
subscribeToTrigger,
|
||||
} from '../utils/ha';
|
||||
import { EntityRegistryManager } from '../utils/ha/entity-registry';
|
||||
import { HassStateDifference, isTriggeredState } from '../utils/ha';
|
||||
import { Capabilities } from './capabilities';
|
||||
import { CameraManagerEngine } from './engine';
|
||||
import { CameraNoIDError } from './error';
|
||||
import { CameraEventCallback } from './types';
|
||||
|
||||
export interface CameraInitializationOptions {
|
||||
stateWatcher: StateWatcherSubscriptionInterface;
|
||||
}
|
||||
type DestroyCallback = () => void | Promise<void>;
|
||||
|
||||
export class Camera {
|
||||
protected _config: CameraConfig;
|
||||
protected _engine: CameraManagerEngine;
|
||||
@@ -35,47 +33,17 @@ export class Camera {
|
||||
this._eventCallback = options?.eventCallback;
|
||||
}
|
||||
|
||||
protected async _convertStateChangeToCameraEvent(data: unknown): Promise<void> {
|
||||
const stateChange = parseStateChangeTrigger(data);
|
||||
if (!stateChange) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._eventCallback?.({
|
||||
cameraID: this.getID(),
|
||||
type: isTriggeredState(stateChange.to_state.state) ? 'new' : 'end',
|
||||
});
|
||||
}
|
||||
|
||||
protected async _subscribeToTriggerEntities(hass: HomeAssistant): Promise<void> {
|
||||
if (!this._config.triggers.entities.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._destroyCallbacks.push(
|
||||
await subscribeToTrigger(
|
||||
hass,
|
||||
(data) => this._convertStateChangeToCameraEvent(data),
|
||||
{
|
||||
entityID: this._config.triggers.entities,
|
||||
platform: 'state',
|
||||
stateOnly: true,
|
||||
},
|
||||
),
|
||||
async initialize(options: CameraInitializationOptions): Promise<Camera> {
|
||||
options.stateWatcher.subscribe(
|
||||
this._stateChangeHandler,
|
||||
this._config.triggers.entities,
|
||||
);
|
||||
}
|
||||
|
||||
async initialize(
|
||||
hass: HomeAssistant,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_entityRegistryManager: EntityRegistryManager,
|
||||
): Promise<Camera> {
|
||||
await this._subscribeToTriggerEntities(hass);
|
||||
this._onDestroy(() => options.stateWatcher.unsubscribe(this._stateChangeHandler));
|
||||
return this;
|
||||
}
|
||||
|
||||
async destroy(): Promise<void> {
|
||||
await allPromises(this._destroyCallbacks, (cb) => cb());
|
||||
public async destroy(): Promise<void> {
|
||||
this._destroyCallbacks.forEach((callback) => callback());
|
||||
}
|
||||
|
||||
public getConfig(): CameraConfig {
|
||||
@@ -100,4 +68,15 @@ export class Camera {
|
||||
public getCapabilities(): Capabilities | null {
|
||||
return this._capabilities ?? null;
|
||||
}
|
||||
|
||||
protected _stateChangeHandler = (difference: HassStateDifference): void => {
|
||||
this._eventCallback?.({
|
||||
cameraID: this.getID(),
|
||||
type: isTriggeredState(difference.newState.state) ? 'new' : 'end',
|
||||
});
|
||||
};
|
||||
|
||||
protected _onDestroy(callback: DestroyCallback): void {
|
||||
this._destroyCallbacks.push(callback);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { StateWatcherSubscriptionInterface } from '../card-controller/hass/state-watcher';
|
||||
import { CameraConfig } from '../config/types';
|
||||
import { localize } from '../localize/localize';
|
||||
import { BrowseMediaManager } from '../utils/ha/browse-media/browse-media-manager';
|
||||
@@ -12,34 +13,41 @@ import { CameraInitializationError } from './error';
|
||||
import { CameraEventCallback, Engine } from './types';
|
||||
import { getCameraEntityFromConfig } from './utils/camera-entity-from-config';
|
||||
|
||||
export class CameraManagerEngineFactory {
|
||||
protected _entityRegistryManager: EntityRegistryManager;
|
||||
protected _resolvedMediaCache: ResolvedMediaCache;
|
||||
interface CameraManagerEngineFactoryOptions {
|
||||
stateWatcher: StateWatcherSubscriptionInterface;
|
||||
resolvedMediaCache: ResolvedMediaCache;
|
||||
eventCallback?: CameraEventCallback;
|
||||
}
|
||||
|
||||
constructor(
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
resolvedMediaCache: ResolvedMediaCache,
|
||||
) {
|
||||
export class CameraManagerEngineFactory {
|
||||
// Entity registry manager is required for the actual function of the factory.
|
||||
protected _entityRegistryManager: EntityRegistryManager;
|
||||
|
||||
constructor(entityRegistryManager: EntityRegistryManager) {
|
||||
this._entityRegistryManager = entityRegistryManager;
|
||||
this._resolvedMediaCache = resolvedMediaCache;
|
||||
}
|
||||
|
||||
public async createEngine(
|
||||
engine: Engine,
|
||||
eventCallback?: CameraEventCallback,
|
||||
options: CameraManagerEngineFactoryOptions,
|
||||
): Promise<CameraManagerEngine> {
|
||||
let cameraManagerEngine: CameraManagerEngine;
|
||||
switch (engine) {
|
||||
case Engine.Generic:
|
||||
const { GenericCameraManagerEngine } = await import('./generic/engine-generic');
|
||||
cameraManagerEngine = new GenericCameraManagerEngine(eventCallback);
|
||||
cameraManagerEngine = new GenericCameraManagerEngine(
|
||||
options.stateWatcher,
|
||||
options.eventCallback,
|
||||
);
|
||||
break;
|
||||
case Engine.Frigate:
|
||||
const { FrigateCameraManagerEngine } = await import('./frigate/engine-frigate');
|
||||
cameraManagerEngine = new FrigateCameraManagerEngine(
|
||||
this._entityRegistryManager,
|
||||
options.stateWatcher,
|
||||
new RecordingSegmentsCache(),
|
||||
new RequestCache(),
|
||||
eventCallback,
|
||||
options.eventCallback,
|
||||
);
|
||||
break;
|
||||
case Engine.MotionEye:
|
||||
@@ -47,10 +55,12 @@ export class CameraManagerEngineFactory {
|
||||
'./motioneye/engine-motioneye'
|
||||
);
|
||||
cameraManagerEngine = new MotionEyeCameraManagerEngine(
|
||||
this._entityRegistryManager,
|
||||
options.stateWatcher,
|
||||
new BrowseMediaManager(new MemoryRequestCache<string, BrowseMedia>()),
|
||||
this._resolvedMediaCache,
|
||||
options.resolvedMediaCache,
|
||||
new RequestCache(),
|
||||
eventCallback,
|
||||
options.eventCallback,
|
||||
);
|
||||
}
|
||||
return cameraManagerEngine;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { CameraConfig, ActionPhase } from '../config/types';
|
||||
import { PTZAction } from '../config/ptz';
|
||||
import { ActionPhase, CameraConfig } from '../config/types';
|
||||
import { ExtendedHomeAssistant } from '../types';
|
||||
import { EntityRegistryManager } from '../utils/ha/entity-registry';
|
||||
import { ViewMedia } from '../view/media';
|
||||
import { Camera } from './camera';
|
||||
import { CameraManagerReadOnlyConfigStore } from './store';
|
||||
@@ -27,18 +27,13 @@ import {
|
||||
RecordingSegmentsQuery,
|
||||
RecordingSegmentsQueryResultsMap,
|
||||
} from './types';
|
||||
import { PTZAction } from '../config/ptz';
|
||||
|
||||
export const CAMERA_MANAGER_ENGINE_EVENT_LIMIT_DEFAULT = 10000;
|
||||
|
||||
export interface CameraManagerEngine {
|
||||
getEngineType(): Engine;
|
||||
|
||||
createCamera(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
cameraConfig: CameraConfig,
|
||||
): Promise<Camera>;
|
||||
createCamera(hass: HomeAssistant, cameraConfig: CameraConfig): Promise<Camera>;
|
||||
|
||||
generateDefaultEventQuery(
|
||||
store: CameraManagerReadOnlyConfigStore,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import uniq from 'lodash-es/uniq';
|
||||
import { StateWatcherSubscriptionInterface } from '../../card-controller/hass/state-watcher';
|
||||
import { CameraConfig } from '../../config/types';
|
||||
import { localize } from '../../localize/localize';
|
||||
import { PTZCapabilities, PTZMovementType } from '../../types';
|
||||
@@ -7,32 +8,52 @@ import {
|
||||
errorToConsole,
|
||||
recursivelyMergeObjectsConcatenatingArraysUniquely,
|
||||
} from '../../utils/basic';
|
||||
import { subscribeToTrigger } from '../../utils/ha';
|
||||
import { EntityRegistryManager } from '../../utils/ha/entity-registry';
|
||||
import { Entity } from '../../utils/ha/entity-registry/types';
|
||||
import { Camera } from '../camera';
|
||||
import { Camera, CameraInitializationOptions } from '../camera';
|
||||
import { Capabilities } from '../capabilities';
|
||||
import { CameraManagerEngine } from '../engine';
|
||||
import { CameraInitializationError } from '../error';
|
||||
import { CameraEventCallback } from '../types';
|
||||
import { getCameraEntityFromConfig } from '../utils/camera-entity-from-config';
|
||||
import { getPTZInfo } from './requests';
|
||||
import { PTZInfo, frigateEventChangeTriggerResponseSchema } from './types';
|
||||
import { getPTZCapabilitiesFromCameraConfig } from '../utils/ptz';
|
||||
import {
|
||||
FrigateEventWatcherRequest,
|
||||
FrigateEventWatcherSubscriptionInterface,
|
||||
} from './event-watcher';
|
||||
import { getPTZInfo } from './requests';
|
||||
import { FrigateEventChange, PTZInfo } from './types';
|
||||
|
||||
const CAMERA_BIRDSEYE = 'birdseye' as const;
|
||||
|
||||
interface FrigateCameraInitializationOptions extends CameraInitializationOptions {
|
||||
entityRegistryManager: EntityRegistryManager;
|
||||
frigateEventWatcher: FrigateEventWatcherSubscriptionInterface;
|
||||
hass: HomeAssistant;
|
||||
stateWatcher: StateWatcherSubscriptionInterface;
|
||||
}
|
||||
|
||||
export const isBirdseye = (cameraConfig: CameraConfig): boolean => {
|
||||
return cameraConfig.frigate.camera_name === CAMERA_BIRDSEYE;
|
||||
};
|
||||
|
||||
export class FrigateCamera extends Camera {
|
||||
public async initialize(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
): Promise<Camera> {
|
||||
await this._initializeConfig(hass, entityRegistryManager);
|
||||
await this._initializeCapabilities(hass);
|
||||
await this._subscribeToEvents(hass);
|
||||
return await super.initialize(hass, entityRegistryManager);
|
||||
constructor(
|
||||
config: CameraConfig,
|
||||
engine: CameraManagerEngine,
|
||||
options?: {
|
||||
capabilities?: Capabilities;
|
||||
eventCallback?: CameraEventCallback;
|
||||
},
|
||||
) {
|
||||
super(config, engine, options);
|
||||
}
|
||||
|
||||
public async initialize(options: FrigateCameraInitializationOptions): Promise<Camera> {
|
||||
await this._initializeConfig(options.hass, options.entityRegistryManager);
|
||||
await this._initializeCapabilities(options.hass);
|
||||
await this._subscribeToEvents(options.hass, options.frigateEventWatcher);
|
||||
return await super.initialize(options);
|
||||
}
|
||||
|
||||
protected async _initializeConfig(
|
||||
@@ -266,49 +287,39 @@ export class FrigateCamera extends Camera {
|
||||
return null;
|
||||
}
|
||||
|
||||
protected async _subscribeToEvents(hass: HomeAssistant): Promise<void> {
|
||||
protected async _subscribeToEvents(
|
||||
hass: HomeAssistant,
|
||||
frigateEventWatcher: FrigateEventWatcherSubscriptionInterface,
|
||||
): Promise<void> {
|
||||
const config = this.getConfig();
|
||||
if (!config.triggers.events.length || !config.frigate.camera_name) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._destroyCallbacks.push(
|
||||
await subscribeToTrigger(hass, (ev) => this._handleEventChange(ev), {
|
||||
platform: 'mqtt',
|
||||
topic: `${config.frigate.client_id}/events`,
|
||||
/* istanbul ignore next -- exercising the matcher is not possible when the
|
||||
test uses an event watcher -- @preserve */
|
||||
const request: FrigateEventWatcherRequest = {
|
||||
instanceID: config.frigate.client_id,
|
||||
callback: (event: FrigateEventChange) => this._frigateEventHandler(event),
|
||||
matcher: (event: FrigateEventChange): boolean =>
|
||||
event.after.camera === config.frigate.camera_name,
|
||||
};
|
||||
|
||||
// Only trigger for events pertaining to this camera.
|
||||
payload: config.frigate.camera_name,
|
||||
valueTemplate: '{{ value_json.after.camera }}',
|
||||
}),
|
||||
);
|
||||
await frigateEventWatcher.subscribe(hass, request);
|
||||
this._onDestroy(() => frigateEventWatcher.unsubscribe(request));
|
||||
}
|
||||
|
||||
protected _handleEventChange(ev: unknown): void {
|
||||
const parseResult = frigateEventChangeTriggerResponseSchema.safeParse(ev);
|
||||
if (!parseResult.success) {
|
||||
console.warn('Ignoring unparseable Frigate event', ev);
|
||||
return;
|
||||
}
|
||||
|
||||
const change = parseResult.data.variables.trigger.payload_json;
|
||||
protected _frigateEventHandler = (ev: FrigateEventChange): void => {
|
||||
const snapshotChange =
|
||||
(!change.before.has_snapshot && change.after.has_snapshot) ||
|
||||
change.before.snapshot?.frame_time !== change.after.snapshot?.frame_time;
|
||||
const clipChange = !change.before.has_clip && change.after.has_clip;
|
||||
(!ev.before.has_snapshot && ev.after.has_snapshot) ||
|
||||
ev.before.snapshot?.frame_time !== ev.after.snapshot?.frame_time;
|
||||
const clipChange = !ev.before.has_clip && ev.after.has_clip;
|
||||
|
||||
const config = this.getConfig();
|
||||
if (config.frigate.camera_name !== change.after.camera) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
(config.frigate.zones?.length &&
|
||||
!config.frigate.zones.some((zone) =>
|
||||
change.after.current_zones.includes(zone),
|
||||
)) ||
|
||||
(config.frigate.labels?.length &&
|
||||
!config.frigate.labels.includes(change.after.label))
|
||||
!config.frigate.zones.some((zone) => ev.after.current_zones.includes(zone))) ||
|
||||
(config.frigate.labels?.length && !config.frigate.labels.includes(ev.after.label))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -327,11 +338,11 @@ export class FrigateCamera extends Camera {
|
||||
this._eventCallback?.({
|
||||
fidelity: 'high',
|
||||
cameraID: this.getID(),
|
||||
type: change.type,
|
||||
type: ev.type,
|
||||
// In cases where there are both clip and snapshot media, ensure to only
|
||||
// trigger on the media type that is allowed by the configuration.
|
||||
clip: clipChange && eventsToTriggerOn.includes('clips'),
|
||||
snapshot: snapshotChange && eventsToTriggerOn.includes('snapshots'),
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import isEqual from 'lodash-es/isEqual';
|
||||
import orderBy from 'lodash-es/orderBy';
|
||||
import throttle from 'lodash-es/throttle';
|
||||
import uniqWith from 'lodash-es/uniqWith';
|
||||
import { StateWatcherSubscriptionInterface } from '../../card-controller/hass/state-watcher';
|
||||
import { PTZAction } from '../../config/ptz';
|
||||
import { ActionPhase, CameraConfig } from '../../config/types';
|
||||
import { ExtendedHomeAssistant } from '../../types';
|
||||
@@ -20,8 +21,8 @@ import { ViewMediaClassifier } from '../../view/media-classifier';
|
||||
import { RecordingSegmentsCache, RequestCache } from '../cache';
|
||||
import { Camera } from '../camera';
|
||||
import {
|
||||
CameraManagerEngine,
|
||||
CAMERA_MANAGER_ENGINE_EVENT_LIMIT_DEFAULT,
|
||||
CameraManagerEngine,
|
||||
} from '../engine';
|
||||
import { GenericCameraManagerEngine } from '../generic/engine-generic';
|
||||
import { DateRange } from '../range';
|
||||
@@ -59,15 +60,16 @@ import {
|
||||
import { getDefaultGo2RTCEndpoint } from '../utils/go2rtc-endpoint';
|
||||
import frigateLogo from './assets/frigate-logo-dark.svg';
|
||||
import { FrigateCamera, isBirdseye } from './camera';
|
||||
import { FrigateEventWatcher } from './event-watcher';
|
||||
import { FrigateViewMediaFactory } from './media';
|
||||
import { FrigateViewMediaClassifier } from './media-classifier';
|
||||
import {
|
||||
getEvents,
|
||||
getEventSummary,
|
||||
getRecordingSegments,
|
||||
getRecordingsSummary,
|
||||
NativeFrigateEventQuery,
|
||||
NativeFrigateRecordingSegmentsQuery,
|
||||
getEventSummary,
|
||||
getEvents,
|
||||
getRecordingSegments,
|
||||
getRecordingsSummary,
|
||||
retainEvent,
|
||||
} from './requests';
|
||||
import {
|
||||
@@ -110,6 +112,8 @@ export class FrigateCameraManagerEngine
|
||||
extends GenericCameraManagerEngine
|
||||
implements CameraManagerEngine
|
||||
{
|
||||
protected _entityRegistryManager: EntityRegistryManager;
|
||||
protected _frigateEventWatcher: FrigateEventWatcher;
|
||||
protected _recordingSegmentsCache: RecordingSegmentsCache;
|
||||
protected _requestCache: RequestCache;
|
||||
|
||||
@@ -121,11 +125,15 @@ export class FrigateCameraManagerEngine
|
||||
);
|
||||
|
||||
constructor(
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
stateWatcher: StateWatcherSubscriptionInterface,
|
||||
recordingSegmentsCache: RecordingSegmentsCache,
|
||||
requestCache: RequestCache,
|
||||
eventCallback?: CameraEventCallback,
|
||||
) {
|
||||
super(eventCallback);
|
||||
super(stateWatcher, eventCallback);
|
||||
this._entityRegistryManager = entityRegistryManager;
|
||||
this._frigateEventWatcher = new FrigateEventWatcher();
|
||||
this._recordingSegmentsCache = recordingSegmentsCache;
|
||||
this._requestCache = requestCache;
|
||||
}
|
||||
@@ -136,13 +144,17 @@ export class FrigateCameraManagerEngine
|
||||
|
||||
public async createCamera(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
cameraConfig: CameraConfig,
|
||||
): Promise<Camera> {
|
||||
const camera = new FrigateCamera(cameraConfig, this, {
|
||||
eventCallback: this._eventCallback,
|
||||
});
|
||||
return await camera.initialize(hass, entityRegistryManager);
|
||||
return await camera.initialize({
|
||||
hass,
|
||||
entityRegistryManager: this._entityRegistryManager,
|
||||
stateWatcher: this._stateWatcher,
|
||||
frigateEventWatcher: this._frigateEventWatcher,
|
||||
});
|
||||
}
|
||||
|
||||
public async getMediaDownloadPath(
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { FrigateEventChange, frigateEventChangeSchema } from './types';
|
||||
|
||||
export interface FrigateEventWatcherRequest {
|
||||
instanceID: string;
|
||||
matcher?(event: FrigateEventChange): boolean;
|
||||
callback(event: FrigateEventChange): void;
|
||||
}
|
||||
|
||||
export interface FrigateEventWatcherSubscriptionInterface {
|
||||
subscribe(hass: HomeAssistant, request: FrigateEventWatcherRequest): Promise<void>;
|
||||
unsubscribe(callback: FrigateEventWatcherRequest): void;
|
||||
}
|
||||
|
||||
type SubscriptionUnsubscribe = () => Promise<void>;
|
||||
|
||||
export class FrigateEventWatcher implements FrigateEventWatcherSubscriptionInterface {
|
||||
protected _requests: FrigateEventWatcherRequest[] = [];
|
||||
protected _unsubscribeCallback: Record<string, SubscriptionUnsubscribe> = {};
|
||||
|
||||
public async subscribe(
|
||||
hass: HomeAssistant,
|
||||
request: FrigateEventWatcherRequest,
|
||||
): Promise<void> {
|
||||
const shouldSubscribe = !this._hasSubscribers(request.instanceID);
|
||||
this._requests.push(request);
|
||||
if (shouldSubscribe) {
|
||||
this._unsubscribeCallback[request.instanceID] =
|
||||
await hass.connection.subscribeMessage<string>(
|
||||
(data) => this._receiveHandler(request.instanceID, data),
|
||||
{ type: 'frigate/events/subscribe', instance_id: request.instanceID },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public async unsubscribe(request: FrigateEventWatcherRequest): Promise<void> {
|
||||
this._requests = this._requests.filter(
|
||||
(existingRequest) => existingRequest !== request,
|
||||
);
|
||||
|
||||
if (!this._hasSubscribers(request.instanceID)) {
|
||||
await this._unsubscribeCallback[request.instanceID]();
|
||||
delete this._unsubscribeCallback[request.instanceID];
|
||||
}
|
||||
}
|
||||
|
||||
protected _hasSubscribers(instanceID: string): boolean {
|
||||
return !!this._requests.filter((request) => request.instanceID === instanceID)
|
||||
.length;
|
||||
}
|
||||
|
||||
protected _receiveHandler(instanceID: string, data: string): void {
|
||||
let json: unknown;
|
||||
try {
|
||||
json = JSON.parse(data);
|
||||
} catch (e) {
|
||||
console.warn('Received non-JSON payload as Frigate event', data);
|
||||
return;
|
||||
}
|
||||
|
||||
const parsedEvent = frigateEventChangeSchema.safeParse(json);
|
||||
if (!parsedEvent.success) {
|
||||
console.warn('Received malformed Frigate event from Home Assistant', data);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const request of this._requests) {
|
||||
if (
|
||||
request.instanceID === instanceID &&
|
||||
(!request.matcher || request.matcher(parsedEvent.data))
|
||||
) {
|
||||
request.callback(parsedEvent.data);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,8 +83,7 @@ export const ptzInfoSchema = z.object({
|
||||
});
|
||||
export type PTZInfo = z.infer<typeof ptzInfoSchema>;
|
||||
|
||||
// Frigate events as stored in MQTT updates.
|
||||
const frigateEventChangeSchema = z.object({
|
||||
const frigateEventChangeBeforeAfterSchema = z.object({
|
||||
camera: z.string(),
|
||||
snapshot: z
|
||||
.object({
|
||||
@@ -96,25 +95,13 @@ const frigateEventChangeSchema = z.object({
|
||||
label: z.string(),
|
||||
current_zones: z.string().array(),
|
||||
});
|
||||
export type FrigateEventChange = z.infer<typeof frigateEventChangeSchema>;
|
||||
|
||||
const frigateEventChangeType = z.enum(['new', 'update', 'end']);
|
||||
export type FrigateEventChangeType = z.infer<typeof frigateEventChangeType>;
|
||||
|
||||
export const frigateEventChangeTriggerResponseSchema = z.object({
|
||||
variables: z.object({
|
||||
trigger: z.object({
|
||||
payload_json: z.object({
|
||||
before: frigateEventChangeSchema,
|
||||
after: frigateEventChangeSchema,
|
||||
type: frigateEventChangeType,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
export const frigateEventChangeSchema = z.object({
|
||||
before: frigateEventChangeBeforeAfterSchema,
|
||||
after: frigateEventChangeBeforeAfterSchema,
|
||||
type: z.enum(['new', 'update', 'end']),
|
||||
});
|
||||
export type FrigateEventChangeTriggerResponse = z.infer<
|
||||
typeof frigateEventChangeTriggerResponseSchema
|
||||
>;
|
||||
export type FrigateEventChange = z.infer<typeof frigateEventChangeSchema>;
|
||||
|
||||
// ==============================
|
||||
// Frigate concrete query results
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
|
||||
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
|
||||
import { PTZAction, PTZ_PAN_TILT_ACTIONS, PTZ_ZOOM_ACTIONS } from '../../config/ptz';
|
||||
import { StateWatcherSubscriptionInterface } from '../../card-controller/hass/state-watcher';
|
||||
import { PTZAction } from '../../config/ptz';
|
||||
import { ActionPhase, CameraConfig } from '../../config/types';
|
||||
import { ExtendedHomeAssistant, PTZCapabilities, PTZMovementType } from '../../types';
|
||||
import { ExtendedHomeAssistant } from '../../types';
|
||||
import { getEntityIcon, getEntityTitle } from '../../utils/ha';
|
||||
import { EntityRegistryManager } from '../../utils/ha/entity-registry';
|
||||
import { ViewMedia } from '../../view/media';
|
||||
import { Camera } from '../camera';
|
||||
import { Capabilities } from '../capabilities';
|
||||
@@ -40,8 +40,13 @@ import { getPTZCapabilitiesFromCameraConfig } from '../utils/ptz';
|
||||
|
||||
export class GenericCameraManagerEngine implements CameraManagerEngine {
|
||||
protected _eventCallback?: CameraEventCallback;
|
||||
protected _stateWatcher: StateWatcherSubscriptionInterface;
|
||||
|
||||
constructor(eventCallback?: CameraEventCallback) {
|
||||
constructor(
|
||||
stateWatcher: StateWatcherSubscriptionInterface,
|
||||
eventCallback?: CameraEventCallback,
|
||||
) {
|
||||
this._stateWatcher = stateWatcher;
|
||||
this._eventCallback = eventCallback;
|
||||
}
|
||||
|
||||
@@ -50,8 +55,7 @@ export class GenericCameraManagerEngine implements CameraManagerEngine {
|
||||
}
|
||||
|
||||
public async createCamera(
|
||||
hass: HomeAssistant,
|
||||
entityRegistryManager: EntityRegistryManager,
|
||||
_hass: HomeAssistant,
|
||||
cameraConfig: CameraConfig,
|
||||
): Promise<Camera> {
|
||||
return await new Camera(cameraConfig, this, {
|
||||
@@ -74,7 +78,7 @@ export class GenericCameraManagerEngine implements CameraManagerEngine {
|
||||
},
|
||||
),
|
||||
eventCallback: this._eventCallback,
|
||||
}).initialize(hass, entityRegistryManager);
|
||||
}).initialize({ stateWatcher: this._stateWatcher });
|
||||
}
|
||||
|
||||
public generateDefaultEventQuery(
|
||||
|
||||
@@ -123,10 +123,7 @@ export class CameraManager {
|
||||
this._api = api;
|
||||
this._engineFactory =
|
||||
options?.factory ??
|
||||
new CameraManagerEngineFactory(
|
||||
this._api.getEntityRegistryManager(),
|
||||
this._api.getResolvedMediaCache(),
|
||||
);
|
||||
new CameraManagerEngineFactory(this._api.getEntityRegistryManager());
|
||||
this._store = options?.store ?? new CameraManagerStore();
|
||||
}
|
||||
|
||||
@@ -157,7 +154,9 @@ export class CameraManager {
|
||||
// rapidly in the config editor).
|
||||
await this._initializationLimit.add(resetAndInitialize);
|
||||
} catch (e: unknown) {
|
||||
this._api.getMessageManager().setErrorIfHigherPriority(e);
|
||||
this._api
|
||||
.getMessageManager()
|
||||
.setErrorIfHigherPriority(e, localize('error.camera_initialization'));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -190,9 +189,11 @@ export class CameraManager {
|
||||
const engineType = engineTypes[index];
|
||||
const engine = engineType
|
||||
? engines.get(engineType) ??
|
||||
(await this._engineFactory.createEngine(engineType, (ev) =>
|
||||
this._api.getTriggersManager().handleCameraEvent(ev),
|
||||
))
|
||||
(await this._engineFactory.createEngine(engineType, {
|
||||
eventCallback: (ev) => this._api.getTriggersManager().handleCameraEvent(ev),
|
||||
stateWatcher: this._api.getHASSManager().getStateWatcher(),
|
||||
resolvedMediaCache: this._api.getResolvedMediaCache(),
|
||||
}))
|
||||
: null;
|
||||
if (!engine || !engineType) {
|
||||
throw new CameraInitializationError(
|
||||
@@ -238,12 +239,7 @@ export class CameraManager {
|
||||
// Configuration is initialized in parallel.
|
||||
const cameras = await allPromises(
|
||||
engineByConfig.entries(),
|
||||
async ([cameraConfig, engine]) =>
|
||||
await engine.createCamera(
|
||||
hass,
|
||||
this._api.getEntityRegistryManager(),
|
||||
cameraConfig,
|
||||
),
|
||||
async ([cameraConfig, engine]) => await engine.createCamera(hass, cameraConfig),
|
||||
);
|
||||
|
||||
// Do the additions based off the result-order, to ensure the map order is
|
||||
|
||||
Reference in New Issue
Block a user