Use custom websocket to avoid needing admin privileges.

This commit is contained in:
Dermot Duffy
2024-08-24 20:00:00 -07:00
parent 5a1d08f3ea
commit 429dd90972
47 changed files with 1219 additions and 874 deletions
+8 -4
View File
@@ -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(
+25 -46
View File
@@ -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);
}
}
+23 -13
View File
@@ -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;
+3 -8
View File
@@ -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,
+55 -44
View File
@@ -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'),
});
}
};
}
+20 -8
View File
@@ -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);
}
}
}
}
+6 -19
View File
@@ -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
+11 -7
View File
@@ -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(
+10 -14
View File
@@ -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
+14 -2
View File
@@ -46,9 +46,9 @@ export class CardElementManager {
this._menuToggleCallback();
}
public update(): void {
public update = (): void => {
this._element.requestUpdate();
}
};
public hasUpdated(): boolean {
return this._element.hasUpdated;
@@ -69,6 +69,17 @@ export class CardElementManager {
this._api.getKeyboardStateManager().initialize();
this._api.getDefaultManager().initialize();
this._api
.getHASSManager()
.getStateWatcher()
?.subscribe(this.update, [
...(this._api.getConfigManager().getConfig()?.view.render_entities ?? []),
// Refresh the card if media player state changes:
// https://github.com/dermotduffy/frigate-hass-card/issues/881
...(this._api.getMediaPlayerManager().getMediaPlayers() ?? []),
]);
// Whether or not the card is in panel mode on the dashboard.
setOrRemoveAttribute(this._element, isCardInPanel(this._element), 'panel');
setOrRemoveAttribute(this._element, true, 'tabindex', '0');
@@ -129,6 +140,7 @@ export class CardElementManager {
this._api.getKeyboardStateManager().uninitialize();
this._api.getActionsManager().uninitialize();
this._api.getDefaultManager().uninitialize();
this._api.getHASSManager().getStateWatcher()?.unsubscribe(this.update);
// Uninitialize cameras to cause them to reinitialize on
// reconnection, to ensure the state subscription/unsubscription works
+1 -1
View File
@@ -20,7 +20,7 @@ import { ConfigManager } from './config/config-manager';
import { DownloadManager } from './download-manager';
import { ExpandManager } from './expand-manager';
import { FullscreenManager } from './fullscreen-manager';
import { HASSManager } from './hass-manager';
import { HASSManager } from './hass/hass-manager';
import { InitializationManager } from './initialization-manager';
import { InteractionManager } from './interaction-manager';
import { MediaLoadedInfoManager } from './media-info-manager';
+11 -18
View File
@@ -1,9 +1,8 @@
import PQueue from 'p-queue';
import { DestroyCallback, subscribeToTrigger } from '../utils/ha';
import { createGeneralAction } from '../utils/action';
import { isActionAllowedBasedOnInteractionState } from '../utils/interaction-mode';
import { Timer } from '../utils/timer';
import { CardDefaultManagerAPI } from './types';
import { createGeneralAction } from '../utils/action';
/**
* Manages automated resetting to the default view.
@@ -11,7 +10,6 @@ import { createGeneralAction } from '../utils/action';
export class DefaultManager {
protected _timer = new Timer();
protected _api: CardDefaultManagerAPI;
protected _unsubscribeCallback: DestroyCallback | null = null;
protected _initializationLimit = new PQueue({ concurrency: 1 });
constructor(api: CardDefaultManagerAPI) {
@@ -47,8 +45,7 @@ export class DefaultManager {
public uninitialize(): void {
this._timer.stop();
this._unsubscribeCallback?.();
this._unsubscribeCallback = null;
this._api.getHASSManager().getStateWatcher().unsubscribe(this._stateChangeHandler);
this._api.getAutomationsManager().deleteAutomations(this);
}
@@ -59,19 +56,11 @@ export class DefaultManager {
return false;
}
if (this._unsubscribeCallback) {
await this._unsubscribeCallback();
}
this._unsubscribeCallback = await subscribeToTrigger(
hass,
() => this._setToDefaultIfAllowed(),
{
entityID: config.entities,
platform: 'state',
stateOnly: true,
},
);
this._api.getHASSManager().getStateWatcher().unsubscribe(this._stateChangeHandler);
this._api
.getHASSManager()
.getStateWatcher()
.subscribe(this._stateChangeHandler, config.entities);
// If the timer is running, restart it with the newly configured timer.
if (this._timer.isRunning()) {
@@ -82,6 +71,10 @@ export class DefaultManager {
return true;
}
protected _stateChangeHandler = (): void => {
this._setToDefaultIfAllowed();
};
protected _setToDefaultIfAllowed(): void {
if (this._isAutomatedUpdateAllowed()) {
this._api.getViewManager().setViewDefault();
@@ -1,11 +1,13 @@
import { localize } from '../localize/localize';
import { ExtendedHomeAssistant } from '../types';
import { hasHAConnectionStateChanged, isHassDifferent } from '../utils/ha';
import { CardHASSAPI } from './types';
import { localize } from '../../localize/localize';
import { ExtendedHomeAssistant } from '../../types';
import { hasHAConnectionStateChanged } from '../../utils/ha';
import { CardHASSAPI } from '../types';
import { StateWatcher, StateWatcherSubscriptionInterface } from './state-watcher';
export class HASSManager {
protected _hass: ExtendedHomeAssistant | null = null;
protected _api: CardHASSAPI;
protected _stateWatcher: StateWatcher = new StateWatcher();
constructor(api: CardHASSAPI) {
this._api = api;
@@ -15,6 +17,10 @@ export class HASSManager {
return this._hass;
}
public getStateWatcher(): StateWatcherSubscriptionInterface {
return this._stateWatcher;
}
public setHASS(hass?: ExtendedHomeAssistant | null): void {
if (hasHAConnectionStateChanged(this._hass, hass)) {
if (!hass?.connected) {
@@ -36,18 +42,6 @@ export class HASSManager {
const oldHass = this._hass;
this._hass = hass;
if (
isHassDifferent(this._hass, oldHass, [
...(this._api.getConfigManager().getConfig()?.view.render_entities ?? []),
// Refresh the card if media player state changes:
// https://github.com/dermotduffy/frigate-hass-card/issues/881
...this._api.getMediaPlayerManager().getMediaPlayers(),
])
) {
this._api.getCardElementManager().update();
}
if (this._api.getConditionsManager().hasHAStateConditions()) {
this._api.getConditionsManager().setState({
state: this._hass.states,
@@ -57,5 +51,7 @@ export class HASSManager {
// Dark mode may depend on HASS.
this._api.getStyleManager().setLightOrDarkMode();
this._stateWatcher.setHASS(oldHass, hass);
}
}
+51
View File
@@ -0,0 +1,51 @@
import { HomeAssistant } from '@dermotduffy/custom-card-helpers';
import { getHassDifferences, HassStateDifference } from '../../utils/ha';
type StateWatcherCallback = (difference: HassStateDifference) => void;
export interface StateWatcherSubscriptionInterface {
subscribe(callback: StateWatcherCallback, entityIDs: string[]): void;
unsubscribe(callback: StateWatcherCallback): void;
}
export class StateWatcher implements StateWatcherSubscriptionInterface {
protected _watcherCallbacks = new Map<StateWatcherCallback, string[]>();
public setHASS(oldHass: HomeAssistant | null, hass: HomeAssistant): void {
if (!oldHass) {
return;
}
for (const [callback, entityIDs] of this._watcherCallbacks.entries()) {
const differences = getHassDifferences(hass, oldHass, entityIDs, {
stateOnly: true,
firstOnly: true,
});
if (differences.length) {
callback(differences[0]);
}
}
}
/**
* Calls callback when the state of any of the entities changes. The callback is
* called with the state difference of the first entity that changed.
* @param callback The callback.
* @param entityIDs An array of entity IDs to watch.
*/
public subscribe(callback: StateWatcherCallback, entityIDs: string[]): boolean {
if (!entityIDs.length) {
return false;
}
if (this._watcherCallbacks.has(callback)) {
this._watcherCallbacks.get(callback)?.push(...entityIDs);
} else {
this._watcherCallbacks.set(callback, entityIDs);
}
return true;
}
public unsubscribe(callback: StateWatcherCallback): void {
this._watcherCallbacks.delete(callback);
}
}
+5 -4
View File
@@ -42,16 +42,17 @@ export class MessageManager {
}
}
public setErrorIfHigherPriority(error: unknown): void {
public setErrorIfHigherPriority(error: unknown, prefix?: string): void {
// This object should accept unknown objects to be able to seamlessly
// process arguments to catch() which can only be unknown/any.
if (!(error instanceof Error)) {
// process arguments to catch() which can only be unknown/any. HA may throw
// non Error() based errors.
if (!error || typeof error !== 'object' || !('message' in error)) {
return;
}
errorToConsole(error);
this.setMessageIfHigherPriority({
message: error.message,
message: prefix ? `${prefix}: ${error.message}` : error.message,
type: 'error',
...(error instanceof FrigateCardError && { context: error.context }),
});
+2 -2
View File
@@ -11,7 +11,7 @@ export class StyleManager {
this._api = api;
}
public setLightOrDarkMode(): void {
public setLightOrDarkMode = (): void => {
const config = this._api.getConfigManager().getConfig();
const isDarkMode =
config?.view.dark_mode === 'on' ||
@@ -24,7 +24,7 @@ export class StyleManager {
isDarkMode,
'dark',
);
}
};
public setExpandedMode(): void {
const card = this._api.getCardElementManager().getElement();
+4 -1
View File
@@ -12,7 +12,7 @@ import type { DefaultManager } from './default-manager';
import type { DownloadManager } from './download-manager';
import type { ExpandManager } from './expand-manager';
import type { FullscreenManager } from './fullscreen-manager';
import type { HASSManager } from './hass-manager';
import type { HASSManager } from './hass/hass-manager';
import type { InitializationManager } from './initialization-manager';
import type { InteractionManager } from './interaction-manager';
import type { KeyboardStateManager } from './keyboard-state-manager';
@@ -121,13 +121,16 @@ export interface CardDownloadAPI {
export interface CardElementAPI {
getActionsManager(): ActionsManager;
getCameraManager(): CameraManager;
getConfigManager(): ConfigManager;
getDefaultManager(): DefaultManager;
getExpandManager(): ExpandManager;
getFullscreenManager(): FullscreenManager;
getInitializationManager(): InitializationManager;
getInteractionManager(): InteractionManager;
getHASSManager(): HASSManager;
getKeyboardStateManager(): KeyboardStateManager;
getMediaLoadedInfoManager(): MediaLoadedInfoManager;
getMediaPlayerManager(): MediaPlayerManager;
getMicrophoneManager(): MicrophoneManager;
getQueryStringManager(): QueryStringManager;
}
+2 -2
View File
@@ -1,5 +1,5 @@
export const PTZ_PAN_TILT_ACTIONS = ['left', 'right', 'up', 'down'] as const;
export const PTZ_ZOOM_ACTIONS = ['zoom_in', 'zoom_out'] as const;
const PTZ_PAN_TILT_ACTIONS = ['left', 'right', 'up', 'down'] as const;
const PTZ_ZOOM_ACTIONS = ['zoom_in', 'zoom_out'] as const;
const PTZ_BASE_ACTIONS = [...PTZ_PAN_TILT_ACTIONS, ...PTZ_ZOOM_ACTIONS] as const;
export type PTZBaseAction = (typeof PTZ_BASE_ACTIONS)[number];
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "S'està esperant que es carregui la transmissió en directe ...",
"camera_initialization": "",
"could_not_render_elements": "No s'han pogut representar els elements de la imatge",
"could_not_resolve": "No s'ha pogut resoldre l'URL multimèdia",
"diagnostics": "Diagnòstic de targetes. Reviseu la informació confidencial abans de compartir-la",
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "Waiting for live stream to load ...",
"camera_initialization": "Camera initialization failed",
"could_not_render_elements": "Could not render picture elements",
"could_not_resolve": "Could not resolve media URL",
"diagnostics": "Card diagnostics. Please review for confidential information prior to sharing",
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "",
"camera_initialization": "",
"could_not_render_elements": "Impossible de restituer les éléments de l'image",
"could_not_resolve": "",
"diagnostics": "Diagnostic de la carte. Veuillez enlever les informations confidentielles avant de les partager",
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "",
"camera_initialization": "",
"could_not_render_elements": "Impossibile renderizzare gli elementi dell'immagine",
"could_not_resolve": "Impossibile risolvere l'URL dei media",
"diagnostics": "Diagnostica delle carte.Si prega di rivedere per informazioni riservate prima di condividere",
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "",
"camera_initialization": "",
"could_not_render_elements": "Não foi possível renderizar os elementos da imagem",
"could_not_resolve": "Não foi possível resolver o URL de mídia",
"diagnostics": "Diagnósticos do cartão. Revise as informações confidenciais antes de compartilhar",
+1
View File
@@ -570,6 +570,7 @@
},
"error": {
"awaiting_live": "",
"camera_initialization": "",
"could_not_render_elements": "Não foi possível renderizar os elementos da imagem",
"could_not_resolve": "Não foi possível resolver o URL de mídia",
"diagnostics": "Diagnósticos do cartão. Reveja as informações confidenciais antes de partilhar",
+1 -1
View File
@@ -56,7 +56,7 @@ export const MESSAGE_TYPE_PRIORITIES: MessagePriority = {
};
export interface Message {
message: string;
message: unknown;
type: MessageType;
icon?: string;
context?: unknown;
+6 -3
View File
@@ -101,14 +101,17 @@ export function contentsChanged(
/**
* Log an error as a warning to the console.
* @param e The Error object.
* @param e The Error-like object.
* @param func The Console func to call.
*/
export function errorToConsole(e: Error, func: CallableFunction = console.warn): void {
export function errorToConsole(
e: Error | { message: unknown },
func: CallableFunction = console.warn,
): void {
if (e instanceof FrigateCardError && e.context) {
func(e, e.context);
} else {
func(e);
func(e.message);
}
}
+4 -62
View File
@@ -17,14 +17,6 @@ import {
} from '../../types.js';
import { domainIcon } from '../icons/domain-icon.js';
import { getParseErrorKeys } from '../zod.js';
import {
HAStateChangeFromTo,
haStateChangeTriggerResponseSchema,
SubscriptionCallback,
SubscriptionUnsubscribe,
} from './types.js';
export type DestroyCallback = () => Promise<void>;
/**
* Make a HomeAssistant websocket request. May throw.
@@ -100,8 +92,8 @@ export async function homeAssistantSignPath(
return hass.hassUrl(response.path);
}
interface HassStateDifference {
entity: string;
export interface HassStateDifference {
entityID: string;
oldState?: HassEntity;
newState: HassEntity;
}
@@ -115,7 +107,7 @@ interface HassStateDifference {
* strings only, firstOnly: whether or not to get the first difference only.
* @returns An array of HassStateDifference objects.
*/
function getHassDifferences(
export function getHassDifferences(
newHass: HomeAssistant | undefined | null,
oldHass: HomeAssistant | undefined | null,
entities: string[] | null,
@@ -137,7 +129,7 @@ function getHassDifferences(
(!options?.stateOnly && oldState !== newState)
) {
differences.push({
entity: entity,
entityID: entity,
oldState: oldState,
newState: newState,
});
@@ -403,53 +395,3 @@ export const hasHAConnectionStateChanged = (
): boolean => {
return oldHass?.connected !== newHass?.connected;
};
/**
* Subscribe to a HA trigger
* @param hass The HA object.
* @param callback The callback to call with the data.
* @param options Parameters to the trigger, see:
* https://www.home-assistant.io/docs/automation/trigger/#state-trigger
* @returns A callback to unsubscribe.
*/
export const subscribeToTrigger = async (
hass: HomeAssistant,
callback: SubscriptionCallback,
options?: {
entityID?: string | string[];
platform?: string;
topic?: string;
payload?: string;
valueTemplate?: string;
stateOnly?: boolean;
},
): Promise<SubscriptionUnsubscribe> => {
return await hass.connection.subscribeMessage(callback, {
type: 'subscribe_trigger',
trigger: {
...(options?.platform && { platform: options.platform }),
...(options?.entityID && { entity_id: options.entityID }),
...(options?.topic && { topic: options.topic }),
...(options?.payload && { payload: options.payload }),
...(options?.valueTemplate && { value_template: options.valueTemplate }),
...(options?.stateOnly && {
from: null,
to: null,
}),
},
});
};
/**
* Parse a state change trigger response.
* @param data The raw data.
* @returns A HAStateChangeFromTo object.
*/
export const parseStateChangeTrigger = (data: unknown): HAStateChangeFromTo | null => {
const parseResult = haStateChangeTriggerResponseSchema.safeParse(data);
if (!parseResult.success) {
console.warn('Ignoring unparseable HA state change', data);
return null;
}
return parseResult.data.variables.trigger;
};
-21
View File
@@ -1,21 +0,0 @@
import { z } from 'zod';
export type SubscriptionUnsubscribe = () => Promise<void>;
export type SubscriptionCallback = (data: unknown) => void;
const haStateChangeSchema = z.object({
entity_id: z.string(),
state: z.string(),
});
const haStateChangeFromToSchema = z.object({
from_state: haStateChangeSchema,
to_state: haStateChangeSchema,
});
export type HAStateChangeFromTo = z.infer<typeof haStateChangeFromToSchema>;
export const haStateChangeTriggerResponseSchema = z.object({
variables: z.object({
trigger: haStateChangeFromToSchema,
}),
});