Autodetect motion and occupancy sensors.

This commit is contained in:
Dermot Duffy
2022-05-21 11:23:31 -07:00
parent 4a40e4a943
commit c8d9e89b78
10 changed files with 358 additions and 80 deletions
+81
View File
@@ -0,0 +1,81 @@
import { HomeAssistant } from 'custom-card-helpers';
import QuickLRU from 'quick-lru';
import { homeAssistantWSRequest } from '.';
import {
FrigateBrowseMediaSource,
ResolvedMedia,
resolvedMediaSchema
} from '../../types.js';
// It's important the cache size be at least as large as the largest likely
// media query or media items will from a given query will be evicted for other
// items in the same query (which would result in only partial results being
// returned to the user).
// Note: Each entry is about 400 bytes.
const RESOLVED_MEDIA_CACHE_SIZE = 1000;
export class ResolvedMediaCache {
protected _cache: QuickLRU<string, ResolvedMedia>;
constructor() {
this._cache = new QuickLRU({ maxSize: RESOLVED_MEDIA_CACHE_SIZE });
}
/**
* Determine if the cache has a given id.
* @param id
* @returns `true` if the id is in the cache, `false` otherwise.
*/
public has(id: string): boolean {
return this._cache.has(id);
}
/**
* Get resolved media information given an id.
* @param id The id.
* @returns The `ResolvedMedia` for this id.
*/
public get(id: string): ResolvedMedia | undefined {
return this._cache.get(id);
}
/**
* Add a given ResolvedMedia to the cache.
* @param id The id for the object.
* @param resolvedMedia The `ResolvedMedia` object.
*/
public set(id: string, resolvedMedia: ResolvedMedia): void {
this._cache.set(id, resolvedMedia);
}
}
/**
* Resolve a given media source item.
* @param hass The Home Assistant object.
* @param mediaSource The media source object.
* @param cache An optional ResolvedMediaCache object.
* @returns
*/
export const resolveMedia = async (
hass: HomeAssistant,
mediaSource?: FrigateBrowseMediaSource,
cache?: ResolvedMediaCache,
): Promise<ResolvedMedia | null> => {
if (!mediaSource) {
return null;
}
const cachedValue = cache ? cache.get(mediaSource.media_content_id) : undefined;
if (cachedValue) {
return cachedValue;
}
const request = {
type: 'media_source/resolve_media',
media_content_id: mediaSource.media_content_id,
};
const resolvedMedia = await homeAssistantWSRequest(hass, resolvedMediaSchema, request);
if (cache && resolvedMedia) {
cache.set(mediaSource.media_content_id, resolvedMedia);
}
return resolvedMedia;
};