generic device editor

This commit is contained in:
ari committed 2022-06-17 16:56:51 -04:00
1 parent ab8ecfeefb
commit 1ce934fd54
11 files changed
+322 -311

No files matched your search

@@ -0,0 +1,96 @@
import {
BaseOption,
InputAutoComplete,
} from "components/Inputs/InputAutoComplete";
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import InputText from "components/Inputs/InputText";
import { cleanUpUndefined } from "components/NodeEditor/OptionManager/OptionManager";
import { DeviceBaseType, DeviceTypeCapability } from "haService/types";
import { AutomationDeviceState } from "types/automations/common";
import { prettyName } from "utils/formatting";
export type DeviceEditorProps<DBT extends DeviceBaseType> = {
type: "action" | "condition" | "trigger";
state: Partial<AutomationDeviceState>;
setState: (n: Partial<AutomationDeviceState & Record<string, any>>) => void;
options: Record<string, BaseOption<{ data: DBT[] }>>;
caps: Partial<DeviceTypeCapability>;
};
export function DeviceEditor<DBT extends DeviceBaseType>({
type,
state,
setState,
caps,
options,
}: DeviceEditorProps<DBT>) {
// aliases
const update = (upd: Partial<AutomationDeviceState & Record<string, any>>) =>
setState(
cleanUpUndefined({
...state,
...upd,
})
);
const actionId = (state.type ?? "") + (state.subtype ?? "");
const entities = ((options[actionId] ?? {}).data ?? [])
.map(({ entity_id }) => entity_id)
.filter((x) => !!x) as string[];
// render
return (
<>
<InputDevice
label="Device"
value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/>
<InputAutoComplete
label="Action"
multiple={false}
value={actionId}
options={Object.keys(options).map((k) => options[k])}
disabled={Object.keys(options).length === 0}
onChange={(key) => {
if (key) {
const opt = options[key].data[0];
const updateObj: any = { ...opt };
delete updateObj["metadata"];
setState(updateObj);
} else {
setState({
device_id: state.device_id,
});
}
}}
/>
{entities.length > 0 && (
<InputEntity
key={"entities" + state.device_id}
label="Entity"
value={state.entity_id ?? ""}
multiple={false}
onChange={(entity_id) =>
update({ entity_id: entity_id ?? undefined })
}
preSelectedEntityIds={entities}
/>
)}
{caps?.extra_fields &&
caps.extra_fields.map((field) => (
<InputText
key={"extra" + state.device_id + field.name}
label={prettyName(field.name)}
value={(state as any)[field.name] ?? ""}
onChange={(v) =>
update({
[field.name]: v,
})
}
/>
))}
{Object.keys(options).length + entities.length === 0 && (
<>This device has no {type}s.</>
)}
</>
);
}
@@ -0,0 +1,5 @@
import { FC } from "react";
export const InputDeviceCapabilties: FC<{}> = () => {
return <></>;
};
@@ -1,11 +1,6 @@
import { InputAutoComplete } from "components/Inputs/InputAutoComplete";
import { InputDevice } from "components/Inputs/InputDevice";
import { InputEntity } from "components/Inputs/InputEntities";
import { InputList } from "components/Inputs/InputList";
import InputText from "components/Inputs/InputText";
import { DeviceEditor } from "components/DeviceEditor";
import { DeviceAction } from "types/automations/actions";
import { prettyName } from "utils/formatting";
import { OptionManager, updateActionData } from "./OptionManager";
import { OptionManager } from "./OptionManager";
export const ActionDeviceState: OptionManager<DeviceAction> = {
defaultState: () => ({
alias: "",
@@ -13,7 +8,6 @@ export const ActionDeviceState: OptionManager<DeviceAction> = {
}),
isReady: () => true,
Component: ({ state, setState, ha }) => {
const update = updateActionData(state, setState);
const options = ha.deviceExtras.useDeviceActions(
state.device_id
? {
@@ -24,67 +18,14 @@ export const ActionDeviceState: OptionManager<DeviceAction> = {
const caps = ha.deviceExtras.useDeviceCapalities(
state.device_id && state.type && state.domain ? (state as any) : undefined
);
// aliases
const actionId = (state.type ?? "") + (state.subtype ?? "");
const entities = ((options[actionId] ?? {}).data ?? [])
.map(({ entity_id }) => entity_id)
.filter((x) => !!x) as string[];
// render
return (
<>
<InputDevice
label="Device"
value={state.device_id ?? ""}
onChange={(device_id) => setState({ device_id: device_id ?? "" })}
/>
<InputAutoComplete
label="Action"
multiple={false}
value={actionId}
options={Object.keys(options).map((k) => options[k])}
disabled={Object.keys(options).length === 0}
onChange={(key) => {
if (key) {
const opt = options[key].data[0];
const updateObj: any = { ...opt };
delete updateObj["metadata"];
setState(updateObj);
} else {
setState({
device_id: state.device_id,
});
}
}}
/>
{entities.length > 0 && (
<InputEntity
key={"entities" + state.device_id}
label="Entity"
value={state.entity_id ?? ""}
multiple={false}
onChange={(entity_id) =>
update({ entity_id: entity_id ?? undefined })
}
preSelectedEntityIds={entities}
/>
)}
{caps?.extra_fields &&
caps.extra_fields.map((field) => (
<InputText
key={"extra" + state.device_id + field.name}
label={prettyName(field.name)}
value={(state as any)[field.name] ?? ""}
onChange={(v) =>
update({
[field.name]: v,
})
}
/>
))}
{Object.keys(options).length + entities.length === 0 && (
<>This device has no actions.</>
)}
</>
<DeviceEditor
state={state}
setState={setState}
options={options}
caps={caps}
type="action"
/>
);
},
};
@@ -1,16 +1,6 @@
import { OptionManager } from "./OptionManager";
import { AutomationTriggerDevice } from "types/automations/triggers";
import InputText from "components/Inputs/InputText";
import { InputEntity } from "components/Inputs/InputEntities";
import InputTextBubble from "components/Inputs/InputTextBubble";
import { InputDevice } from "components/Inputs/InputDevice";
import InputAutoText from "components/Inputs/InputAutoText";
import {
BaseOption,
InputAutoComplete,
} from "components/Inputs/InputAutoComplete";
import { prettyName } from "utils/formatting";
import { DeviceTypeTrigger } from "haService/extras";
import { DeviceEditor } from "components/DeviceEditor";
export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
defaultState: () => ({
@@ -18,61 +8,31 @@ export const TriggerDevice: OptionManager<AutomationTriggerDevice> = {
}),
isReady: () => true,
Component: ({ state, setState, ha }) => {
const triggers: Record<
string,
BaseOption<{
data: DeviceTypeTrigger;
}>
> = ha.deviceExtras
.useDeviceTriggers(
state.device_id
? {
deviceId: state.device_id,
}
: undefined
)
.reduce(
(all, opt) => ({
...all,
[opt.type + (opt.subtype ?? "")]: {
id: opt.type + (opt.subtype ?? ""),
label:
prettyName(opt.type) + (opt.subtype ? ` ${opt.subtype}` : ""),
data: opt,
},
}),
{}
);
return (
<>
<InputDevice
label="Device"
value={state.device_id ?? ""}
onChange={(device_id) =>
setState({ device_id: device_id ?? "", platform: "device" })
// state
const triggers = ha.deviceExtras.useDeviceTriggers(
state.device_id
? {
deviceId: state.device_id,
}
/>
<InputAutoComplete
label="Event"
multiple={false}
value={(state.type ?? "") + (state.subtype ?? "")}
options={Object.keys(triggers).map((k) => triggers[k])}
disabled={Object.keys(triggers).length === 0}
onChange={(key) => {
if (key) {
const opt = triggers[key];
const updateObj: any = { ...opt.data };
delete updateObj["metadata"];
setState(updateObj);
} else {
setState({
device_id: state.device_id,
platform: state.platform,
});
}
}}
/>
</>
: undefined
);
const caps = ha.deviceExtras.useDeviceTriggerCapalities(
state.device_id && state.type && state.domain ? (state as any) : undefined
);
return (
<DeviceEditor
type="trigger"
state={state}
setState={(s) =>
setState({
platform: "device",
...s,
})
}
options={triggers}
caps={caps}
/>
);
},
};
@@ -68,6 +68,7 @@ DeviceTriggerExample.args = {
...DeviceTriggerExample.args,
node: {
platform: "device",
device_id: "bd83b10cb1c7aa028c12dade5b4e87d5",
},
};
+22 -30
View File
@@ -2,33 +2,13 @@ import { BaseOption } from "components/Inputs/InputAutoComplete";
import { MessageBase } from "home-assistant-js-websocket";
import { useEffect, useRef, useState } from "react";
import { prettyName } from "utils/formatting";
import { HASendMessage } from "./types";
import {
DeviceTriggerType,
DeviceTypeAction,
DeviceTypeCapability,
HASendMessage,
} from "./types";
export type DeviceTypeAction = {
type: string;
subtype?: string;
entity_id?: string;
device_id?: string;
domain: string;
};
export type DeviceTypeTrigger = {
type: string;
subtype?: string;
platform: string;
device_id: string;
entity_id?: string;
domain: string;
metadata: Record<string, any>;
} & Record<string, any>;
export type DeviceTypeCapability = {
extra_fields: Array<{
name: string;
required?: true;
optional?: true;
type: string;
}>;
};
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
const createUseThing = function <Args, HAData, STData>(
convertArgsToMessage: (a: Args) => MessageBase,
@@ -110,17 +90,29 @@ export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
(data) => data,
{}
),
useDeviceTriggerCapalities: createUseThing<
DeviceTypeAction,
DeviceTypeCapability,
Partial<DeviceTypeCapability>
>(
(trigger) => ({
type: "device_automation/trigger/capabilities",
trigger,
}),
(data) => data,
{}
),
useDeviceTriggers: createUseThing<
{ deviceId: string },
DeviceTypeTrigger[],
DeviceTypeTrigger[]
DeviceTriggerType[],
Record<string, BaseOption<{ data: DeviceTriggerType[] }>>
>(
({ deviceId }) => ({
type: "device_automation/trigger/list",
device_id: deviceId,
}),
(data) => data,
[]
reduceDeviceThings,
{}
),
};
};
+16
View File
@@ -1,4 +1,5 @@
import { MessageBase } from "home-assistant-js-websocket";
import { AutomationDeviceState } from "types/automations/common";
export type EntityRegisteryItem = {
area_id: null | string;
@@ -26,3 +27,18 @@ export type DeviceRegistryItem = {
export type HassDevices = Array<DeviceRegistryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
export type HASendMessage = (sendMsg: MessageBase) => Promise<any>;
export type DeviceBaseType = AutomationDeviceState & {
metadata: Record<string, any>;
} & Record<string, any>;
export type DeviceTypeAction = DeviceBaseType;
export type DeviceTriggerType = DeviceBaseType & {
platform: string;
};
export type DeviceTypeCapability = {
extra_fields: Array<{
name: string;
required?: true;
type: string;
}>;
};
+6 -5
View File
@@ -1,7 +1,8 @@
import * as st from 'superstruct'
import * as st from "superstruct";
import * as v from "types/validators/common";
export type AutomationTime = st.Infer<typeof v.AutomationTime>
export type AutomationTimeObject = st.Infer<typeof v.AutomationTimeObject>
export type AutomationTimeString = st.Infer<typeof v.AutomationTimeString>
export type EntityId = st.Infer<typeof v.EntityId>;
export type AutomationTime = st.Infer<typeof v.AutomationTime>;
export type AutomationTimeObject = st.Infer<typeof v.AutomationTimeObject>;
export type AutomationTimeString = st.Infer<typeof v.AutomationTimeString>;
export type EntityId = st.Infer<typeof v.EntityId>;
export type AutomationDeviceState = st.Infer<typeof v.AutomationDeviceState>;
+2 -8
View File
@@ -1,5 +1,5 @@
import * as st from "superstruct";
import { AutomationTime } from "./common";
import { AutomationDeviceState, AutomationTime } from "./common";
import { AutomationTrigger } from "./triggers";
export const AutomationActionNodeBase = st.type({
@@ -54,13 +54,7 @@ export const FireEventAction = st.intersection([
export const DeviceAction = st.intersection([
AutomationActionNodeBase,
st.type({
type: st.optional(st.string()),
subtype: st.optional(st.string()),
device_id: st.optional(st.string()),
entity_id: st.optional(st.string()),
domain: st.optional(st.string()),
}),
st.partial(AutomationDeviceState),
]);
export const ChooseAction = st.intersection([
+49 -44
View File
@@ -1,52 +1,57 @@
import * as st from 'superstruct'
import * as st from "superstruct";
export const EntityId = st.union([
st.string(),
st.array(st.string()),
])
export const AutomationTimeString = st.refine(st.string(), 'TimeString', (v, c) => {
export const EntityId = st.union([st.string(), st.array(st.string())]);
export const AutomationTimeString = st.refine(
st.string(),
"TimeString",
(v, c) => {
// https://www.home-assistant.io/docs/automation/trigger/#time-string
const bits: string[] = v.split(':')
if ((bits.length !== 2) && (bits.length !== 3)) {
return {
"branch": c.branch,
"message": "Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string",
"path": c.path,
}
const bits: string[] = v.split(":");
if (bits.length !== 2 && bits.length !== 3) {
return {
branch: c.branch,
message:
"Time string should be either in the form 'HH:MM' or 'HH:MM:SS' as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string",
path: c.path,
};
}
for (let i = 0; i < bits.length; i++) {
const b = bits[i];
const num = Number(b);
if (Number.isInteger(num)) {
let max = 23;
if (i > 0) {
max = 59;
}
if ((num < 0) || (num > max)) {
return {
"branch": c.branch,
"message": `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
"path": c.path.concat(
bits.slice(0, i)
).concat([`<<${b}>>`])
}
}
} else {
return {
"branch": c.branch,
"message": `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
"path": c.path.concat(
bits.slice(0, i)
).concat([`<<${b}>>`])
}
const b = bits[i];
const num = Number(b);
if (Number.isInteger(num)) {
let max = 23;
if (i > 0) {
max = 59;
}
if (num < 0 || num > max) {
return {
branch: c.branch,
message: `Time string should contain only positive numbers between 0-${max} as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]),
};
}
} else {
return {
branch: c.branch,
message: `Time string should contain only positive numbers as specified in https://www.home-assistant.io/docs/automation/trigger/#time-string`,
path: c.path.concat(bits.slice(0, i)).concat([`<<${b}>>`]),
};
}
}
return true
})
return true;
}
);
export const AutomationTimeObject = st.object({
hours: st.optional(st.number()),
minutes: st.optional(st.number()),
seconds: st.optional(st.number()),
milliseconds: st.optional(st.number()),
hours: st.optional(st.number()),
minutes: st.optional(st.number()),
seconds: st.optional(st.number()),
milliseconds: st.optional(st.number()),
});
export const AutomationTime = st.union([st.string(), AutomationTimeObject]);
export const AutomationDeviceState = st.type({
subtype: st.optional(st.string()),
entity_id: st.optional(st.string()),
type: st.string(),
device_id: st.string(),
domain: st.string(),
});
export const AutomationTime = st.union([st.string(), AutomationTimeObject])
+91 -91
View File
@@ -1,119 +1,119 @@
import * as st from 'superstruct'
import { AutomationTimeString, AutomationTime, EntityId } from './common'
import * as st from "superstruct";
import {
AutomationTimeString,
AutomationTime,
AutomationDeviceState,
} from "./common";
const AutomationTriggerBase = {
id: st.optional(st.string()),
enabled: st.optional(st.boolean()),
}
id: st.optional(st.string()),
enabled: st.optional(st.boolean()),
};
export const AutomationTriggerEvent = st.type({
...AutomationTriggerBase,
platform: st.literal('event'),
event_type: st.union([st.string(), st.array(st.string())]),
event_data: st.any(),
context: st.any(),
})
...AutomationTriggerBase,
platform: st.literal("event"),
event_type: st.union([st.string(), st.array(st.string())]),
event_data: st.any(),
context: st.any(),
});
export const AutomationTriggerHA = st.type({
...AutomationTriggerBase,
platform: st.literal('homeassistant'),
event: st.enums(['start', 'shutdown']),
})
...AutomationTriggerBase,
platform: st.literal("homeassistant"),
event: st.enums(["start", "shutdown"]),
});
export const AutomationTriggerMQTT = st.type({
...AutomationTriggerBase,
platform: st.literal('mqtt'),
topic: st.string(),
payload: st.string(),
value_template: st.string(),
})
...AutomationTriggerBase,
platform: st.literal("mqtt"),
topic: st.string(),
payload: st.string(),
value_template: st.string(),
});
export const AutomationTriggerNumericState = st.type({
...AutomationTriggerBase,
platform: st.literal('numeric_state'),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
above: st.optional(st.string()),
below: st.optional(st.string()),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("numeric_state"),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
value_template: st.optional(st.string()),
above: st.optional(st.string()),
below: st.optional(st.string()),
for: st.optional(AutomationTime),
});
export const AutomationTriggerState = st.type({
...AutomationTriggerBase,
platform: st.literal('state'),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
from: st.optional(st.string()),
to: st.optional(st.string()),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("state"),
entity_id: st.union([st.string(), st.array(st.string())]),
attribute: st.optional(st.string()),
from: st.optional(st.string()),
to: st.optional(st.string()),
for: st.optional(AutomationTime),
});
export const AutomationTriggerTag = st.type({
...AutomationTriggerBase,
platform: st.literal('tag'),
tag_id: st.string(),
device_id: st.union([st.string(), st.array(st.string())]),
})
...AutomationTriggerBase,
platform: st.literal("tag"),
tag_id: st.string(),
device_id: st.union([st.string(), st.array(st.string())]),
});
export const AutomationTriggerTemplate = st.type({
...AutomationTriggerBase,
platform: st.literal('template'),
value_template: st.string(),
for: st.optional(AutomationTime),
})
...AutomationTriggerBase,
platform: st.literal("template"),
value_template: st.string(),
for: st.optional(AutomationTime),
});
export const AutomationTriggerTime = st.type({
...AutomationTriggerBase,
platform: st.literal('time'),
at: AutomationTimeString,
})
...AutomationTriggerBase,
platform: st.literal("time"),
at: AutomationTimeString,
});
export const AutomationTriggerTimePattern = st.type({
...AutomationTriggerBase,
platform: st.literal('time_pattern'),
hours: st.optional(st.string()),
minutes: st.optional(st.string()),
seconds: st.optional(st.string()),
})
...AutomationTriggerBase,
platform: st.literal("time_pattern"),
hours: st.optional(st.string()),
minutes: st.optional(st.string()),
seconds: st.optional(st.string()),
});
export const AutomationTriggerWebhook = st.type({
...AutomationTriggerBase,
platform: st.literal('webhook'),
webhook_id: st.string(),
})
...AutomationTriggerBase,
platform: st.literal("webhook"),
webhook_id: st.string(),
});
export const AutomationTriggerZone = st.type({
...AutomationTriggerBase,
platform: st.literal('zone'),
entity_id: st.union([st.string(), st.array(st.string())]),
zone: st.string(),
event: st.enums(['enter', 'leave'])
})
...AutomationTriggerBase,
platform: st.literal("zone"),
entity_id: st.union([st.string(), st.array(st.string())]),
zone: st.string(),
event: st.enums(["enter", "leave"]),
});
export const AutomationTriggerDevice = st.type({
export const AutomationTriggerDevice = st.assign(
st.partial(AutomationDeviceState),
st.type({
...AutomationTriggerBase,
platform: st.literal('device'),
entity_id: st.optional(EntityId),
device_id: st.optional(st.string()),
domain: st.optional(st.string()),
type: st.optional(st.string()),
subtype: st.optional(st.string()),
})
platform: st.literal("device"),
})
);
export const AutomationTrigger = st.union([
AutomationTriggerEvent,
AutomationTriggerHA,
AutomationTriggerMQTT,
AutomationTriggerNumericState,
AutomationTriggerState,
AutomationTriggerTag,
AutomationTriggerTemplate,
AutomationTriggerTime,
AutomationTriggerTimePattern,
AutomationTriggerWebhook,
AutomationTriggerZone,
AutomationTriggerDevice
])
AutomationTriggerEvent,
AutomationTriggerHA,
AutomationTriggerMQTT,
AutomationTriggerNumericState,
AutomationTriggerState,
AutomationTriggerTag,
AutomationTriggerTemplate,
AutomationTriggerTime,
AutomationTriggerTimePattern,
AutomationTriggerWebhook,
AutomationTriggerZone,
AutomationTriggerDevice,
]);