Removed client_server.js and refactored devices

This commit is contained in:
Claudio Maggioni (maggicl) 2020-04-11 00:42:23 +02:00
parent b5cbad53d1
commit ad54cae0e2
12 changed files with 88 additions and 521 deletions

View File

@ -1,279 +0,0 @@
// vim: set ts=2 sw=2 et tw=80:
import axios from "axios";
let config;
if (window.BACKEND_URL !== "__BACKEND_URL__") {
config = window.BACKEND_URL + "/";
} else {
config = "http://localhost:8080/";
}
var tkn = localStorage.getItem("token");
/** the ServiceSocket instance valid for the current session */
var socket;
// requests data devices
/*
{
params : data,
device: 'tipoDiDevice',
id: se serve
}
device routes:
- buttonDimmer
- dimmableLight
- knobDimmer
- motionSensor
- regularLight
- sensor
- smartPlug
- switch
*/
/** The number of times a connection to the socket was tried */
var retries = 0;
/** Class to handle connection with the sensor socket */
class ServiceSocket {
/**
* Create a new sensor socket connection
* @param {string} token - The JWT token (needed for authentication)
* @param {Object.<number, function>|null} callbacks - A callback map from
* device id to callback function
*/
constructor(token, callbacks) {
this.token = token;
this.authenticated = false;
this.callbacks = callbacks || {};
this.connection = new WebSocket("ws://localhost:8080/sensor-socket");
this.connection.onopen = (evt) => {
this.connection.send(JSON.stringify({ token }));
};
this.connection.onmessage = (evt) => {
let data = JSON.parse(evt.data);
if (!this.authenticated) {
if (data.authenticated) {
this.authenticated = true;
retries = 0;
} else {
console.error("socket authentication failed");
}
} else {
this.invokeCallbacks(data);
}
};
this.connection.onerror = (evt) => {
if (retries >= 5) {
console.error("too many socket connection retries");
return;
}
retries++;
socket = new ServiceSocket(this.token, this.callbacks);
};
}
invokeCallbacks(data) {
if (data.id && this.callbacks[data.id]) {
this.callbacks[data.id].forEach((f) => f(data));
}
}
/**
* Registers a new callback function to be called when updates on the device
* with the id given are recieved
* @param {number} id - the id of the device to check updates for
* @param {function} stateCallback - a function that recieves a device as the
* first parameter, that will be called whenever a update is recieved
*/
subscribe(id, stateCallback) {
if (this.callbacks[id] === undefined) {
this.callbacks[id] = [];
}
this.callbacks[id].push(stateCallback);
}
/**
* Unregisters a function previously registered with `subscribe(...)`.
* @param {number} id - the id of the device to stop checking updates for
* @param {function} stateCallback - the callback to unregister
*/
unsubscribe(id, stateCallback) {
this.callbacks[id].splice(this.callbacks[id].indexOf(stateCallback), 1);
}
/**
* Closes the underlying websocket connection
*/
close() {
this.connection.close();
}
}
if (tkn) {
socket = new ServiceSocket(tkn);
}
export var call = {
setToken: function (token) {
tkn = token;
if (tkn) {
if (socket) {
socket.close();
}
socket = new ServiceSocket(tkn);
}
},
/**
* Registers a new callback function to be called when updates on the device
* with the id given are recieved
* @param {number} id - the id of the device to check updates for
* @param {function} stateCallback - a function that recieves a device as the
* first parameter, that will be called whenever a update is recieved
*/
socketSubscribe: function (id, callback) {
socket.subscribe(id, callback);
},
/**
* Unregisters a function previously registered with `subscribe(...)`.
* @param {number} id - the id of the device to stop checking updates for
* @param {function} stateCallback - the callback to unregister
*/
socketUnsubscribe: function (id, callback) {
socket.unsubscribe(id, callback);
},
login: function (data, headers) {
return axios.post(config + "auth/login", data);
},
register: function (data, headers) {
return axios.post(config + "register", data);
},
getUserInfo: function (token) {
if (!token) {
token = tkn;
}
return axios.get(config + "auth/profile", {
headers: { Authorization: "Bearer " + token },
});
},
initResetPassword: function (data, headers) {
return axios.post(config + "register/init-reset-password", data);
},
resetPassword: function (data, headers) {
return axios.put(config + "register/reset-password", data);
},
getAllRooms: function (token) {
if (!token) {
token = tkn;
}
return axios.get(config + "room", {
headers: { Authorization: "Bearer " + token },
});
},
getAllDevices: function (token) {
if (!token) {
token = tkn;
}
return axios.get(config + "device", {
headers: { Authorization: "Bearer " + token },
});
},
getAllDevicesByRoom: function (id, token) {
if (!token) {
token = tkn;
}
return axios.get(config + "room/" + id + "/devices", {
headers: { Authorization: "Bearer " + token },
});
},
createRoom: function (data, headers) {
return axios.post(config + "room", data, {
headers: { Authorization: "Bearer " + tkn },
});
},
updateRoom: function (data, headers) {
return axios.put(config + "room/" + data.id, data, {
headers: { Authorization: "Bearer " + tkn },
});
},
deleteRoom: function (data, headers) {
return axios.delete(config + "room/" + data.id, {
headers: { Authorization: "Bearer " + tkn },
});
},
devicePost: function (data, headers) {
return axios
.post(config + data.device, data.params, {
headers: { Authorization: "Bearer " + tkn },
})
.then((res) => {
if (
res.status === 200 &&
(data.device === "switch" ||
data.device === "buttonDimmer" ||
data.device === "knobDimmer")
) {
let type = "lightId=";
if (data.device === "switch") {
type = "switchableId=";
}
data.params.lights.forEach((e) => {
let urlUp =
config + data.device + "/" + res.data.id + "/lights?" + type + e;
axios.post(
urlUp,
{},
{ headers: { Authorization: "Bearer " + tkn } }
);
});
}
return res;
});
},
deviceUpdate: function (data, typeDevice) {
let url = "device";
if (typeDevice) {
url = typeDevice;
}
let promiseRes = axios.put(config + url, data, {
headers: { Authorization: "Bearer " + tkn },
});
// also for btn/knob dimmer
if (
typeDevice === "switch/operate" ||
typeDevice === "buttonDimmer/dim" ||
typeDevice === "knobDimmer/dimTo"
) {
promiseRes = promiseRes.then((e) => {
if (e.status === 200) {
e.data.forEach((device) => socket.invokeCallbacks(device));
}
return e;
});
}
return promiseRes;
},
deviceDelete: function (data, headers) {
return axios.delete(config + data.device + "/" + data.id, {
headers: { Authorization: "Bearer " + tkn },
});
},
smartPlugReset: function (id) {
return axios.delete(config + "smartPlug/" + id + "/meter", {
headers: { Authorization: "Bearer " + tkn },
});
},
};

View File

@ -49,7 +49,7 @@ const mapStateToProps = (state, _) => ({
if (state.active.activeRoom === -1) {
return Object.values(state.devices);
} else {
const deviceArray = [...state.rooms[state.active.activeRoom].devices];
const deviceArray = [...state.rooms[state.active.activeRoom].devices].sort();
console.log(deviceArray);
return deviceArray.map((id) => state.devices[id]);
}

View File

@ -29,43 +29,25 @@ import {
} from "./DimmerStyle";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
import { call } from "../../../client_server";
export class ButtonDimmerComponent extends Component {
constructor(props) {
super(props);
this.state = {};
}
increaseIntensity = () => {
let data = {
dimType: "UP",
id: this.props.device.id,
};
call.deviceUpdate(data, "buttonDimmer/dim").then((res) => {
if (res.status === 200) {
}
});
};
decreaseIntensity = () => {
let data = {
dimType: "DOWN",
id: this.props.device.id,
};
call.deviceUpdate(data, "buttonDimmer/dim").then((res) => {
if (res.status === 200) {
}
});
this.props.device.buttonDimmerDim(this.props.id, "UP")
.catch((err) => console.error('button dimmer increase error', err));
};
componentDidMount() {}
decreaseIntensity = () => {
this.props.device.buttonDimmerDim(this.props.id, "DOWN")
.catch((err) => console.error('button dimmer decrease error', err));
};
render() {
return (
<ButtonDimmerContainer>
<img alt="icon" src="/img/buttonDimmer.svg" />
<span className="knob">
{this.props.device.name} ({this.props.device.id})
Button Dimmer
</span>
<PlusPanel name="UP" onClick={this.increaseIntensity}>
<span>&#43;</span>
@ -79,41 +61,19 @@ export class ButtonDimmerComponent extends Component {
}
export class KnobDimmerComponent extends Component {
constructor(props) {
super(props);
this.state = {
pointingDevices: [],
value: 1,
};
}
setIntensity = (newValue) => {
let val = Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100);
let data = {
id: this.props.device.id,
intensity: val,
};
call.deviceUpdate(data, "knobDimmer/dimTo").then((res) => {
if (res.status === 200) {
this.setState({
value: val,
});
}
});
const val = Math.round(newValue * 100);
this.props.device.knobDimmerDimTok(this.props.id, val)
.catch((err) => console.error('knob dimmer set intensity error', err));
};
componentDidMount() {
this.setState({
value: 1,
});
}
render() {
return (
<div style={knobContainer}>
<CircularInput
style={KnobDimmerStyle}
value={+(Math.round(this.state.value / 100 + "e+2") + "e-2")}
value={+(Math.round(this.props.device.intensity / 100 + "e+2") + "e-2")}
onChange={this.setIntensity}
>
<text
@ -124,10 +84,10 @@ export class KnobDimmerComponent extends Component {
dy="0.3em"
fontWeight="bold"
>
{this.props.device.name} ({this.props.device.id})
Knob Dimmer
</text>
<CircularProgress
style={{ ...KnobProgress, opacity: this.state.value + 0.1 }}
style={{ ...KnobProgress, opacity: this.props.device.intensity + 0.1 }}
/>
<CircularThumb style={CircularThumbStyle} />
<ThumbText color={"#1a2849"} />

View File

@ -30,65 +30,40 @@ import {
CircularThumbStyle,
knobIcon,
} from "./LightStyle";
import { call } from "../../../client_server";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
class Light extends Component {
constructor(props) {
super(props);
this.state = {
turnedOn: false,
intensity: props.device.intensity,
};
this.iconOn = "/img/lightOn.svg";
this.iconOff = "/img/lightOff.svg";
}
this.stateCallback = (e) => {
this.setState(
Object.assign(this.state, {
intensity: e.intensity,
turnedOn: e.on,
})
);
};
get turnedOn() {
return this.props.device.on;
}
// call.socketSubscribe(this.props.device.id, this.stateCallback);
get intensity() {
return this.props.device.intensity;
}
onClickDevice = () => {
this.props.device.on = !this.state.turnedOn;
call.deviceUpdate(this.props.device, "regularLight").then((res) => {
if (res.status === 200) {
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn }));
}
});
this.props.device.on = !this.turnedOn;
this.props.saveDevice({ ...this.props.device, on: !this.turnedOn })
.catch((err) => console.error('regular light update error', err))
};
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
return this.iconOff;
return this.turnedOn ? this.iconOn : this.iconOff;
};
setIntensity = (newValue) => {
this.props.device.intensity =
Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100);
call.deviceUpdate(this.props.device, "dimmableLight").then((res) => {
if (res.status === 200) {
this.setState({
intensity:
Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100),
});
}
});
const intensity = Math.round(newValue * 100);
this.props.saveDevice({ ...this.props.device, intensity })
.catch((err) => console.error('intensity light update error', err))
};
get intensity() {
return isNaN(this.state.intensity) ? 0 : this.state.intensity;
}
render() {
const intensityLightView = (
<div style={LightDimmerContainer}>
@ -105,7 +80,7 @@ class Light extends Component {
dy="0.3em"
fontWeight="bold"
>
{this.props.device.name} <br /> ({this.props.device.id})
Intensity light
</text>
<CircularProgress
style={{
@ -126,7 +101,7 @@ class Light extends Component {
<Image src={this.getIcon()} style={iconStyle} />
<BottomPanel style={{ backgroundColor: "#ffa41b" }}>
<h5 style={nameStyle}>
{this.props.device.name} ({this.props.device.id})
Light
</h5>
</BottomPanel>
</div>

View File

@ -35,7 +35,6 @@ import {
humiditySensorColors,
iconSensorStyle,
} from "./SensorStyle";
import { call } from "../../../client_server";
import { Image } from "semantic-ui-react";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
@ -54,12 +53,6 @@ class Sensor extends Component {
this.colors = temperatureSensorColors;
this.icon = "temperatureIcon.svg";
call.socketSubscribe(this.props.device.id, this.stateCallback);
}
componentWillUnmount() {
call.socketUnsubscribe(this.props.device.id, this.stateCallback);
}
setName = () => {

View File

@ -18,84 +18,50 @@ import {
kwhStyle,
nameStyle,
} from "./SmartPlugStyle";
import { call } from "../../../client_server";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
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);
get turnedOn() {
return this.props.device.on;
}
get energyConsumed() {
return (this.props.device.totalConsumption / 1000).toFixed(3);
}
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),
});
}
});
const on = !this.turnedOn;
this.props.saveDevice({ ...this.props.device, on })
.catch((err) => console.error('smart plug update error', err));
};
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
return this.iconOff;
return this.turnedOn ? this.iconOn : this.iconOff;
};
componentDidMount() {
this.setState({
turnedOn: this.props.device.on,
energyConsumed: (this.props.device.totalConsumption / 1000).toFixed(3),
});
}
render() {
return (
<StyledDiv onClick={this.onClickDevice}>
<Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}>
{this.props.device.name} ({this.props.device.id})
Smart Plug
</span>
<BottomPanel
style={
this.state.turnedOn
this.turnedOn
? { backgroundColor: "#505bda" }
: { backgroundColor: "#1a2849" }
}
>
<span style={energyConsumedStyle}>{this.state.energyConsumed}</span>
<span style={energyConsumedStyle}>{this.energyConsumed}</span>
<span style={kwhStyle}>KWh</span>
</BottomPanel>
</StyledDiv>

View File

@ -9,70 +9,48 @@ 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";
}
get turnedOn() {
return this.props.device.on;
}
getIcon = () => {
if (this.state.turnedOn) {
return this.iconOn;
}
return this.iconOff;
return this.turnedOn ? this.iconOn : 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 }));
}
});
const newOn = !this.turnedOn;
const type = newOn ? "ON" : "OFF";
this.props.switchOperate(this.props.id, type)
.catch(err => console.error('switch operate failed', err))
};
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})
Switch
</span>
<BottomPanel
style={
this.state.turnedOn
this.turnedOn
? { backgroundColor: "#505bda" }
: { backgroundColor: "#1a2849" }
}
>
<span style={turnedOnStyle}>
{this.state.turnedOn ? "ON" : "OFF"}
{this.turnedOn ? "ON" : "OFF"}
</span>
</BottomPanel>
</StyledDiv>

View File

@ -306,9 +306,9 @@ export const RemoteService = {
return (dispatch) => {
return Endpoint.put(url, {}, action)
.then(async (res) => {
const inputDevice = Endpoint.get(getUrl);
const inputDevice = await Endpoint.get(getUrl);
delete inputDevice.outputs;
dispatch(actions.deviceOperationUpdate([...res.data, inputDevice]));
dispatch(actions.deviceOperationUpdate([...res.data, inputDevice.data]));
})
.catch((err) => {
console.warn(`${url} error`, err);
@ -328,7 +328,7 @@ export const RemoteService = {
* with user-fiendly errors as a RemoteError
*/
switchOperate: (switchId, type) => {
return this._operateInput("/switch/operate", `/switch/${switchId}`, {
return RemoteService._operateInput("/switch/operate", `/switch/${switchId}`, {
type: type.toUpperCase(),
id: switchId,
});
@ -343,7 +343,7 @@ export const RemoteService = {
* with user-fiendly errors as a RemoteError
*/
knobDimmerDimTo: (dimmerId, intensity) => {
return this._operateInput("/knobDimmer/dimTo", `/knobDimmer/${dimmerId}`, {
return RemoteService._operateInput("/knobDimmer/dimTo", `/knobDimmer/${dimmerId}`, {
intensity,
id: dimmerId,
});
@ -360,7 +360,7 @@ export const RemoteService = {
* with user-fiendly errors as a RemoteError
*/
buttonDimmerDim: (dimmerId, dimType) => {
return this._operateInput(
return RemoteService._operateInput(
"/buttonDimmer/dim",
`/buttonDimmer/${dimmerId}`,
{
@ -532,7 +532,7 @@ export class Forms {
"/register/init-reset-password",
{},
{
usernameOrEmail: email,
email: email,
}
)
.then((_) => void 0)
@ -547,15 +547,17 @@ export class Forms {
* performed email verification
* This method does not update the global state,
* please check its return value.
* @param {String} confirmationToken the confirmation token got from the email
* @param {String} password the new password
* @returns {Promise<Undefined, String[]>} promise that resolves to void and rejects
* with validation errors as a String array
*/
static submitResetPassword(password) {
static submitResetPassword(confirmationToken, password) {
return Endpoint.post(
"/register/reset-password",
{},
{
confirmationToken,
password,
}
)

View File

@ -92,9 +92,13 @@ function reducer(previousState, action) {
};
for (const room of Object.values(previousState.rooms)) {
change.rooms[room.id].devices = { $set: new Set() };
if (change.rooms[room.id]) {
change.rooms[room.id].devices = { $set: new Set() };
}
}
}
console.log(change, action.devices);
newState = update(previousState, change);
change = {
@ -106,8 +110,9 @@ function reducer(previousState, action) {
change.devices[device.id] = { $set: device };
if (device.roomId in newState.rooms) {
change.rooms[device.roomId] = {};
change.rooms[device.roomId].devices = {};
change.rooms[device.roomId] = change.rooms[device.roomId] || {};
change.rooms[device.roomId].devices =
change.rooms[device.roomId].devices || {};
const devices = change.rooms[device.roomId].devices;
devices.$add = devices.$add || [];
devices.$add.push(device.id);
@ -124,6 +129,8 @@ function reducer(previousState, action) {
}
}
}
console.log(change);
newState = update(newState, change);
break;
case "ROOM_SAVE":

View File

@ -8,8 +8,8 @@ import {
Icon,
Message,
} from "semantic-ui-react";
import { call } from "../client_server";
import { Redirect } from "react-router-dom";
import { Forms } from "../remote";
export default class ChangePass extends Component {
constructor(props) {
@ -32,10 +32,6 @@ export default class ChangePass extends Component {
};
handleChangePassword = (e) => {
const params = {
confirmationToken: this.props.query.token,
password: this.state.password,
};
if (this.state.confirmPassword !== this.state.password) {
this.setState({
error: {
@ -45,18 +41,10 @@ export default class ChangePass extends Component {
});
}
call
.resetPassword(params)
.then((res) => {
if (res.status === 200) {
this.setState({ success: true });
} else {
this.setState({ error: { state: true, message: "Errore" } });
}
})
.catch((err) => {
console.log(err);
});
Forms.submitResetPassword(this.props.query.token, this.state.password)
.then(() => this.setState({ success: true }))
.catch((err) => this.setState({ error:
{ state: true, message: err.messages.join(' - ') }}));
};
render() {

View File

@ -9,7 +9,7 @@ import {
Message,
} from "semantic-ui-react";
import { Redirect } from "react-router-dom";
import { call } from "../client_server";
import { Forms } from "../remote";
export default class ForgotPass extends Component {
constructor(props) {
@ -32,23 +32,10 @@ export default class ForgotPass extends Component {
handleSendEmail = (e) => {
e.preventDefault();
const params = {
email: this.state.user,
};
call
.initResetPassword(params)
.then((res) => {
if (res.status === 200) {
this.setState({ success: true });
}
})
.catch((err) => {
let errs = [
...new Set(err.response.data.errors.map((e) => e.defaultMessage)),
];
this.setState({ error: { state: true, message: errs } });
});
Forms.submitInitResetPassword(this.state.user)
.then(() => this.setState({ success: true }))
.catch((err) => this.setState({ error: { state: true, message: err.messages }}));
};
render() {

View File

@ -10,7 +10,7 @@ import {
Message,
} from "semantic-ui-react";
import { Redirect } from "react-router-dom";
import { call } from "../client_server";
import { Forms } from "../remote";
export default class Signup extends Component {
constructor(props) {
@ -34,20 +34,10 @@ export default class Signup extends Component {
username: this.state.username,
};
call
.register(params)
.then((res) => {
if (res.status === 200 && res.data) {
this.setState({ success: true });
}
})
.catch((err) => {
//console.log(err);
let errs = [
...new Set(err.response.data.errors.map((e) => e.defaultMessage)),
];
this.setState({ error: { state: true, message: errs } });
});
Forms.
submitRegistration(params)
.then(() => this.setState({ success: true }))
.catch((err) => this.setState({ error: { state: true, message: err.messages }}));
};
onChangeHandler = (event) => {