/** 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. **/ import React, { Component } from "react"; import { BottomPanel, StyledDiv, editModeIconStyle, editModeStyleLeft, } from "./styleComponents"; import Settings from "./DeviceSettings"; import { Image } from "semantic-ui-react"; import { energyConsumedStyle, imageStyle, kwhStyle, nameStyle, } from "./SmartPlugStyle"; import { call } from "../../../client_server"; export default class SmartPlug extends Component { constructor(props) { super(props); this.state = { turnedOn: false, energyConsumed: 0, // kWh }; 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); } 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 })); } }); }; resetSmartPlug = () => { call.smartPlugReset(this.props.device.id).then((res) => { if (res.status === 200) { this.setState({ energyConsumed: (res.data.totalConsumption / 1000).toFixed(3), }); } }); }; getIcon = () => { if (this.state.turnedOn) { return this.iconOn; } return this.iconOff; }; componentDidMount() { this.setState({ turnedOn: this.props.device.on, energyConsumed: (this.props.device.totalConsumption / 1000).toFixed(3), }); } render() { return ( {} : this.onClickDevice}> this.props.onChangeData(id, newSettings) } /> {this.props.edit.mode ? ( ) : ( "" )} {this.props.device.name} ({this.props.device.id}) {this.state.energyConsumed} KWh ); } }