device action builder

This commit is contained in:
ari committed 2022-06-17 13:37:25 -04:00
1 parent 6be6005531
commit 029df7932e
16 files changed
+725 -434

No files matched your search

@@ -11,3 +11,13 @@ test("similarity score", () => {
].map((x) => computeSimilarity(x, "light.balcony", "Balcony Light"));
expect(searchTerms).toStrictEqual(searchTerms.sort());
});
test("similarity score", () => {
expect(
computeSimilarity(
"li",
"6592b3d6d05d3de6fa26c3dbd2edecc2",
"Balcony Lights"
)
).toBeGreaterThan(0);
});
@@ -51,7 +51,7 @@ export function computeSimilarity(
if (lowCaseId.includes(segment)) {
similarityScore += lowCaseId.length / lowCaseId.length;
}
if (lowCaseId.includes(segment)) {
if (lowCaseLabel.includes(segment)) {
similarityScore += lowCaseLabel.length / lowCaseLabel.length;
}
}
+42 -16
View File
@@ -1,22 +1,48 @@
import { FC } from "react";
import { useHAEntities } from 'haService';
import { InputAutoComplete, InputAutoCompletePropsBase } from './InputAutoComplete';
import { useHAEntities } from "haService";
import {
InputAutoComplete,
InputAutoCompletePropsBase,
} from "./InputAutoComplete";
import { prettyName } from "utils/formatting";
export type InputEntityProps = InputAutoCompletePropsBase & {
restrictToDomain?: string[],
}
restrictToDomain?: string[];
preSelectedEntityIds?: string[];
};
export const InputEntity: FC<InputEntityProps> = props => {
// state
const entities = useHAEntities();
return <InputAutoComplete
{...props}
validateOption={v => entities.validateOptions(v, props.restrictToDomain)}
options={entities.getOptions(props.restrictToDomain)}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={opt => (typeof opt !== 'string') ? prettyName(opt.domain) : ''}
export const InputEntity: FC<InputEntityProps> = (props) => {
// state
const entities = useHAEntities();
let options = entities.getOptions(props.restrictToDomain);
if (props.preSelectedEntityIds) {
options = options.filter((opt) =>
props.preSelectedEntityIds?.includes(entities.getID(opt))
);
}
const validateOptions = (v: string[]): null | string[] => {
const errors: string[] = [];
if (props.preSelectedEntityIds) {
v.forEach((eid) => {
if (!props.preSelectedEntityIds?.includes(eid)) {
errors.push(`"${eid}" is not a valid selection`);
}
});
}
errors.concat(entities.validateOptions(v, props.restrictToDomain) ?? []);
if (errors.length > 0) {
return errors;
}
return null;
};
return (
<InputAutoComplete
{...props}
validateOption={validateOptions}
options={options}
getID={entities.getID}
getLabel={entities.getLabel}
groupBy={(opt) => (typeof opt !== "string" ? prettyName(opt.domain) : "")}
/>
}
);
};
@@ -19,6 +19,7 @@ export type Props<T extends string | Object> = {
title?: string;
helperText?: string;
endAdornment?: ReactNode;
disabled?: boolean;
};
export function InputList<T extends string | Object>({
current,
@@ -33,6 +34,7 @@ export function InputList<T extends string | Object>({
title,
helperText,
endAdornment,
disabled,
}: Props<T>) {
const invalidCurrent =
current && !options.map(getKey).includes(getKey(current));
@@ -42,6 +44,7 @@ export function InputList<T extends string | Object>({
variant="filled"
sx={{ marginRight: "0.25em", minWidth: `${label.length * 0.75}em` }}
fullWidth
disabled={disabled}
>
<InputLabel>{label}</InputLabel>
<Select
@@ -60,6 +63,7 @@ export function InputList<T extends string | Object>({
variant="filled"
error={invalidCurrent}
fullWidth
disabled={disabled}
>
{options.map((t, i) => (
<MenuItem key={i} value={getKey(t)}>
@@ -1,36 +1,83 @@
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 { DeviceAction } from "types/automations/actions";
import { OptionManager, updateActionData } from './OptionManager';
import { prettyName } from "utils/formatting";
import { OptionManager, updateActionData } from "./OptionManager";
export const ActionDeviceState: OptionManager<DeviceAction> = {
defaultState: () => ({
alias: "",
device_id: ""
device_id: "",
}),
isReady: () => true,
renderOptionList: (state, setState, entities) => {
Component: ({ state, setState, ha }) => {
const update = updateActionData(state, setState);
return <>
<InputDevice
value={state.device_id ?? ""}
onChange={device_id => update({ device_id: device_id ?? "" })}
/>
<InputText
textBoxFor="type"
label="Action"
value={state.type ?? ""}
onChange={type => update({ type })}
/>
<InputEntity
value={state.entity_id ?? ""}
onChange={entity_id => update({
entity_id: entity_id ? entity_id : undefined,
domain: entity_id ? entity_id.split('.')[0] : ""
})}
/>
</>
}
}
const options = ha.deviceExtras.useDeviceActions(state.device_id);
const caps = ha.deviceExtras.useDeviceCapalities(state as any);
// aliases
let actions: DeviceAction[] = [];
if (options.length > 0 && state.type) {
const currentTypeOptions = options.filter(
({ type }) => type === state.type
);
if (currentTypeOptions.length > 0) {
actions = currentTypeOptions[0].actions;
}
}
const entities = actions
.map(({ entity_id }) => entity_id)
.filter((x) => !!x) as string[];
// render
return (
<>
<InputDevice
value={state.device_id ?? ""}
onChange={(device_id) => update({ device_id: device_id ?? "" })}
/>
{options.length > 0 && (
<InputList
key={"actions" + state.device_id}
label="Action"
current={state.type}
onChange={(type) =>
setState({
device_id: state.device_id,
...options.filter((opt) => type === opt.type)[0].actions[0],
})
}
options={options.map(({ type }) => type)}
/>
)}
{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[field.name] ?? ""}
onChange={(v) =>
update({
[field.name]: v,
})
}
/>
))}
{actions.length + options.length === 0 && (
<>This device has no actions.</>
)}
</>
);
},
};
@@ -10,7 +10,7 @@ export const ActionCallServiceState: OptionManager<ServiceAction> = {
data: {},
}),
isReady: ({ service }) => service !== "",
Component: ({ state, setState, services }) => {
Component: ({ state, setState, ha: { services } }) => {
const { service, target, data } = state;
const update = updateActionData(state, setState);
const serviceOption = services.getOption(service);
@@ -1,47 +1,53 @@
import { HAEntitiesState, HAServicesState } from 'haService';
import { FC } from 'react';
import { AutomationAction } from 'types/automations/actions';
import { AutomationCondition } from 'types/automations/conditions';
import { HAEntitiesState, HAService } from "haService";
import { FC } from "react";
import { AutomationAction } from "types/automations/actions";
import { AutomationCondition } from "types/automations/conditions";
export type OptionManager<T> = {
defaultState(): T;
isReady(s: T): boolean;
} & ({
renderOptionList(s: T, set: (s: T) => void, entities: HAEntitiesState): JSX.Element;
} | {
Component: FC<{
state: T,
setState: (s: T) => void,
entities: HAEntitiesState,
services: HAServicesState,
}>
})
} & (
| {
renderOptionList(
s: T,
set: (s: T) => void,
entities: HAEntitiesState
): JSX.Element;
}
| {
Component: FC<{
state: T;
setState: (s: T) => void;
ha: HAService;
}>;
}
);
export const cleanUpUndefined = (data: Record<string, any>): any => {
const clean: any = {};
Object.keys(data).forEach(k => {
if ((data[k] !== undefined) && (data[k] !== null)) {
clean[k] = data[k]
Object.keys(data).forEach((k) => {
if (data[k] !== undefined && data[k] !== null) {
clean[k] = data[k];
}
})
});
return clean;
}
};
export const updateConditionData = <T extends AutomationCondition>(
setState: (s: T) => void
) => (
state: T,
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateConditionData =
<T extends AutomationCondition>(setState: (s: T) => void) =>
(state: T, data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
export const updateActionData = <T extends AutomationAction>(
state: T,
setState: (s: T) => void
) => (
data: Partial<T>,
) => setState(cleanUpUndefined({
...state,
...data,
}))
export const updateActionData =
<T extends AutomationAction>(state: T, setState: (s: T) => void) =>
(data: Partial<T>) =>
setState(
cleanUpUndefined({
...state,
...data,
})
);
@@ -15,7 +15,7 @@ export const TriggerState: OptionManager<AutomationTriggerState> = {
entity_id: "",
}),
isReady: () => true,
Component: ({ state, setState, entities }) => {
Component: ({ state, setState, ha: { entities } }) => {
const attributes = entities.getAttributes(state.entity_id);
const states = entities.getStates(state.entity_id, state.attribute);
return (
@@ -28,7 +28,7 @@ export const useEditorNodeState = (
isModified: false,
...computeInvalidYaml(originalNode, allowedTypes),
});
const { entities, namer, services } = useHA();
const ha = useHA();
// aliases
const {
node: currentNode,
@@ -115,7 +115,7 @@ export const useEditorNodeState = (
<InputText
key="alias"
label="Alias"
value={getDescriptionFromAutomationNode(allState.node, namer)}
value={getDescriptionFromAutomationNode(allState.node, ha.namer)}
onChange={(alias) =>
setState({
...allState.node,
@@ -142,13 +142,12 @@ export const useEditorNodeState = (
<>
{aliasEditor}
{"renderOptionList" in optionManager ? (
optionManager.renderOptionList(currentNode, setState, entities)
optionManager.renderOptionList(currentNode, setState, ha.entities)
) : (
<optionManager.Component
state={currentNode}
setState={setState}
entities={entities}
services={services}
ha={ha}
/>
)}
</>
@@ -123,3 +123,14 @@ StateTriggerExample.args = {
entity_id: "binary_sensor.door_main",
},
};
export const DeviceFilledExample = Action.bind({});
DeviceFilledExample.args = {
...DeviceFilledExample.args,
node: {
type: "toggle",
device_id: "29c3443815620745c4bf4100b11588fd",
entity_id: "light.switch_island",
domain: "light",
},
};
+84
View File
@@ -0,0 +1,84 @@
import { OptionsObject, useSnackbar } from "notistack";
import { useEffect, useRef, useState } from "react";
import { HASendMessage } from "./types";
export type DeviceTypeAction = {
type: string;
entity_id?: string;
device_id?: string;
domain: string;
};
export type DeviceTypeCapability = {
extra_fields: Array<{
name: string;
required?: true;
optional?: true;
type: string;
}>;
};
export const getDeviceExtraWsCalls = (callHA: HASendMessage) => {
return {
useDeviceActions(deviceId?: string) {
const lastDeviceId = useRef<string | null>(null);
const [options, setOptions] = useState<
Array<{
type: string;
actions: DeviceTypeAction[];
}>
>([]);
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);
}
})
.catch((err) => {
console.warn(err);
});
}
}, [action]);
return caps;
},
};
};
+12 -1
View File
@@ -2,12 +2,13 @@ import { entitiesColl, servicesColl } from "home-assistant-js-websocket";
import { Namer } from "utils/formatting";
import { deviceRegistryColl } from "./DeviceRegistry";
import { entityRegistryColl } from "./EntityRegistry";
import { DeviceRegistryItem } from "./types";
import { DeviceRegistryItem, HASendMessage } from "./types";
import { useHassCollection } from "./useHassCollection";
import { useHAConnection } from "./connection";
import { useSnackbar } from "notistack";
import { TypedHassService } from "./fieldTypes";
import { Option } from "components/Inputs/InputAutoComplete";
import { getDeviceExtraWsCalls } from "./extras";
export type EntityOption = Option<{ domain: string }>;
export type HAEntitiesState = ReturnType<typeof useHAEntities>;
@@ -216,6 +217,7 @@ export const useHAServices = () => {
};
export type DeviceRegistryOption = Option<{ manufacturer: string }>;
export type HADeviceRegistry = ReturnType<typeof useHADeviceRegistry>;
export const useHADeviceRegistry = () => {
const dr = useHassCollection(deviceRegistryColl);
const getLabelForItem = (item: DeviceRegistryItem) =>
@@ -255,6 +257,7 @@ export const useHAEntityRegistry = () => {
return dr;
};
export type HAService = ReturnType<typeof useHA>;
export const useHA = () => {
const entities = useHAEntities();
const devices = useHADeviceRegistry();
@@ -312,6 +315,12 @@ export const useHA = () => {
}
};
const callHA: HASendMessage = async (sendMsg) => {
if (conn.status === "loaded") {
return await conn.connection.sendMessagePromise(sendMsg);
}
};
const namer: Namer = {
getDeviceName(device_id) {
return devices.getLabel(device_id);
@@ -336,6 +345,8 @@ export const useHA = () => {
services,
namer,
callService,
callHA,
deviceExtras: getDeviceExtraWsCalls(callHA),
reloadAutomations: () => callService("automation", "reload"),
};
};
+23 -36
View File
@@ -1,41 +1,28 @@
export type EntityRegisteryItem = {
area_id: null | string;
config_entry_id: null | string;
device_id: null | string;
disabled_by:
| "integration"
| "user"
| "config_entry"
| string
| null
;
entity_category:
| "diagnostic"
| "config"
| string
| null
;
hidden_by:
| "integration"
| "user"
| string
| null
;
entity_id: string;
icon: null | string;
name: null | string;
platform: string;
}
area_id: null | string;
config_entry_id: null | string;
device_id: null | string;
disabled_by: "integration" | "user" | "config_entry" | string | null;
entity_category: "diagnostic" | "config" | string | null;
hidden_by: "integration" | "user" | string | null;
entity_id: string;
icon: null | string;
name: null | string;
platform: string;
};
export type DeviceRegistryItem = {
id: string;
name: string;
name_by_user: string | null;
manufacturer: string | null;
entry_type: 'service' | string | null;
disabled_by: EntityRegisteryItem['disabled_by'];
area_id: string | null;
}
id: string;
name: string;
name_by_user: string | null;
manufacturer: string | null;
entry_type: "service" | string | null;
disabled_by: EntityRegisteryItem["disabled_by"];
area_id: string | null;
};
export type HassDevices = Array<DeviceRegistryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
export type HassEntitiesRegistry = Array<EntityRegisteryItem>;
export type HASendMessage = (
sendMsg: { type: string } & Record<string, any>
) => Promise<any>;
+54 -55
View File
@@ -1,78 +1,77 @@
import * as st from 'superstruct'
import { AutomationTime } from './common';
import { AutomationTrigger } from './triggers';
import * as st from "superstruct";
import { AutomationTime } from "./common";
import { AutomationTrigger } from "./triggers";
export const AutomationActionNodeBase = st.type({
alias: st.optional(st.string()),
variables: st.optional(st.record(st.string(), st.any())),
enabled: st.optional(st.boolean())
})
alias: st.optional(st.string()),
variables: st.optional(st.record(st.string(), st.any())),
enabled: st.optional(st.boolean()),
});
export const ServiceAction = st.intersection([
AutomationActionNodeBase,
st.type({
data: st.any(),
target: st.any(),
service: st.string(),
})
AutomationActionNodeBase,
st.type({
data: st.any(),
target: st.any(),
service: st.string(),
}),
]);
export const RepeatAction = st.intersection([
AutomationActionNodeBase,
st.type({
repeat: st.object({
count: st.number(),
sequence: st.array(st.object()),
})
})
AutomationActionNodeBase,
st.type({
repeat: st.object({
count: st.number(),
sequence: st.array(st.object()),
}),
}),
]);
export const WaitAction = st.intersection([
AutomationActionNodeBase,
st.type({
timeout: st.optional(AutomationTime),
continue_on_timeout: st.optional(st.boolean()),
wait_template: st.optional(st.string()),
wait_for_trigger: st.optional(st.array(AutomationTrigger)),
}),
AutomationActionNodeBase,
st.type({
timeout: st.optional(AutomationTime),
continue_on_timeout: st.optional(st.boolean()),
wait_template: st.optional(st.string()),
wait_for_trigger: st.optional(st.array(AutomationTrigger)),
}),
]);
export const DelayAction = st.intersection([
AutomationActionNodeBase,
st.type({
delay: AutomationTime
})
AutomationActionNodeBase,
st.type({
delay: AutomationTime,
}),
]);
export const FireEventAction = st.intersection([
AutomationActionNodeBase,
st.type({
event: st.string(),
event_data: st.any(),
})
AutomationActionNodeBase,
st.type({
event: st.string(),
event_data: st.any(),
}),
]);
export const DeviceAction = st.intersection([
AutomationActionNodeBase,
st.type({
type: st.optional(st.string()),
device_id: st.optional(st.string()),
entity_id: st.optional(st.string()),
domain: st.optional(st.string()),
})
AutomationActionNodeBase,
st.type({
type: st.optional(st.string()),
device_id: st.optional(st.string()),
entity_id: st.optional(st.string()),
domain: st.optional(st.string()),
}),
st.record(st.string(), st.any()),
]);
export const ChooseAction = st.intersection([
AutomationActionNodeBase,
st.type({
choose: st.array(st.type({
conditions: st.array(st.object()),
sequence: st.array(st.object()),
})),
default: st.optional(st.array(st.object())),
})
AutomationActionNodeBase,
st.type({
choose: st.array(
st.type({
conditions: st.array(st.object()),
sequence: st.array(st.object()),
})
),
default: st.optional(st.array(st.object())),
}),
]);
+237 -136
View File
@@ -1,170 +1,271 @@
import { convertTimeToString, getDescriptionFromAutomationNode, Namer, prettyName } from "./formatting";
import {
convertTimeToString,
getDescriptionFromAutomationNode,
Namer,
prettyName,
} from "./formatting";
const dummyNamer: Namer = {
getDeviceName(device_id) {
return device_id
},
getServiceName(service) {
return service
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).join(' and ')
} else {
return entity_id
}
},
}
test('converting time to a string', () => {
expect(convertTimeToString({ hours: 1 })).toEqual('01:00:00:00')
expect(convertTimeToString({ hours: 1, minutes: 5 })).toEqual('01:05:00:00')
expect(convertTimeToString({ hours: 1, minutes: 5, seconds: 24 })).toEqual('01:05:24:00')
expect(convertTimeToString({ hours: 1, milliseconds: 100 })).toEqual('01:00:00:100')
})
getDeviceName(device_id) {
return device_id;
},
getServiceName(service) {
return service;
},
getEntityName(entity_id, maxEntities = 1) {
if (Array.isArray(entity_id)) {
return entity_id.slice(0, maxEntities).join(" and ");
} else {
return entity_id;
}
},
};
test("converting time to a string", () => {
expect(convertTimeToString({ hours: 1 })).toEqual("01:00:00:00");
expect(convertTimeToString({ hours: 1, minutes: 5 })).toEqual("01:05:00:00");
expect(convertTimeToString({ hours: 1, minutes: 5, seconds: 24 })).toEqual(
"01:05:24:00"
);
expect(convertTimeToString({ hours: 1, milliseconds: 100 })).toEqual(
"01:00:00:100"
);
});
test('using alias as description', () => {
expect(getDescriptionFromAutomationNode({
test("using alias as description", () => {
expect(
getDescriptionFromAutomationNode(
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
service: "media_player.play_media",
target: {
entity_id: "media_player.kitchen_dot"
entity_id: "media_player.kitchen_dot",
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}, dummyNamer)).toEqual("Start Music In Kitchen")
})
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
},
},
dummyNamer
)
).toEqual("Start Music In Kitchen");
});
test('get service action description', () => {
expect(getDescriptionFromAutomationNode({
service: 'media_player.play_media',
test("get service action description", () => {
expect(
getDescriptionFromAutomationNode(
{
service: "media_player.play_media",
target: {
entity_id: "media_player.kitchen_dot"
entity_id: "media_player.kitchen_dot",
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}, dummyNamer)).toEqual("media_player.play_media")
})
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
},
},
dummyNamer
)
).toEqual("media_player.play_media");
});
test('get repeat action description', () => {
expect(getDescriptionFromAutomationNode({
test("get repeat action description", () => {
expect(
getDescriptionFromAutomationNode(
{
repeat: {
count: 10,
sequence: []
}
}, dummyNamer)).toEqual("Repeat 10")
})
count: 10,
sequence: [],
},
},
dummyNamer
)
).toEqual("Repeat 10");
});
test('get wait action description', () => {
expect(getDescriptionFromAutomationNode({
wait_template: "states(switch.kitchen_light) == 'on'"
}, dummyNamer)).toEqual("Wait on states(switch.kitchen_light) == 'on'")
expect(getDescriptionFromAutomationNode({
test("get wait action description", () => {
expect(
getDescriptionFromAutomationNode(
{
wait_template: "states(switch.kitchen_light) == 'on'",
},
dummyNamer
)
).toEqual("Wait on states(switch.kitchen_light) == 'on'");
expect(
getDescriptionFromAutomationNode(
{
wait_template: "states(switch.kitchen_light) == 'on'",
timeout: {
'minutes': 1,
}
}, dummyNamer)).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00")
})
minutes: 1,
},
},
dummyNamer
)
).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00");
});
test('get fire event action description', () => {
expect(getDescriptionFromAutomationNode({
event: 'test_event',
test("get fire event action description", () => {
expect(
getDescriptionFromAutomationNode(
{
event: "test_event",
event_data: {},
}, dummyNamer)).toEqual("Trigger test_event")
})
},
dummyNamer
)
).toEqual("Trigger test_event");
});
test('get device action description', () => {
expect(getDescriptionFromAutomationNode({
test("get device action description", () => {
expect(
getDescriptionFromAutomationNode(
{
device_id: "12310das01231",
domain: "zwave_js",
type: "set_value"
}, dummyNamer)).toEqual("set_value on 12310das01231")
})
type: "set_value",
},
dummyNamer
)
).toEqual("set_value on 12310das01231");
});
test('get choose action description', () => {
expect(getDescriptionFromAutomationNode({
test("get choose action description", () => {
expect(
getDescriptionFromAutomationNode(
{
choose: [],
default: [],
}, dummyNamer)).toEqual("Choose")
})
},
dummyNamer
)
).toEqual("Choose");
});
test('get and/or/not condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'and',
test("get and/or/not condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "and",
conditions: [],
}, dummyNamer)).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'or',
},
dummyNamer
)
).toEqual("Logic");
expect(
getDescriptionFromAutomationNode(
{
condition: "or",
conditions: [],
}, dummyNamer)).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'not',
},
dummyNamer
)
).toEqual("Logic");
expect(
getDescriptionFromAutomationNode(
{
condition: "not",
conditions: [],
}, dummyNamer)).toEqual("Logic")
})
},
dummyNamer
)
).toEqual("Logic");
});
test('get Numeric State condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
}, dummyNamer)).toEqual("sensor.temperature?>?<")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: ""
}, dummyNamer)).toEqual("Numeric State Condition")
expect(getDescriptionFromAutomationNode({
test("get Numeric State condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
},
dummyNamer
)
).toEqual("sensor.temperature?>?<");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "",
},
dummyNamer
)
).toEqual("Numeric State Condition");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
},
dummyNamer
)
).toEqual("sensor.temperature > 17");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
below: "5",
},
dummyNamer
)
).toEqual("sensor.temperature < 5");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
below: "20",
},
dummyNamer
)
).toEqual("17 < sensor.temperature < 20");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: "sensor.temperature",
above: "17",
below: "20",
value_template: "{{ float(state.state) + 2 }}",
},
dummyNamer
)
).toEqual("17 < sensor.temperature < 20");
expect(
getDescriptionFromAutomationNode(
{
condition: "numeric_state",
entity_id: 'sensor.temperature',
above: '17',
}, dummyNamer)).toEqual("sensor.temperature > 17")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
below: '5',
}, dummyNamer)).toEqual("sensor.temperature < 5")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: '17',
below: '20',
}, dummyNamer)).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}, dummyNamer)).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: [
"sensor.kitchen_temperature",
"sensor.living_room_temperature"
"sensor.kitchen_temperature",
"sensor.living_room_temperature",
],
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}, dummyNamer)).toEqual("17 < ... < 20")
})
above: "17",
below: "20",
value_template: "{{ float(state.state) + 2 }}",
},
dummyNamer
)
).toEqual("17 < ... < 20");
});
test('get State condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'state',
entity_id: 'switch.kitchen_light',
state: "on"
}, dummyNamer)).toEqual("switch.kitchen_light is 'on'")
})
test("get State condition description", () => {
expect(
getDescriptionFromAutomationNode(
{
condition: "state",
entity_id: "switch.kitchen_light",
state: "on",
},
dummyNamer
)
).toEqual("switch.kitchen_light is 'on'");
});
test('pretty naming', () => {
expect(prettyName('sensor')).toEqual("Sensor")
expect(prettyName('sensor.phone')).toEqual("Sensor Phone")
expect(prettyName('device_tracker')).toEqual("Device Tracker")
})
test("pretty naming", () => {
expect(prettyName("sensor")).toEqual("Sensor");
expect(prettyName("sensor.phone")).toEqual("Sensor Phone");
expect(prettyName("device_tracker")).toEqual("Device Tracker");
expect(prettyName("Baby Name")).toEqual("Baby Name");
});
+125 -119
View File
@@ -1,135 +1,141 @@
import { AutomationNode, AutomationNodeTypes } from "types/automations";
import { AutomationTime } from "types/automations/common";
export interface Namer {
getEntityName(entity_id: string | string[], maxEntities?: number): string;
getDeviceName(device_id: string): string;
getServiceName(service: string): string;
getEntityName(entity_id: string | string[], maxEntities?: number): string;
getDeviceName(device_id: string): string;
getServiceName(service: string): string;
}
export const convertTimeToString = (t: AutomationTime) => {
if (typeof t === 'string') {
return t
} else {
const {
hours = 0,
minutes = 0,
seconds = 0,
milliseconds = 0,
} = t
return [hours, minutes, seconds, milliseconds].map(n => String(n).padStart(2, '0')).join(':')
}
}
if (typeof t === "string") {
return t;
} else {
const { hours = 0, minutes = 0, seconds = 0, milliseconds = 0 } = t;
return [hours, minutes, seconds, milliseconds]
.map((n) => String(n).padStart(2, "0"))
.join(":");
}
};
export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(
node: AutomationNode<N>,
namer: Namer,
node: AutomationNode<N>,
namer: Namer
): string => {
if (('alias' in node) && node.alias) {
return node.alias;
}
if ("alias" in node && node.alias) {
return node.alias;
}
if ('platform' in node) {
if (node.id) {
return node.id ?? '';
}
if (node.platform === 'time') {
return node.at
}
if (node.platform === 'homeassistant') {
if (node.event === 'start') {
return 'HA is starting'
} else {
return 'HA is shutting down'
if ("platform" in node) {
if (node.id) {
return node.id ?? "";
}
if (node.platform === "time") {
return node.at;
}
if (node.platform === "homeassistant") {
if (node.event === "start") {
return "HA is starting";
} else {
return "HA is shutting down";
}
}
if (node.platform === "tag") {
return `Tag = ${node.tag_id}`;
}
if (node.platform === "state") {
let out = "";
if (typeof node.entity_id === "string") {
out = namer.getEntityName(node.entity_id);
} else {
out = namer.getEntityName(node.entity_id[0]) + " and more";
}
if (node.from) {
out += ` from ${node.from}`;
}
if (node.to) {
out += ` to ${node.to}`;
}
return out;
}
if (node.platform === "device") {
return node.device_id
? namer.getDeviceName(node.device_id)
: node.entity_id
? namer.getEntityName(node.entity_id)
: node.platform;
}
return node.platform;
}
if ("condition" in node) {
if (
node.condition === "and" ||
node.condition === "or" ||
node.condition === "not"
) {
return "Logic";
} else {
switch (node.condition) {
case "numeric_state":
if (node.entity_id) {
const center =
Array.isArray(node.entity_id) && node.entity_id.length > 1
? "..."
: namer.getEntityName(node.entity_id);
if (node.above) {
if (node.below) {
return `${node.above} < ${center} < ${node.below}`;
}
return `${center} > ${node.above}`;
}
}
if (node.platform === 'tag') {
return `Tag = ${node.tag_id}`
}
if (node.platform === 'state') {
let out = "";
if (typeof node.entity_id === 'string') {
out = namer.getEntityName(node.entity_id)
} else {
out = namer.getEntityName(node.entity_id[0]) + " and more"
if (node.below) {
return `${center} < ${node.below}`;
}
if (node.from) {
out += ` from ${node.from}`
}
if (node.to) {
out += ` to ${node.to}`
}
return out
}
if (node.platform === 'device') {
return node.device_id ? namer.getDeviceName(node.device_id) : node.entity_id ? namer.getEntityName(node.entity_id) : node.platform
}
return node.platform
return `${center}?>?<`;
}
return "Numeric State Condition";
case "state":
return `${namer.getEntityName(node.entity_id)} is '${node.state}'`;
case "template":
return node.value_template;
default:
return "n/a";
}
}
if ('condition' in node) {
if (
(node.condition === 'and') ||
(node.condition === 'or') ||
(node.condition === 'not')
) {
return "Logic"
} else {
switch (node.condition) {
case "numeric_state":
if (node.entity_id) {
const center = (Array.isArray(node.entity_id) && node.entity_id.length > 1) ?
'...' :
namer.getEntityName(node.entity_id);
if (node.above) {
if (node.below) {
return `${node.above} < ${center} < ${node.below}`
}
return `${center} > ${node.above}`
}
if (node.below) {
return `${center} < ${node.below}`
}
return `${center}?>?<`
}
return "Numeric State Condition"
case "state":
return `${namer.getEntityName(node.entity_id)} is '${node.state}'`
case 'template':
return node.value_template
default:
return 'n/a'
}
}
}
if ("service" in node) {
return namer.getServiceName(node.service);
}
if ("repeat" in node) {
return "Repeat " + node.repeat.count;
}
if ("delay" in node) {
return `Wait for ${convertTimeToString(node.delay)}`;
}
if ("wait_template" in node) {
let out = "Wait on " + node.wait_template;
if (node.timeout) {
out += " for " + convertTimeToString(node.timeout);
}
if ('service' in node) {
return namer.getServiceName(node.service)
}
if ('repeat' in node) {
return 'Repeat ' + node.repeat.count
}
if ('delay' in node) {
return `Wait for ${convertTimeToString(node.delay)}`
}
if ('wait_template' in node) {
let out = 'Wait on ' + node.wait_template;
if (node.timeout) {
out += (' for ' + convertTimeToString(node.timeout))
}
return out;
}
if ('event' in node) {
return `Trigger ${node.event}`
}
if ('device_id' in node) {
return `${node.type ?? ""} on ${node.device_id ? namer.getDeviceName(node.device_id) : ''}`
}
if ('choose' in node) {
return "Choose"
}
return 'n/a'
}
return out;
}
if ("event" in node) {
return `Trigger ${node.event}`;
}
if ("device_id" in node) {
return `${node.type ?? ""} on ${
node.device_id ? namer.getDeviceName(node.device_id) : ""
}`;
}
if ("choose" in node) {
return "Choose";
}
return "n/a";
};
export const prettyName = (n: string) => {
const clean = n.replaceAll(/[.-_]/g, ' ');
return clean.split(' ').map(x => x.slice(0, 1).toUpperCase() + x.slice(1)).join(' ')
}
const clean = n.replaceAll(/[.\-_]/g, " ");
return clean
.split(" ")
.map((x) => x.slice(0, 1).toUpperCase() + x.slice(1))
.join(" ");
};