input entities
This commit is contained in:
1 parent
878035e748
commit
996626f9af
27 files changed
+596
-92
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import React, { FC } from "react";
|
||||
import { ComponentMeta, ComponentStory } from '@storybook/react';
|
||||
import { Page } from "components/Page";
|
||||
import { useHAConnection } from './connection';
|
||||
|
||||
const Test: FC = () => {
|
||||
const conn = useHAConnection();
|
||||
|
||||
return <code>
|
||||
{JSON.stringify(conn, null, 4)}
|
||||
</code>
|
||||
}
|
||||
|
||||
export default {
|
||||
title: 'Services/HA Service',
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {
|
||||
}
|
||||
} as ComponentMeta<typeof Test>
|
||||
|
||||
export const Base: ComponentStory<typeof Test> = props => {
|
||||
|
||||
return <Page>
|
||||
<Test {...props} />
|
||||
</Page>
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import {
|
||||
getAuth,
|
||||
createConnection,
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
createLongLivedTokenAuth,
|
||||
Auth,
|
||||
Connection,
|
||||
ERR_CANNOT_CONNECT,
|
||||
ERR_CONNECTION_LOST,
|
||||
ERR_INVALID_AUTH,
|
||||
ERR_INVALID_HTTPS_TO_HTTP,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { useDelayEffect } from 'utils/useDelay';
|
||||
|
||||
const HASS_URL = process.env.REACT_APP_HASS_URL as string;
|
||||
const HASS_TOKEN = process.env.REACT_APP_HASS_TOKEN;
|
||||
@@ -24,6 +27,25 @@ let haConnection: HAConnection = {
|
||||
status: 'loading',
|
||||
};
|
||||
|
||||
const translateErrorCodes = (errorCode: number) => {
|
||||
if (errorCode === ERR_HASS_HOST_REQUIRED) {
|
||||
return "Missing HASS host"
|
||||
}
|
||||
if (errorCode === ERR_CANNOT_CONNECT) {
|
||||
return "Failed to connect"
|
||||
}
|
||||
if (errorCode === ERR_CONNECTION_LOST) {
|
||||
return "Connection Lost"
|
||||
}
|
||||
if (errorCode === ERR_INVALID_AUTH) {
|
||||
return "Invalid Host"
|
||||
}
|
||||
if (errorCode === ERR_INVALID_HTTPS_TO_HTTP) {
|
||||
return "Invalid https to http"
|
||||
}
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
const createAuth = async () => {
|
||||
console.log("detecting auth")
|
||||
let auth: Auth
|
||||
@@ -61,7 +83,7 @@ async function startHAConnection() {
|
||||
} catch (error) {
|
||||
haConnection = {
|
||||
status: 'error',
|
||||
error,
|
||||
error: translateErrorCodes(error),
|
||||
}
|
||||
throw error
|
||||
}
|
||||
@@ -70,10 +92,24 @@ async function startHAConnection() {
|
||||
startHAConnection().then(console.log).catch(console.error);
|
||||
export const useHAConnection = (): HAConnection => {
|
||||
const [conn, setConn] = useState<HAConnection>(haConnection);
|
||||
useDelayEffect(() => {
|
||||
const timeID = useRef<number | undefined>(undefined);
|
||||
console.log("connecting to HA")
|
||||
useEffect(() => {
|
||||
console.log('connection state', conn.status)
|
||||
if (conn.status !== haConnection.status) {
|
||||
setConn(haConnection);
|
||||
}
|
||||
}, [conn], conn.status === 'loading' ? 500 : 50000);
|
||||
const waiter = () => {
|
||||
if (conn.status !== haConnection.status) {
|
||||
console.log('setting status', conn.status, haConnection.status)
|
||||
setConn(haConnection);
|
||||
}
|
||||
timeID.current = window.setTimeout(() => {
|
||||
waiter()
|
||||
}, conn.status === 'loading' ? 500 : 5000)
|
||||
}
|
||||
waiter()
|
||||
return () => window.clearTimeout(timeID.current)
|
||||
}, [conn, setConn])
|
||||
return conn;
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import React, { FC } from "react";
|
||||
import { ComponentMeta, ComponentStory } from '@storybook/react';
|
||||
import { Page } from "components/Page";
|
||||
import { useHAEntities } from "haService";
|
||||
|
||||
const Test: FC<{ onRender: () => void }> = ({ onRender }) => {
|
||||
const conn = useHAEntities();
|
||||
onRender && onRender()
|
||||
return <code>
|
||||
{JSON.stringify(conn, null, 4)}
|
||||
</code>
|
||||
}
|
||||
|
||||
export default {
|
||||
title: 'Services/HA Entities',
|
||||
component: Test,
|
||||
parameters: { actions: { argTypesRegex: '^on.*' } },
|
||||
args: {}
|
||||
} as ComponentMeta<typeof Test>
|
||||
|
||||
export const Base: ComponentStory<typeof Test> = props => {
|
||||
|
||||
return <Page>
|
||||
<Test {...props} />
|
||||
</Page>
|
||||
};
|
||||
@@ -1,13 +1,77 @@
|
||||
import { entitiesColl, servicesColl } from "home-assistant-js-websocket"
|
||||
import { useHassCollection } from "./useHassCollection"
|
||||
|
||||
export type Option = string | {
|
||||
id: string,
|
||||
label: string,
|
||||
domain: string,
|
||||
}
|
||||
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
|
||||
export const useHAEntities = () => {
|
||||
const entities = useHassCollection(entitiesColl, state => ({
|
||||
domains: Array.from(new Set(Object.keys(state).map(x => x.split('.')[0])).keys()).sort(),
|
||||
}));
|
||||
const methods = {
|
||||
getDomainList(): string[] {
|
||||
return entities.additional?.domains ?? []
|
||||
},
|
||||
validateOptions(options: string[], restrictedDomains?: string[]): null | string[] {
|
||||
if (restrictedDomains) {
|
||||
const domains = restrictedDomains.map(x => x.toLowerCase())
|
||||
const domainsStr = domains.length > 1 ?
|
||||
`one of "${domains.join(', ')}"` :
|
||||
`"${domains[0]}"`
|
||||
return options.reduce<string[]>((all = [], key) => {
|
||||
if (!domains.includes(key.toLowerCase().split('.')[0])) {
|
||||
return [
|
||||
...all,
|
||||
`${methods.getLabel(key)} is not ${domainsStr}`
|
||||
]
|
||||
}
|
||||
return all
|
||||
}, [])
|
||||
}
|
||||
return null
|
||||
},
|
||||
getOptions(restrictToDomain?: string[]): Option[] {
|
||||
if (!entities.ready) {
|
||||
return []
|
||||
}
|
||||
let keys = Object.keys(entities.collection.state);
|
||||
if (restrictToDomain) {
|
||||
const domains = restrictToDomain.map(x => x.toLowerCase())
|
||||
keys = keys.filter(key => domains.includes(key.toLowerCase().split('.')[0]))
|
||||
}
|
||||
return keys.map(key => ({
|
||||
id: key,
|
||||
label: entities.collection.state[key].attributes.friendly_name ?? key,
|
||||
domain: key.split('.')[0] ?? "n/a",
|
||||
}))
|
||||
},
|
||||
getLabel: (opt: Option): string => {
|
||||
if (typeof opt === 'string') {
|
||||
if (entities.ready) {
|
||||
return entities.collection.state[opt]?.attributes.friendly_name ?? opt;
|
||||
}
|
||||
return opt
|
||||
}
|
||||
return opt.label ?? opt.id
|
||||
},
|
||||
getID: (opt: Option): string => {
|
||||
if (typeof opt === 'string') {
|
||||
return opt
|
||||
}
|
||||
return opt.id
|
||||
}
|
||||
}
|
||||
return {
|
||||
...entities,
|
||||
...methods
|
||||
}
|
||||
}
|
||||
|
||||
export const useHAService = () => {
|
||||
const entities = useHassCollection(entitiesColl);
|
||||
export const useHAServices = () => {
|
||||
const services = useHassCollection(servicesColl);
|
||||
|
||||
return {
|
||||
entities,
|
||||
services,
|
||||
}
|
||||
return services
|
||||
}
|
||||
@@ -9,7 +9,10 @@ export type HACollectionState<T> = {
|
||||
ready: true,
|
||||
collection: Collection<T>,
|
||||
}
|
||||
export const useHassCollection = <T>(getHACollection: (c: Connection) => Collection<T>) => {
|
||||
export const useHassCollection = <T, D extends {} = {}>(
|
||||
getHACollection: (c: Connection) => Collection<T>,
|
||||
updateAdditionalProps?: (n: T | {}) => D,
|
||||
) => {
|
||||
const [state, setState] = useState<HACollectionState<T>>({
|
||||
ready: false
|
||||
});
|
||||
@@ -22,21 +25,32 @@ export const useHassCollection = <T>(getHACollection: (c: Connection) => Collect
|
||||
ready: false,
|
||||
collection,
|
||||
})
|
||||
return collection.subscribe(d => {
|
||||
const unsub = collection.subscribe(d => {
|
||||
if (d && !state.ready) {
|
||||
setState({
|
||||
ready: true,
|
||||
collection,
|
||||
})
|
||||
unsub();
|
||||
} else if (!d && state.ready) {
|
||||
setState({
|
||||
ready: true,
|
||||
collection,
|
||||
})
|
||||
unsub();
|
||||
}
|
||||
})
|
||||
});
|
||||
return unsub
|
||||
}
|
||||
}, [conn, getHACollection, state.ready]);
|
||||
|
||||
return state;
|
||||
return {
|
||||
...state,
|
||||
get additional(): Partial<D> {
|
||||
if (state.ready && updateAdditionalProps) {
|
||||
return updateAdditionalProps(state.collection.state)
|
||||
}
|
||||
return {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user