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) { if (state.active.activeRoom === -1) {
return Object.values(state.devices); return Object.values(state.devices);
} else { } else {
const deviceArray = [...state.rooms[state.active.activeRoom].devices]; const deviceArray = [...state.rooms[state.active.activeRoom].devices].sort();
console.log(deviceArray); console.log(deviceArray);
return deviceArray.map((id) => state.devices[id]); return deviceArray.map((id) => state.devices[id]);
} }

View file

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

View file

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

View file

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

View file

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

View file

@ -9,70 +9,48 @@ import React, { Component } from "react";
import { BottomPanel, StyledDiv } from "./styleComponents"; import { BottomPanel, StyledDiv } from "./styleComponents";
import { Image } from "semantic-ui-react"; import { Image } from "semantic-ui-react";
import { imageStyle, nameStyle, turnedOnStyle } from "./SwitchStyle"; import { imageStyle, nameStyle, turnedOnStyle } from "./SwitchStyle";
import { call } from "../../../client_server";
import { RemoteService } from "../../../remote"; import { RemoteService } from "../../../remote";
import { connect } from "react-redux"; import { connect } from "react-redux";
class Switch extends Component { class Switch extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = {
turnedOn: false,
pointingLights: [],
};
this.iconOn = "/img/switchOn.svg"; this.iconOn = "/img/switchOn.svg";
this.iconOff = "/img/switchOff.svg"; this.iconOff = "/img/switchOff.svg";
} }
getIcon = () => { get turnedOn() {
if (this.state.turnedOn) { return this.props.device.on;
return this.iconOn;
} }
return this.iconOff;
getIcon = () => {
return this.turnedOn ? this.iconOn : this.iconOff;
}; };
onClickDevice = () => { onClickDevice = () => {
this.props.device.on = !this.state.turnedOn; const newOn = !this.turnedOn;
let state = ""; const type = newOn ? "ON" : "OFF";
if (this.props.device.on) { this.props.switchOperate(this.props.id, type)
state = "ON"; .catch(err => console.error('switch operate failed', err))
} 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() { render() {
return ( return (
<StyledDiv onClick={this.onClickDevice}> <StyledDiv onClick={this.onClickDevice}>
<Image src={this.getIcon()} style={imageStyle} /> <Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}> <span style={nameStyle}>
{this.props.device.name} ({this.props.device.id}) Switch
</span> </span>
<BottomPanel <BottomPanel
style={ style={
this.state.turnedOn this.turnedOn
? { backgroundColor: "#505bda" } ? { backgroundColor: "#505bda" }
: { backgroundColor: "#1a2849" } : { backgroundColor: "#1a2849" }
} }
> >
<span style={turnedOnStyle}> <span style={turnedOnStyle}>
{this.state.turnedOn ? "ON" : "OFF"} {this.turnedOn ? "ON" : "OFF"}
</span> </span>
</BottomPanel> </BottomPanel>
</StyledDiv> </StyledDiv>

View file

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

View file

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

View file

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

View file

@ -9,7 +9,7 @@ import {
Message, Message,
} from "semantic-ui-react"; } from "semantic-ui-react";
import { Redirect } from "react-router-dom"; import { Redirect } from "react-router-dom";
import { call } from "../client_server"; import { Forms } from "../remote";
export default class ForgotPass extends Component { export default class ForgotPass extends Component {
constructor(props) { constructor(props) {
@ -32,23 +32,10 @@ export default class ForgotPass extends Component {
handleSendEmail = (e) => { handleSendEmail = (e) => {
e.preventDefault(); e.preventDefault();
const params = {
email: this.state.user,
};
call Forms.submitInitResetPassword(this.state.user)
.initResetPassword(params) .then(() => this.setState({ success: true }))
.then((res) => { .catch((err) => this.setState({ error: { state: true, message: err.messages }}));
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 } });
});
}; };
render() { render() {

View file

@ -10,7 +10,7 @@ import {
Message, Message,
} from "semantic-ui-react"; } from "semantic-ui-react";
import { Redirect } from "react-router-dom"; import { Redirect } from "react-router-dom";
import { call } from "../client_server"; import { Forms } from "../remote";
export default class Signup extends Component { export default class Signup extends Component {
constructor(props) { constructor(props) {
@ -34,20 +34,10 @@ export default class Signup extends Component {
username: this.state.username, username: this.state.username,
}; };
call Forms.
.register(params) submitRegistration(params)
.then((res) => { .then(() => this.setState({ success: true }))
if (res.status === 200 && res.data) { .catch((err) => this.setState({ error: { state: true, message: err.messages }}));
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 } });
});
}; };
onChangeHandler = (event) => { onChangeHandler = (event) => {