generic ha extras
This commit is contained in:
1 parent
0b183353d3
commit
04f3e6194f
6 files changed
+186
-161
No files matched your search
@@ -13,8 +13,16 @@ export const ActionDeviceState: OptionManager<DeviceAction> = {
|
||||
isReady: () => true,
|
||||
Component: ({ state, setState, ha }) => {
|
||||
const update = updateActionData(state, setState);
|
||||
const options = ha.deviceExtras.useDeviceActions(state.device_id);
|
||||
const caps = ha.deviceExtras.useDeviceCapalities(state as any);
|
||||
const options = ha.deviceExtras.useDeviceActions(
|
||||
state.device_id
|
||||
? {
|
||||
deviceId: state.device_id,
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
const caps = ha.deviceExtras.useDeviceCapalities(
|
||||
state.device_id && state.type && state.domain ? (state as any) : undefined
|
||||
);
|
||||
// aliases
|
||||
let actions: DeviceAction[] = [];
|
||||
if (options.length > 0 && state.type) {
|
||||
@@ -33,7 +41,7 @@ export const ActionDeviceState: OptionManager<DeviceAction> = {
|
||||
<>
|
||||
<InputDevice
|
||||
value={state.device_id ?? ""}
|
||||
onChange={(device_id) => update({ device_id: device_id ?? "" })}
|
||||
onChange={(device_id) => setState({ device_id: device_id ?? "" })}
|
||||
/>
|
||||
{options.length > 0 && (
|
||||
<InputList
|
||||
|
||||
@@ -1,101 +1,107 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
ERR_HASS_HOST_REQUIRED,
|
||||
createLongLivedTokenAuth,
|
||||
Connection,
|
||||
ERR_CANNOT_CONNECT,
|
||||
ERR_CONNECTION_LOST,
|
||||
ERR_INVALID_AUTH,
|
||||
ERR_INVALID_HTTPS_TO_HTTP,
|
||||
createConnection as _createConnection,
|
||||
ERR_HASS_HOST_REQUIRED,
|
||||
createLongLivedTokenAuth,
|
||||
Connection,
|
||||
ERR_CANNOT_CONNECT,
|
||||
ERR_CONNECTION_LOST,
|
||||
ERR_INVALID_AUTH,
|
||||
ERR_INVALID_HTTPS_TO_HTTP,
|
||||
createConnection as _createConnection,
|
||||
} from "home-assistant-js-websocket";
|
||||
import { wsURL } from 'apiService';
|
||||
import { wsURL } from "apiService";
|
||||
|
||||
export type HAConnection = {
|
||||
status: 'loading'
|
||||
} | {
|
||||
status: 'loaded',
|
||||
connection: Connection,
|
||||
} | {
|
||||
status: 'error',
|
||||
error: any,
|
||||
};
|
||||
export type HAConnection =
|
||||
| {
|
||||
status: "loading";
|
||||
}
|
||||
| {
|
||||
status: "loaded";
|
||||
connection: Connection;
|
||||
}
|
||||
| {
|
||||
status: "error";
|
||||
error: any;
|
||||
};
|
||||
let haConnection: HAConnection = {
|
||||
status: 'loading',
|
||||
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;
|
||||
}
|
||||
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 createConnection = async () => {
|
||||
try {
|
||||
return _createConnection({
|
||||
auth: createLongLivedTokenAuth(wsURL, 'xxx'),
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line
|
||||
throw {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
return _createConnection({
|
||||
auth: createLongLivedTokenAuth(wsURL, "xxx"),
|
||||
});
|
||||
} catch (error) {
|
||||
// eslint-disable-next-line
|
||||
throw {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
async function startHAConnection() {
|
||||
let connection: Connection;
|
||||
try {
|
||||
connection = await createConnection();
|
||||
} catch (error) {
|
||||
haConnection = {
|
||||
status: 'error',
|
||||
error: {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
let connection: Connection;
|
||||
try {
|
||||
connection = await createConnection();
|
||||
} catch (error) {
|
||||
haConnection = {
|
||||
status: 'loaded',
|
||||
connection,
|
||||
}
|
||||
return haConnection;
|
||||
status: "error",
|
||||
error: {
|
||||
originalError: JSON.stringify(error),
|
||||
message: translateErrorCodes(error as any),
|
||||
},
|
||||
};
|
||||
throw error;
|
||||
}
|
||||
haConnection = {
|
||||
status: "loaded",
|
||||
connection,
|
||||
};
|
||||
return haConnection;
|
||||
}
|
||||
|
||||
startHAConnection().then(console.log).catch(console.error);
|
||||
startHAConnection().then(console.info).catch(console.error);
|
||||
export const useHAConnection = (): HAConnection => {
|
||||
const [conn, setConn] = useState<HAConnection>(haConnection);
|
||||
const timeID = useRef<number | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (conn.status !== haConnection.status) {
|
||||
setConn(haConnection);
|
||||
}
|
||||
const waiter = () => {
|
||||
if (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;
|
||||
};
|
||||
const [conn, setConn] = useState<HAConnection>(haConnection);
|
||||
const timeID = useRef<number | undefined>(undefined);
|
||||
useEffect(() => {
|
||||
if (conn.status !== haConnection.status) {
|
||||
setConn(haConnection);
|
||||
}
|
||||
const waiter = () => {
|
||||
if (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;
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { MessageBase } from "home-assistant-js-websocket";
|
||||
import { OptionsObject, useSnackbar } from "notistack";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { HASendMessage } from "./types";
|
||||
@@ -17,68 +18,79 @@ export type DeviceTypeCapability = {
|
||||
}>;
|
||||
};
|
||||
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
|
||||
return {
|
||||
useDeviceActions(deviceId?: string) {
|
||||
const lastDeviceId = useRef<string | null>(null);
|
||||
const [options, setOptions] = useState<
|
||||
Array<{
|
||||
type: string;
|
||||
actions: DeviceTypeAction[];
|
||||
}>
|
||||
>([]);
|
||||
const createUseThing = function <Args, HAData, STData>(
|
||||
convertArgsToMessage: (a: Args) => MessageBase,
|
||||
transformHAData: (ha: HAData) => STData,
|
||||
defaultSTData: STData
|
||||
) {
|
||||
return function useThis(args?: Args) {
|
||||
const lastThing = useRef<string | null>(null);
|
||||
const [stData, setStData] = useState<STData>(defaultSTData);
|
||||
useEffect(() => {
|
||||
if (deviceId && lastDeviceId.current !== deviceId) {
|
||||
lastDeviceId.current = deviceId;
|
||||
callHA({
|
||||
type: "device_automation/action/list",
|
||||
device_id: deviceId,
|
||||
}).then((data: any[]) => {
|
||||
if (lastDeviceId.current === deviceId) {
|
||||
const dataMap: Record<string, DeviceTypeAction[]> = data.reduce(
|
||||
(all = {}, opt: any) => {
|
||||
if (!all[opt.type]) {
|
||||
all[opt.type] = [];
|
||||
}
|
||||
all[opt.type].push(opt);
|
||||
return all;
|
||||
},
|
||||
{}
|
||||
);
|
||||
setOptions(
|
||||
Object.keys(dataMap).map((type) => ({
|
||||
type,
|
||||
actions: dataMap[type],
|
||||
}))
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [deviceId]);
|
||||
return options;
|
||||
},
|
||||
useDeviceCapalities(action?: DeviceTypeAction) {
|
||||
const snackbr = useSnackbar();
|
||||
const lastAction = useRef<string | null>(null);
|
||||
const [caps, setCaps] = useState<Partial<DeviceTypeCapability>>({});
|
||||
useEffect(() => {
|
||||
const currentAction = JSON.stringify(action);
|
||||
if (action && lastAction.current !== currentAction) {
|
||||
lastAction.current = currentAction;
|
||||
callHA({
|
||||
type: "device_automation/action/capabilities",
|
||||
action,
|
||||
})
|
||||
.then((data: DeviceTypeCapability) => {
|
||||
if (lastAction.current === currentAction) {
|
||||
setCaps(data);
|
||||
const currentThing = JSON.stringify(args);
|
||||
if (args && currentThing && lastThing.current !== currentThing) {
|
||||
lastThing.current = currentThing;
|
||||
const msg = convertArgsToMessage(args);
|
||||
callHA(msg)
|
||||
.then((raw: HAData) => {
|
||||
if (lastThing.current === currentThing) {
|
||||
setStData(transformHAData(raw));
|
||||
}
|
||||
})
|
||||
.catch((err) => {
|
||||
console.warn(err);
|
||||
.catch((error) => {
|
||||
console.warn({ msg, args, currentThing, error });
|
||||
});
|
||||
} else if (lastThing.current !== currentThing) {
|
||||
lastThing.current = currentThing;
|
||||
setStData(defaultSTData);
|
||||
}
|
||||
}, [action]);
|
||||
return caps;
|
||||
},
|
||||
}, [args]);
|
||||
return stData;
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
useDeviceActions: createUseThing<
|
||||
{ deviceId: string },
|
||||
any[],
|
||||
Array<{
|
||||
type: string;
|
||||
actions: DeviceTypeAction[];
|
||||
}>
|
||||
>(
|
||||
({ deviceId }) => ({
|
||||
type: "device_automation/action/list",
|
||||
device_id: deviceId,
|
||||
}),
|
||||
(data) => {
|
||||
const dataMap: Record<string, DeviceTypeAction[]> = data.reduce(
|
||||
(all = {}, opt: any) => {
|
||||
if (!all[opt.type]) {
|
||||
all[opt.type] = [];
|
||||
}
|
||||
all[opt.type].push(opt);
|
||||
return all;
|
||||
},
|
||||
{}
|
||||
);
|
||||
return Object.keys(dataMap).map((type) => ({
|
||||
type,
|
||||
actions: dataMap[type],
|
||||
}));
|
||||
},
|
||||
[]
|
||||
),
|
||||
useDeviceCapalities: createUseThing<
|
||||
DeviceTypeAction,
|
||||
DeviceTypeCapability,
|
||||
Partial<DeviceTypeCapability>
|
||||
>(
|
||||
(action) => ({
|
||||
type: "device_automation/action/capabilities",
|
||||
action,
|
||||
}),
|
||||
(data) => data,
|
||||
{}
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -37,7 +37,7 @@ const Test: FC = () => {
|
||||
// )
|
||||
// })
|
||||
|
||||
// console.log(flattened)
|
||||
// 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> }>> = {}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { MessageBase } from "home-assistant-js-websocket";
|
||||
|
||||
export type EntityRegisteryItem = {
|
||||
area_id: null | string;
|
||||
config_entry_id: null | string;
|
||||
@@ -23,6 +25,4 @@ export type DeviceRegistryItem = {
|
||||
|
||||
export type HassDevices = Array<DeviceRegistryItem>;
|
||||
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
|
||||
export type HASendMessage = (
|
||||
sendMsg: { type: string } & Record<string, any>
|
||||
) => Promise<any>;
|
||||
export type HASendMessage = (sendMsg: MessageBase) => Promise<any>;
|
||||
+9
-10
@@ -1,25 +1,24 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './styles/root.css';
|
||||
import App from './App';
|
||||
import reportWebVitals from './reportWebVitals';
|
||||
import React from "react";
|
||||
import ReactDOM from "react-dom";
|
||||
import "./styles/root.css";
|
||||
import App from "./App";
|
||||
import reportWebVitals from "./reportWebVitals";
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
document.getElementById("root")
|
||||
);
|
||||
|
||||
// If you want to start measuring performance in your app, pass a function
|
||||
// to log results (for example: reportWebVitals(console.log))
|
||||
// to log results (for example: reportWebVitals(console.info))
|
||||
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
|
||||
reportWebVitals();
|
||||
|
||||
reportWebVitals(console.info);
|
||||
|
||||
// import { createRoot } from 'react-dom/client';
|
||||
// const container = document.getElementById('root');
|
||||
// const root = createRoot(container!);
|
||||
// root.render(<React.StrictMode>
|
||||
// <App />
|
||||
// </React.StrictMode>);
|
||||
// </React.StrictMode>);
|
||||
Reference in new issue
Block a user