Merge branch '71-6-users-can-add-conditions-to-automations' into 'dev'

Resolve "6. Users can add conditions to automations"

Closes #71

See merge request sa4-2020/the-sanmarinoes/frontend!152
This commit is contained in:
Andrea Brites Marto 2020-05-21 16:17:17 +02:00
commit 9df8a7f19a
4 changed files with 12965 additions and 569 deletions

View file

@ -49,8 +49,21 @@ const deviceStateOptions = [
{ key: 'on', text: 'on', value: true }, { key: 'on', text: 'on', value: true },
]; ];
const thermostatOptions = [
{ key: 'HEATING', text: 'HEATING', value: 'HEATING' },
{ key: 'COOLING', text: 'COOLING', value: 'COOLING' },
{ key: 'IDLE', text: 'IDLE', value: 'IDLE' },
{ key: 'OFF', text: 'OFF', value: 'OFF' },
];
const thermostatOperands = [
{ key: 'EQUAL', text: '=', value: 'EQUAL' },
{ key: 'NOTEQUAL', text: '\u2260', value: 'NOTEQUAL' },
];
const CreateTrigger = (props) => { const CreateTrigger = (props) => {
const [activeOperand, setActiveOperand] = useState(true); const [activeOperand, setActiveOperand] = useState(true);
const [activeThermostat, setActiveThermostat] = useState(false);
const operandsRef = useRef(null); const operandsRef = useRef(null);
const valuesRef = useRef(null); const valuesRef = useRef(null);
const notAdmitedDevices = ['buttonDimmer']; const notAdmitedDevices = ['buttonDimmer'];
@ -72,7 +85,7 @@ const CreateTrigger = (props) => {
const onChange = (e, val) => { const onChange = (e, val) => {
props.inputChange(val); props.inputChange(val);
setActiveOperand(hasOperand.has(props.devices[val.value].kind)); setActiveOperand(hasOperand.has(props.devices[val.value].kind));
setActiveThermostat(props.devices[val.value].kind === 'thermostat');
if (operandsRef.current) operandsRef.current.setValue(''); if (operandsRef.current) operandsRef.current.setValue('');
if (valuesRef.current) valuesRef.current.inputRef.current.valueAsNumber = undefined; if (valuesRef.current) valuesRef.current.inputRef.current.valueAsNumber = undefined;
}; };
@ -92,7 +105,32 @@ const CreateTrigger = (props) => {
placeholder="Device" placeholder="Device"
/> />
</Form.Field> </Form.Field>
{activeOperand ? ( {
activeThermostat ? (
<>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
ref={operandsRef}
name="operand"
compact
selection
options={thermostatOperands}
/>
</Form.Field>
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
placeholder="State"
name="mode"
compact
selection
options={thermostatOptions}
/>
</Form.Field>
</>
)
: activeOperand ? (
<> <>
<Form.Field inline width={2}> <Form.Field inline width={2}>
<Dropdown <Dropdown
@ -127,7 +165,8 @@ const CreateTrigger = (props) => {
options={deviceStateOptions} options={deviceStateOptions}
/> />
</Form.Field> </Form.Field>
)} )
}
</Form.Group> </Form.Group>
</Form> </Form>
</List.Content> </List.Content>
@ -165,7 +204,9 @@ const SceneItem = (props) => {
const Trigger = ({ const Trigger = ({
deviceName, trigger, onRemove, index, deviceName, trigger, onRemove, index,
}) => { }) => {
const { operand, value, on } = trigger; const {
operand, value, on, mode,
} = 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;
@ -175,7 +216,7 @@ const Trigger = ({
<Menu compact> <Menu compact>
<Menu.Item as="span">{deviceName}</Menu.Item> <Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</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">{mode || (operand ? value : on ? 'on' : 'off')}</Menu.Item>
</Menu> </Menu>
<Icon <Icon
as="i" as="i"
@ -192,10 +233,12 @@ class AutomationSaveModal extends Component {
super(props); super(props);
this.state = { this.state = {
triggerList: [], triggerList: [],
conditionsList: [],
order: [], order: [],
automationName: 'New Automation', automationName: 'New Automation',
editName: false, editName: false,
newTrigger: {}, newTrigger: {},
newCondition: {},
scenesFilter: null, scenesFilter: null,
openModal: false, openModal: false,
}; };
@ -226,13 +269,17 @@ class AutomationSaveModal extends Component {
this.setautomationName = this._setter('automationName'); this.setautomationName = this._setter('automationName');
this.setEditName = this._setter('editName'); this.setEditName = this._setter('editName');
this.setNewTrigger = this._setter('newTrigger'); this.setNewTrigger = this._setter('newTrigger');
this.addTrigger = this.addTrigger.bind(this); this.addTrigger = this.addTrigger.bind(this);
this.removeTrigger = this.removeTrigger.bind(this); this.removeTrigger = this.removeTrigger.bind(this);
this.onInputChange = this.onInputChange.bind(this); this.onInputChange = this.onInputChange.bind(this);
this.searchScenes = this.searchScenes.bind(this); this.searchScenes = this.searchScenes.bind(this);
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
this.setNewCondition = this._setter('newCondition');
this.addCondition = this.addCondition.bind(this);
this.removeCondition = this.removeCondition.bind(this);
} }
openModal = (e) => { openModal = (e) => {
@ -254,14 +301,29 @@ class AutomationSaveModal extends Component {
triggerKind(trigger) { triggerKind(trigger) {
if ('operand' in trigger && 'value' in trigger) { if ('operand' in trigger && 'value' in trigger) {
return 'rangeTrigger'; return 'rangeTrigger';
} if ('on' in trigger) { }
if ('on' in trigger) {
return 'booleanTrigger'; return 'booleanTrigger';
} }
return false; return false;
// throw new Error("Trigger kind not handled"); // throw new Error("Trigger kind not handled");
} }
_checkNewTrigger(trigger) { 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) {
const error = { const error = {
result: false, result: false,
message: 'There are missing fields!', message: 'There are missing fields!',
@ -271,19 +333,24 @@ class AutomationSaveModal extends Component {
)[0]; )[0];
const triggerKind = this.triggerKind(trigger); const triggerKind = this.triggerKind(trigger);
const conditionKind = this.conditionKind(trigger);
if (!isCondition && (!device || !triggerKind)) {
error.message = 'There are missing fields';
return error;
}
if (!device || !triggerKind) { if (isCondition && !conditionKind) {
error.message = 'There are missing fields'; error.message = 'There are missing fields';
return error; return error;
} }
const deviceKind = device.kind; const deviceKind = device.kind;
const devicesWithPercentage = ['dimmableLight', 'curtains', 'knobDimmer']; const devicesWithPercentage = ['dimmableLight', 'curtains', 'knobDimmer'];
switch (triggerKind) { switch (isCondition ? conditionKind : triggerKind) {
case 'booleanTrigger': case 'booleanTrigger' || 'booleanCondition':
if (!trigger.device || trigger.on === null || trigger.on === undefined) return error; if (!trigger.device || trigger.on === null || trigger.on === undefined) return error;
break; break;
case 'rangeTrigger': case 'rangeTrigger' || 'rangeCondition':
if (!trigger.device || !trigger.operand || !trigger.value) { if (!trigger.device || !trigger.operand || !trigger.value) {
return error; return error;
} }
@ -298,7 +365,8 @@ class AutomationSaveModal extends Component {
) { ) {
error.message = "The value can't exceed 100, as it's a percentage"; error.message = "The value can't exceed 100, as it's a percentage";
return error; return error;
} if ( }
if (
deviceKind === 'sensor' deviceKind === 'sensor'
&& device.sensor === 'HUMIDITY' && device.sensor === 'HUMIDITY'
&& trigger.value > 100 && trigger.value > 100
@ -307,25 +375,36 @@ class AutomationSaveModal extends Component {
return error; return error;
} }
break; break;
case 'thermostatCondition':
if (!trigger.device || trigger.mode === null || trigger.mode === undefined || !trigger.operand) return error;
break;
default: default:
throw new Error('theoretically unreachable statement'); throw new Error('theoretically unreachable statement');
} }
const isNotDuplicate = !this.state.triggerList.some( let isNotDuplicate = null;
if (isCondition === true) {
isNotDuplicate = !this.state.conditionsList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand, (t) => t.device === trigger.device && t.operand === trigger.operand,
); );
} else {
isNotDuplicate = !this.state.triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand,
);
}
const type = isCondition ? 'condition' : 'trigger';
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
: 'You have already created a trigger for this device with the same conditions', : 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, {
@ -383,12 +462,14 @@ class AutomationSaveModal extends Component {
return this.props.scenes.filter((e) => e.name.includes(this.scenesFilter)); return this.props.scenes.filter((e) => e.name.includes(this.scenesFilter));
} }
_generateKey = (trigger) => { _generateKey = (trigger, isCondition = false) => {
switch (this.triggerKind(trigger)) { switch (isCondition ? this.conditionKind(trigger) : this.triggerKind(trigger)) {
case 'booleanTrigger': case 'booleanTrigger' || 'booleanCondition':
return `${trigger.device}${trigger.on}`; return `${trigger.device}${trigger.on}`;
case 'rangeTrigger': case 'rangeTrigger' || 'rangeCondition':
return `${trigger.device}${trigger.operand}${trigger.value}`; return `${trigger.device}${trigger.operand}${trigger.value}`;
case 'thermostatCondition':
return `${trigger.device}${trigger.operand}${trigger.mode}`;
default: default:
throw new Error('theoretically unreachable statement'); throw new Error('theoretically unreachable statement');
} }
@ -444,6 +525,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)
@ -454,6 +554,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);
@ -478,6 +579,39 @@ Create new automation
); );
} }
// CONDITIONS
addCondition() {
// Same method used to check triggers and conditions, not a mistake
const { result, message } = this._checkNewTrigger(this.state.newCondition, true);
if (result) {
this.setState(
update(this.state, {
conditionsList: { $push: [this.state.newCondition] },
}),
);
} else {
alert(message);
}
}
removeCondition(index) {
this.setState(
update(this.state, { conditionsList: { $splice: [[index, 1]] } }),
);
}
onInputChangeCondition = (val) => {
if (val.name === 'device') {
this.setNewCondition({ [val.name]: val.value });
} else {
this.setNewCondition({
...this.state.newCondition,
[val.name]: val.value,
});
}
}
render() { render() {
return ( return (
<Modal <Modal
@ -499,7 +633,6 @@ Create new automation
this.state.automationName this.state.automationName
)} )}
</Header> </Header>
<Button <Button
onClick={() => this.setEditName((prev) => !prev)} onClick={() => this.setEditName((prev) => !prev)}
style={{ display: 'inline' }} style={{ display: 'inline' }}
@ -578,6 +711,42 @@ Create new automation
</Grid.Row> </Grid.Row>
</Grid> </Grid>
</Segment> </Segment>
<Grid columns={1} stackable textAlign="center">
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Add Conditions</Header>
<List divided relaxed>
{this.state.conditionsList.length > 0
&& this.state.conditionsList.map((condition, i) => {
const deviceName = this.deviceList.filter(
(d) => d.id === condition.device,
)[0].name;
const key = this._generateKey(condition, true);
return (
<Trigger
key={key}
index={i}
deviceName={deviceName}
trigger={condition}
onRemove={this.removeCondition}
/>
);
})}
<CreateTrigger
devices={this.props.devices}
inputChange={this.onInputChangeCondition}
/>
</List>
<Button
onClick={this.addCondition}
circular
icon="add"
color="blue"
size="huge"
/>
</Grid.Column>
</Grid.Row>
</Grid>
<Grid> <Grid>
<Grid.Row> <Grid.Row>
<Grid.Column style={{ marginRight: '1rem' }}> <Grid.Column style={{ marginRight: '1rem' }}>

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.mode ? condition.mode : condition.range}`
: condition.on
? ' - on'
: ' - off'}
</Menu.Item>
</Menu>
);
})}
</List>
</Grid.Column>
</Grid.Row>
</Grid>
</> </>
); );
}; };

View file

@ -556,19 +556,31 @@ 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);
debugger;
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 +603,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 +613,50 @@ 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) {
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 = {

12141
smart-hut/yarn.lock Normal file

File diff suppressed because it is too large Load diff