frontend/smart-hut/src/components/dashboard/devices/Switch.js

79 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-03-17 16:38:03 +00:00
/**
* Users can add on-off switches. A on-off switch can turn on (or off) lights.
* If a light has an intensity level, when it gets switched back on, it gets the last available
* intensity level that was set by the user (or 100% if no such level exists).
* The user can change the state of a switch through the SmartHut interface.
*/
import React, { Component } from 'react';
import { BottomPanel, StyledDiv } from "./styleComponents";
2020-03-17 16:38:03 +00:00
import Settings from "./DeviceSettings";
2020-03-23 20:24:17 +00:00
import { Image } from "semantic-ui-react";
2020-03-25 15:04:02 +00:00
import { imageStyle, nameStyle, turnedOnStyle } from "./SwitchStyle";
2020-03-23 20:24:17 +00:00
import { call } from "../../../client_server";
2020-03-17 16:38:03 +00:00
export default class Switch extends Component {
2020-03-23 20:24:17 +00:00
constructor(props) {
2020-03-17 16:38:03 +00:00
super(props);
this.state = {
turnedOn: false,
pointingLights: []
2020-03-17 16:38:03 +00:00
};
this.iconOn = "/img/switchOn.svg";
this.iconOff = "/img/switchOff.svg";
}
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
return this.iconOff;
};
2020-03-17 16:38:03 +00:00
onClickDevice = () => {
2020-03-23 18:08:31 +00:00
this.props.device.on = !this.state.turnedOn;
let state = "";
2020-03-23 20:24:17 +00:00
if (this.props.device.on) {
state = "ON";
2020-03-23 18:08:31 +00:00
} else {
2020-03-23 20:24:17 +00:00
state = "OFF";
2020-03-23 18:08:31 +00:00
}
let data = {
2020-03-23 20:24:17 +00:00
type: state,
id: this.props.device.id,
};
call.deviceUpdate(data, "switch/operate").then((res) => {
if (res.status === 200) {
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn }));
}
});
2020-03-17 16:38:03 +00:00
};
componentDidMount() {
2020-03-23 18:08:31 +00:00
this.setState({
2020-03-23 20:24:17 +00:00
turnedOn: this.props.device.on,
});
2020-03-17 16:38:03 +00:00
}
2020-03-23 20:24:17 +00:00
render() {
2020-03-17 16:38:03 +00:00
return (
<StyledDiv
onClick={this.props.edit.mode ? () => {
} : this.onClickDevice}>
2020-03-17 16:38:03 +00:00
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) => this.props.onChangeData(id, newSettings)} />
2020-03-23 20:24:17 +00:00
<Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}>{this.props.device.name}</span>
<BottomPanel style={this.state.turnedOn ? { backgroundColor: "#505bda" } : { backgroundColor: "#1a2849" }}>
2020-03-25 15:04:02 +00:00
<span style={turnedOnStyle}>{this.state.turnedOn ? "ON" : "OFF"}</span>
</BottomPanel>
2020-03-17 16:38:03 +00:00
</StyledDiv>
2020-03-25 15:04:02 +00:00
)
2020-03-17 16:38:03 +00:00
}
2020-03-25 15:04:02 +00:00
2020-03-17 16:38:03 +00:00
}