updated data type

This commit is contained in:
Ari Sosnovsky committed 2021-11-11 16:21:12 -05:00
1 parent 7127c3c0b9
commit 9b50f73b62
26 files changed
+590 -927

No files matched your search

@@ -1,12 +0,0 @@
import { useState } from "react";
export abstract class BaseState<T> {
abstract defaultState(): T ;
abstract isReady(s: T): boolean;
abstract renderOptionList(s: T): JSX.Element;
constructor(public setState: (s: T) => void) {}
}
@@ -1,40 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputYaml from "../../components/InputYaml";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { BaseState } from "./BaseState";
import { LogicCondition } from "../types/condition";
import InputList from "../../components/InputList";
export default class ConditionLogicState extends BaseState<LogicCondition> {
defaultState = () => ({
alias: "",
condition: 'and',
conditions: [],
} as LogicCondition)
isReady(state: LogicCondition): boolean {
return state.alias !== '' &&
(state?.conditions)?.length > 0
}
renderOptionList(state: LogicCondition): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputList
label="Condition"
current={state.condition}
options={['and', 'or', 'not']}
onChange={(condition: any) => this.setState({...state, condition})}
/>
<InputYaml
label="Sequence"
value={state.conditions}
onChange={conditions => this.setState({...state, conditions})}
/>
</div>
}
}
@@ -1,45 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputYaml from "../../components/InputYaml";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { BaseState } from "./BaseState";
import { NumericCondition } from "../types/condition";
import InputList from "../../components/InputList";
export default class ConditionNumStateState extends BaseState<NumericCondition> {
defaultState = () => ({
alias: "",
condition: 'numeric_state',
entity_id: '',
// above: '',
// below: '',
// attribute: '',
value_template: '',
} as NumericCondition)
isReady(state: NumericCondition): boolean {
return state.alias !== '' &&
state.entity_id !== '' &&
state.value_template !== '';
}
renderOptionList(state: NumericCondition): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputText
textBoxFor="entity_id"
label="Entity ID"
value={state.entity_id}
onChange={entity_id => this.setState({...state, entity_id})}
/>
<InputText
label="Template"
value={state.value_template ?? ""}
onChange={value_template => this.setState({...state, value_template})}
/>
</div>
}
}
@@ -1,22 +0,0 @@
import InputText from "../../components/InputText";
import { BaseState } from "./BaseState";
export default class Generic extends BaseState<{alias: string}> {
defaultState = () => ({
alias: "Unknown",
})
isReady(state: any): boolean {
return true;
}
renderOptionList(state: any): JSX.Element {
return <div className="state-manager-options">
<InputText label="Description"
value={state.alias??""}
onChange={alias => this.setState({...state, alias})}
/>
<br/>
<b>THIS IS NOT SUPPORTED YET!</b>
</div>
}
}
@@ -1,37 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputYaml from "../../components/InputYaml";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { ChooseScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptChooseState extends BaseState<ChooseScript> {
defaultState = () => ({
alias: "Choose",
default: [],
choose: [],
})
isReady(state: ChooseScript): boolean {
return state.alias !== ''
}
renderOptionList(state: ChooseScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputYaml
label="Choose Sequence"
value={state.choose}
onChange={choose => this.setState({...state, choose})}
/>
<InputYaml
label="Default Sequence"
value={state.default}
onChange={d => this.setState({...state, default: d})}
/>
</div>
}
}
@@ -1,51 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputYaml from "../../components/InputYaml";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { DeviceScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptDeviceState extends BaseState<DeviceScript> {
defaultState = () => ({
alias: "Device",
type: "",
entity_id: "",
device_id: "",
domain: "",
})
isReady(state: DeviceScript): boolean {
return state.alias !== '' &&
state.type !== "" &&
state.entity_id !== "" &&
state.device_id !== "" &&
state.domain !== ""
}
renderOptionList(state: DeviceScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputText
textBoxFor="device_id"
label="Device"
value={state.device_id}
onChange={device_id => this.setState({...state, device_id})}
/>
<InputText
textBoxFor="type"
label="Action"
value={state.type}
onChange={type => this.setState({...state, type})}
/>
<InputText
textBoxFor="entity_id"
label="Entity ID"
value={state.entity_id ?? ""}
onChange={entity_id => this.setState({...state, entity_id, domain: entity_id.split('.')[0]})}
/>
</div>
}
}
@@ -1,39 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputYaml from "../../components/InputYaml";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { FireEventScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptEventState extends BaseState<FireEventScript> {
defaultState = () => ({
alias: "Fire Event",
event: "",
event_data: {},
})
isReady(state: FireEventScript): boolean {
return state.alias !== '' &&
state.event !== ""
}
renderOptionList(state: FireEventScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputText
textBoxFor="event"
label="Event"
value={state.event}
onChange={event => this.setState({...state, event})}
/>
<InputYaml
label="Event Data"
value={state.event_data}
onChange={event_data => this.setState({...state, event_data})}
/>
</div>
}
}
@@ -1,39 +0,0 @@
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import InputYaml from "../../components/InputYaml";
import { RepeatScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptRepeatState extends BaseState<RepeatScript> {
defaultState = () => ({
alias: "Repeat",
repeat: {
count: 1,
sequence: [],
}
})
isReady(state: RepeatScript): boolean {
return state.alias !== '' &&
state?.repeat?.sequence.length > 0
}
renderOptionList(state: RepeatScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputNumber
label="How many times?"
value={state?.repeat?.count}
onChange={count => this.setState({...state, repeat: {...state.repeat, count}})}
/>
<InputYaml
label="Sequence"
value={state?.repeat?.sequence ?? {}}
onChange={sequence => this.setState({...state, repeat: {...state.repeat, sequence}})}
/>
</div>
}
}
@@ -1,39 +0,0 @@
import InputText from "../../components/InputText";
import InputWrapper from "../../components/InputWrapper";
import { ServiceScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptCallServiceState extends BaseState<ServiceScript> {
defaultState = () => ({
service: "",
alias: "Call Service",
target: "",
data: {},
})
isReady(state: ServiceScript): boolean {
return state.service !== '' &&
state.alias !== '' &&
state.target !== ''
}
renderOptionList(state: ServiceScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputText
textBoxFor="service"
label="Service"
value={state.service}
onChange={service => this.setState({...state, service})}
/>
<InputText
label="Target"
value={state.target}
onChange={target => this.setState({...state, target})}
/>
</div>
}
}
@@ -1,44 +0,0 @@
import InputBoolean from "../../components/InputBoolean";
import InputNumber from "../../components/InputNumber";
import InputText from "../../components/InputText";
import { WaitScript } from "../types/script";
import { BaseState } from "./BaseState";
export default class ScriptWaitState extends BaseState<WaitScript> {
defaultState = () => ({
alias: "Wait",
wait_template: "",
timeout: 0,
continue_on_timeout: false,
})
isReady(state: WaitScript): boolean {
return state.alias !== '' &&
state.wait_template !== ""
}
renderOptionList(state: WaitScript): JSX.Element {
return <div className="state-manager-options">
<InputText
label="Description"
value={state.alias ?? ""}
onChange={alias => this.setState({...state, alias})}
/>
<InputText
textBoxFor="template"
label="Template"
value={state.wait_template}
onChange={wait_template => this.setState({...state, wait_template})}
/>
<InputNumber
label="Timeout"
value={state.timeout ?? 0}
onChange={timeout => this.setState({...state, timeout})}
/>
<InputBoolean
label="Continue on Timeout"
value={state.continue_on_timeout ?? false}
onChange={continue_on_timeout => this.setState({...state, continue_on_timeout})}
/>
</div>
}
}
@@ -1,38 +0,0 @@
import { AutomationNodeType, NodeSubType } from "../types"
import ConditionLogicState from "./ConditionLogic"
import ScriptChooseState from "./ScriptChoose"
import ScriptDeviceState from "./ScriptDevice"
import ScriptEventState from "./ScriptEvent"
import ScriptRepeatState from "./ScriptRepeat"
import ScriptCallServiceState from "./ScriptService"
import ScriptWaitState from "./ScriptWait"
export const getBaseState = <T extends AutomationNodeType>(
node_type: T,
node_subtype: NodeSubType<T>
) : any => {
if ( node_type === 'action') {
switch (node_subtype) {
case 'Service':
return ScriptCallServiceState
case "Repeat":
return ScriptRepeatState;
case "Wait":
return ScriptWaitState;
case "Event":
return ScriptEventState;
case "Device":
return ScriptDeviceState;
case "Choose":
return ScriptChooseState;
}
}
if (node_type === 'condition') {
switch (node_subtype) {
case 'Logic':
return ConditionLogicState
}
}
throw new Error(`Invalid or Not implemented node type ${node_type} -> ${node_subtype}`)
}
-41
View File
@@ -1,41 +0,0 @@
import { useEffect, useState } from "react";
import { AutomationNodeType, NodeSubType } from "../types";
import { BaseState } from "./BaseState";
import Generic from "./Generic";
import { getBaseState } from "./getBaseState";
export default class StateManager {
public state: any;
private setState: (s: any) => void;
private baseState: BaseState<any>;
constructor(
public nodeType: AutomationNodeType,
public nodeSubtype: NodeSubType,
initialState: any | undefined = undefined,
){
[this.state, this.setState] = useState(initialState ?? {});
this.baseState = this.swapBaseState(this.nodeType, this.nodeSubtype);
if (!initialState) {
useEffect(() => {
this.setState(this.baseState.defaultState());
}, [this.nodeType, this.nodeSubtype]);
}
}
swapBaseState(nodeType: AutomationNodeType, nodeSubtype: NodeSubType) {
try {
this.baseState = new (getBaseState(nodeType, nodeSubtype))(this.setState);
} catch (error) {
this.baseState = new Generic(this.setState);
}
this.nodeType = nodeType;
this.nodeSubtype = nodeSubtype;
return this.baseState;
}
renderOptionList() {
return this.baseState.renderOptionList(this.state)
}
get isReady() {
return this.baseState.isReady(this.state);
}
}
-68
View File
@@ -1,68 +0,0 @@
import { AutomationTime } from "./common";
interface BaseCondition {
alias?: string;
};
export interface LogicCondition extends BaseCondition {
condition: 'and' | 'or' | 'not';
conditions: AutomationCondition[];
}
export interface NumericCondition extends BaseCondition {
condition: 'numeric_state';
entity_id: string;
above?: string;
below?: string;
attribute?: string;
value_template?: string;
}
export interface StateCondition extends BaseCondition {
condition: 'state';
entity_id: string | string[];
state: string | string[];
for?: AutomationTime | string;
attribute?: string;
}
export interface TemplateCondition extends BaseCondition {
condition: 'template';
value_template: string;
}
export interface TimeCondition extends BaseCondition {
condition: 'time';
after?: string;
before?: string;
weekday?: Array<'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun'>;
}
export interface TriggerCondition extends BaseCondition {
condition: 'trigger';
id: string | string[];
}
export interface ZoneCondition extends BaseCondition {
condition: 'zone';
zone: string;
entity_id: string | string[];
state: string | string[];
}
export interface GenericCondition extends BaseCondition {
condition: string;
}
export type AutomationCondition =
| LogicCondition
| NumericCondition
| StateCondition
| TemplateCondition
| TimeCondition
| TriggerCondition
| ZoneCondition
| GenericCondition
;
export const conditionTypes = [
'Logic',
'Numeric State',
'State',
'Template',
'Time',
'Trigger',
'Zone',
'Generic',
] as const;
export type ConditionType = typeof conditionTypes[number];
-32
View File
@@ -1,32 +0,0 @@
import { AutomationCondition, ConditionType, conditionTypes } from "./condition";
import { AutomationScript, ScriptType, scriptTypes } from "./script";
import { AutomationTrigger, TriggerType, triggerTypes } from "./triggers";
export interface Automation {
id: string;
alias: string;
description: string;
trigger_variables?: Record<string, string>;
mode: "single" | "restart" | "queued" | "parallel";
trigger: AutomationTrigger[];
condition: AutomationCondition[];
action: AutomationAction[];
}
export type AutomationNodeTypes = Pick<Automation, 'trigger' | 'condition' | 'action'>;
export type AutomationNodeType = keyof AutomationNodeTypes;
export type AutomationAction = AutomationScript | AutomationCondition;
export type AutomationNode<T extends AutomationNodeType> =
AutomationNodeTypes[T][number];
export type NodeSubType<T=any> =
T extends 'action' ? ScriptType :
T extends 'condition' ? ConditionType :
T extends 'trigger' ? TriggerType :
never;
export const typeList = {
'action': scriptTypes,
'condition': conditionTypes,
'trigger': triggerTypes,
} as const;
-57
View File
@@ -1,57 +0,0 @@
import { AutomationCondition } from "./condition";
interface BaseScript {
alias?: string;
variables?: Record<string, any>;
}
export interface ServiceScript extends BaseScript {
service: string;
target: any;
data: any;
}
export interface RepeatScript extends BaseScript {
repeat: {
count: number;
sequence: AutomationScript[];
}
}
export interface WaitScript extends BaseScript {
wait_template: string;
timeout?: number;
continue_on_timeout?: boolean;
}
export interface FireEventScript extends BaseScript {
event: string;
event_data: any;
}
export interface DeviceScript extends BaseScript {
type: string;
device_id: string;
entity_id?: string;
domain: string;
}
export interface ChooseScript extends BaseScript {
choose: Array<{
conditions: AutomationCondition[];
sequence: AutomationScript[];
}>;
default: AutomationScript[];
}
export type AutomationScript =
| ServiceScript
| RepeatScript
| WaitScript
| FireEventScript
| DeviceScript
| ChooseScript
;
export const scriptTypes = [
'Service',
'Repeat',
'Wait',
'Event',
'Device',
'Choose'
] as const;
export type ScriptType = typeof scriptTypes[number];
-138
View File
@@ -1,138 +0,0 @@
import {getDescriptionFromAutomationNode} from "./utils";
test('using alias as description', () => {
expect(getDescriptionFromAutomationNode({
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
})).toEqual("Start Music In Kitchen")
})
test('get service action description', () => {
expect(getDescriptionFromAutomationNode({
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
})).toEqual("media_player.play_media")
})
test('get repeat action description', () => {
expect(getDescriptionFromAutomationNode({
repeat: {
count: 10,
sequence: []
}
})).toEqual("Repeat 10")
})
test('get wait action description', () => {
expect(getDescriptionFromAutomationNode({
wait_template: "states(switch.kitchen_light) == 'on'"
})).toEqual("Wait on states(switch.kitchen_light) == 'on'")
expect(getDescriptionFromAutomationNode({
wait_template: "states(switch.kitchen_light) == 'on'",
timeout: '00:01:00'
})).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00")
})
test('get fire event action description', () => {
expect(getDescriptionFromAutomationNode({
event: 'test_event',
event_data: {},
})).toEqual("Trigger test_event")
})
test('get device action description', () => {
expect(getDescriptionFromAutomationNode({
device_id: "12310das01231",
domain: "zwave_js",
type: "set_value"
})).toEqual("set_value on 12310das01231")
})
test('get choose action description', () => {
expect(getDescriptionFromAutomationNode({
choose: [],
default: [],
})).toEqual("Choose")
})
test('get and/or/not condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'and',
conditions: [],
})).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'or',
conditions: [],
})).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
condition: 'not',
conditions: [],
})).toEqual("Logic")
})
test('get Numeric State condition description', () => {
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
})).toEqual("sensor.temperature?>?<")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
})).toEqual("Numeric State Condition")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: 17,
})).toEqual("sensor.temperature > 17")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
below: 5,
})).toEqual("sensor.temperature < 5")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: 17,
below: 20,
})).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: 'sensor.temperature',
above: 17,
below: 20,
value_template: "{{ float(state.state) + 2 }}"
})).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
condition: 'numeric_state',
entity_id: [
"sensor.kitchen_temperature",
"sensor.living_room_temperature"
],
above: 17,
below: 20,
value_template: "{{ float(state.state) + 2 }}"
})).toEqual("17 < ... < 20")
})
// test('get State condition description', () => {
// expect(getDescriptionFromAutomationNode({
// condition: 'state',
// entity_id: 'sensor.temperature',
// })).toEqual("sensor.temperature?>?<")
// })
-135
View File
@@ -1,135 +0,0 @@
import { AutomationNode, AutomationNodeType, NodeSubType } from "./types";
export const getDescriptionFromAutomationNode = (action: AutomationNode<any>): string => {
if(typeof action === 'string') {
return action;
}
if ('alias' in action && action.alias){
return action.alias;
}
if ('condition' in action) {
if(
(action.condition === 'and') ||
(action.condition === 'or') ||
(action.condition === 'not')
) {
return "Logic"
} else {
switch(action.condition) {
case "numeric_state":
if(action.entity_id) {
const center = typeof action.entity_id === 'string' ? action.entity_id : '...'
if(action.above) {
if(action.below) {
return `${action.above} < ${center} < ${action.below}`
}
return `${center} > ${action.above}`
}
if(action.below) {
return `${center} < ${action.below}`
}
return `${center}?>?<`
}
return "Numeric State Condition"
}
}
}
if ('service' in action) {
return action.service
}
if ('repeat' in action) {
return 'Repeat ' + action.repeat.count;
}
if ('wait_template' in action) {
let out= 'Wait on ' + action.wait_template;
if (action.timeout) {
out += (' for ' + action.timeout)
}
return out;
}
if ('event' in action) {
return `Trigger ${action.event}`
}
if ('type' in action) {
return `${action.type} on ${action.device_id}`
}
if ('choose' in action) {
return 'Choose'
}
return 'n/a'
}
export const determineNodeTypes = (action: AutomationNode<any>) : [AutomationNodeType, NodeSubType] => {
if ('condition' in action) {
switch (action.condition) {
case 'and':
return ['condition', 'Logic']
case 'or':
return ['condition', 'Logic']
case 'not':
return ['condition', 'Logic']
case 'numeric_state':
return ['condition', 'Numeric State']
case 'state':
return ['condition', 'State']
case 'template':
return ['condition', 'Template']
case 'trigger':
return ['condition', 'Trigger']
case 'zone':
return ['condition', 'Zone']
default:
return ['condition', 'Generic']
}
}
if ('platform' in action) {
switch (action.platform) {
case 'event':
return ['trigger', 'Event']
case 'homeassistant':
return ['trigger', 'Home Assistant']
case 'mqtt':
return ['trigger', 'MQTT']
case 'numeric_state':
return ['trigger', 'Numeric State']
case 'state':
return ['trigger', 'State']
case 'tag':
return ['trigger', 'Tag']
case 'template':
return ['trigger', 'Template']
case 'time':
return ['trigger', 'Time']
case 'time_pattern':
return ['trigger', 'Time Pattern']
case 'webhook':
return ['trigger', 'Webhook']
case 'zone':
return ['trigger', 'Zone']
default:
return ['trigger', 'Generic']
}
}
if ('service' in action) {
return ["action", "Service"]
}
if ('repeat' in action) {
return ["action", "Repeat"]
}
if ('wait_template' in action) {
return ["action", "Wait"]
}
if ('event' in action) {
return ["action", "Event"]
}
if (('type' in action) && ('device_id' in action)) {
return ["action", "Device"]
}
if ('choose' in action) {
return ["action", "Choose"]
}
throw Error(`Could not determine node type ${JSON.stringify(action)}`)
}
+63
View File
@@ -0,0 +1,63 @@
import { AutomationSequenceNode } from ".";
import { AutomationTime } from "./common";
import { AutomationCondition } from "./conditions";
interface AutomationActionNodeBase<Name extends String,Data extends Object> {
$smType: 'action';
action: Name;
action_data: Data & {
alias?: string;
variables?: Record<string, any>;
};
}
export interface ServiceAction extends AutomationActionNodeBase<"service", {
service: string;
target: any;
data: any;
}>{}
export interface RepeatAction extends AutomationActionNodeBase<"repeat", {
repeat: {
count: number;
sequence: AutomationAction[];
}
}>{}
export interface WaitAction extends AutomationActionNodeBase<"wait", {
wait_template: string;
timeout?: AutomationTime;
continue_on_timeout?: boolean;
}>{}
export interface FireEventAction extends AutomationActionNodeBase<"event", {
event: string;
event_data: any;
}>{}
export interface DeviceAction extends AutomationActionNodeBase<"device", {
type: string;
device_id: string;
entity_id?: string;
domain: string;
}>{}
export interface ChooseAction extends AutomationActionNodeBase<"choose", {
choose: Array<{
conditions: AutomationCondition[];
sequence: AutomationSequenceNode[];
}>;
default: AutomationAction[];
}>{}
export type AutomationAction =
| ServiceAction
| RepeatAction
| WaitAction
| FireEventAction
| DeviceAction
| ChooseAction
;
export const ActionTypes = [
'Service',
'Repeat',
'Wait',
'Event',
'Device',
'Choose'
] as const;
export type ActionType = typeof ActionTypes[number];
@@ -4,4 +4,3 @@ export interface AutomationTime {
seconds?: number;
milliseconds?: number;
}
+60
View File
@@ -0,0 +1,60 @@
import { AutomationTime } from "./common";
interface AutomationConditionNodeBase<Name extends String,Data extends Object> {
$smType: 'condition';
condition: Name;
condition_data: Data & {
alias?: string;
};
}
export interface LogicCondition extends AutomationConditionNodeBase<'and' | 'or' | 'not',{
conditions: AutomationCondition[];
}> {}
export interface NumericCondition extends AutomationConditionNodeBase<'numeric_state', {
entity_id: string | string[];
above?: string;
below?: string;
attribute?: string;
value_template?: string;
}> {}
export interface StateCondition extends AutomationConditionNodeBase<'state',{
entity_id: string | string[];
state: string | string[];
for?: AutomationTime;
attribute?: string;
}>{}
export interface TemplateCondition extends AutomationConditionNodeBase<'template',{
value_template: string;
}> {}
export interface TimeCondition extends AutomationConditionNodeBase<'time', {
after?: AutomationTime;
before?: AutomationTime;
weekday?: Array<'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun'>;
}> {}
export interface TriggerCondition extends AutomationConditionNodeBase <'trigger', {
id: string | string[];
}>{}
export interface ZoneCondition extends AutomationConditionNodeBase <'zone', {
zone: string;
entity_id: string | string[];
state: string | string[];
}>{}
export type AutomationCondition =
| LogicCondition
| NumericCondition
| StateCondition
| TemplateCondition
| TimeCondition
| TriggerCondition
| ZoneCondition
;
export const conditionTypes = [
'Logic',
'Numeric State',
'State',
'Template',
'Time',
'Trigger',
'Zone',
] as const;
export type ConditionType = typeof conditionTypes[number];
+27
View File
@@ -0,0 +1,27 @@
import { AutomationAction } from "./actions";
import { AutomationCondition } from "./conditions";
import { AutomationTrigger } from "./triggers";
export interface AutomationMetadata {
id: string;
alias: string;
description: string;
trigger_variables?: Record<string, string>;
mode: "single" | "restart" | "queued" | "parallel";
}
export interface AutomationData {
metadata: AutomationMetadata;
trigger: AutomationTrigger[];
condition: AutomationCondition[];
action: AutomationSequenceNode[];
}
export type AutomationSequenceNode = AutomationAction | AutomationCondition;
type AutomationNodeMapping = {
"trigger": AutomationTrigger;
"action": AutomationAction;
"condition": AutomationCondition;
"sequence": AutomationSequenceNode;
}
export type AutomationNodeTypes = keyof AutomationNodeMapping;
export type AutomationNode<N extends AutomationNodeTypes = any> = AutomationNodeMapping[N];
File renamed without changes.
+215
View File
@@ -0,0 +1,215 @@
import {convertTimeToString, getDescriptionFromAutomationNode} from "./utils";
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({
$smType: "action",
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
})).toEqual("Start Music In Kitchen")
})
test('get service action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: "action",
action: "service",
action_data: {
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
})).toEqual("media_player.play_media")
})
test('get repeat action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: "action",
action: "repeat",
action_data: {
repeat: {
count: 10,
sequence: []
}
}
})).toEqual("Repeat 10")
})
test('get wait action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: "action",
action: "wait",
action_data: {
wait_template: "states(switch.kitchen_light) == 'on'"
}
})).toEqual("Wait on states(switch.kitchen_light) == 'on'")
expect(getDescriptionFromAutomationNode({
$smType: "action",
action: "wait",
action_data: {
wait_template: "states(switch.kitchen_light) == 'on'",
// timeout: '00:01:00',
timeout: {
'minutes': 1,
}
}
})).toEqual("Wait on states(switch.kitchen_light) == 'on' for 00:01:00:00")
})
test('get fire event action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'action',
action: 'event',
action_data: {
event: 'test_event',
event_data: {},
}
})).toEqual("Trigger test_event")
})
test('get device action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'action',
action: 'device',
action_data: {
device_id: "12310das01231",
domain: "zwave_js",
type: "set_value"
}
})).toEqual("set_value on 12310das01231")
})
test('get choose action description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'action',
action: 'choose',
action_data: {
choose: [],
default: [],
}
})).toEqual("Choose")
})
test('get and/or/not condition description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'and',
condition_data: {
conditions: [],
}
})).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'or',
condition_data: {
conditions: [],
}
})).toEqual("Logic")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'not',
condition_data: {
conditions: [],
}
})).toEqual("Logic")
})
test('get Numeric State condition description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature',
}
})).toEqual("sensor.temperature?>?<")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: ""
}
})).toEqual("Numeric State Condition")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: "numeric_state",
condition_data: {
entity_id: 'sensor.temperature',
above: '17',
}
})).toEqual("sensor.temperature > 17")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature',
below: '5',
}
})).toEqual("sensor.temperature < 5")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature',
above: '17',
below: '20',
}
})).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: 'sensor.temperature',
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}
})).toEqual("17 < sensor.temperature < 20")
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'numeric_state',
condition_data: {
entity_id: [
"sensor.kitchen_temperature",
"sensor.living_room_temperature"
],
above: '17',
below: '20',
value_template: "{{ float(state.state) + 2 }}"
}
})).toEqual("17 < ... < 20")
})
test('get State condition description', () => {
expect(getDescriptionFromAutomationNode({
$smType: 'condition',
condition: 'state',
condition_data: {
entity_id: 'switch.kitchen_light',
state: "on"
}
})).toEqual("switch.kitchen_light is 'on'")
})
+145
View File
@@ -0,0 +1,145 @@
import { AutomationNode, AutomationNodeTypes } from "./types";
import { AutomationTime } from "./types/common";
export const convertTimeToString = ({
hours=0,
minutes=0,
seconds=0,
milliseconds=0,
}: AutomationTime) => [hours,minutes,seconds,milliseconds].map(n => String(n).padStart(2, '0')).join(':')
export const getDescriptionFromAutomationNode = <N extends AutomationNodeTypes>(node: AutomationNode<N>): string => {
if ('$smType' in node) {
switch (node['$smType']) {
case "action":
if (node.action_data.alias) {
return node.action_data.alias;
}
switch(node.action) {
case 'service':
return node.action_data.service
case 'repeat':
return 'Repeat ' + node.action_data.repeat.count;
case 'wait':
let out= 'Wait on ' + node.action_data.wait_template;
if (node.action_data.timeout) {
out += (' for ' + convertTimeToString(node.action_data.timeout))
}
return out;
case 'event':
return `Trigger ${node.action_data.event}`
case 'device':
return `${node.action_data.type} on ${node.action_data.device_id}`
case 'choose':
return "Choose"
}
case "condition":
if (node.condition_data.alias) {
return node.condition_data.alias;
}
if(
(node.condition === 'and') ||
(node.condition === 'or') ||
(node.condition === 'not')
) {
return "Logic"
} else {
switch(node.condition) {
case "numeric_state":
if(node.condition_data.entity_id) {
const center = typeof node.condition_data.entity_id === 'string' ? node.condition_data.entity_id : '...'
if(node.condition_data.above) {
if(node.condition_data.below) {
return `${node.condition_data.above} < ${center} < ${node.condition_data.below}`
}
return `${center} > ${node.condition_data.above}`
}
if(node.condition_data.below) {
return `${center} < ${node.condition_data.below}`
}
return `${center}?>?<`
}
return "Numeric State Condition"
case "state":
return `${node.condition_data.entity_id} is '${node.condition_data.state}'`
}
}
}
}
return 'n/a'
}
// export const determineNodeTypes = (action: AutomationNode<any>) : [AutomationNodeType, NodeSubType] => {
// if ('condition' in action) {
// switch (action.condition) {
// case 'and':
// return ['condition', 'Logic']
// case 'or':
// return ['condition', 'Logic']
// case 'not':
// return ['condition', 'Logic']
// case 'numeric_state':
// return ['condition', 'Numeric State']
// case 'state':
// return ['condition', 'State']
// case 'template':
// return ['condition', 'Template']
// case 'trigger':
// return ['condition', 'Trigger']
// case 'zone':
// return ['condition', 'Zone']
// default:
// return ['condition', 'Generic']
// }
// }
// if ('platform' in action) {
// switch (action.platform) {
// case 'event':
// return ['trigger', 'Event']
// case 'homeassistant':
// return ['trigger', 'Home Assistant']
// case 'mqtt':
// return ['trigger', 'MQTT']
// case 'numeric_state':
// return ['trigger', 'Numeric State']
// case 'state':
// return ['trigger', 'State']
// case 'tag':
// return ['trigger', 'Tag']
// case 'template':
// return ['trigger', 'Template']
// case 'time':
// return ['trigger', 'Time']
// case 'time_pattern':
// return ['trigger', 'Time Pattern']
// case 'webhook':
// return ['trigger', 'Webhook']
// case 'zone':
// return ['trigger', 'Zone']
// default:
// return ['trigger', 'Generic']
// }
// }
// if ('service' in action) {
// return ["action", "Service"]
// }
// if ('repeat' in action) {
// return ["action", "Repeat"]
// }
// if ('wait_template' in action) {
// return ["action", "Wait"]
// }
// if ('event' in action) {
// return ["action", "Event"]
// }
// if (('type' in action) && ('device_id' in action)) {
// return ["action", "Device"]
// }
// if ('choose' in action) {
// return ["action", "Choose"]
// }
// throw Error(`Could not determine node type ${JSON.stringify(action)}`)
// }
@@ -18,10 +18,12 @@ test('it clips overflowing values', () => {
test('simple empty input dag', () => {
expect(computeDAG({
id: "root",
alias: "root",
description: 'root',
mode: 'single',
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [],
condition: [],
action: [
@@ -35,10 +37,12 @@ test('simple empty input dag', () => {
test('simple single node type input dag', () => {
expect(computeDAG({
id: "root",
alias: "root",
description: 'root',
mode: 'single',
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
@@ -47,20 +51,27 @@ test('simple single node type input dag', () => {
],
condition: [
{
$smType: 'condition',
condition: 'template',
value_template: 'states(switch.kitchen_light) == "on"'
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
$smType: 'action',
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
@@ -95,28 +106,37 @@ test('simple single node type input dag', () => {
test('simple dag with no triggers', () => {
expect(computeDAG({
id: "root",
alias: "root",
description: 'root',
mode: 'single',
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
],
condition: [
{
$smType: "condition",
condition: 'template',
value_template: 'states(switch.kitchen_light) == "on"'
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
$smType: "action",
action: "service",
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
@@ -144,10 +164,12 @@ test('simple dag with no triggers', () => {
test('simple dag with no conditions', () => {
expect(computeDAG({
id: "root",
alias: "root",
description: 'root',
mode: 'single',
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
@@ -157,14 +179,18 @@ test('simple dag with no conditions', () => {
condition: [],
action: [
{
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
$smType: 'action',
action: 'service',
action_data: {
alias: "Start Music In Kitchen",
service: 'media_player.play_media',
target: {
entity_id: "media_player.kitchen_dot"
},
data: {
media_content_id: "Good Morning",
media_content_type: "SPOTIFY",
}
}
}
],
@@ -192,10 +218,12 @@ test('simple dag with no conditions', () => {
test('simple dag with no actions', () => {
expect(computeDAG({
id: "root",
alias: "root",
description: 'root',
mode: 'single',
metadata: {
id: "root",
alias: "root",
description: 'root',
mode: 'single',
},
trigger: [
{
platform: 'time',
@@ -204,8 +232,11 @@ test('simple dag with no actions', () => {
],
condition: [
{
$smType: "condition",
condition: 'template',
value_template: 'states(switch.kitchen_light) == "on"'
condition_data: {
value_template: 'states(switch.kitchen_light) == "on"'
}
}
],
action: [
+2 -2
View File
@@ -1,5 +1,5 @@
import { Automation } from "../../automation/types";
import { AutomationData } from "../../automations/types";
import { GRAPH_HEIGHT, GRAPH_WIDTH, NODE_HEIGHT, NODE_WIDTH } from "./constants";
import {DAG, Node, Point, NormalizedDag} from "./types";
@@ -22,7 +22,7 @@ export const normalizeDAG = (dag: DAG): NormalizedDag => {
edges: dag.edges,
}
}
export const computeDAG = (automation: Automation) : DAG => {
export const computeDAG = (automation: AutomationData) : DAG => {
const nodes: DAG['nodes'] = {};
const edges: DAG['edges'] = [];