refactored entity listener so that live events actually come in

This commit is contained in:
ari committed 2022-07-28 22:27:57 -04:00
1 parent 57c86093a4
commit 883955e523
12 files changed
+214 -266

No files matched your search

@@ -20,8 +20,6 @@ export const useTagDB = (
const c = JSON.stringify(automations);
if (lastAuto.current !== c) {
lastAuto.current = c;
console.log("updating...");
setState({
automationTags: convertAutoListToMap(automations),
changed: new Set(),
@@ -52,7 +52,7 @@ export const AutomationManager: FC<AutomationManagerProps> = ({
// alias
const configAutomations = api.state.automations.data;
const hassEntities = haEntities.collection.state;
const hassEntities = haEntities.collection;
return (
<AutomationManagerLoaded
configAutomations={configAutomations.data}
+9 -9
View File
@@ -68,7 +68,7 @@ export const useHAAreas = () => {
return true;
}
for (const d of domains) {
if (!areas.collection.state[areaId].domains.has(d)) {
if (!areas.collection[areaId].domains.has(d)) {
return false;
}
}
@@ -79,7 +79,7 @@ export const useHAAreas = () => {
return true;
}
for (const d of integrations) {
if (!areas.collection.state[areaId].integrations.has(d)) {
if (!areas.collection[areaId].integrations.has(d)) {
return false;
}
}
@@ -92,8 +92,8 @@ export const useHAAreas = () => {
if (typeof opt === "string") {
return {
id: opt,
label: areas.collection.state[opt].name ?? prettyName(opt),
data: areas.collection.state[opt],
label: areas.collection[opt].name ?? prettyName(opt),
data: areas.collection[opt],
};
}
return opt;
@@ -105,7 +105,7 @@ export const useHAAreas = () => {
if (!areas.ready) {
return [];
}
let keys = Object.keys(areas.collection.state);
let keys = Object.keys(areas.collection);
if (restrictToDomain) {
const domains = restrictToDomain.map((x) => x.toLowerCase());
keys = keys.filter((key) => methods.areaHasEntityDomain(key, domains));
@@ -118,15 +118,15 @@ export const useHAAreas = () => {
}
return keys.map((key) => ({
id: key,
label: areas.collection.state[key].name ?? prettyName(key),
data: areas.collection.state[key],
label: areas.collection[key].name ?? prettyName(key),
data: areas.collection[key],
}));
},
getLabel: (opt: AreaOption): string => {
if (typeof opt === "string") {
if (areas.ready) {
return areas.collection.state[opt]
? areas.collection.state[opt].name ?? prettyName(opt)
return areas.collection[opt]
? areas.collection[opt].name ?? prettyName(opt)
: prettyName(opt);
}
return opt;
+2 -20
View File
@@ -17,20 +17,10 @@ export const useMockHAEntities = (args: MockHAEntitiesProps) => {
{
additional: {},
ready: false,
collection: {
state: {},
refresh: () => new Promise(() => {}),
subscribe: () => () => {},
},
},
{
additional: {},
ready: false,
collection: {
state: {},
refresh: () => new Promise(() => {}),
subscribe: () => () => {},
},
}
);
} else {
@@ -38,20 +28,12 @@ export const useMockHAEntities = (args: MockHAEntitiesProps) => {
{
additional: {},
ready: true,
collection: {
state: args.entities,
refresh: () => new Promise(() => {}),
subscribe: () => () => {},
},
collection: args.entities,
},
{
additional: {},
ready: true,
collection: {
state: args.entitySource,
refresh: () => new Promise(() => {}),
subscribe: () => () => {},
},
collection: args.entitySource,
}
);
}
+13 -17
View File
@@ -12,8 +12,6 @@ export const useHAEntities = (): HAEntitiesState => {
new Set(Object.keys(state).map((x) => x.split(".")[0])).keys()
).sort(),
}));
entities.collection?.subscribe(console.log);
console.log("ha entities refreshing...");
const entitySource = useHassCollection(entitySourceColl);
return createHAEntitiesState(entities, entitySource);
};
@@ -40,11 +38,11 @@ export const createHAEntitiesState = (
}
let state: Set<string> = new Set();
entityIds.forEach((entityId) => {
if (entities.collection.state[entityId]) {
if (entities.collection[entityId]) {
if (!attribute) {
state.add(entities.collection.state[entityId].state);
state.add(entities.collection[entityId].state);
} else {
const val = (entities.collection.state[entityId]?.attributes ?? {})[
const val = (entities.collection[entityId]?.attributes ?? {})[
attribute
];
if (val) {
@@ -68,7 +66,7 @@ export const createHAEntitiesState = (
let attributes: Set<string> = new Set();
entityIds.forEach((entityId) => {
const thisAttrs = new Set(
Object.keys(entities.collection.state[entityId]?.attributes ?? {})
Object.keys(entities.collection[entityId]?.attributes ?? {})
);
if (attributes.size === 0) {
attributes = thisAttrs;
@@ -107,7 +105,7 @@ export const createHAEntitiesState = (
? `one of "${domains.join(", ")}"`
: `"${domains[0]}"`;
out = out.reduce<string[]>((all = [], key) => {
const integration = entitySource.collection.state[key].domain;
const integration = entitySource.collection[key].domain;
if (!domains.includes(integration.toLowerCase())) {
return [...all, `${methods.getLabel(key)} is not ${domainsStr}`];
}
@@ -135,7 +133,7 @@ export const createHAEntitiesState = (
const integrations = (restrictedIntegrations ?? []).map((x) =>
x.toLowerCase()
);
return Object.keys(entities.collection.state)
return Object.keys(entities.collection)
.filter((entityId) => {
if (mode === "and") {
let keep = true;
@@ -147,14 +145,14 @@ export const createHAEntitiesState = (
keep =
keep &&
integrations.includes(
entitySource.collection.state[entityId]?.domain ?? ""
entitySource.collection[entityId]?.domain ?? ""
);
}
if (deviceClasses.length > 0) {
keep =
keep &&
deviceClasses.includes(
entities.collection.state[
entities.collection[
entityId
].attributes.device_class?.toLowerCase() ?? ""
);
@@ -176,13 +174,13 @@ export const createHAEntitiesState = (
keep =
keep ||
integrations.includes(
entitySource.collection.state[entityId]?.domain ?? ""
entitySource.collection[entityId]?.domain ?? ""
);
}
keep =
keep ||
deviceClasses.includes(
entities.collection.state[
entities.collection[
entityId
].attributes.device_class?.toLowerCase() ?? ""
);
@@ -191,19 +189,17 @@ export const createHAEntitiesState = (
})
.map((key) => ({
id: key,
label: entities.collection.state[key].attributes.friendly_name ?? key,
label: entities.collection[key].attributes.friendly_name ?? key,
domain: key.split(".")[0] ?? "n/a",
integration: entitySource.ready
? (entitySource.collection.state[key] ?? {}).domain ?? "n/a"
? (entitySource.collection[key] ?? {}).domain ?? "n/a"
: "...",
}));
},
getLabel: (opt: EntityOption): string => {
if (typeof opt === "string") {
if (entities.ready) {
return (
entities.collection.state[opt]?.attributes.friendly_name ?? opt
);
return entities.collection[opt]?.attributes.friendly_name ?? opt;
}
return opt;
}
@@ -0,0 +1,94 @@
import React, { FC, useEffect, useState } from "react";
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHA } from "haService";
import InputYaml from "components/Inputs/InputYaml";
import { InputList } from "components/Inputs/InputList";
import { Button } from "components/Inputs/Button";
import { ServiceEditor } from "components/ServiceEditor";
const Test: FC = () => {
const { services, callService, entities } = useHA();
const data = services.collection ?? {};
const domain = "automation";
const domains = Object.keys(data[domain] ?? "").sort();
const [service, setService] = useState(domains[0] ?? "");
const serviceDefn = (data[domain] ?? {})[service] ?? {};
const [serviceData, setServiceData] = useState({ field: {}, target: {} });
useEffect(() => {
setService(domains[0] ?? "");
setServiceData({ field: {}, target: {} });
}, [domain, setService]);
let serviceEditElm = <>Failed to load</>;
try {
if (service) {
serviceEditElm = (
<div
style={{
border: "1px solid var(--mui-grey-400)",
maxWidth: "100vw",
padding: "2.5em",
margin: "2.5em",
}}
>
<ServiceEditor
service={serviceDefn}
serviceId={`${domain}.${service}`}
data={serviceData}
onUpdate={setServiceData}
/>
</div>
);
}
} catch (err) {
serviceEditElm = <>{JSON.stringify(err)}</>;
}
return (
<div style={{ overflow: "auto", maxHeight: "100vh" }}>
<InputList
label="Services"
current={service}
onChange={setService}
options={domains}
/>
<Button
onClick={() =>
callService(domain, service, serviceData.field, serviceData.target)
}
>
Call
</Button>
{serviceEditElm}
<InputYaml label="Service Data" value={serviceDefn} onChange={() => {}} />
{(((serviceData.target ?? {}) as any).entity_id ?? []).map((eid: any) => (
<span>
{eid}: {entities.getStates([eid])}
</span>
))}
</div>
);
};
export default {
title: "Services/HA Service",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
export const AutomationCall: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
</Page>
);
};
+41 -32
View File
@@ -1,42 +1,51 @@
import React, { FC } from "react";
import { ComponentMeta, ComponentStory } from '@storybook/react';
import { ComponentMeta, ComponentStory } from "@storybook/react";
import { Page } from "components/Page";
import { useHADeviceRegistry } from "haService";
import InputYaml from "components/Inputs/InputYaml";
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
const conn = useHADeviceRegistry();
onRender && onRender()
if (conn.ready) {
return <div>
{Object.keys(conn.collection.state).length} items
<ul style={{
maxHeight: '100vh',
overflow: 'auto'
}}>
{Object.keys(conn.collection.state).map(k => <li key={k}>
<b>{k}</b>
{/* <u>{conn.collection.state[k].length > 1 ? conn.collection.state[k].length : ''}</u> */}
<InputYaml value={conn.collection.state[k]} onChange={() => { }} label={k} />
</li>)}
</ul>
</div>
}
return <code>
Loading...
</code>
}
const conn = useHADeviceRegistry();
onRender && onRender();
if (conn.ready) {
return (
<div>
{Object.keys(conn.collection).length} items
<ul
style={{
maxHeight: "100vh",
overflow: "auto",
}}
>
{Object.keys(conn.collection).map((k) => (
<li key={k}>
<b>{k}</b>
{/* <u>{conn.collection[k].length > 1 ? conn.collection[k].length : ''}</u> */}
<InputYaml
value={conn.collection[k]}
onChange={() => {}}
label={k}
/>
</li>
))}
</ul>
</div>
);
}
return <code>Loading...</code>;
};
export default {
title: 'Services/Device Registry',
component: Test,
parameters: { actions: { argTypesRegex: '^on.*' } },
args: {}
} as ComponentMeta<typeof Test>
title: "Services/Device Registry",
component: Test,
parameters: { actions: { argTypesRegex: "^on.*" } },
args: {},
} as ComponentMeta<typeof Test>;
export const Base: ComponentStory<typeof Test> = props => {
return <Page>
<Test {...props} />
export const Base: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
</Page>
};
);
};
+1 -1
View File
@@ -22,7 +22,7 @@ const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
overflow: "auto",
}}
>
{Object.entries(conn.collection?.state ?? {})
{Object.entries(conn.collection ?? {})
.filter(([key, _]) => key.toLowerCase().includes(searchTerm))
.map(([key, value]) => {
return (
+2 -2
View File
@@ -9,14 +9,14 @@ const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
if (conn.ready) {
return (
<div>
{conn.collection.state.length}
{conn.collection.length}
<ul
style={{
maxHeight: "100vh",
overflow: "auto",
}}
>
{conn.collection.state.map((row, i) => (
{conn.collection.map((row, i) => (
<li key={i}>
{row.entity_id}
{/* {Object.keys(row).map(k => <>
+17 -21
View File
@@ -31,12 +31,10 @@ export const useHAServices = () => {
const [domain, action] = name.split(".");
return {
name:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
services.collection[domain][action].name ?? `${domain}.${action}`,
description: services.collection[domain][action].description ?? "",
target: services.collection[domain][action].target,
fields: services.collection[domain][action].fields,
};
} catch (err: any) {
console.warn(err);
@@ -47,27 +45,25 @@ export const useHAServices = () => {
if (!services.ready) {
return [];
}
return Object.keys(services.collection.state).reduce<ServiceOption[]>(
return Object.keys(services.collection).reduce<ServiceOption[]>(
(all, domain) => {
const opts = Object.keys(
services.collection.state[domain]
services.collection[domain]
).map<ServiceOption>((action) => ({
id: `${domain}.${action}`,
label:
services.collection.state[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
services.collection[domain][action].name ?? `${domain}.${action}`,
description: services.collection[domain][action].description ?? "",
domain,
action,
data: {
name:
services.collection.state[domain][action].name ??
services.collection[domain][action].name ??
`${domain}.${action}`,
description:
services.collection.state[domain][action].description ?? "",
target: services.collection.state[domain][action].target,
fields: services.collection.state[domain][action].fields,
services.collection[domain][action].description ?? "",
target: services.collection[domain][action].target,
fields: services.collection[domain][action].fields,
},
}));
return all.concat(opts);
@@ -80,7 +76,7 @@ export const useHAServices = () => {
if (services.ready) {
try {
const [domain, action] = opt.split(".");
return services.collection.state[domain][action].name ?? opt;
return services.collection[domain][action].name ?? opt;
} catch (_) {}
}
return opt;
@@ -109,17 +105,17 @@ export const useHADeviceRegistry = () => {
if (!dr.ready) {
return [];
}
const keys = Object.keys(dr.collection.state);
const keys = Object.keys(dr.collection);
return keys.map((key) => ({
id: key,
label: getLabelForItem(dr.collection.state[key]) ?? key,
manufacturer: dr.collection.state[key].manufacturer ?? "",
label: getLabelForItem(dr.collection[key]) ?? key,
manufacturer: dr.collection[key].manufacturer ?? "",
}));
},
getLabel: (opt: DeviceRegistryOption): string => {
if (typeof opt === "string") {
if (dr.ready) {
return getLabelForItem(dr.collection.state[opt]) ?? opt;
return getLabelForItem(dr.collection[opt]) ?? opt;
}
return opt;
}
+14 -137
View File
@@ -10,86 +10,9 @@ import { ServiceEditor } from "components/ServiceEditor";
const Test: FC = () => {
const { services, callService } = useHA();
const data = services.collection?.state ?? {};
const data = services.collection ?? {};
const options = Object.keys(data).sort();
// const flattened: any[] = [];
// Object.keys(data).forEach(domain => {
// Object.keys(data[domain]).forEach(
// service_name => {
// const service = data[domain][service_name];
// const all: any = {
// domain, service_name,
// }
// flattened.push({
// domain, service_name,
// fields: Object.keys(service.fields).map(k => ({
// name: k,
// data: service.fields[k]
// })),
// target: Object.keys(service.target ?? {}).map(k => ({
// name: k,
// data: (service.target as any)[k]
// }))
// })
// }
// )
// })
// console.info(flattened)
// const summary: Record<string, Record<string, { total: number, domains: string[], values: Set<string> }>> = {}
// const fields: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
// const target: Record<string, Record<string, { total: number, values: Set<string> }>> = {}
// Object.keys(data).forEach(domain =>
// Object.keys(data[domain]).forEach(
// action => {
// const service = data[domain][action];
// Object.keys(service.fields).forEach(field => {
// const value = service.fields[field];
// const valueType = `${typeof value}-${Array.isArray(value)}`;
// fields[field] = fields[field] ?? {}
// fields[field][valueType] = fields[field][valueType] ?? {
// total: 0,
// domains: [],
// values: new Set()
// }
// fields[field][valueType].total += 1
// fields[field][valueType].values.add(JSON.stringify(value))
// })
// Object.keys(service.target ?? {}).forEach(field => {
// const value = (service.target as any)[field];
// const valueType = `${typeof value}-${Array.isArray(value)}`;
// target[field] = target[field] ?? {}
// target[field][valueType] = target[field][valueType] ?? {
// total: 0,
// domains: [],
// values: new Set()
// }
// target[field][valueType].total += 1
// target[field][valueType].values.add(JSON.stringify(value))
// })
// Object.keys(service).forEach(field => {
// const value = (service as any)[field];
// const valueType = `${typeof value}-${Array.isArray(value)}`;
// summary[field] = summary[field] ?? {}
// summary[field][valueType] = summary[field][valueType] ?? {
// total: 0,
// domains: [],
// values: new Set()
// }
// summary[field][valueType].total += 1
// summary[field][valueType].domains.push(`${domain}.${action}`)
// summary[field][valueType].values.add(JSON.stringify(value))
// })
// }
// )
// )
const [domain, setDomain] = useState(options[0] ?? "");
const domains = Object.keys(data[domain] ?? "").sort();
@@ -97,8 +20,11 @@ const Test: FC = () => {
const [service, setService] = useState(domains[0] ?? "");
const serviceDefn = (data[domain] ?? {})[service] ?? {};
const [serviceData, setServiceData] = useState({ field: {}, target: {} });
useEffect(() => {
setService(domains[0] ?? "");
setServiceData({ field: {}, target: {} });
}, [domain, setService]);
let serviceEditElm = <>Failed to load</>;
@@ -117,8 +43,8 @@ const Test: FC = () => {
<ServiceEditor
service={serviceDefn}
serviceId={`${domain}.${service}`}
data={{ field: {}, target: {} }}
onUpdate={() => {}}
data={serviceData}
onUpdate={setServiceData}
/>
</div>
);
@@ -141,64 +67,15 @@ const Test: FC = () => {
onChange={setService}
options={domains}
/>
<Button onClick={() => callService(domain, service)}>Call</Button>
<Button
onClick={() =>
callService(domain, service, serviceData.field, serviceData.target)
}
>
Call
</Button>
{serviceEditElm}
<InputYaml label="Service Data" value={serviceDefn} onChange={() => {}} />
<code>{JSON.stringify(serviceDefn, null, 4)}</code>
{/* <ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(summary).map(k => <li key={k}>
<b>{k}</b> <ul>
{Object.keys(summary[k]).map(t => <li key={k + t}>
<b>{t}</b> ({summary[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(summary[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul>
<h1>Fields</h1>
<ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(fields).map(k => <li key={k}>
<b>{k}</b> <ul>
{Object.keys(fields[k]).map(t => <li key={k + t}>
<b>{t}</b> ({fields[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(fields[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul>
<h1>Targets</h1>
<ul style={{
maxHeight: '20vh',
overflow: 'auto',
}}>
{Object.keys(target).map(k => <li key={k}>
<b>{k}</b> <ul>
{Object.keys(target[k]).map(t => <li key={k + t}>
<b>{t}</b> ({target[k][t].total})
<ul style={{ maxHeight: '200px', overflow: 'auto' }}>
{Array.from(target[k][t].values.values()).sort().map((v, i) => <li key={i}>
{v}
</li>)}
</ul>
</li>)}
</ul>
</li>)}
</ul> */}
</div>
);
};
@@ -210,7 +87,7 @@ export default {
args: {},
} as ComponentMeta<typeof Test>;
export const Base: ComponentStory<typeof Test> = (props) => {
export const ServiceCall: ComponentStory<typeof Test> = (props) => {
return (
<Page>
<Test {...props} />
+20 -24
View File
@@ -1,15 +1,15 @@
import { Collection, Connection } from "home-assistant-js-websocket";
import { useState, useEffect } from "react";
import { useState, useEffect, useRef, useMemo } from "react";
import { useHAConnection } from "./connection";
type _HACollectionState<T> =
| {
ready: false;
collection?: Collection<T>;
collection?: undefined;
}
| {
ready: true;
collection: Collection<T>;
collection: T;
};
export type HACollectionState<T, D = {}> = _HACollectionState<T> & {
additional: Partial<D>;
@@ -22,39 +22,35 @@ export const useHassCollection = <T, D extends {} = {}>(
ready: false,
});
const conn = useHAConnection();
const collection = useMemo(() => {
if (conn.status === "loaded") {
return getHACollection(conn.connection);
}
}, [conn.status]);
useEffect(() => {
if (conn.status === "loaded" && !state.ready) {
const collection = getHACollection(conn.connection);
if (collection) {
setState({
ready: false,
collection,
ready: true,
collection: collection.state,
});
const unsub = collection.subscribe((d) => {
console.log("updating collection", d);
if (d && !state.ready) {
setState({
ready: true,
collection,
});
// unsub();
} else if (!d && state.ready) {
setState({
ready: true,
collection,
});
// unsub();
}
setState({
ready: true,
collection: d,
});
});
return unsub;
return () => {
unsub();
};
}
}, [conn, getHACollection, state.ready]);
}, [collection, state.ready]);
return {
...state,
get additional(): Partial<D> {
if (state.ready && updateAdditionalProps) {
return updateAdditionalProps(state.collection.state);
return updateAdditionalProps(state.collection ?? {});
}
return {};
},