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 { connect } from "react-redux";
import { RemoteService } from "../../remote";
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>
<Form.Field inline width={2}>
<Dropdown
onChange={(e, val) => props.inputChange(val)}
name="operand"
compact
selection
options={options}
/>
</Form.Field>
<Form.Field inline width={7}>
<Input
onChange={(e, val) => props.inputChange(val)}
name="value"
type="number"
placeholder="Value"
/>
</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>
@ -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,37 +169,59 @@ const SceneItem = (props) => {
);
};
const Trigger = ({ trigger }) => {
console.log(trigger);
const { device, operand, value } = trigger;
const symbol = options.filter((opt) => opt.key === operand)[0].text;
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 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) => {
if (!trigger.device || !trigger.operand || !trigger.value) {
return {
result: false,
message: "There are missing fields",
};
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 onInputChange = (val) => {
setNewTrigger({ ...newTrigger, [val.name]: val.value });
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}
<Header style={{display: "inline", marginRight: "1rem"}}>
{editName ? (
<Input
focus
transparent
placeholder="New automation name..."
onChange={onChangeName}
/>
) : (
automationName
)}
</Header>
<Button
style={{ display: "inline" }}
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,26 +373,31 @@ 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 />
<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>
) : (
<React.Fragment>
<Header icon>
<Icon name="world" />
<Icon name="world"/>
</Header>
<Button primary>Create Scene</Button>
</React.Fragment>
@ -229,11 +408,11 @@ const Automation = (props) => {
</Segment>
<Grid>
<Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}>
<Button color="green">SAVE</Button>
<Grid.Column style={{marginRight: "1rem"}}>
<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 (
<List style={{ marginTop: "3rem" }}>
<Automation />
</List>
<Grid>
<Grid.Row>
<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, _) => ({
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

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