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 { .list-index {
font-size: 1.5rem; 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 {connect} from "react-redux";
import { RemoteService } from "../../remote"; import {RemoteService} from "../../remote";
import "./Automations.css"; import "./Automations.css";
import { import {
Segment, Segment,
Grid, Grid,
@ -15,40 +16,64 @@ import {
Divider, Divider,
Checkbox, Checkbox,
Menu, Menu,
Label, Label
} from "semantic-ui-react"; } from "semantic-ui-react";
const options = [ const operands = [
{ key: "equal", text: "=", value: "equal" }, {key: "EQUAL", text: "=", value: "EQUAL"},
{ {
key: "greater-than-or-equal", key: "GREATER_EQUAL",
text: "\u2265", text: "\u2265",
value: "greater-than-or-equal", value: "GREATER_EQUAL",
}, },
{ {
key: "greater-than", key: "GREATER",
text: ">", text: ">",
value: "greater-than", value: "GREATER",
}, },
{ {
key: "less-than-or-equal", key: "LESS_EQUAL",
text: "\u2264", text: "\u2264",
value: "less-than-or-equal", value: "LESS_EQUAL",
}, },
{ {
key: "less-than", key: "LESS",
text: "<", text: "<",
value: "less-than", value: "LESS",
}, },
]; ];
const deviceStateOptions = [
{key: "off", text: "off", value: false},
{key: "on", text: "on", value: true},
];
const CreateTrigger = (props) => { const CreateTrigger = (props) => {
const devices = [ const [activeOperand, setActiveOperand] = useState(true);
{ key: "Light-1", text: "Light-1", value: "Light-1" }, const admitedDevices = ["sensor", "regularLight", "dimmableLight"]; // TODO Complete this list
{ key: "Light-2", text: "Light-2", value: "Light-2" }, const deviceList = props.devices
{ key: "SmartPlug-1", text: "SmartPlug-1", value: "SmartPlug-1" }, .map((device) => {
{ key: "SmartPlug-2", text: "SmartPlug-2", value: "SmartPlug-2" }, 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 ( return (
<List.Item> <List.Item>
@ -57,32 +82,52 @@ const CreateTrigger = (props) => {
<Form.Group> <Form.Group>
<Form.Field inline width={7}> <Form.Field inline width={7}>
<Dropdown <Dropdown
onChange={(e, val) => props.inputChange(val)} onChange={onChange}
name="device" name="device"
search search
selection selection
options={devices} options={deviceList}
placeholder="Device" placeholder="Device"
/> />
</Form.Field> </Form.Field>
{activeOperand ? (
<Form.Field inline width={2}> <React.Fragment>
<Dropdown <Form.Field inline width={2}>
onChange={(e, val) => props.inputChange(val)} <Dropdown
name="operand" onChange={(e, val) =>
compact props.inputChange(val)
selection }
options={options} name="operand"
/> compact
</Form.Field> selection
<Form.Field inline width={7}> options={operands}
<Input />
onChange={(e, val) => props.inputChange(val)} </Form.Field>
name="value" <Form.Field inline width={7}>
type="number" <Input
placeholder="Value" onChange={(e, val) =>
/> props.inputChange(val)
</Form.Field> }
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.Group>
</Form> </Form>
</List.Content> </List.Content>
@ -91,16 +136,31 @@ const CreateTrigger = (props) => {
}; };
const SceneItem = (props) => { const SceneItem = (props) => {
let position = props.order.indexOf(props.scene.id);
return ( return (
<List.Item> <List.Item>
<List.Header> <List.Header>
<Grid textAlign="center"> <Grid textAlign="center">
<Grid.Row> <Grid.Row>
<Grid.Column width={4}> <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>
<Grid.Column width={4}> <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.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>
@ -109,37 +169,59 @@ const SceneItem = (props) => {
); );
}; };
const Trigger = ({ trigger }) => { const Trigger = ({deviceName, trigger, onRemove, index}) => {
console.log(trigger); const {device, operand, value} = trigger;
const { device, operand, value } = trigger; let symbol;
const symbol = options.filter((opt) => opt.key === operand)[0].text; if (operand) {
symbol = operands.filter((opt) => opt.key === operand)[0].text;
}
return ( return (
<List.Item fluid> <List.Item className="trigger-item">
<Menu compact> <Menu compact>
<Menu.Item as="span">{device}</Menu.Item> <Menu.Item as="span">{deviceName}</Menu.Item>
<Menu.Item as="span">{symbol}</Menu.Item> {operand ? <Menu.Item as="span">{symbol}</Menu.Item> : ""}
<Menu.Item as="span">{value}</Menu.Item> <Menu.Item as="span">{value ? "on" : "off"}</Menu.Item>
</Menu> </Menu>
<Icon
as={"i"}
onClick={() => onRemove(device, index)}
className="remove-icon"
name="remove"
/>
</List.Item> </List.Item>
); );
}; };
const Automation = (props) => { const CreateAutomation = (props) => {
const [triggerList, setTrigger] = useState([]); const [triggerList, setTrigger] = useState([]);
const [newTrigger, setNewTrigger] = useState({ const [order, setOrder] = useState([]);
device: null, const [stateScenes, setScenes] = useState(props.scenes);
operand: null, const [automationName, setautomationName] = useState("New Automation");
value: null, const [editName, setEditName] = useState(false);
}); const [newTrigger, setNewTrigger] = useState({});
const scenes = ["scene-1", "scene-2", "scene-3"];
const automationName = "Automation Name";
const checkNewTrigger = (trigger) => { useEffect(() => {
if (!trigger.device || !trigger.operand || !trigger.value) { setScenes(props.scenes);
return { }, [props]);
result: false,
message: "There are missing fields", 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( const result = !triggerList.some(
(t) => t.device === trigger.device && t.operand === trigger.operand (t) => t.device === trigger.device && t.operand === trigger.operand
@ -152,43 +234,135 @@ const Automation = (props) => {
}; };
}; };
const addTrigger = () => { const addTrigger = () => {
const { result, message } = checkNewTrigger(newTrigger); const {result, message} = _checkNewTrigger(newTrigger);
const auxTrigger = newTrigger;
if (result) { 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 { } else {
alert(message); alert(message);
} }
}; };
const onInputChange = (val) => { const removeTrigger = (trigger) => {
setNewTrigger({ ...newTrigger, [val.name]: val.value }); // 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 ( return (
<React.Fragment> <React.Fragment>
<Header style={{ display: "inline", marginRight: "1rem" }}> <Header style={{display: "inline", marginRight: "1rem"}}>
{automationName} {editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={onChangeName}
/>
) : (
automationName
)}
</Header> </Header>
<Button <Button
style={{ display: "inline" }} onClick={() => setEditName((prev) => !prev)}
style={{display: "inline"}}
circular circular
size="small" size="small"
icon="edit" icon={editName ? "save" : "edit"}
/> />
<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> <Divider vertical/>
<Grid.Row verticalAlign="middle"> <Grid.Row verticalAlign="middle">
<Grid.Column> <Grid.Column>
<Header>Create Triggers</Header> <Header>Create Triggers</Header>
<List divided relaxed> <List divided relaxed>
{triggerList.length > 0 && {triggerList.length > 0 &&
triggerList.map((trigger) => ( triggerList.map((trigger, i) => {
<Trigger trigger={trigger} /> const deviceName = props.devices.filter(
))} (d) => d.id === trigger.device
<CreateTrigger inputChange={onInputChange} /> )[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> </List>
<Button <Button
onClick={addTrigger} onClick={addTrigger}
@ -199,26 +373,31 @@ const Automation = (props) => {
/> />
</Grid.Column> </Grid.Column>
<Grid.Column> <Grid.Column>
{scenes.length > 0 ? ( {props.scenes.length > 0 ? (
<React.Fragment> <React.Fragment>
<Header>Activate Scenes</Header> <Header>Activate Scenes</Header>
<Input <Input
//loading
icon="search" icon="search"
placeholder="Search..." placeholder="Search..."
fluid fluid
onChange={searchScenes}
/> />
<Divider horizontal /> <Divider horizontal/>
<List divided relaxed> <List divided relaxed>
{scenes.map((scene) => ( {stateScenes.map((scene) => (
<SceneItem sceneName={scene} /> <SceneItem
key={scene.id}
scene={scene}
order={order}
orderScenes={orderScenes}
/>
))} ))}
</List> </List>
</React.Fragment> </React.Fragment>
) : ( ) : (
<React.Fragment> <React.Fragment>
<Header icon> <Header icon>
<Icon name="world" /> <Icon name="world"/>
</Header> </Header>
<Button primary>Create Scene</Button> <Button primary>Create Scene</Button>
</React.Fragment> </React.Fragment>
@ -229,11 +408,11 @@ const Automation = (props) => {
</Segment> </Segment>
<Grid> <Grid>
<Grid.Row> <Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}> <Grid.Column style={{marginRight: "1rem"}}>
<Button color="green">SAVE</Button> <Button onClick={() => saveAutomation()} color="green">SAVE</Button>
</Grid.Column> </Grid.Column>
<Grid.Column> <Grid.Column>
<Button color="red">DELETE</Button> <Button color="red">CLEAN</Button>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </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 { class AutomationsPanel extends Component {
constructor(props) { constructor(props) {
super(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() { render() {
return ( return (
<List style={{ marginTop: "3rem" }}> <Grid>
<Automation /> <Grid.Row>
</List> <Grid.Column width={16}>
<List style={{marginTop: "3rem"}}>
<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, _) => ({ const mapStateToProps = (state, _) => ({
activeRoom: state.active.activeRoom, activeRoom: state.active.activeRoom,
activeTab: state.active.activeTab, 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( const AutomationsPanelContainer = connect(
mapStateToProps, mapStateToProps,

View file

@ -8,58 +8,58 @@ import { connect } from "react-redux";
import { RemoteService } from "../../remote"; import { RemoteService } from "../../remote";
class DevicePanel extends Component { class DevicePanel extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.getDevices(); this.getDevices();
}
getDevices() {
if (this.props.tab === "Devices") {
this.props
.fetchDevices()
.catch((err) => console.error(`error fetching devices:`, err));
} }
}
render() { getDevices() {
return ( if (this.props.tab === "Devices") {
<Grid doubling columns={2} divided="vertically"> this.props
{this.props.devices.map((e, i) => { .fetchDevices()
return ( .catch((err) => console.error(`error fetching devices:`, err));
<Grid.Column key={i}> }
<Device tab={this.props.tab} id={e.id} /> }
</Grid.Column>
); render() {
})} return (
{!this.props.isActiveRoomHome ? ( <Grid doubling columns={2} divided="vertically">
<Grid.Column> {this.props.devices.map((e, i) => {
<NewDevice /> return (
</Grid.Column> <Grid.Column key={i}>
) : null} <Device tab={this.props.tab} id={e.id} />
</Grid> </Grid.Column>
); );
} })}
{!this.props.isActiveRoomHome ? (
<Grid.Column>
<NewDevice />
</Grid.Column>
) : null}
</Grid>
);
}
} }
const mapStateToProps = (state, _) => ({ const mapStateToProps = (state, _) => ({
get devices() { get devices() {
if (state.active.activeRoom === -1) { if (state.active.activeRoom === -1) {
return Object.values(state.devices); return Object.values(state.devices);
} else { } else {
const deviceArray = [ const deviceArray = [
...state.rooms[state.active.activeRoom].devices, ...state.rooms[state.active.activeRoom].devices,
].sort(); ].sort();
return deviceArray.map((id) => state.devices[id]); return deviceArray.map((id) => state.devices[id]);
} }
}, },
get isActiveRoomHome() { get isActiveRoomHome() {
return state.active.activeRoom === -1; return state.active.activeRoom === -1;
}, },
activeRoom: state.active.activeRoom, activeRoom: state.active.activeRoom,
}); });
const DevicePanelContainer = connect( const DevicePanelContainer = connect(
mapStateToProps, mapStateToProps,
RemoteService RemoteService
)(DevicePanel); )(DevicePanel);
export default DevicePanelContainer; export default DevicePanelContainer;

File diff suppressed because it is too large Load diff

View file

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

View file

@ -25,6 +25,24 @@ const actions = {
type: "DEVICE_SAVE", type: "DEVICE_SAVE",
device, 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) => ({ stateSave: (sceneState) => ({
type: "STATE_SAVE", type: "STATE_SAVE",
sceneState, sceneState,