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

96 lines
2.6 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-25 16:20:53 +00:00
import React, { Component } from "react";
2020-03-25 15:04:02 +00:00
import { BottomPanel, StyledDiv } from "./styleComponents";
import Settings from "./DeviceSettings";
2020-03-23 20:24:17 +00:00
import { Image } from "semantic-ui-react";
2020-03-25 16:20:53 +00:00
import {
energyConsumedStyle,
imageStyle,
kwhStyle,
nameStyle,
} from "./SmartPlugStyle";
2020-03-23 20:24:17 +00:00
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";
this.stateCallback = (e) => {
this.setState(
Object.assign(this.state, {
energyConsumed: (e.totalConsumption / 1000).toFixed(3),
turnedOn: e.on,
})
);
};
call.socketSubscribe(this.props.device.id, this.stateCallback);
}
2020-03-25 15:04:02 +00:00
componentWillUnmount() {
call.socketUnsubscribe(this.props.device.id, this.stateCallback);
}
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 (
2020-03-25 16:20:53 +00:00
<StyledDiv onClick={this.props.edit.mode ? () => {} : this.onClickDevice}>
2020-03-23 20:24:17 +00:00
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
2020-03-25 16:20:53 +00:00
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
2020-03-23 20:24:17 +00:00
<Image src={this.getIcon()} style={imageStyle} />
2020-03-25 23:15:02 +00:00
<span style={nameStyle}>
{this.props.device.name} ({this.props.device.id})
</span>
2020-03-25 16:20:53 +00:00
<BottomPanel
style={
this.state.turnedOn
? { backgroundColor: "#505bda" }
: { backgroundColor: "#1a2849" }
}
>
<span style={energyConsumedStyle}>{this.state.energyConsumed}</span>
<span style={kwhStyle}>KWh</span>
</BottomPanel>
2020-03-23 20:24:17 +00:00
</StyledDiv>
2020-03-25 16:20:53 +00:00
);
2020-03-23 20:24:17 +00:00
}
}