From 883955e523aed18391e5444646f280dddd36bfd4 Mon Sep 17 00:00:00 2001 From: Ari Date: Thu, 28 Jul 2022 22:27:57 -0400 Subject: [PATCH] refactored entity listener so that live events actually come in --- .../src/components/AutomationManager/TagDB.ts | 2 - .../components/AutomationManager/index.tsx | 2 +- webapp/src/haService/AreaRegistry.ts | 18 +-- webapp/src/haService/HAEntities.mock.ts | 22 +-- webapp/src/haService/HAEntities.ts | 30 ++-- webapp/src/haService/automation.stories.tsx | 94 +++++++++++ webapp/src/haService/dr.stories.tsx | 73 +++++---- webapp/src/haService/entities.stories.tsx | 2 +- webapp/src/haService/er.stories.tsx | 4 +- webapp/src/haService/index.ts | 38 ++--- webapp/src/haService/services.stories.tsx | 151 ++---------------- webapp/src/haService/useHassCollection.ts | 44 +++-- 12 files changed, 214 insertions(+), 266 deletions(-) create mode 100644 webapp/src/haService/automation.stories.tsx diff --git a/webapp/src/components/AutomationManager/TagDB.ts b/webapp/src/components/AutomationManager/TagDB.ts index 63c00f7..4099ffa 100644 --- a/webapp/src/components/AutomationManager/TagDB.ts +++ b/webapp/src/components/AutomationManager/TagDB.ts @@ -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(), diff --git a/webapp/src/components/AutomationManager/index.tsx b/webapp/src/components/AutomationManager/index.tsx index 4546d57..4f3d5d6 100644 --- a/webapp/src/components/AutomationManager/index.tsx +++ b/webapp/src/components/AutomationManager/index.tsx @@ -52,7 +52,7 @@ export const AutomationManager: FC = ({ // alias const configAutomations = api.state.automations.data; - const hassEntities = haEntities.collection.state; + const hassEntities = haEntities.collection; return ( { 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; diff --git a/webapp/src/haService/HAEntities.mock.ts b/webapp/src/haService/HAEntities.mock.ts index 80a607d..805dc0c 100644 --- a/webapp/src/haService/HAEntities.mock.ts +++ b/webapp/src/haService/HAEntities.mock.ts @@ -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, } ); } diff --git a/webapp/src/haService/HAEntities.ts b/webapp/src/haService/HAEntities.ts index 5fb8ff0..a1400f3 100644 --- a/webapp/src/haService/HAEntities.ts +++ b/webapp/src/haService/HAEntities.ts @@ -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 = 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 = 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((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; } diff --git a/webapp/src/haService/automation.stories.tsx b/webapp/src/haService/automation.stories.tsx new file mode 100644 index 0000000..0230279 --- /dev/null +++ b/webapp/src/haService/automation.stories.tsx @@ -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 = ( +
+ +
+ ); + } + } catch (err) { + serviceEditElm = <>{JSON.stringify(err)}; + } + + return ( +
+ + + {serviceEditElm} + {}} /> + {(((serviceData.target ?? {}) as any).entity_id ?? []).map((eid: any) => ( + + {eid}: {entities.getStates([eid])} + + ))} +
+ ); +}; + +export default { + title: "Services/HA Service", + component: Test, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; + +export const AutomationCall: ComponentStory = (props) => { + return ( + + + + ); +}; diff --git a/webapp/src/haService/dr.stories.tsx b/webapp/src/haService/dr.stories.tsx index 4feb3ca..d8a6ad7 100644 --- a/webapp/src/haService/dr.stories.tsx +++ b/webapp/src/haService/dr.stories.tsx @@ -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
- {Object.keys(conn.collection.state).length} items -
    - {Object.keys(conn.collection.state).map(k =>
  • - {k} - {/* {conn.collection.state[k].length > 1 ? conn.collection.state[k].length : ''} */} - { }} label={k} /> -
  • )} -
-
- } - return - Loading... - -} + const conn = useHADeviceRegistry(); + onRender && onRender(); + if (conn.ready) { + return ( +
+ {Object.keys(conn.collection).length} items +
    + {Object.keys(conn.collection).map((k) => ( +
  • + {k} + {/* {conn.collection[k].length > 1 ? conn.collection[k].length : ''} */} + {}} + label={k} + /> +
  • + ))} +
+
+ ); + } + return Loading...; +}; export default { - title: 'Services/Device Registry', - component: Test, - parameters: { actions: { argTypesRegex: '^on.*' } }, - args: {} -} as ComponentMeta + title: "Services/Device Registry", + component: Test, + parameters: { actions: { argTypesRegex: "^on.*" } }, + args: {}, +} as ComponentMeta; -export const Base: ComponentStory = props => { - - return - +export const Base: ComponentStory = (props) => { + return ( + + -}; \ No newline at end of file + ); +}; diff --git a/webapp/src/haService/entities.stories.tsx b/webapp/src/haService/entities.stories.tsx index 7ae97ac..526fd6a 100644 --- a/webapp/src/haService/entities.stories.tsx +++ b/webapp/src/haService/entities.stories.tsx @@ -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 ( diff --git a/webapp/src/haService/er.stories.tsx b/webapp/src/haService/er.stories.tsx index 18363b9..902e3e2 100644 --- a/webapp/src/haService/er.stories.tsx +++ b/webapp/src/haService/er.stories.tsx @@ -9,14 +9,14 @@ const Test: FC<{ onRender: () => void }> = ({ onRender }) => { if (conn.ready) { return (
- {conn.collection.state.length} + {conn.collection.length}
    - {conn.collection.state.map((row, i) => ( + {conn.collection.map((row, i) => (
  • {row.entity_id} {/* {Object.keys(row).map(k => <> diff --git a/webapp/src/haService/index.ts b/webapp/src/haService/index.ts index 9983d45..61aaed0 100644 --- a/webapp/src/haService/index.ts +++ b/webapp/src/haService/index.ts @@ -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( + return Object.keys(services.collection).reduce( (all, domain) => { const opts = Object.keys( - services.collection.state[domain] + services.collection[domain] ).map((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; } diff --git a/webapp/src/haService/services.stories.tsx b/webapp/src/haService/services.stories.tsx index 43ab013..7705437 100644 --- a/webapp/src/haService/services.stories.tsx +++ b/webapp/src/haService/services.stories.tsx @@ -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 }>> = {} - // const fields: Record }>> = {} - // const target: Record }>> = {} - - // 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 = () => { {}} + data={serviceData} + onUpdate={setServiceData} />
); @@ -141,64 +67,15 @@ const Test: FC = () => { onChange={setService} options={domains} /> - + {serviceEditElm} {}} /> - {JSON.stringify(serviceDefn, null, 4)} - - {/*
    - {Object.keys(summary).map(k =>
  • - {k}
      - {Object.keys(summary[k]).map(t =>
    • - {t} ({summary[k][t].total}) -
        - {Array.from(summary[k][t].values.values()).sort().map((v, i) =>
      • - {v} -
      • )} -
      -
    • )} -
    -
  • )} -
-

Fields

-
    - {Object.keys(fields).map(k =>
  • - {k}
      - {Object.keys(fields[k]).map(t =>
    • - {t} ({fields[k][t].total}) -
        - {Array.from(fields[k][t].values.values()).sort().map((v, i) =>
      • - {v} -
      • )} -
      -
    • )} -
    -
  • )} -
-

Targets

-
    - {Object.keys(target).map(k =>
  • - {k}
      - {Object.keys(target[k]).map(t =>
    • - {t} ({target[k][t].total}) -
        - {Array.from(target[k][t].values.values()).sort().map((v, i) =>
      • - {v} -
      • )} -
      -
    • )} -
    -
  • )} -
*/} ); }; @@ -210,7 +87,7 @@ export default { args: {}, } as ComponentMeta; -export const Base: ComponentStory = (props) => { +export const ServiceCall: ComponentStory = (props) => { return ( diff --git a/webapp/src/haService/useHassCollection.ts b/webapp/src/haService/useHassCollection.ts index d3fe64a..3976b1c 100644 --- a/webapp/src/haService/useHassCollection.ts +++ b/webapp/src/haService/useHassCollection.ts @@ -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 = | { ready: false; - collection?: Collection; + collection?: undefined; } | { ready: true; - collection: Collection; + collection: T; }; export type HACollectionState = _HACollectionState & { additional: Partial; @@ -22,39 +22,35 @@ export const useHassCollection = ( 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 { if (state.ready && updateAdditionalProps) { - return updateAdditionalProps(state.collection.state); + return updateAdditionalProps(state.collection ?? {}); } return {}; },