More fixes on automations

This commit is contained in:
Claudio Maggioni (maggicl) 2020-05-01 20:05:39 +02:00
parent 96184c76c9
commit ac1bcdbc29
6 changed files with 247 additions and 181 deletions

View file

@ -11,6 +11,7 @@ import {
Header, Header,
Input, Input,
Button, Button,
Modal,
List, List,
Divider, Divider,
Menu, Menu,
@ -50,8 +51,14 @@ const deviceStateOptions = [
const CreateTrigger = (props) => { const CreateTrigger = (props) => {
const [activeOperand, setActiveOperand] = useState(true); const [activeOperand, setActiveOperand] = useState(true);
const admitedDevices = ["sensor", "regularLight", "dimmableLight"]; // TODO: Complete this list const notAdmitedDevices = ["buttonDimmer"];
const deviceList = props.devices const hasOperand = new Set([
"knobDimmer",
"dimmableLight",
"curtains",
"sensor",
]);
const deviceList = Object.values(props.devices)
.map((device) => { .map((device) => {
return { return {
key: device.id, key: device.id,
@ -60,17 +67,11 @@ const CreateTrigger = (props) => {
kind: device.kind, kind: device.kind,
}; };
}) })
.filter((e) => admitedDevices.includes(e.kind)); .filter((e) => !notAdmitedDevices.includes(e.kind));
const onChange = (e, val) => { const onChange = (e, val) => {
props.inputChange(val); props.inputChange(val);
if ( setActiveOperand(hasOperand.has(props.devices[val.value].kind));
props.devices.filter((d) => d.id === val.value)[0].hasOwnProperty("on")
) {
setActiveOperand(false);
} else {
setActiveOperand(true);
}
}; };
return ( return (
@ -182,7 +183,6 @@ const Trigger = ({ deviceName, trigger, onRemove, index }) => {
class AutomationSaveModal extends Component { class AutomationSaveModal extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.props = props;
this.state = { this.state = {
triggerList: [], triggerList: [],
order: [], order: [],
@ -190,8 +190,29 @@ class AutomationSaveModal extends Component {
editName: false, editName: false,
newTrigger: {}, newTrigger: {},
scenesFilter: null, scenesFilter: null,
openModal: false,
}; };
if (this.props.automation) {
this.state.automationName = this.props.automation.name;
for (const scenePriority of this.props.automation.scenes) {
this.state.order[scenePriority.priority] = scenePriority.sceneId;
}
for (const trigger of this.props.automation.triggers) {
this.state.triggerList.push(
Object.assign(
{
device: trigger.deviceId,
kind: trigger.kind,
},
trigger.kind === "booleanTrigger"
? { on: trigger.on }
: { operand: trigger.operator, value: trigger.value }
)
);
}
}
this.setTrigger = this._setter("triggerList"); this.setTrigger = this._setter("triggerList");
this.setOrder = this._setter("order"); this.setOrder = this._setter("order");
this.setautomationName = this._setter("automationName"); this.setautomationName = this._setter("automationName");
@ -203,8 +224,17 @@ class AutomationSaveModal extends Component {
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);
} }
openModal = (e) => {
this.setState({ openModal: true });
};
closeModal = (e) => {
this.setState({ openModal: false });
};
get deviceList() { get deviceList() {
return Object.values(this.props.devices); return Object.values(this.props.devices);
} }
@ -216,9 +246,9 @@ class AutomationSaveModal extends Component {
triggerKind(trigger) { triggerKind(trigger) {
if ("on" in trigger) { if ("on" in trigger) {
return "BooleanTrigger"; return "booleanTrigger";
} else if ("operand" in trigger && "value" in trigger) { } else if ("operand" in trigger && "value" in trigger) {
return "RangeTrigger"; return "rangeTrigger";
} else { } else {
throw new Error("Trigger kind not handled"); throw new Error("Trigger kind not handled");
} }
@ -234,10 +264,11 @@ class AutomationSaveModal extends Component {
}; };
switch (this.triggerKind(trigger)) { switch (this.triggerKind(trigger)) {
case "BooleanTrigger": case "booleanTrigger":
if (!trigger.device || !trigger.on) return error; if (!trigger.device || trigger.on === null || trigger.on === undefined)
return error;
break; break;
case "RangeTrigger": case "rangeTrigger":
if (!trigger.device || !trigger.operand || !trigger.value) return error; if (!trigger.device || !trigger.operand || !trigger.value) return error;
break; break;
} }
@ -310,10 +341,10 @@ class AutomationSaveModal extends Component {
_generateKey = (trigger) => { _generateKey = (trigger) => {
switch (this.triggerKind(trigger)) { switch (this.triggerKind(trigger)) {
case "BooleanTrigger": case "booleanTrigger":
return trigger.device + trigger.value; return "" + trigger.device + trigger.on;
case "RangeTrigger": case "rangeTrigger":
return trigger.device + trigger.operand + trigger.value; return "" + trigger.device + trigger.operand + trigger.value;
} }
}; };
@ -338,17 +369,77 @@ class AutomationSaveModal extends Component {
const automation = { const automation = {
name: this.state.automationName, name: this.state.automationName,
}; };
this.props.save({
if (this.props.id) {
automation.id = this.props.id;
automation.triggers = [];
automation.scenes = [];
for (let i = 0; i < this.state.order.length; i++) {
automation.scenes.push({
priority: i,
sceneId: this.state.order[i],
});
}
for (const trigger of this.state.triggerList) {
const kind = trigger.kind || this.triggerKind(trigger);
automation.triggers.push(
Object.assign(
{
deviceId: trigger.device,
kind,
},
kind
? { on: trigger.on }
: { operator: trigger.operand, value: trigger.value }
)
);
}
console.log(automation);
this.props
.fastUpdateAutomation(automation)
.then(this.closeModal)
.catch(console.error);
} else {
this.props
.saveAutomation({
automation, automation,
triggerList: this.state.triggerList, triggerList: this.state.triggerList,
order: this.state.order, order: this.state.order,
}); })
.then(this.closeModal)
.catch(console.error);
}
} }
}; };
get trigger() {
return this.props.id ? (
<Button
style={{ display: "inline" }}
circular
size="small"
icon="edit"
onClick={this.openModal}
/>
) : (
<Button icon labelPosition="left" color="green" onClick={this.openModal}>
<Icon name="add"></Icon>Create new automation
</Button>
);
}
render() { render() {
return ( return (
<React.Fragment> <Modal
closeIcon
trigger={this.trigger}
open={this.state.openModal}
onClose={this.closeModal}
>
<Segment basic>
<Header style={{ display: "inline", marginRight: "1rem" }}> <Header style={{ display: "inline", marginRight: "1rem" }}>
{this.state.editName ? ( {this.state.editName ? (
<Input <Input
@ -394,7 +485,7 @@ class AutomationSaveModal extends Component {
); );
})} })}
<CreateTrigger <CreateTrigger
devices={this.deviceList} devices={this.props.devices}
inputChange={this.onInputChange} inputChange={this.onInputChange}
/> />
</List> </List>
@ -444,26 +535,21 @@ class AutomationSaveModal extends Component {
<Grid.Row> <Grid.Row>
<Grid.Column style={{ marginRight: "1rem" }}> <Grid.Column style={{ marginRight: "1rem" }}>
<Button onClick={() => this.saveAutomation()} color="green"> <Button onClick={() => this.saveAutomation()} color="green">
SAVE {this.props.id ? "Save" : "Create"}
</Button> </Button>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>
</React.Fragment> </Segment>
</Modal>
); );
} }
} }
const mapStateToProps = (state, _) => ({ const mapStateToProps = (state, ownProps) => ({
activeRoom: state.active.activeRoom, scenes: Object.values(state.scenes),
activeTab: state.active.activeTab,
get scenes() {
return Object.values(state.scenes);
},
devices: state.devices, devices: state.devices,
get automations() { automation: ownProps.id ? state.automations[ownProps.id] : null,
return Object.values(state.automations);
},
}); });
const AutomationSaveModalContainer = connect( const AutomationSaveModalContainer = connect(
mapStateToProps, mapStateToProps,

View file

@ -25,12 +25,7 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
<Header style={{ display: "inline", marginRight: "1rem" }}> <Header style={{ display: "inline", marginRight: "1rem" }}>
{automation.name} {automation.name}
</Header> </Header>
<Button <CreateAutomation id={automation.id} />
style={{ display: "inline" }}
circular
size="small"
icon={"edit"}
/>
<Button <Button
style={{ display: "inline" }} style={{ display: "inline" }}
circular circular
@ -59,7 +54,7 @@ const Automation = ({ automation, devices, scenes, removeAutomation }) => {
? getOperator(trigger.operator) + ? getOperator(trigger.operator) +
" " + " " +
trigger.range trigger.range
: trigger.value : trigger.on
? " - on" ? " - on"
: " - off"} : " - off"}
</Menu.Item> </Menu.Item>
@ -129,7 +124,7 @@ class AutomationsPanel extends Component {
<Grid.Column textAlign="center" width={16}> <Grid.Column textAlign="center" width={16}>
{!this.state.openModal ? ( {!this.state.openModal ? (
<List> <List>
<CreateAutomation save={this.props.saveAutomation} /> <CreateAutomation />
</List> </List>
) : ( ) : (
<Button color="green">CREATE AUTOMATION</Button> <Button color="green">CREATE AUTOMATION</Button>
@ -138,7 +133,6 @@ class AutomationsPanel extends Component {
</Grid.Row> </Grid.Row>
<Grid.Row> <Grid.Row>
{this.props.automations.map((automation, i) => { {this.props.automations.map((automation, i) => {
console.log(23, automation, i, this.props.automations);
return ( return (
<Grid.Column key={i} width={8} style={{ margin: "2rem 0" }}> <Grid.Column key={i} width={8} style={{ margin: "2rem 0" }}>
<Automation <Automation

View file

@ -1,7 +1,7 @@
// vim: set ts=2 sw=2 et tw=80: // vim: set ts=2 sw=2 et tw=80:
import React, { Component } from "react"; import React, { Component } from "react";
import { Grid, Card } from "semantic-ui-react"; import { Segment, Card } from "semantic-ui-react";
import Device from "./devices/Device"; import Device from "./devices/Device";
import NewDevice from "./devices/NewDevice"; import NewDevice from "./devices/NewDevice";
import { connect } from "react-redux"; import { connect } from "react-redux";
@ -24,18 +24,16 @@ class DevicePanel extends Component {
render() { render() {
return ( return (
<Card.Group style={{ paddingTop: "3rem" }}> <Card.Group centered style={{ paddingTop: "3rem" }}>
{this.props.devices.map((e, i) => { {this.props.devices.map((e, i) => {
return ( return <Device tab={this.props.tab} id={e.id} />;
<Grid.Column key={i}>
<Device tab={this.props.tab} id={e.id} />
</Grid.Column>
);
})} })}
{!this.props.isActiveRoomHome ? ( {!this.props.isActiveRoomHome ? (
<Grid.Column> <Card style={{ height: "23em" }}>
<Segment basic style={{ width: "100%", height: "100%" }}>
<NewDevice /> <NewDevice />
</Grid.Column> </Segment>
</Card>
) : null} ) : null}
</Card.Group> </Card.Group>
); );

View file

@ -341,7 +341,14 @@ class NewDevice extends Component {
open={this.state.openModal} open={this.state.openModal}
onClose={this.resetState} onClose={this.resetState}
trigger={ trigger={
<StyledDiv onClick={this.handleOpen}> <StyledDiv
onClick={this.handleOpen}
style={{
position: "relative",
top: "calc(50% - 5rem)",
left: "calc(50% - 5rem)",
}}
>
<Image src="/img/add.svg" style={{ filter: "invert()" }} /> <Image src="/img/add.svg" style={{ filter: "invert()" }} />
</StyledDiv> </StyledDiv>
} }

View file

@ -315,36 +315,7 @@ export const RemoteService = {
fetchAutomations: () => { fetchAutomations: () => {
return (dispatch) => { return (dispatch) => {
return Endpoint.get("/automation/") return Endpoint.get("/automation/")
.then((res) => { .then((res) => void dispatch(actions.automationsUpdate(res.data)))
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)
);
}
});
});
});
});
})
.catch((err) => { .catch((err) => {
console.error(`Fetch automations error`, err); console.error(`Fetch automations error`, err);
throw new RemoteError(["Network error"]); throw new RemoteError(["Network error"]);
@ -502,11 +473,22 @@ export const RemoteService = {
}; };
}, },
fastUpdateAutomation: (automation) => {
return (dispatch) => {
return Endpoint.put("/automation/fast", {}, automation)
.then((res) => dispatch(actions.automationSave(res.data)))
.catch((err) => {
console.warn("Update automation: ", automation, "error: ", err);
throw new RemoteError(["Network error"]);
});
};
},
/** /**
* Creates/Updates an automation with the given data. If * Creates/Updates an automation with the given data. If
* data.id is truthy, then a update call is performed, * data.id is truthy, then a update call is performed,
* otherwise a create call is performed. * otherwise a create call is performed.
* @param {Automation} data the device to update. * @param {Automation} data the automation to update.
* @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects * @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects
* with user-fiendly errors as a RemoteError * with user-fiendly errors as a RemoteError
*/ */

View file

@ -257,7 +257,6 @@ function reducer(previousState, action) {
break; break;
case "AUTOMATION_UPDATE": case "AUTOMATION_UPDATE":
newState = previousState;
const automations = {}; const automations = {};
for (const automation of action.automations) { for (const automation of action.automations) {
automations[automation.id] = automation; automations[automation.id] = automation;