frontend/smart-hut/src/components/dashboard/AutomationsPanel.js

598 lines
21 KiB
JavaScript
Raw Normal View History

import React, {Component, useState, useEffect} from "react";
import {connect} from "react-redux";
import {RemoteService} from "../../remote";
import "./Automations.css";
import {
Segment,
Grid,
Icon,
Header,
Input,
Button,
List,
Dropdown,
Form,
Divider,
Checkbox,
Menu,
2020-04-28 09:39:38 +00:00
Label,
} from "semantic-ui-react";
const operands = [
{key: "EQUAL", text: "=", value: "EQUAL"},
{
key: "GREATER_EQUAL",
text: "\u2265",
value: "GREATER_EQUAL",
},
{
key: "GREATER",
text: ">",
value: "GREATER",
},
{
key: "LESS_EQUAL",
text: "\u2264",
value: "LESS_EQUAL",
},
{
key: "LESS",
text: "<",
value: "LESS",
},
];
const deviceStateOptions = [
{key: "off", text: "off", value: false},
{key: "on", text: "on", value: true},
];
const CreateTrigger = (props) => {
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>
<List.Content>
<Form>
<Form.Group>
<Form.Field inline width={7}>
<Dropdown
onChange={onChange}
name="device"
search
selection
options={deviceList}
placeholder="Device"
/>
</Form.Field>
{activeOperand ? (
<React.Fragment>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) =>
props.inputChange(val)
}
name="operand"
compact
selection
options={operands}
/>
</Form.Field>
<Form.Field inline width={7}>
<Input
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>
</List.Item>
);
};
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
onChange={(e, val) =>
props.orderScenes(
props.scene.id,
val.checked
)
}
checked={position + 1 > 0}
/>
</Grid.Column>
2020-04-28 09:39:38 +00:00
<Grid.Column width={8}>
<h3>{props.scene.name}</h3>
</Grid.Column>
<Grid.Column width={4}>
<h3>
{position !== -1 ? "# " + (position + 1) : ""}
</h3>
</Grid.Column>
</Grid.Row>
</Grid>
</List.Header>
</List.Item>
);
};
const Trigger = ({deviceName, trigger, onRemove, index}) => {
const {device, operand, value} = trigger;
let symbol;
if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text;
}
return (
<List.Item className="trigger-item">
<Menu compact>
<Menu.Item as="span">{deviceName}</Menu.Item>
{operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
2020-04-28 09:39:38 +00:00
<Menu.Item as="span">
{operand ? value : value ? "on" : "off"}
</Menu.Item>
</Menu>
<Icon
as={"i"}
2020-04-28 09:39:38 +00:00
onClick={() => onRemove(index)}
className="remove-icon"
name="remove"
/>
</List.Item>
);
};
2020-04-28 09:39:38 +00:00
export const CreateAutomation = (props) => {
const [triggerList, setTrigger] = useState([]);
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({});
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
);
return {
result: result,
message: result
? ""
: "You have already created a trigger for this device with the same conditions",
};
};
const addTrigger = () => {
const {result, message} = _checkNewTrigger(newTrigger);
const auxTrigger = newTrigger;
if (result) {
if (
props.devices
.filter((d) => d.id === newTrigger.device)[0]
.hasOwnProperty("on")
) {
delete auxTrigger.operand;
}
setTrigger((prevList) => [...prevList, auxTrigger]);
} else {
alert(message);
}
};
2020-04-28 09:39:38 +00:00
const removeTrigger = (index) => {
setTrigger((prevList) => prevList.filter((t, i) => i !== index));
};
// 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) => {
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;
2020-04-28 09:39:38 +00:00
};
const saveAutomation = () => {
//if(checkBeforeSave()){
const automation = {
2020-04-28 09:39:38 +00:00
name: automationName,
};
props.save({automation, triggerList, order});
//}
2020-04-28 09:39:38 +00:00
};
return (
<React.Fragment>
<Header style={{display: "inline", marginRight: "1rem"}}>
{editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={onChangeName}
/>
) : (
automationName
)}
</Header>
<Button
onClick={() => setEditName((prev) => !prev)}
style={{display: "inline"}}
circular
size="small"
icon={editName ? "save" : "edit"}
/>
<Segment placeholder className="segment-automations">
<Grid columns={2} stackable textAlign="center">
<Divider vertical/>
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Create Triggers</Header>
<List divided relaxed>
{triggerList.length > 0 &&
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}
circular
icon="add"
color="blue"
size="huge"
/>
</Grid.Column>
<Grid.Column>
{props.scenes.length > 0 ? (
<React.Fragment>
<Header>Activate Scenes</Header>
<Input
icon="search"
placeholder="Search..."
fluid
onChange={searchScenes}
/>
<Divider horizontal/>
<List divided relaxed>
{stateScenes.map((scene) => (
<SceneItem
key={scene.id}
scene={scene}
order={order}
orderScenes={orderScenes}
/>
))}
</List>
</React.Fragment>
) : (
<React.Fragment>
<Header icon>
<Icon name="world"/>
</Header>
<Button primary>Create Scene</Button>
</React.Fragment>
)}
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
<Grid>
<Grid.Row>
<Grid.Column style={{marginRight: "1rem"}}>
2020-04-28 09:39:38 +00:00
<Button onClick={() => saveAutomation()} color="green">
SAVE
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</React.Fragment>
);
};
2020-04-14 12:58:03 +00:00
2020-04-28 09:39:38 +00:00
const Automation = ({automation, devices, scenes, removeAutomation}) => {
const {triggers} = automation;
const scenePriorities = automation.scenes;
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"}
/>
2020-04-28 09:39:38 +00:00
<Button
style={{display: "inline"}}
circular
onClick={() => removeAutomation(automation.id)}
color="red"
size="small"
icon={"trash alternate outline"}
/>
<Segment placeholder>
<Grid columns={2} stackable textAlign="center">
<Divider vertical></Divider>
<Grid.Row verticalAlign="middle">
<Grid.Column>
<Header>Triggers</Header>
<List divided relaxed>
2020-04-28 09:39:38 +00:00
{triggers !== undefined &&
triggers.map((trigger) => {
const device = devices.filter(
(d) => d.id === trigger.deviceId
)[0];
return (
<Menu key={trigger.id} compact>
2020-04-28 09:39:38 +00:00
<Menu.Item as="span">
{device.name}{" "}
{trigger.operator
? getOperator(
trigger.operator
) +
" " +
trigger.range
: trigger.value
? " - on"
: " - off"}
</Menu.Item>
</Menu>
2020-04-28 09:39:38 +00:00
);
})}
</List>
</Grid.Column>
<Grid.Column>
<Header>Scenes</Header>
2020-04-28 09:39:38 +00:00
<List divided relaxed>
{scenePriorities !== undefined &&
scenePriorities.map((sp) => {
const sceneData = scenes.filter(
(s) => s.id === sp.sceneId
)[0];
return (
<Menu key={sceneData.id} compact>
<Menu.Item as="span">
{sceneData.name}
</Menu.Item>
</Menu>
);
})}
</List>
</Grid.Column>
</Grid.Row>
</Grid>
</Segment>
</React.Fragment>
);
};
2020-04-14 12:58:03 +00:00
class AutomationsPanel extends Component {
constructor(props) {
super(props);
2020-04-28 09:39:38 +00:00
this.state = {openModal: false}
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));
}
2020-04-14 12:58:03 +00:00
2020-04-28 09:39:38 +00:00
removeAutomation = (id) => {
this.props
.deleteAutomation(id)
.catch((err) => console.error(`error removing automation ${id}:`, err));
}
render() {
return (
2020-04-28 09:39:38 +00:00
<Grid style={{marginTop: "3rem"}}>
<Grid.Row>
2020-04-28 09:39:38 +00:00
<Grid.Column textAlign="center" width={16}>
{!this.state.openModal ?
(
<List>
<CreateAutomation
save={this.props.saveAutomation}
scenes={this.props.scenes}
devices={this.props.devices}
/>
</List>
) :
(
<Button color="green">CREATE AUTOMATION</Button>
)}
</Grid.Column>
</Grid.Row>
<Grid.Row>
2020-04-28 09:39:38 +00:00
{this.props.automations.map((automation, i) => {
return (
2020-04-28 09:39:38 +00:00
<Grid.Column
key={i}
width={8}
style={{margin: "2rem 0"}}
>
<Automation
removeAutomation={this.removeAutomation}
scenes={this.props.scenes}
devices={this.props.devices}
automation={automation}
/>
</Grid.Column>
);
})}
</Grid.Row>
</Grid>
);
}
2020-04-14 12:58:03 +00:00
}
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() {
return Object.values(state.automations);
2020-04-28 09:39:38 +00:00
},
2020-04-14 12:58:03 +00:00
});
const AutomationsPanelContainer = connect(
mapStateToProps,
RemoteService
2020-04-14 12:58:03 +00:00
)(AutomationsPanel);
export default AutomationsPanelContainer;