connected automation conditions to the backend

This commit is contained in:
britea 2020-05-19 16:23:30 +02:00
parent fa4bae7c10
commit 0d2a2e92ba
3 changed files with 367 additions and 248 deletions

View file

@ -1,6 +1,6 @@
import React, {Component, useState, useRef} from 'react'; import React, { Component, useState, useRef } from 'react';
import {connect} from 'react-redux'; import { connect } from 'react-redux';
import {RemoteService} from '../../remote'; import { RemoteService } from '../../remote';
import update from 'immutability-helper'; import update from 'immutability-helper';
import './Automations.css'; import './Automations.css';
@ -21,7 +21,7 @@ import {
} from 'semantic-ui-react'; } from 'semantic-ui-react';
export const operands = [ export const operands = [
{key: 'EQUAL', text: '=', value: 'EQUAL'}, { key: 'EQUAL', text: '=', value: 'EQUAL' },
{ {
key: 'GREATER_EQUAL', key: 'GREATER_EQUAL',
text: '\u2265', text: '\u2265',
@ -45,8 +45,8 @@ export const operands = [
]; ];
const deviceStateOptions = [ const deviceStateOptions = [
{key: 'off', text: 'off', value: false}, { key: 'off', text: 'off', value: false },
{key: 'on', text: 'on', value: true}, { key: 'on', text: 'on', value: true },
]; ];
const CreateTrigger = (props) => { const CreateTrigger = (props) => {
@ -165,7 +165,7 @@ const SceneItem = (props) => {
const Trigger = ({ const Trigger = ({
deviceName, trigger, onRemove, index, deviceName, trigger, onRemove, index,
}) => { }) => {
const {operand, value, on} = trigger; const { operand, value, on } = trigger;
let symbol; let symbol;
if (operand) { if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text; symbol = operands.filter((opt) => opt.key === operand)[0].text;
@ -213,7 +213,7 @@ class AutomationSaveModal extends Component {
device: trigger.deviceId, device: trigger.deviceId,
kind: trigger.kind, kind: trigger.kind,
...(trigger.kind === 'booleanTrigger' ...(trigger.kind === 'booleanTrigger'
? {on: trigger.on} ? { on: trigger.on }
: { : {
operand: trigger.operator, operand: trigger.operator,
value: trigger.value, value: trigger.value,
@ -235,19 +235,18 @@ class AutomationSaveModal extends Component {
this.orderScenes = this.orderScenes.bind(this); this.orderScenes = this.orderScenes.bind(this);
this.onChangeName = this.onChangeName.bind(this); this.onChangeName = this.onChangeName.bind(this);
//Conditions // Conditions
this.setNewCondition = this._setter("newCondition"); this.setNewCondition = this._setter('newCondition');
this.addCondition = this.addCondition.bind(this); this.addCondition = this.addCondition.bind(this);
this.removeCondition = this.removeCondition.bind(this); this.removeCondition = this.removeCondition.bind(this);
} }
openModal = (e) => { openModal = (e) => {
this.setState({openModal: true}); this.setState({ openModal: true });
}; };
closeModal = (e) => { closeModal = (e) => {
this.setState({openModal: false}); this.setState({ openModal: false });
}; };
get deviceList() { get deviceList() {
@ -255,7 +254,7 @@ class AutomationSaveModal extends Component {
} }
_setter(property) { _setter(property) {
return (value) => this.setState(update(this.state, {[property]: {$set: value}})); return (value) => this.setState(update(this.state, { [property]: { $set: value } }));
} }
triggerKind(trigger) { triggerKind(trigger) {
@ -269,6 +268,20 @@ class AutomationSaveModal extends Component {
// throw new Error("Trigger kind not handled"); // throw new Error("Trigger kind not handled");
} }
conditionKind(condition) {
if ('operand' in condition && 'value' in condition) {
return 'rangeTrigger';
}
if ('on' in condition) {
return 'booleanTrigger';
}
if ('operand' in condition && 'mode' in condition) {
return 'thermostatCondition';
}
return false;
}
_checkNewTrigger(trigger, isCondition = false) { _checkNewTrigger(trigger, isCondition = false) {
const error = { const error = {
result: false, result: false,
@ -322,31 +335,31 @@ class AutomationSaveModal extends Component {
let isNotDuplicate = null; let isNotDuplicate = null;
if(isCondition === true){ if (isCondition === true) {
isNotDuplicate = !this.state.conditionsList.some( isNotDuplicate = !this.state.conditionsList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand, (t) => t.device === trigger.device && t.operand === trigger.operand,
); );
}else{ } else {
isNotDuplicate = !this.state.triggerList.some( isNotDuplicate = !this.state.triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand, (t) => t.device === trigger.device && t.operand === trigger.operand,
); );
} }
const type = isCondition ? "condition" : "trigger" const type = isCondition ? 'condition' : 'trigger';
const duplicationMessage = `You have already created a ${type} for this device with the same conditions`; const duplicationMessage = `You have already created a ${type} for this device with the same conditions`;
return { return {
result: isNotDuplicate, result: isNotDuplicate,
message: isNotDuplicate message: isNotDuplicate
? null ? null
: duplicationMessage : duplicationMessage,
}; };
} }
addTrigger() { addTrigger() {
const {result, message} = this._checkNewTrigger(this.state.newTrigger); const { result, message } = this._checkNewTrigger(this.state.newTrigger);
if (result) { if (result) {
this.setState( this.setState(
update(this.state, { update(this.state, {
triggerList: {$push: [this.state.newTrigger]}, triggerList: { $push: [this.state.newTrigger] },
}), }),
); );
} else { } else {
@ -356,14 +369,14 @@ class AutomationSaveModal extends Component {
removeTrigger(index) { removeTrigger(index) {
this.setState( this.setState(
update(this.state, {triggerList: {$splice: [[index, 1]]}}), update(this.state, { triggerList: { $splice: [[index, 1]] } }),
); );
} }
// This gets triggered when the devices dropdown changes the value. // This gets triggered when the devices dropdown changes the value.
onInputChange(val) { onInputChange(val) {
if (val.name === 'device') { if (val.name === 'device') {
this.setNewTrigger({[val.name]: val.value}); this.setNewTrigger({ [val.name]: val.value });
} else { } else {
this.setNewTrigger({ this.setNewTrigger({
...this.state.newTrigger, ...this.state.newTrigger,
@ -378,7 +391,7 @@ class AutomationSaveModal extends Component {
orderScenes = (id, checked) => { orderScenes = (id, checked) => {
if (checked) { if (checked) {
this.setState(update(this.state, {order: {$push: [id]}})); this.setState(update(this.state, { order: { $push: [id] } }));
} else { } else {
this.setState( this.setState(
update(this.state, { update(this.state, {
@ -388,8 +401,8 @@ class AutomationSaveModal extends Component {
} }
}; };
searchScenes(_, {value}) { searchScenes(_, { value }) {
this.setState(update(this.state, {scenesFilter: {$set: value}})); this.setState(update(this.state, { scenesFilter: { $set: value } }));
this.forceUpdate(); this.forceUpdate();
} }
@ -452,7 +465,7 @@ class AutomationSaveModal extends Component {
deviceId: trigger.device, deviceId: trigger.device,
kind, kind,
...(kind === 'booleanTrigger' ...(kind === 'booleanTrigger'
? {on: trigger.on} ? { on: trigger.on }
: { : {
operator: trigger.operand, operator: trigger.operand,
range: parseInt(trigger.value), range: parseInt(trigger.value),
@ -461,6 +474,25 @@ class AutomationSaveModal extends Component {
); );
} }
for (const condition of this.state.conditionsList) {
const kind = condition.kind || this.conditionKind(condition);
const loSpagnolo = (kind === 'thermostatCondition' ? { operator: condition.operand, mode: condition.mode }
: {
operator: condition.operand,
range: parseInt(condition.value),
});
automation.conditions.push(
{
deviceId: condition.device,
kind,
...(kind === 'booleanTrigger'
? { on: condition.on }
: loSpagnolo
),
},
);
}
this.props this.props
.fastUpdateAutomation(automation) .fastUpdateAutomation(automation)
.then(this.closeModal) .then(this.closeModal)
@ -471,6 +503,7 @@ class AutomationSaveModal extends Component {
automation, automation,
triggerList: this.state.triggerList, triggerList: this.state.triggerList,
order: this.state.order, order: this.state.order,
conditionList: this.state.conditionsList,
}) })
.then(this.closeModal) .then(this.closeModal)
.catch(console.error); .catch(console.error);
@ -481,7 +514,7 @@ class AutomationSaveModal extends Component {
get trigger() { get trigger() {
return this.props.id ? ( return this.props.id ? (
<Button <Button
style={{display: 'inline'}} style={{ display: 'inline' }}
circular circular
size="small" size="small"
icon="edit" icon="edit"
@ -489,7 +522,7 @@ class AutomationSaveModal extends Component {
/> />
) : ( ) : (
<Button icon labelPosition="left" color="green" onClick={this.openModal}> <Button icon labelPosition="left" color="green" onClick={this.openModal}>
<Icon name="add"/> <Icon name="add" />
Create new automation Create new automation
</Button> </Button>
); );
@ -499,11 +532,11 @@ class AutomationSaveModal extends Component {
addCondition() { addCondition() {
// Same method used to check triggers and conditions, not a mistake // Same method used to check triggers and conditions, not a mistake
const {result, message} = this._checkNewTrigger(this.state.newCondition, true); const { result, message } = this._checkNewTrigger(this.state.newCondition, true);
if (result) { if (result) {
this.setState( this.setState(
update(this.state, { update(this.state, {
conditionsList: {$push: [this.state.newCondition]}, conditionsList: { $push: [this.state.newCondition] },
}), }),
); );
} else { } else {
@ -513,13 +546,13 @@ class AutomationSaveModal extends Component {
removeCondition(index) { removeCondition(index) {
this.setState( this.setState(
update(this.state, {conditionsList: {$splice: [[index, 1]]}}), update(this.state, { conditionsList: { $splice: [[index, 1]] } }),
); );
} }
onInputChangeCondition = (val) => { onInputChangeCondition = (val) => {
if (val.name === 'device') { if (val.name === 'device') {
this.setNewCondition({[val.name]: val.value}); this.setNewCondition({ [val.name]: val.value });
} else { } else {
this.setNewCondition({ this.setNewCondition({
...this.state.newCondition, ...this.state.newCondition,
@ -537,7 +570,7 @@ class AutomationSaveModal extends Component {
onClose={this.closeModal} onClose={this.closeModal}
> >
<Segment basic> <Segment basic>
<Header style={{display: 'inline', marginRight: '1rem'}}> <Header style={{ display: 'inline', marginRight: '1rem' }}>
{this.state.editName ? ( {this.state.editName ? (
<Input <Input
focus focus
@ -551,7 +584,7 @@ class AutomationSaveModal extends Component {
</Header> </Header>
<Button <Button
onClick={() => this.setEditName((prev) => !prev)} onClick={() => this.setEditName((prev) => !prev)}
style={{display: 'inline'}} style={{ display: 'inline' }}
circular circular
size="small" size="small"
icon={this.state.editName ? 'save' : 'edit'} icon={this.state.editName ? 'save' : 'edit'}
@ -559,7 +592,7 @@ class AutomationSaveModal extends Component {
<Segment placeholder className="segment-automations"> <Segment placeholder className="segment-automations">
<Grid columns={2} stackable textAlign="center"> <Grid columns={2} stackable textAlign="center">
<Divider vertical/> <Divider vertical />
<Grid.Row verticalAlign="middle"> <Grid.Row verticalAlign="middle">
<Grid.Column> <Grid.Column>
<Header>Create Triggers</Header> <Header>Create Triggers</Header>
@ -603,7 +636,7 @@ class AutomationSaveModal extends Component {
fluid fluid
onChange={this.searchScenes} onChange={this.searchScenes}
/> />
<Divider horizontal/> <Divider horizontal />
<List divided relaxed> <List divided relaxed>
{this.sceneList.map((scene) => ( {this.sceneList.map((scene) => (
<SceneItem <SceneItem
@ -618,7 +651,7 @@ class AutomationSaveModal extends Component {
) : ( ) : (
<> <>
<Header icon> <Header icon>
<Icon name="world"/> <Icon name="world" />
</Header> </Header>
<Button primary>Create Scene</Button> <Button primary>Create Scene</Button>
</> </>
@ -665,7 +698,7 @@ class AutomationSaveModal extends Component {
</Grid> </Grid>
<Grid> <Grid>
<Grid.Row> <Grid.Row>
<Grid.Column style={{marginRight: '1rem'}}> <Grid.Column style={{ marginRight: '1rem' }}>
<Button onClick={() => this.saveAutomation()} color="green"> <Button onClick={() => this.saveAutomation()} color="green">
{this.props.id ? 'Save' : 'Create'} {this.props.id ? 'Save' : 'Create'}
</Button> </Button>

View file

@ -17,7 +17,7 @@ import CreateAutomation, { operands } from './AutomationCreationModal';
const Automation = ({ const Automation = ({
automation, devices, scenes, removeAutomation, automation, devices, scenes, removeAutomation,
}) => { }) => {
const { triggers } = automation; const { triggers, conditions } = automation;
const scenePriorities = automation.scenes; const scenePriorities = automation.scenes;
const getOperator = (operand) => operands.filter((o) => o.key === operand)[0].text; const getOperator = (operand) => operands.filter((o) => o.key === operand)[0].text;
@ -85,6 +85,36 @@ const Automation = ({
</Grid.Row> </Grid.Row>
</Grid> </Grid>
</Segment> </Segment>
<Grid columns={1} stackable textAlign="center">
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Conditions</Header>
<List divided relaxed>
{conditions !== undefined
&& conditions.map((condition) => {
const device = devices.filter(
(d) => d.id === condition.deviceId,
)[0];
return (
<Menu key={condition.id} compact>
<Menu.Item as="span">
{device.name}
{' '}
{condition.operator
? `${getOperator(condition.operator)
} ${
condition.range}`
: condition.on
? ' - on'
: ' - off'}
</Menu.Item>
</Menu>
);
})}
</List>
</Grid.Column>
</Grid.Row>
</Grid>
</> </>
); );
}; };

View file

@ -556,19 +556,30 @@ export const RemoteService = {
* with user-fiendly errors as a RemoteError * with user-fiendly errors as a RemoteError
*/ */
saveAutomation: (data) => { saveAutomation: (data) => {
const { automation, triggerList, order } = data; const {
automation, triggerList, order, conditionList,
} = data;
automation.triggers = []; automation.triggers = [];
automation.scenes = []; automation.scenes = [];
automation.condition = [];
return (dispatch) => { return (dispatch) => {
const urlAutomation = '/automation'; const urlAutomation = '/automation';
const urlBooleanTrigger = '/booleanTrigger'; const urlBooleanTrigger = '/booleanTrigger';
const urlRangeTrigger = '/rangeTrigger'; const urlRangeTrigger = '/rangeTrigger';
const urlScenePriority = '/scenePriority'; const urlScenePriority = '/scenePriority';
// conditions
const urlRangeCondition = '/rangeCondition';
const urlBooleanCondition = '/booleanCondition';
const urlThermostatCondition = '/thermostatCondition';
const rangeTriggerList = triggerList.filter((trigger) => 'operand' in trigger); const rangeTriggerList = triggerList.filter((trigger) => 'operand' in trigger);
const booleanTriggerList = triggerList.filter( const booleanTriggerList = triggerList.filter(
(trigger) => !('operand' in trigger), (trigger) => !('operand' in trigger),
); );
const rangeConditionList = conditionList.filter((condition) => 'operand' in condition && 'value' in condition);
const booleanConditionList = conditionList.filter((condition) => 'on' in condition);
const thermostatConditionList = conditionList.filter((condition) => 'operand' in condition && 'mode' in condition);
return Endpoint.post(urlAutomation, {}, automation).then( return Endpoint.post(urlAutomation, {}, automation).then(
async (automationRes) => { async (automationRes) => {
@ -591,7 +602,7 @@ export const RemoteService = {
const trigger = { const trigger = {
automationId: id, automationId: id,
deviceId: t.device, deviceId: t.device,
on: t.value, on: t.on,
}; };
resBoolTriggers.push(Endpoint.post( resBoolTriggers.push(Endpoint.post(
urlBooleanTrigger, urlBooleanTrigger,
@ -601,6 +612,51 @@ export const RemoteService = {
} }
automation.triggers.push(...((await Promise.all(resBoolTriggers)).map((v) => v.data))); automation.triggers.push(...((await Promise.all(resBoolTriggers)).map((v) => v.data)));
// Conditions
const resRangeConditions = [];
for (const t of rangeConditionList) {
const condition = {
automationId: id,
deviceId: t.device,
operator: t.operand,
range: t.value,
};
resRangeConditions.push(Endpoint.post(urlRangeCondition, {}, condition));
}
automation.conditions = (await Promise.all(resRangeConditions)).map((v) => v.data);
const resBoolConditions = [];
for (const t of booleanConditionList) {
console.log('HERE', t);
const condition = {
automationId: id,
deviceId: t.device,
on: t.on,
};
resBoolConditions.push(Endpoint.post(
urlBooleanCondition,
{},
condition,
));
}
automation.conditions.push(...((await Promise.all(resBoolConditions)).map((v) => v.data)));
const resThermoConditions = [];
for (const t of thermostatConditionList) {
const condition = {
automationId: id,
deviceId: t.device,
mode: t.mode,
operator: t.operand,
};
resThermoConditions.push(Endpoint.post(
urlThermostatCondition,
{},
condition,
));
}
automation.conditions.push(...((await Promise.all(resThermoConditions)).map((v) => v.data)));
const resScenePriorities = []; const resScenePriorities = [];
for (const [priority, sceneId] of order.entries()) { for (const [priority, sceneId] of order.entries()) {
const scenePriority = { const scenePriority = {