Use custom websocket to avoid needing admin privileges.
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user