Check values for different types of sensors when creating a trigger for an automation

This commit is contained in:
Christian Capeáns Pérez 2020-05-06 21:36:32 +02:00
parent b61148b24a
commit 78f6e508ec
3 changed files with 1396 additions and 1255 deletions

View file

@ -1,4 +1,4 @@
import React, { Component, useState } from "react";
import React, { Component, useState, useRef } from "react";
import { connect } from "react-redux";
import { RemoteService } from "../../remote";
import update from "immutability-helper";
@ -51,6 +51,8 @@ const deviceStateOptions = [
const CreateTrigger = (props) => {
const [activeOperand, setActiveOperand] = useState(true);
const operandsRef = useRef(null);
const valuesRef = useRef(null);
const notAdmitedDevices = ["buttonDimmer"];
const hasOperand = new Set([
"knobDimmer",
@ -72,6 +74,10 @@ const CreateTrigger = (props) => {
const onChange = (e, val) => {
props.inputChange(val);
setActiveOperand(hasOperand.has(props.devices[val.value].kind));
if (operandsRef.current) operandsRef.current.setValue("");
if (valuesRef.current)
valuesRef.current.inputRef.current.valueAsNumber = undefined;
};
return (
@ -93,7 +99,10 @@ const CreateTrigger = (props) => {
<React.Fragment>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
onChange={(e, val) =>
props.inputChange(val)
}
ref={operandsRef}
name="operand"
compact
selection
@ -102,7 +111,10 @@ const CreateTrigger = (props) => {
</Form.Field>
<Form.Field inline width={7}>
<Input
onChange={(e, val) => props.inputChange(val)}
onChange={(e, val) => {
props.inputChange(val);
}}
ref={valuesRef}
name="value"
type="number"
placeholder="Value"
@ -112,7 +124,9 @@ const CreateTrigger = (props) => {
) : (
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
onChange={(e, val) =>
props.inputChange(val)
}
placeholder="State"
name="on"
compact
@ -139,7 +153,10 @@ const SceneItem = (props) => {
<Checkbox
toggle
onChange={(e, val) =>
props.orderScenes(props.scene.id, val.checked)
props.orderScenes(
props.scene.id,
val.checked
)
}
checked={position + 1 > 0}
/>
@ -148,7 +165,9 @@ const SceneItem = (props) => {
<h3>{props.scene.name}</h3>
</Grid.Column>
<Grid.Column width={4}>
<h3>{position !== -1 ? "# " + (position + 1) : ""}</h3>
<h3>
{position !== -1 ? "# " + (position + 1) : ""}
</h3>
</Grid.Column>
</Grid.Row>
</Grid>
@ -168,7 +187,9 @@ const Trigger = ({ deviceName, trigger, onRemove, index }) => {
<Menu compact>
<Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
<Menu.Item as="span">{operand ? value : on ? "on" : "off"}</Menu.Item>
<Menu.Item as="span">
{operand ? value : on ? "on" : "off"}
</Menu.Item>
</Menu>
<Icon
as={"i"}
@ -196,7 +217,8 @@ class AutomationSaveModal extends Component {
if (this.props.automation) {
this.state.automationName = this.props.automation.name;
for (const scenePriority of this.props.automation.scenes) {
this.state.order[scenePriority.priority] = scenePriority.sceneId;
this.state.order[scenePriority.priority] =
scenePriority.sceneId;
}
for (const trigger of this.props.automation.triggers) {
this.state.triggerList.push(
@ -207,7 +229,10 @@ class AutomationSaveModal extends Component {
},
trigger.kind === "booleanTrigger"
? { on: trigger.on }
: { operand: trigger.operator, value: trigger.value }
: {
operand: trigger.operator,
value: trigger.value,
}
)
);
}
@ -245,29 +270,72 @@ class AutomationSaveModal extends Component {
}
triggerKind(trigger) {
if ("on" in trigger) {
return "booleanTrigger";
} else if ("operand" in trigger && "value" in trigger) {
if ("operand" in trigger && "value" in trigger) {
return "rangeTrigger";
} else if ("on" in trigger) {
return "booleanTrigger";
} else {
throw new Error("Trigger kind not handled");
return false;
//throw new Error("Trigger kind not handled");
}
}
_checkNewTrigger(trigger) {
// Check for missing fields for creation
const error = {
result: false,
message: "There are missing fields!",
};
let device = Object.values(this.props.devices).filter(
(d) => d.id === trigger.device
)[0];
switch (this.triggerKind(trigger)) {
let triggerKind = this.triggerKind(trigger);
if (!device || !triggerKind) {
error.message = "There are missing fields";
return error;
}
let deviceKind = device.kind;
const devicesWithPercentage = [
"dimmableLight",
"curtains",
"knobDimmer",
];
switch (triggerKind) {
case "booleanTrigger":
if (!trigger.device || trigger.on === null || trigger.on === undefined)
if (
!trigger.device ||
trigger.on === null ||
trigger.on === undefined
)
return error;
break;
case "rangeTrigger":
if (!trigger.device || !trigger.operand || !trigger.value) return error;
if (!trigger.device || !trigger.operand || !trigger.value) {
return error;
}
if (trigger.value < 0) {
error.message = "Values cannot be negative";
return error;
}
// If the device's range is a percentage, values cannot exceed 100
else if (
devicesWithPercentage.includes(deviceKind) &&
trigger.value > 100
) {
error.message =
"The value can't exceed 100, as it's a percentage";
return error;
} else if (
deviceKind === "sensor" &&
device.sensor === "HUMIDITY" &&
trigger.value > 100
) {
error.message =
"The value can't exceed 100, as it's a percentage";
return error;
}
break;
default:
throw new Error("theoretically unreachable statement");
@ -286,11 +354,15 @@ class AutomationSaveModal extends Component {
}
addTrigger() {
const { result, message } = this._checkNewTrigger(this.state.newTrigger);
const { result, message } = this._checkNewTrigger(
this.state.newTrigger
);
if (result) {
this.setState(
update(this.state, { triggerList: { $push: [this.state.newTrigger] } })
update(this.state, {
triggerList: { $push: [this.state.newTrigger] },
})
);
} else {
alert(message);
@ -305,7 +377,14 @@ class AutomationSaveModal extends Component {
// This gets triggered when the devices dropdown changes the value.
onInputChange(val) {
this.setNewTrigger({ ...this.state.newTrigger, [val.name]: val.value });
if (val.name === "device") {
this.setNewTrigger({ [val.name]: val.value });
} else {
this.setNewTrigger({
...this.state.newTrigger,
[val.name]: val.value,
});
}
}
onChangeName(_, val) {
@ -394,12 +473,14 @@ class AutomationSaveModal extends Component {
},
kind
? { on: trigger.on }
: { operator: trigger.operand, value: trigger.value }
: {
operator: trigger.operand,
value: trigger.value,
}
)
);
}
console.log(automation);
this.props
.fastUpdateAutomation(automation)
.then(this.closeModal)
@ -427,7 +508,12 @@ class AutomationSaveModal extends Component {
onClick={this.openModal}
/>
) : (
<Button icon labelPosition="left" color="green" onClick={this.openModal}>
<Button
icon
labelPosition="left"
color="green"
onClick={this.openModal}
>
<Icon name="add"></Icon>Create new automation
</Button>
);
@ -471,21 +557,32 @@ class AutomationSaveModal extends Component {
<Header>Create Triggers</Header>
<List divided relaxed>
{this.state.triggerList.length > 0 &&
this.state.triggerList.map((trigger, i) => {
this.state.triggerList.map(
(trigger, i) => {
const deviceName = this.deviceList.filter(
(d) => d.id === trigger.device
(d) =>
d.id ===
trigger.device
)[0].name;
const key = this._generateKey(trigger);
const key = this._generateKey(
trigger
);
return (
<Trigger
key={key}
index={i}
deviceName={deviceName}
deviceName={
deviceName
}
trigger={trigger}
onRemove={this.removeTrigger}
onRemove={
this
.removeTrigger
}
/>
);
})}
}
)}
<CreateTrigger
devices={this.props.devices}
inputChange={this.onInputChange}
@ -516,7 +613,9 @@ class AutomationSaveModal extends Component {
key={scene.id}
scene={scene}
order={this.state.order}
orderScenes={this.orderScenes}
orderScenes={
this.orderScenes
}
/>
))}
</List>
@ -526,7 +625,9 @@ class AutomationSaveModal extends Component {
<Header icon>
<Icon name="world" />
</Header>
<Button primary>Create Scene</Button>
<Button primary>
Create Scene
</Button>
</React.Fragment>
)}
</Grid.Column>
@ -536,7 +637,10 @@ class AutomationSaveModal extends Component {
<Grid>
<Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}>
<Button onClick={() => this.saveAutomation()} color="green">
<Button
onClick={() => this.saveAutomation()}
color="green"
>
{this.props.id ? "Save" : "Create"}
</Button>
</Grid.Column>

View file

@ -51,7 +51,9 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
<Menu.Item as="span">
{device.name}{" "}
{trigger.operator
? getOperator(trigger.operator) +
? getOperator(
trigger.operator
) +
" " +
trigger.range
: trigger.on
@ -74,7 +76,9 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
if (!sceneData) return "";
return (
<Menu key={sceneData.id} compact>
<Menu.Item as="span">{sceneData.name}</Menu.Item>
<Menu.Item as="span">
{sceneData.name}
</Menu.Item>
</Menu>
);
})}
@ -115,7 +119,9 @@ class AutomationsPanel extends Component {
removeAutomation = (id) => {
this.props
.deleteAutomation(id)
.catch((err) => console.error(`error removing automation ${id}:`, err));
.catch((err) =>
console.error(`error removing automation ${id}:`, err)
);
};
render() {
@ -135,7 +141,11 @@ class AutomationsPanel extends Component {
<Grid.Row>
{this.props.automations.map((automation, i) => {
return (
<Grid.Column key={i} width={8} style={{ margin: "2rem 0" }}>
<Grid.Column
key={i}
width={8}
style={{ margin: "2rem 0" }}
>
<Automation
removeAutomation={this.removeAutomation}
scenes={this.props.scenes}
@ -161,7 +171,6 @@ const mapStateToProps = (state, _) => ({
return Object.values(state.devices);
},
get automations() {
console.log(state.automations);
return Object.values(state.automations);
},
});

View file

@ -41,7 +41,9 @@ function reducer(previousState, action) {
const createOrUpdateScene = (scene) => {
if (!newState.scenes[scene.id]) {
newState = update(newState, {
scenes: { [scene.id]: { $set: { ...scene, sceneStates: new Set() } } },
scenes: {
[scene.id]: { $set: { ...scene, sceneStates: new Set() } },
},
});
} else {
newState = update(newState, {
@ -92,7 +94,9 @@ function reducer(previousState, action) {
newState = update(previousState, { login: { $set: action.login } });
break;
case "USER_INFO_UPDATE":
newState = update(previousState, { userInfo: { $set: action.userInfo } });
newState = update(previousState, {
userInfo: { $set: action.userInfo },
});
break;
case "ROOMS_UPDATE":
newState = previousState;
@ -137,7 +141,9 @@ function reducer(previousState, action) {
// and remove any join between that scene and deleted
// sceneStates
change = {
scenes: { [action.sceneId]: { sceneStates: { $set: new Set() } } },
scenes: {
[action.sceneId]: { sceneStates: { $set: new Set() } },
},
sceneStates: { $unset: [] },
};
@ -168,7 +174,8 @@ function reducer(previousState, action) {
change.scenes[sceneState.sceneId] || {};
change.scenes[sceneState.sceneId].sceneStates =
change.scenes[sceneState.sceneId].sceneStates || {};
const sceneStates = change.scenes[sceneState.sceneId].sceneStates;
const sceneStates =
change.scenes[sceneState.sceneId].sceneStates;
sceneStates.$add = sceneStates.$add || [];
sceneStates.$add.push(sceneState.id);
} else {
@ -198,7 +205,9 @@ function reducer(previousState, action) {
// devices
if (action.roomId) {
change = {
rooms: { [action.roomId]: { devices: { $set: new Set() } } },
rooms: {
[action.roomId]: { devices: { $set: new Set() } },
},
devices: { $unset: [] },
};
@ -257,7 +266,8 @@ function reducer(previousState, action) {
}
if (device.roomId in newState.rooms) {
change.rooms[device.roomId] = change.rooms[device.roomId] || {};
change.rooms[device.roomId] =
change.rooms[device.roomId] || {};
change.rooms[device.roomId].devices =
change.rooms[device.roomId].devices || {};
const devices = change.rooms[device.roomId].devices;
@ -272,7 +282,9 @@ function reducer(previousState, action) {
$set: new Set([device.id]),
};
} else {
change.pendingJoins.rooms[device.roomId].$set.add(device.id);
change.pendingJoins.rooms[device.roomId].$set.add(
device.id
);
}
}
}
@ -368,7 +380,9 @@ function reducer(previousState, action) {
case "AUTOMATION_SAVE":
change = {
automations: { [action.automation.id]: { $set: action.automation } },
automations: {
[action.automation.id]: { $set: action.automation },
},
};
newState = update(previousState, change);
@ -377,7 +391,9 @@ function reducer(previousState, action) {
case "STATE_SAVE":
change = {
sceneStates: { [action.sceneState.id]: { $set: action.sceneState } },
sceneStates: {
[action.sceneState.id]: { $set: action.sceneState },
},
};
if (previousState.scenes[action.sceneState.sceneId]) {
@ -432,7 +448,9 @@ function reducer(previousState, action) {
break;
case "SCENE_DELETE":
if (!(action.sceneId in previousState.scenes)) {
console.warn(`Scene to delete ${action.sceneId} does not exist`);
console.warn(
`Scene to delete ${action.sceneId} does not exist`
);
break;
}
@ -455,7 +473,9 @@ function reducer(previousState, action) {
break;
case "STATE_DELETE":
if (!(action.stateId in previousState.sceneStates)) {
console.warn(`State to delete ${action.stateId} does not exist`);
console.warn(
`State to delete ${action.stateId} does not exist`
);
break;
}
@ -464,7 +484,9 @@ function reducer(previousState, action) {
};
if (
previousState.scenes[previousState.sceneStates[action.stateId].sceneId]
previousState.scenes[
previousState.sceneStates[action.stateId].sceneId
]
) {
change.scenes = {
[previousState.sceneStates[action.stateId].sceneId]: {
@ -478,7 +500,9 @@ function reducer(previousState, action) {
case "DEVICE_DELETE":
if (!(action.deviceId in previousState.devices)) {
console.warn(`Device to delete ${action.deviceId} does not exist`);
console.warn(
`Device to delete ${action.deviceId} does not exist`
);
break;
}
@ -486,7 +510,11 @@ function reducer(previousState, action) {
devices: { $unset: [action.deviceId] },
};
if (previousState.rooms[previousState.devices[action.deviceId].roomId]) {
if (
previousState.rooms[
previousState.devices[action.deviceId].roomId
]
) {
change.rooms = {
[previousState.devices[action.deviceId].roomId]: {
devices: { $remove: [action.deviceId] },
@ -512,7 +540,8 @@ function reducer(previousState, action) {
const allDevices = JSON.parse(action.payload.message);
const devices = allDevices.filter(
(d) =>
(d.fromHostId === null || d.fromHostId === undefined) && !d.deleted
(d.fromHostId === null || d.fromHostId === undefined) &&
!d.deleted
);
const hostDevicesMapByHostId = allDevices
.filter((d) => d.fromHostId)
@ -527,7 +556,6 @@ function reducer(previousState, action) {
}
return a;
}, {});
console.log(devices);
newState = reducer(previousState, {
type: "DEVICES_UPDATE",
partial: true,