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

88 lines
2.3 KiB
JavaScript

/**
* 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";
import { Image } from "semantic-ui-react";
import { imageStyle, nameStyle, turnedOnStyle } from "./SwitchStyle";
import { call } from "../../../client_server";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
class Switch extends Component {
constructor(props) {
super(props);
this.state = {
turnedOn: false,
pointingLights: [],
};
this.iconOn = "/img/switchOn.svg";
this.iconOff = "/img/switchOff.svg";
}
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
return this.iconOff;
};
onClickDevice = () => {
this.props.device.on = !this.state.turnedOn;
let state = "";
if (this.props.device.on) {
state = "ON";
} else {
state = "OFF";
}
let data = {
type: state,
id: this.props.device.id,
};
call.deviceUpdate(data, "switch/operate").then((res) => {
if (res.status === 200) {
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn }));
}
});
};
componentDidMount() {
this.setState({
turnedOn: this.props.device.on,
});
}
render() {
return (
<StyledDiv onClick={this.onClickDevice}>
<Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}>
{this.props.device.name} ({this.props.device.id})
</span>
<BottomPanel
style={
this.state.turnedOn
? { backgroundColor: "#505bda" }
: { backgroundColor: "#1a2849" }
}
>
<span style={turnedOnStyle}>
{this.state.turnedOn ? "ON" : "OFF"}
</span>
</BottomPanel>
</StyledDiv>
);
}
}
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const SwitchContainer = connect(mapStateToProps, RemoteService)(Switch);
export default SwitchContainer;