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

65 lines
1.9 KiB
JavaScript
Raw Normal View History

/**
A smart plug is a plug that has a boolean internal state, i.e., that can be turned on or off, either with the
SmartHut interface or by a switch.
The smart plug also stores the total energy consumed while the plug is active, in terms of kilowatt-hours 2(kWh) .
The user can reset this value.
**/
2020-03-23 20:24:17 +00:00
import React, { Component } from "react";
import { StyledDiv } from "./styleComponents";
import Settings from "./DeviceSettings";
2020-03-23 20:24:17 +00:00
import { Image } from "semantic-ui-react";
import { energyConsumedStyle, imageStyle, nameStyle } from "./SmartPlugStyle";
import { call } from "../../../client_server";
export default class SmartPlug extends Component {
2020-03-23 20:24:17 +00:00
constructor(props) {
super(props);
this.state = {
turnedOn: false,
energyConsumed: 0, // kWh
};
2020-03-23 20:24:17 +00:00
this.iconOn = "/img/smart-plug.svg";
this.iconOff = "/img/smart-plug-off.svg";
}
2020-03-23 20:24:17 +00:00
onClickDevice = () => {
this.props.device.on = !this.state.turnedOn;
call.deviceUpdate(this.props.device, "smartPlug").then((res) => {
if (res.status === 200) {
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn }));
}
});
};
2020-03-23 20:24:17 +00:00
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
2020-03-23 20:24:17 +00:00
return this.iconOff;
};
2020-03-23 20:24:17 +00:00
componentDidMount() {
this.setState({
turnedOn: this.props.device.on,
energyConsumed: this.props.device.totalConsumption,
});
}
render() {
return (
<StyledDiv onClick={this.props.edit.mode ? () => {} : this.onClickDevice}>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<Image src={this.getIcon()} style={imageStyle} />
<h4 style={energyConsumedStyle}>{this.state.energyConsumed} KWh</h4>
<h5 style={nameStyle}>{this.props.device.name}</h5>
</StyledDiv>
);
}
}