Automations basic stuff is working: create, get

This commit is contained in:
Christian Capeáns Pérez 2020-04-27 17:00:46 +02:00
parent 48c0988063
commit cc23824a37
6 changed files with 1221 additions and 764 deletions

View file

@ -5,3 +5,14 @@
.list-index {
font-size: 1.5rem;
}
.remove-icon {
display: inline !important;
margin-left: 1rem !important;
}
.trigger-item {
display: flex !important;
justify-content: center !important;
align-items: center !important;
}

View file

@ -1,7 +1,8 @@
import React, { Component, useState } from "react";
import React, {Component, useState, useEffect} from "react";
import {connect} from "react-redux";
import {RemoteService} from "../../remote";
import "./Automations.css";
import {
Segment,
Grid,
@ -15,40 +16,64 @@ import {
Divider,
Checkbox,
Menu,
Label,
Label
} from "semantic-ui-react";
const options = [
{ key: "equal", text: "=", value: "equal" },
const operands = [
{key: "EQUAL", text: "=", value: "EQUAL"},
{
key: "greater-than-or-equal",
key: "GREATER_EQUAL",
text: "\u2265",
value: "greater-than-or-equal",
value: "GREATER_EQUAL",
},
{
key: "greater-than",
key: "GREATER",
text: ">",
value: "greater-than",
value: "GREATER",
},
{
key: "less-than-or-equal",
key: "LESS_EQUAL",
text: "\u2264",
value: "less-than-or-equal",
value: "LESS_EQUAL",
},
{
key: "less-than",
key: "LESS",
text: "<",
value: "less-than",
value: "LESS",
},
];
const deviceStateOptions = [
{key: "off", text: "off", value: false},
{key: "on", text: "on", value: true},
];
const CreateTrigger = (props) => {
const devices = [
{ key: "Light-1", text: "Light-1", value: "Light-1" },
{ key: "Light-2", text: "Light-2", value: "Light-2" },
{ key: "SmartPlug-1", text: "SmartPlug-1", value: "SmartPlug-1" },
{ key: "SmartPlug-2", text: "SmartPlug-2", value: "SmartPlug-2" },
];
const [activeOperand, setActiveOperand] = useState(true);
const admitedDevices = ["sensor", "regularLight", "dimmableLight"]; // TODO Complete this list
const deviceList = props.devices
.map((device) => {
return {
key: device.id,
text: device.name,
value: device.id,
kind: device.kind,
};
})
.filter((e) => admitedDevices.includes(e.kind));
const onChange = (e, val) => {
props.inputChange(val);
if (
props.devices
.filter((d) => d.id === val.value)[0]
.hasOwnProperty("on")
) {
setActiveOperand(false);
} else {
setActiveOperand(true);
}
};
return (
<List.Item>
@ -57,32 +82,52 @@ const CreateTrigger = (props) => {
<Form.Group>
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
onChange={onChange}
name="device"
search
selection
options={devices}
options={deviceList}
placeholder="Device"
/>
</Form.Field>
{activeOperand ? (
<React.Fragment>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
onChange={(e, val) =>
props.inputChange(val)
}
name="operand"
compact
selection
options={options}
options={operands}
/>
</Form.Field>
<Form.Field inline width={7}>
<Input
onChange={(e, val) => props.inputChange(val)}
onChange={(e, val) =>
props.inputChange(val)
}
name="value"
type="number"
placeholder="Value"
/>
</Form.Field>
</React.Fragment>
) : (
<Form.Field inline width={7}>
<Dropdown
onChange={(e, val) =>
props.inputChange(val)
}
placeholder="State"
name="value"
compact
selection
options={deviceStateOptions}
/>
</Form.Field>
)}
</Form.Group>
</Form>
</List.Content>
@ -91,16 +136,31 @@ const CreateTrigger = (props) => {
};
const SceneItem = (props) => {
let position = props.order.indexOf(props.scene.id);
return (
<List.Item>
<List.Header>
<Grid textAlign="center">
<Grid.Row>
<Grid.Column width={4}>
<Checkbox toggle />
<Checkbox
toggle
onChange={(e, val) =>
props.orderScenes(
props.scene.id,
val.checked
)
}
checked={position + 1 > 0}
/>
</Grid.Column>
<Grid.Column width={4}>
<h3>{props.sceneName}</h3>
<h3>{props.scene.name}</h3>
</Grid.Column>
<Grid.Column width={4}>
<h3>
{position !== -1 ? "# " + (position + 1) : ""}
</h3>
</Grid.Column>
</Grid.Row>
</Grid>
@ -109,38 +169,60 @@ const SceneItem = (props) => {
);
};
const Trigger = ({ trigger }) => {
console.log(trigger);
const Trigger = ({deviceName, trigger, onRemove, index}) => {
const {device, operand, value} = trigger;
const symbol = options.filter((opt) => opt.key === operand)[0].text;
let symbol;
if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text;
}
return (
<List.Item fluid>
<List.Item className="trigger-item">
<Menu compact>
<Menu.Item as="span">{device}</Menu.Item>
<Menu.Item as="span">{symbol}</Menu.Item>
<Menu.Item as="span">{value}</Menu.Item>
<Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
<Menu.Item as="span">{value ? "on" : "off"}</Menu.Item>
</Menu>
<Icon
as={"i"}
onClick={() => onRemove(device, index)}
className="remove-icon"
name="remove"
/>
</List.Item>
);
};
const Automation = (props) => {
const CreateAutomation = (props) => {
const [triggerList, setTrigger] = useState([]);
const [newTrigger, setNewTrigger] = useState({
device: null,
operand: null,
value: null,
});
const scenes = ["scene-1", "scene-2", "scene-3"];
const automationName = "Automation Name";
const [order, setOrder] = useState([]);
const [stateScenes, setScenes] = useState(props.scenes);
const [automationName, setautomationName] = useState("New Automation");
const [editName, setEditName] = useState(false);
const [newTrigger, setNewTrigger] = useState({});
const checkNewTrigger = (trigger) => {
useEffect(() => {
setScenes(props.scenes);
}, [props]);
const _checkNewTrigger = (trigger) => {
const auxDevice = props.devices.filter(
(d) => d.id === trigger.device
)[0];
if (auxDevice && auxDevice.hasOwnProperty("on")) {
if (!trigger.device || !trigger.value == null) {
return {
result: false,
message: "There are missing fields!",
};
}
} else {
if (!trigger.device || !trigger.operand || !trigger.value) {
return {
result: false,
message: "There are missing fields",
};
}
}
const result = !triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand
);
@ -152,43 +234,135 @@ const Automation = (props) => {
};
};
const addTrigger = () => {
const { result, message } = checkNewTrigger(newTrigger);
const {result, message} = _checkNewTrigger(newTrigger);
const auxTrigger = newTrigger;
if (result) {
setTrigger((prevList) => [...prevList, newTrigger]);
if (
props.devices
.filter((d) => d.id === newTrigger.device)[0]
.hasOwnProperty("on")
) {
delete auxTrigger.operand;
}
setTrigger((prevList) => [...prevList, auxTrigger]);
} else {
alert(message);
}
};
const removeTrigger = (trigger) => {
// TODO When this is connected to the backend each trigger will have an id which can be used to remove it
};
// This gets triggered when the devices dropdown changes the value.
const onInputChange = (val) => {
setNewTrigger({...newTrigger, [val.name]: val.value});
};
const onChangeName = (e, val) => setautomationName(val.value);
const orderScenes = (id, checked) => {
if (checked) {
setOrder((prevList) => [...prevList, id]);
} else {
setOrder((prevList) => prevList.filter((e) => e !== id));
}
};
const searchScenes = (e, {value}) => {
if (value.length > 0) {
setScenes((prevScenes) => {
return stateScenes.filter((e) => {
console.log(e.name.includes(value));
return e.name.includes(value);
});
});
} else {
setScenes(props.scenes);
}
};
const _generateKey = (trigger) => {
if (trigger.hasOwnProperty("operand")) {
return trigger.device + trigger.operand + trigger.value;
}
return trigger.device + trigger.value;
};
const checkBeforeSave = () => {
if (automationName.length <= 0) {
alert("Give a name to the automation");
return false;
}
if (triggerList.length <= 0) {
alert("You have to create a trigger");
return false;
}
if (order.length <= 0) {
alert("You need at least one active scene");
return false;
}
return true;
}
const saveAutomation = () => {
console.log("trigger list: ", triggerList);
//if(checkBeforeSave()){
const automation = {
name: automationName
}
props.save({automation, triggerList, order});
//}
}
return (
<React.Fragment>
<Header style={{display: "inline", marginRight: "1rem"}}>
{automationName}
{editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={onChangeName}
/>
) : (
automationName
)}
</Header>
<Button
onClick={() => setEditName((prev) => !prev)}
style={{display: "inline"}}
circular
size="small"
icon="edit"
icon={editName ? "save" : "edit"}
/>
<Segment placeholder className="segment-automations">
<Grid columns={2} stackable textAlign="center">
<Divider vertical></Divider>
<Divider vertical/>
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Create Triggers</Header>
<List divided relaxed>
{triggerList.length > 0 &&
triggerList.map((trigger) => (
<Trigger trigger={trigger} />
))}
<CreateTrigger inputChange={onInputChange} />
triggerList.map((trigger, i) => {
const deviceName = props.devices.filter(
(d) => d.id === trigger.device
)[0].name;
const key = _generateKey(trigger);
return (
<Trigger
key={key}
index={i}
deviceName={deviceName}
trigger={trigger}
onRemove={removeTrigger}
/>
);
})}
<CreateTrigger
devices={props.devices}
inputChange={onInputChange}
/>
</List>
<Button
onClick={addTrigger}
@ -199,19 +373,24 @@ const Automation = (props) => {
/>
</Grid.Column>
<Grid.Column>
{scenes.length > 0 ? (
{props.scenes.length > 0 ? (
<React.Fragment>
<Header>Activate Scenes</Header>
<Input
//loading
icon="search"
placeholder="Search..."
fluid
onChange={searchScenes}
/>
<Divider horizontal/>
<List divided relaxed>
{scenes.map((scene) => (
<SceneItem sceneName={scene} />
{stateScenes.map((scene) => (
<SceneItem
key={scene.id}
scene={scene}
order={order}
orderScenes={orderScenes}
/>
))}
</List>
</React.Fragment>
@ -230,10 +409,10 @@ const Automation = (props) => {
<Grid>
<Grid.Row>
<Grid.Column style={{marginRight: "1rem"}}>
<Button color="green">SAVE</Button>
<Button onClick={() => saveAutomation()} color="green">SAVE</Button>
</Grid.Column>
<Grid.Column>
<Button color="red">DELETE</Button>
<Button color="red">CLEAN</Button>
</Grid.Column>
</Grid.Row>
</Grid>
@ -241,17 +420,99 @@ const Automation = (props) => {
);
};
const Automation = ({automation, devices}) => {
const {triggers, scenes} = automation;
const getOperator = (operand) => operands.filter(o => o.key == operand)[0].text;
return (
<React.Fragment>
<Header style={{display: "inline", marginRight: "1rem"}}>
{automation.name}
</Header>
<Button
style={{display: "inline"}}
circular
size="small"
icon={"edit"}
/>
<Segment placeholder>
<Grid columns={2} stackable textAlign="center">
<Divider vertical></Divider>
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Triggers</Header>
<List divided relaxed>
{triggers !== undefined && triggers.map(trigger => {
const device = devices.filter(d => d.id === trigger.deviceId)[0];
return (
<Menu key={trigger.id} compact>
<Menu.Item as='span'>
{device.name} {trigger.operator ? getOperator(trigger.operator) + " " + trigger.range : (trigger.value ? " - on" : " - off")}
</Menu.Item>
</Menu>
)
})}
</List>
</Grid.Column>
<Grid.Column>
<Header>Scenes</Header>
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
</React.Fragment>
);
};
class AutomationsPanel extends Component {
constructor(props) {
super(props);
this.state = {};
this.getDevices();
this.getScenes();
this.getAutomations();
}
getScenes() {
this.props.fetchAllScenes().catch(console.error);
}
getDevices() {
this.props
.fetchDevices()
.catch((err) => console.error(`error fetching devices:`, err));
}
getAutomations() {
this.props
.fetchAutomations()
.catch((err) => console.error(`error fetching automations:`, err));
}
render() {
return (
<Grid>
<Grid.Row>
<Grid.Column width={16}>
<List style={{marginTop: "3rem"}}>
<Automation />
<CreateAutomation
save={this.props.saveAutomation}
scenes={this.props.scenes}
devices={this.props.devices}
/>
</List>
</Grid.Column>
</Grid.Row>
<Grid.Row>
{this.props.automations.map((automation) => {
return (
<Grid.Column key={automation.id} width={8} style={{margin: "2rem 0"}}>
<Automation devices={this.props.devices} automation={automation}/>
</Grid.Column>
);
})}
</Grid.Row>
</Grid>
);
}
}
@ -259,6 +520,16 @@ class AutomationsPanel extends Component {
const mapStateToProps = (state, _) => ({
activeRoom: state.active.activeRoom,
activeTab: state.active.activeTab,
get scenes() {
return Object.values(state.scenes);
},
get devices() {
return Object.values(state.devices);
},
get automations() {
console.log(Object.values(state.automations));
return Object.values(state.automations);
}
});
const AutomationsPanelContainer = connect(
mapStateToProps,

View file

@ -98,7 +98,10 @@ const Endpoint = {
})
.then((res) => {
localStorage.setItem("token", res.data.jwttoken);
localStorage.setItem("exp", new Date().getTime() + 5 * 60 * 60 * 1000);
localStorage.setItem(
"exp",
new Date().getTime() + 5 * 60 * 60 * 1000
);
return res.data.jwttoken;
});
},
@ -291,7 +294,7 @@ export const RemoteService = {
/**
* Fetches all devices in a particular room, or fetches all devices.
* This also updates the devices attribute on values in the map rooms.
* @param {Number|null} roomId the room to which fetch devices
* @param {Number|null} roomId the rsoom to which fetch devices
* from, null to fetch from all rooms
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
@ -299,7 +302,10 @@ export const RemoteService = {
fetchDevices: (roomId = null) => {
return (dispatch) => {
return Endpoint.get(roomId ? `/room/${roomId}/device` : "/device")
.then((res) => void dispatch(actions.devicesUpdate(roomId, res.data)))
.then(
(res) =>
void dispatch(actions.devicesUpdate(roomId, res.data))
)
.catch((err) => {
console.error(`Fetch devices roomId=${roomId} error`, err);
throw new RemoteError(["Network error"]);
@ -307,6 +313,57 @@ export const RemoteService = {
};
},
/**
* Fetches all the automations
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
fetchAutomations: () => {
return (dispatch) => {
return Endpoint.get("/automation/")
.then(
(res) => {
const length = res.data.length;
const automations = [];
res.data.forEach((a, index) => {
const {id, name} = a;
const automation = {
name,
id,
triggers: [],
scenes: []
}
return Endpoint.get(`/booleanTrigger/${id}`)
.then(res => {
automation.triggers.push(...res.data);
return Endpoint.get(`/rangeTrigger/${id}`)
.then(res => {
automation.triggers.push(...res.data);
return Endpoint.get(`/scenePriority/${id}`)
.then(res => {
automation.scenes.push(...res.data);
automations.push(automation);
if ((index + 1) === length) {
return void dispatch(actions.automationsUpdate(automations));
}
console.log("automation after trigger: ", automation);
})
})
});
});
}
)
.catch((err) => {
console.error(`Fetch automations error`, err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Fetches all devices in a particular scene, or fetches all devices.
* This also updates the devices attribute on values in the map scenes.
@ -318,9 +375,15 @@ export const RemoteService = {
fetchStates: (sceneId) => {
return (dispatch) => {
return Endpoint.get(`/scene/${sceneId}/states`)
.then((res) => void dispatch(actions.statesUpdate(sceneId, res.data)))
.then(
(res) =>
void dispatch(actions.statesUpdate(sceneId, res.data))
)
.catch((err) => {
console.error(`Fetch devices sceneId=${sceneId} error`, err);
console.error(
`Fetch devices sceneId=${sceneId} error`,
err
);
throw new RemoteError(["Network error"]);
});
};
@ -405,6 +468,70 @@ export const RemoteService = {
};
},
/**
* Creates/Updates an automation with the given data. If
* data.id is truthy, then a update call is performed,
* otherwise a create call is performed.
* @param {Automation} data the device to update.
* @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects
* with user-fiendly errors as a RemoteError
*/
saveAutomation: (data) => {
const {automation, triggerList, order} = data;
automation.triggers = [];
automation.scenes = [];
return (dispatch) => {
let urlAutomation = "/automation";
let urlBooleanTrigger = "/booleanTrigger";
let urlRangeTrigger = "/rangeTrigger";
let urlScenePriority = "/scenePriority";
let rangeTriggerList = triggerList.filter(trigger => trigger.hasOwnProperty("operand"));
let booleanTriggerList = triggerList.filter(trigger => !trigger.hasOwnProperty("operand"));
return Endpoint["post"](urlAutomation, {}, automation)
.then(async automationRes => {
const {id} = automationRes.data;
// Introduce the range triggers in the automation
for (let t of rangeTriggerList) {
const trigger = {
automationId: id,
deviceId: t.device,
operator: t.operand,
range: t.value
};
let resRange = await Endpoint.post(urlRangeTrigger, {}, trigger)
automation.triggers.push(resRange.data);
}
for (let t of booleanTriggerList) {
const trigger = {
automationId: id,
deviceId: t.device,
on: t.value
};
let resBoolean = await Endpoint.post(urlBooleanTrigger, {}, trigger)
automation.triggers.push(resBoolean.data);
console.log("TRIGGERS: ", automation);
}
for (let [priority, sceneId] of order.entries()) {
const scenePriority = {
automationId: id,
priority,
sceneId,
}
let resScenes = await Endpoint["post"](urlScenePriority, {}, scenePriority)
automation.scenes.push(resScenes.data);
}
console.log("This is an automtion: ", automation);
dispatch(actions.automationSave(automation));
});
}
},
/**
* Creates/Updates a state with the given data. If
* data.id is truthy, then a update call is performed,
@ -420,7 +547,12 @@ export const RemoteService = {
saveState: (data) => {
return (dispatch) => {
let url =
"/" + data.kind + "/" + data.id + "/state?sceneId=" + data.sceneId;
"/" +
data.kind +
"/" +
data.id +
"/state?sceneId=" +
data.sceneId;
return Endpoint["post"](url, {}, data)
.then((res) => {
@ -477,7 +609,10 @@ export const RemoteService = {
const inputDevice = await Endpoint.get(getUrl);
delete inputDevice.outputs;
dispatch(
actions.deviceOperationUpdate([...res.data, inputDevice.data])
actions.deviceOperationUpdate([
...res.data,
inputDevice.data,
])
);
})
.catch((err) => {
@ -558,13 +693,16 @@ export const RemoteService = {
smartPlugReset(smartPlugId) {
return (dispatch) => {
return Endpoint.delete(`/smartPlug/${smartPlugId}/meter`)
.then((res) => dispatch(actions.deviceOperationUpdate([res.data])))
.then((res) =>
dispatch(actions.deviceOperationUpdate([res.data]))
)
.catch((err) => {
console.warn(`Smartplug reset error`, err);
throw new RemoteError(["Network error"]);
});
};
},
}
,
/**
* Deletes a room
@ -616,9 +754,11 @@ export const RemoteService = {
});
};
},
};
}
;
for (const key in RemoteService) {
for (const key in RemoteService
) {
RemoteService[key] = RemoteService[key].bind(RemoteService);
}

View file

@ -253,6 +253,14 @@ function reducer(previousState, action) {
newState = update(newState, change);
break;
case "AUTOMATION_UPDATE":
newState = previousState;
change = {
automations : {$set: action.automations}
};
newState = update(previousState, change);
break;
case "ROOM_SAVE":
newState = previousState;
createOrUpdateRoom(action.room);
@ -285,6 +293,15 @@ function reducer(previousState, action) {
}
newState = update(previousState, change);
break;
case "AUTOMATION_SAVE":
change = {
automations : {[action.automation.id] : {$set : action.automation}}
};
newState = update(previousState, change);
break;
case "STATE_SAVE":
console.log("Store", action.sceneState);
change = {
@ -418,7 +435,7 @@ function reducer(previousState, action) {
break;
case "REDUX_WEBSOCKET::MESSAGE":
const devices = JSON.parse(action.payload.message);
console.log(devices);
newState = reducer(previousState, {
type: "DEVICES_UPDATE",
partial: true,

View file

@ -25,6 +25,24 @@ const actions = {
type: "DEVICE_SAVE",
device,
}),
triggerSave: (automation) => ({
type: "TRIGGER_SAVE",
automation,
}),
scenePrioritySave: (automation) => ({
type: "SCENE_PRIORITY_SAVE",
automation,
}),
automationSave: (automation) => ({
type: "AUTOMATION_SAVE",
automation,
}),
automationsUpdate: (automations) => ({
type: "AUTOMATION_UPDATE",
automations,
}),
stateSave: (sceneState) => ({
type: "STATE_SAVE",
sceneState,