Merge branch '73-redux-refactor-for-device-state' into 'dev'

Resolve "Redux refactor for device state"

Closes #73

See merge request sa4-2020/the-sanmarinoes/frontend!81
This commit is contained in:
Claudio Maggioni 2020-04-12 17:55:55 +02:00
commit 2976ed7dc3
32 changed files with 1654 additions and 1525 deletions

View file

@ -1,2 +1 @@
# frontend # frontend

View file

@ -3,6 +3,7 @@
"version": "0.1.0", "version": "0.1.0",
"private": true, "private": true,
"dependencies": { "dependencies": {
"@giantmachines/redux-websocket": "^1.1.7",
"@material-ui/core": "^4.9.4", "@material-ui/core": "^4.9.4",
"@material-ui/icons": "^4.9.1", "@material-ui/icons": "^4.9.1",
"@testing-library/jest-dom": "^4.2.4", "@testing-library/jest-dom": "^4.2.4",
@ -10,6 +11,7 @@
"@testing-library/user-event": "^7.1.2", "@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2", "axios": "^0.19.2",
"classnames": "^2.2.6", "classnames": "^2.2.6",
"immutability-helper": "^3.0.2",
"material-ui-image": "^3.2.3", "material-ui-image": "^3.2.3",
"react": "^16.12.0", "react": "^16.12.0",
"react-axios": "^2.0.3", "react-axios": "^2.0.3",
@ -17,10 +19,13 @@
"react-circular-slider-svg": "^0.1.5", "react-circular-slider-svg": "^0.1.5",
"react-device-detect": "^1.11.14", "react-device-detect": "^1.11.14",
"react-dom": "^16.12.0", "react-dom": "^16.12.0",
"react-redux": "^7.2.0",
"react-round-slider": "^1.0.1", "react-round-slider": "^1.0.1",
"react-router": "^5.1.2", "react-router": "^5.1.2",
"react-router-dom": "^5.1.2", "react-router-dom": "^5.1.2",
"react-scripts": "3.4.0", "react-scripts": "3.4.0",
"redux": "^4.0.5",
"redux-thunk": "^2.3.0",
"semantic-ui-react": "^0.88.2", "semantic-ui-react": "^0.88.2",
"styled-components": "^5.0.1" "styled-components": "^5.0.1"
}, },

View file

@ -12,44 +12,17 @@ import ConfirmRegistration from "./views/ConfirmRegistration";
import ConfirmResetPassword from "./views/ConfirmResetPassword"; import ConfirmResetPassword from "./views/ConfirmResetPassword";
import Instruction from "./views/Instruction"; import Instruction from "./views/Instruction";
import queryString from "query-string"; import queryString from "query-string";
import { RemoteService } from "./remote";
import { call } from "./client_server"; import { connect } from "react-redux";
/*let userJsonString = JSON.parse(localStorage.getItem("token"));
let date = new Date().getTime().toString();
let delta = date - userJsonString.timestamp;
if (delta < 5*60*60*1000) {
loggedIn = true;
}*/
class App extends Component { class App extends Component {
constructor(props) { constructor(props, context) {
super(props); super(props, context);
let loggedIn = false;
let token = undefined;
try {
let userJsonString = localStorage.getItem("token");
let exp = localStorage.getItem("exp");
let date = new Date().getTime();
if (userJsonString && exp && date < exp) {
loggedIn = true;
token = userJsonString;
} else {
localStorage.removeItem("token");
localStorage.removeItem("exp");
}
} catch (exception) {}
this.state = { this.state = {
loggedIn: loggedIn, query: "",
token: token,
info: "", info: "",
}; };
this.auth = this.auth.bind(this);
this.logout = this.logout.bind(this);
} }
componentDidMount() { componentDidMount() {
@ -58,70 +31,21 @@ class App extends Component {
this.setState({ this.setState({
query: values, query: values,
}); });
} else {
this.setState({
query: "ciao",
});
} }
} }
auth(data) {
return call
.login(data.params)
.then((res) => {
if (res.data && res.status === 200) {
let expire = new Date().getTime() + 60 * 60 * 5 * 1000;
localStorage.setItem("token", res.data.jwttoken);
localStorage.setItem("exp", expire);
call.setToken(res.data.jwttoken);
this.setState({
user: data.params.user,
token: res.data.jwttoken,
loggedIn: true,
});
this.getInfo();
return res;
//this.props.history.push("/dashboard");
} else {
this.setState({
error: res.data.message,
});
return res.status;
}
})
.catch((err) => {
return err;
});
}
logout() {
this.setState({
loggedIn: false,
});
localStorage.removeItem("token");
localStorage.removeItem("exp");
}
render() { render() {
console.log("rendering root", this.props.loggedIn, this.state.query);
return ( return (
<BrowserRouter> <BrowserRouter>
<Switch> <Switch>
<Route path="/" exact component={Home} /> <Route path="/" exact component={Home} />
<Route path="/login"> <Route path="/login">
{this.state.loggedIn && this.state.token ? ( {this.props.loggedIn ? <Redirect to="/dashboard" /> : <Login />}
<Redirect tkn={this.state.token} to="/dashboard" />
) : (
<Login auth={this.auth} />
)}
</Route> </Route>
<Route path="/signup" exact component={Signup} /> <Route path="/signup" exact component={Signup} />
<Route path="/dashboard"> <Route path="/dashboard">
{this.state.loggedIn ? ( {this.props.loggedIn ? <Dashboard /> : <Redirect to="/login" />}
<Dashboard tkn={this.state.token} logout={this.logout} />
) : (
<Redirect to="/login" />
)}
</Route> </Route>
<Route path="/forgot-password"> <Route path="/forgot-password">
<ForgotPass /> <ForgotPass />
@ -149,4 +73,6 @@ class App extends Component {
} }
} }
export default App; const mapStateToProps = (state, _) => ({ loggedIn: state.login.loggedIn });
const AppContainer = connect(mapStateToProps, RemoteService)(App);
export default AppContainer;

View file

@ -3,12 +3,16 @@ import { render } from "@testing-library/react";
import { Router } from "react-router"; import { Router } from "react-router";
import { createMemoryHistory } from "history"; import { createMemoryHistory } from "history";
import App from "./App"; import App from "./App";
import { Provider } from "react-redux";
import smartHutStore from "./store";
test("redirects to homepage", () => { test("redirects to homepage", () => {
const history = createMemoryHistory(); const history = createMemoryHistory();
render( render(
<Router history={history}> <Router history={history}>
<App /> <Provider store={smartHutStore}>
<App />
</Provider>
</Router> </Router>
); );
expect(history.location.pathname).toBe("/"); expect(history.location.pathname).toBe("/");

View file

@ -1,285 +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 },
});
},
deviceGetById: function (data, headers) {
return axios.get(config + data.device + "/" + data.id);
},
deviceGetAll: function (data, headers) {
return axios.get(config + data.device);
},
smartPlugReset: function (id) {
return axios.delete(config + "smartPlug/" + id + "/meter", {
headers: { Authorization: "Bearer " + tkn },
});
},
};

View file

@ -1,7 +1,9 @@
import React from "react"; import React from "react";
import { Grid, Divider, Button, Label, Responsive } from "semantic-ui-react"; import { Grid, Divider, Button, Label, Responsive } from "semantic-ui-react";
import { Segment, Image } from "semantic-ui-react"; import { Segment, Image } from "semantic-ui-react";
import { call } from "../client_server"; import { RemoteService } from "../remote";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
const IconHomeImage = () => ( const IconHomeImage = () => (
<Image <Image
@ -15,24 +17,24 @@ const IconHomeImage = () => (
const TitleImage = () => <Image src="sm_logo.png" size="medium" centered />; const TitleImage = () => <Image src="sm_logo.png" size="medium" centered />;
export default class MyHeader extends React.Component { export class MyHeader extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = {
username: "",
};
this.getInfo(); this.getInfo();
this.logout = this.logout.bind(this);
} }
logout() {
this.props.logout().then(() => this.props.history.push("/"));
}
getInfo() { getInfo() {
call.getUserInfo(this.state.token).then((res) => { this.props
if (res.status === 200) { .fetchUserInfo()
this.setState({ .catch((err) => console.error("MyHeader fetch user info error", err));
username: res.data.username,
});
}
});
} }
render() { render() {
return ( return (
<div> <div>
@ -52,10 +54,10 @@ export default class MyHeader extends React.Component {
<Grid.Column width={2} heigth={1}> <Grid.Column width={2} heigth={1}>
<Label as="a" image color="black"> <Label as="a" image color="black">
<img alt="SmartHut logo" src="smart-home.png" /> <img alt="SmartHut logo" src="smart-home.png" />
{this.state.username} {this.props.username}
</Label> </Label>
<Divider /> <Divider />
<Button onClick={this.props.logout}>Logout</Button> <Button onClick={this.logout}>Logout</Button>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>
@ -74,10 +76,10 @@ export default class MyHeader extends React.Component {
<Grid.Column> <Grid.Column>
<Label as="a" image color="black"> <Label as="a" image color="black">
<img alt="SmartHut logo" src="smart-home.png" /> <img alt="SmartHut logo" src="smart-home.png" />
{this.state.username} {this.props.username}
</Label> </Label>
<Divider /> <Divider />
<Button onClick={this.props.logout}>Logout</Button> <Button onClick={this.logout}>Logout</Button>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>
@ -86,3 +88,13 @@ export default class MyHeader extends React.Component {
); );
} }
} }
const mapStateToProps = (state, _) => ({
username:
state.userInfo && state.userInfo.username ? state.userInfo.username : "",
});
const LoginContainer = connect(
mapStateToProps,
RemoteService
)(withRouter(MyHeader));
export default LoginContainer;

View file

@ -10,31 +10,50 @@ import {
Image, Image,
} from "semantic-ui-react"; } from "semantic-ui-react";
import SelectIcons from "./SelectIcons"; import SelectIcons from "./SelectIcons";
import { connect } from "react-redux";
import { RemoteService } from "../remote";
import { appActions } from "../storeActions";
import { update } from "immutability-helper";
const NO_IMAGE = "https://react.semantic-ui.com/images/wireframe/image.png"; const NO_IMAGE = "https://react.semantic-ui.com/images/wireframe/image.png";
export default class ModalWindow extends Component { class RoomModal extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = this.initialState;
if (typeof this.props.idRoom === "function") { this.setInitialState();
this.idRoom = this.props.idRoom();
} else {
this.idRoom = this.props.idRoom;
}
this.state = {
id: "",
selectedIcon: "",
name: this.props.type === "new" ? "New Room" : this.idRoom.name,
img: this.props.type === "new" ? null : this.idRoom.image,
openModal: false,
};
this.fileInputRef = React.createRef(); this.fileInputRef = React.createRef();
this.addRoomModal = this.addRoomModal.bind(this); this.addRoomModal = this.addRoomModal.bind(this);
this.updateIcon = this.updateIcon.bind(this); this.updateIcon = this.updateIcon.bind(this);
this.removeImage = this.removeImage.bind(this);
}
get initialState() {
return {
selectedIcon: this.type === "new" ? "home" : this.props.room.icon,
name: this.type === "new" ? "New Room" : this.props.room.name,
img: this.type === "new" ? null : this.props.room.image,
openModal: false,
};
}
removeImage(e) {
e.preventDefault();
this.setState(
update(this.state, {
image: { $set: null },
})
);
}
setInitialState() {
this.setState(this.initialState);
}
get type() {
return !this.props.id ? "new" : "modify";
} }
addRoomModal = (e) => { addRoomModal = (e) => {
@ -43,29 +62,39 @@ export default class ModalWindow extends Component {
name: this.state.name, name: this.state.name,
image: this.state.img, image: this.state.img,
}; };
this.props.addRoom(data);
this.setState({ this.props
name: "Device", .saveRoom(data, null)
}); .then(() => {
this.closeModal(); this.setInitialState();
this.closeModal();
})
.catch((err) => console.error("error in creating room", err));
}; };
modifyRoomModal = (e) => { modifyRoomModal = (e) => {
let data = { let data = {
icon: icon: this.state.selectedIcon,
this.state.selectedIcon === "" name: this.state.name,
? this.idRoom.icon
: this.state.selectedIcon,
name: this.state.name === "" ? this.idRoom.name : this.state.name,
image: this.state.img, image: this.state.img,
}; };
this.props.updateRoom(data);
this.closeModal(); console.log("data", data);
this.props
.saveRoom(data, this.props.id)
.then(() => {
this.setInitialState();
this.closeModal();
})
.catch((err) => console.error("error in updating room", err));
}; };
deleteRoom = (e) => { deleteRoom = (e) => {
this.props.deleteRoom(); this.props
this.closeModal(); .deleteRoom(this.props.id)
.then(() => this.closeModal())
.catch((err) => console.error("error in deleting room", err));
}; };
changeSomething = (event) => { changeSomething = (event) => {
@ -76,7 +105,6 @@ export default class ModalWindow extends Component {
closeModal = (e) => { closeModal = (e) => {
this.setState({ openModal: false }); this.setState({ openModal: false });
this.updateIcon("home");
}; };
openModal = (e) => { openModal = (e) => {
@ -107,7 +135,7 @@ export default class ModalWindow extends Component {
{!this.props.nicolaStop ? ( {!this.props.nicolaStop ? (
<div> <div>
<Responsive minWidth={768}> <Responsive minWidth={768}>
{this.props.type === "new" ? ( {this.type === "new" ? (
<Button <Button
icon icon
labelPosition="left" labelPosition="left"
@ -122,7 +150,7 @@ export default class ModalWindow extends Component {
)} )}
</Responsive> </Responsive>
<Responsive maxWidth={768}> <Responsive maxWidth={768}>
{this.props.type === "new" ? ( {this.type === "new" ? (
<Button <Button
icon icon
fluid fluid
@ -147,9 +175,9 @@ export default class ModalWindow extends Component {
</div> </div>
) : null} ) : null}
<Modal onClose={this.closeModal} open={this.state.openModal}> <Modal closeIcon onClose={this.closeModal} open={this.state.openModal}>
<Header> <Header>
{this.props.type === "new" ? "Add new room" : "Modify room"} {this.type === "new" ? "Add new room" : "Modify room"}
</Header> </Header>
<Modal.Content> <Modal.Content>
<Form> <Form>
@ -167,7 +195,7 @@ export default class ModalWindow extends Component {
<p>Insert an image of the room:</p> <p>Insert an image of the room:</p>
<Form.Field> <Form.Field>
<Image <Image
src={this.state.img == null ? NO_IMAGE : this.state.img} src={!this.state.img ? NO_IMAGE : this.state.img}
size="small" size="small"
onClick={() => this.fileInputRef.current.click()} onClick={() => this.fileInputRef.current.click()}
/> />
@ -182,6 +210,9 @@ export default class ModalWindow extends Component {
onChange={this.getBase64.bind(this)} onChange={this.getBase64.bind(this)}
/> />
</Form.Field> </Form.Field>
{this.state.img ? (
<Button onClick={this.unsetImage}>Remove image</Button>
) : null}
</Form> </Form>
<div style={spaceDiv}> <div style={spaceDiv}>
@ -189,12 +220,12 @@ export default class ModalWindow extends Component {
<SelectIcons <SelectIcons
updateIcon={this.updateIcon} updateIcon={this.updateIcon}
currentIcon={ currentIcon={
this.props.type === "new" ? "home" : this.idRoom.icon this.type === "new" ? "home" : this.props.room.icon
} }
/> />
</div> </div>
{this.props.type === "modify" ? ( {this.type === "modify" ? (
<Button <Button
icon icon
labelPosition="left" labelPosition="left"
@ -210,19 +241,17 @@ export default class ModalWindow extends Component {
<Modal.Actions> <Modal.Actions>
<Button color="red" onClick={this.closeModal}> <Button color="red" onClick={this.closeModal}>
<Icon name="remove" />{" "} <Icon name="remove" />{" "}
{this.props.type === "new" ? "Cancel" : "Discard changes"} {this.type === "new" ? "Cancel" : "Discard changes"}
</Button> </Button>
<Button <Button
color="green" color="green"
onClick={ onClick={
this.props.type === "new" this.type === "new" ? this.addRoomModal : this.modifyRoomModal
? this.addRoomModal
: this.modifyRoomModal
} }
> >
<Icon name="checkmark" />{" "} <Icon name="checkmark" />{" "}
{this.props.type === "new" ? "Add room" : "Save changes"} {this.type === "new" ? "Add room" : "Save changes"}
</Button> </Button>
</Modal.Actions> </Modal.Actions>
</Modal> </Modal>
@ -230,3 +259,18 @@ export default class ModalWindow extends Component {
); );
} }
} }
const setActiveRoom = (activeRoom) => {
return (dispatch) => dispatch(appActions.setActiveRoom(activeRoom));
};
const mapStateToProps = (state, ownProps) => ({
room: ownProps.id ? state.rooms[ownProps.id] : null,
});
const RoomModalContainer = connect(
mapStateToProps,
{ ...RemoteService, setActiveRoom },
null,
{ forwardRef: true }
)(RoomModal);
export default RoomModalContainer;

View file

@ -2,178 +2,39 @@
import React, { Component } from "react"; import React, { Component } from "react";
import { Grid } from "semantic-ui-react"; import { Grid } from "semantic-ui-react";
import { editButtonStyle, panelStyle } from "./devices/styleComponents"; import { panelStyle } from "./devices/styleComponents";
import { checkMaxLength, DEVICE_NAME_MAX_LENGTH } from "./devices/constants"; import Device from "./devices/Device";
import DeviceType from "./devices/DeviceTypeController";
import NewDevice from "./devices/NewDevice"; import NewDevice from "./devices/NewDevice";
import SettingsModal from "./devices/SettingsModal"; import { connect } from "react-redux";
import { call } from "../../client_server"; import { RemoteService } from "../../remote";
export default class DevicePanel extends Component { class DevicePanel extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = {
editMode: false,
};
this.addDevice = this.addDevice.bind(this); this.getDevices();
} }
editModeController = (e) => getDevices() {
this.setState((prevState) => ({ editMode: !prevState.editMode })); this.props
.fetchDevices()
openModal = (settingsDeviceId) => { .catch((err) => console.error(`error fetching devices:`, err));
this.setState((prevState) => ({
openSettingsModal: !prevState.openSettingsModal,
settingsDeviceId: settingsDeviceId,
}));
};
changeDeviceData = (deviceId, newSettings) => {
console.log(newSettings.name, " <-- new name --> ", deviceId);
this.props.devices.map((device) => {
if (device.id === deviceId) {
for (let prop in newSettings) {
if (device.hasOwnProperty(prop)) {
if (prop === "name") {
if (checkMaxLength(newSettings[prop])) {
device[prop] = newSettings[prop];
} else {
alert(
"Name must be less than " +
DEVICE_NAME_MAX_LENGTH +
" characters."
);
}
} else {
device[prop] = newSettings[prop];
}
}
}
}
return null;
});
this.forceUpdate();
};
getDevices = () => {
if (this.props.activeItem === -1) {
call
.getAllDevices()
.then((res) => {
if (res.status === 200) {
this.setState({
devices: res.data,
});
}
})
.catch((err) => {
console.log(err);
});
} else {
call
.getAllDevicesByRoom(this.props.activeItem)
.then((res) => {
if (res.status === 200) {
this.setState({
devices: res.data,
});
}
})
.catch((err) => {});
}
};
async addDevice(data) {
const ds = await this.props.addDevice(data);
this.setState({
devices: ds,
});
this.forceUpdate();
} }
updateDevice = (data) => {
const roomId = this.props.devices.filter(
(d) => d.id === this.state.settingsDeviceId
)[0].roomId;
data["id"] = this.state.settingsDeviceId;
data["roomId"] = roomId;
call
.deviceUpdate(data)
.then((res) => {
if (res.status === 200) {
this.getDevices();
this.forceUpdate();
}
})
.catch((err) => {});
};
removeDevice = () => {
const item = this.props.devices.filter(
(d) => d.id === this.state.settingsDeviceId
)[0];
const data = {
device: item.kind,
id: this.state.settingsDeviceId,
};
call
.deviceDelete(data)
.then((res) => {
if (res.status === 200) {
this.openModal();
this.getDevices();
this.forceUpdate();
}
})
.catch((err) => {});
};
render() { render() {
const edit = {
mode: this.state.editMode,
openModal: this.openModal,
};
/*var backGroundImg =
this.props.activeItem === -1 ? "" : this.props.room.image;*/
const ds = this.state.devices ? this.state.devices : this.props.devices;
return ( return (
<div style={panelStyle}> <div style={panelStyle}>
<button style={editButtonStyle} onClick={this.editModeController}> <Grid doubling columns={2} divided="vertically">
Edit {this.props.devices.map((e, i) => {
</button> return (
<Grid doubling columns={4} divided="vertically"> <Grid.Column key={i}>
{this.state.openSettingsModal ? ( <Device id={e.id} />
<SettingsModal </Grid.Column>
openModal={this.openModal} );
updateDevice={this.updateDevice} })}
removeDevice={this.removeDevice} {!this.props.isActiveRoomHome ? (
device={ds.filter((d) => d.id === this.state.settingsDeviceId)[0]}
/>
) : (
""
)}
{ds
? ds.map((e, i) => {
return (
<Grid.Column key={i}>
<DeviceType
updateDev={this.props.updateDeviceUi}
type={e.kind}
onChangeData={this.changeDeviceData}
device={e}
edit={edit}
/>
</Grid.Column>
);
})
: null}
{this.props.activeItem !== -1 ? (
<Grid.Column> <Grid.Column>
<NewDevice addDevice={this.addDevice} devices={ds} /> <NewDevice />
</Grid.Column> </Grid.Column>
) : null} ) : null}
</Grid> </Grid>
@ -181,3 +42,25 @@ export default class DevicePanel extends Component {
); );
} }
} }
const mapStateToProps = (state, _) => ({
get devices() {
if (state.active.activeRoom === -1) {
return Object.values(state.devices);
} else {
const deviceArray = [
...state.rooms[state.active.activeRoom].devices,
].sort();
return deviceArray.map((id) => state.devices[id]);
}
},
get isActiveRoomHome() {
return state.active.activeRoom === -1;
},
activeRoom: state.active.activeRoom,
});
const DevicePanelContainer = connect(
mapStateToProps,
RemoteService
)(DevicePanel);
export default DevicePanelContainer;

View file

@ -0,0 +1,89 @@
import React from "react";
import Light from "./Light";
import SmartPlug from "./SmartPlug";
import Sensor from "./Sensor";
import { ButtonDimmer, KnobDimmer } from "./Dimmer";
import Switcher from "./Switch";
import { Segment, Grid, Header, Button, Icon } from "semantic-ui-react";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
import DeviceSettingsModal from "./DeviceSettingsModal";
class Device extends React.Component {
constructor(props) {
super(props);
this.modalRef = React.createRef();
this.edit = this.edit.bind(this);
this.resetSmartPlug = this.resetSmartPlug.bind(this);
}
edit() {
console.log("editing device with id=" + this.props.id);
this.modalRef.current.openModal();
}
resetSmartPlug() {
this.props
.smartPlugReset(this.props.id)
.catch((err) => console.error(`Smart plug reset error`, err));
}
renderDeviceComponent() {
switch (this.props.device.kind) {
case "regularLight":
return <Light id={this.props.id} />;
case "sensor":
return <Sensor id={this.props.id} />;
case "motionSensor":
return <Sensor id={this.props.id} />;
case "buttonDimmer":
return <ButtonDimmer id={this.props.id} />;
case "knobDimmer":
return <KnobDimmer id={this.props.id} />;
case "smartPlug":
return <SmartPlug id={this.props.id} />;
case "switch":
return <Switcher id={this.props.id} />;
case "dimmableLight":
return <Light id={this.props.id} />;
default:
throw new Error("Device type unknown");
}
}
render() {
return (
<Segment>
<Grid columns={2}>
<Grid.Column>{this.renderDeviceComponent()}</Grid.Column>
<Grid.Column textAlign="center">
<Header as="h3">{this.props.device.name}</Header>
<Button color="blue" icon onClick={this.edit} labelPosition="left">
<Icon name="pencil" />
Edit
</Button>
{this.props.device.kind === "smartPlug" ? (
<Button
color="orange"
icon
onClick={this.resetSmartPlug}
labelPosition="left"
>
<Icon name="undo" />
Reset
</Button>
) : null}
</Grid.Column>
<DeviceSettingsModal ref={this.modalRef} id={this.props.id} />
</Grid>
</Segment>
);
}
}
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const DeviceContainer = connect(mapStateToProps, RemoteService)(Device);
export default DeviceContainer;

View file

@ -1,26 +0,0 @@
import React, { Component } from "react";
import { editModeIconStyle, editModeStyle } from "./styleComponents";
export default class Settings extends Component {
constructor(props) {
super(props);
this.state = {
displayForm: true,
};
}
displayForm = () => {
this.setState((prevState) => ({ displayForm: !prevState.displayForm }));
};
render() {
const view = (
<div onClick={() => this.props.edit.openModal(this.props.deviceId)}>
<span style={editModeStyle}>
<img src="/img/settings.svg" alt="" style={editModeIconStyle} />
</span>
</div>
);
return <React.Fragment>{this.props.edit.mode ? view : ""}</React.Fragment>;
}
}

View file

@ -1,5 +1,7 @@
import React, { Component, useState } from "react"; import React, { Component, useState } from "react";
import { Button, Checkbox, Form, Icon, Header, Modal } from "semantic-ui-react"; import { Button, Form, Icon, Header, Modal } from "semantic-ui-react";
import { connect } from "react-redux";
import { RemoteService } from "../../../remote";
const DeleteModal = (props) => ( const DeleteModal = (props) => (
<Modal trigger={<Button color="red">Remove</Button>} closeIcon> <Modal trigger={<Button color="red">Remove</Button>} closeIcon>
@ -21,11 +23,6 @@ const SettingsForm = (props) => {
setValues({ ...values, [name]: value }); setValues({ ...values, [name]: value });
}; };
const handleCheckboxChange = (e, d) => {
const { name, checked } = d;
setValues({ ...values, [name]: checked });
};
const [values, setValues] = useState({ name: "" }); const [values, setValues] = useState({ name: "" });
return ( return (
@ -41,18 +38,6 @@ const SettingsForm = (props) => {
/> />
</Form.Field> </Form.Field>
{props.type === "smart-plug" ? (
<Form.Field>
<Checkbox
slider
name={"reset"}
onClick={handleCheckboxChange}
label="Reset Energy Consumption"
/>
</Form.Field>
) : (
""
)}
<Form.Field> <Form.Field>
<DeleteModal removeDevice={() => props.removeDevice(values)} /> <DeleteModal removeDevice={() => props.removeDevice(values)} />
</Form.Field> </Form.Field>
@ -67,41 +52,55 @@ const SettingsForm = (props) => {
); );
}; };
export default class SettingsModal extends Component { class DeviceSettingsModal extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
open: true, open: false,
}; };
this.updateDevice = this.updateDevice.bind(this);
this.deleteDevice = this.deleteDevice.bind(this);
} }
handleClose = () => { openModal() {
this.setState({ open: false }); this.setState({ open: true });
}; }
saveSettings = (device) => { updateDevice(values) {
// TODO Here there should be all the connections to save the data in the backend if (values.name.length === 0) return;
console.log("SAVED: ", device); this.props
if (device.name.length > 0) { .saveDevice({ ...this.props.device, name: values.name })
this.props.updateDevice(device); .then(() => this.setState({ open: false }))
} .catch((err) =>
console.error(
`settings modal for device ${this.props.id} deletion error`,
err
)
);
}
this.props.openModal(); deleteDevice() {
}; this.props
.deleteDevice(this.props.device)
.then(() => this.setState({ open: false }))
.catch((err) =>
console.error(
`settings modal for device ${this.props.id} deletion error`,
err
)
);
}
render() { render() {
const SettingsModal = () => ( const SettingsModal = () => (
<Modal <Modal open={this.state.open}>
open={true}
onOpen={this.props.openModal}
onClose={this.props.openModal}
>
<Modal.Header>Settings of {this.props.device.name}</Modal.Header> <Modal.Header>Settings of {this.props.device.name}</Modal.Header>
<Modal.Content> <Modal.Content>
<SettingsForm <SettingsForm
type={this.props.device.type} type={this.props.device.type}
removeDevice={this.props.removeDevice} removeDevice={this.deleteDevice}
saveFunction={this.saveSettings} saveFunction={this.updateDevice}
/> />
</Modal.Content> </Modal.Content>
</Modal> </Modal>
@ -109,3 +108,14 @@ export default class SettingsModal extends Component {
return <SettingsModal />; return <SettingsModal />;
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const DeviceSettingsModalContainer = connect(
mapStateToProps,
RemoteService,
null,
{ forwardRef: true }
)(DeviceSettingsModal);
export default DeviceSettingsModalContainer;

View file

@ -1,87 +0,0 @@
import React from "react";
import Light from "./Light";
import SmartPlug from "./SmartPlug";
import Sensor from "./Sensor";
import { ButtonDimmer, KnobDimmer } from "./Dimmer";
import Switcher from "./Switch";
const DeviceType = (props) => {
switch (props.type) {
case "regularLight":
return (
<Light
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "sensor":
return (
<Sensor
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "motionSensor":
return (
<Sensor
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "buttonDimmer":
return (
<ButtonDimmer
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "knobDimmer":
return (
<KnobDimmer
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "smartPlug":
return (
<SmartPlug
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "switch":
return (
<Switcher
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
case "dimmableLight":
return (
<Light
updateDev={props.updateDeviceUi}
onChangeData={props.changeDeviceData}
device={props.device}
edit={props.edit}
/>
);
default:
return "";
}
};
export default DeviceType;

View file

@ -1,63 +0,0 @@
/**
* Users can add sensors in their rooms.
* Sensors typically measure physical quantities in a room.
* You must support temperature sensors, humidity sensors, light sensors (which measure luminosity1).
* Sensors have an internal state that cannot be changed by the user.
* For this story, make the sensors return a constant value with some small random error.
*/
import React, { Component } from "react";
import {
CircularInput,
CircularProgress,
CircularTrack,
} from "react-circular-input";
import { errorStyle, sensorText, style, valueStyle } from "./SensorStyle";
import { StyledDiv } from "./styleComponents";
import Settings from "./DeviceSettings";
import { Image } from "semantic-ui-react";
import { imageStyle, nameStyle } from "./DigitalSensorStyle";
export default class DigitalSensor extends Component {
constructor(props) {
super(props);
this.state = {
value: false, // This value is a boolean, was this type of sensor returns presence/absence
};
this.iconOn = "/img/sensorOn.svg";
this.iconOff = "/img/sensorOff.svg";
}
setName = () => {
if (this.props.device.name.length > 15) {
return this.props.device.name.slice(0, 12) + "...";
}
return this.props.device.name;
};
getIcon = () => {
if (this.state.value) {
return this.iconOn;
}
return this.iconOff;
};
componentDidMount() {}
render() {
return (
<StyledDiv>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<Image src={this.getIcon()} style={imageStyle} />
<h5 style={nameStyle}>{this.props.device.name}</h5>
</StyledDiv>
);
}
}

View file

@ -1,17 +0,0 @@
export const imageStyle = {
width: "3.5rem",
height: "auto",
position: "absolute",
top: "20%",
left: "50%",
transform: "translateX(-50%)",
filter: "drop-shadow( 1px 1px 0.5px rgba(0, 0, 0, .25))",
};
export const nameStyle = {
color: "black",
position: "absolute",
top: "40%",
left: "50%",
transform: "translateX(-50%)",
};

View file

@ -19,7 +19,6 @@ import {
PlusPanel, PlusPanel,
ThumbText, ThumbText,
} from "./styleComponents"; } from "./styleComponents";
import Settings from "./DeviceSettings";
import { import {
CircularThumbStyle, CircularThumbStyle,
KnobDimmerStyle, KnobDimmerStyle,
@ -28,52 +27,27 @@ import {
knobIcon, knobIcon,
knobContainer, knobContainer,
} from "./DimmerStyle"; } from "./DimmerStyle";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
import { call } from "../../../client_server"; export class ButtonDimmerComponent extends Component {
export class ButtonDimmer extends Component {
constructor(props) {
super(props);
this.state = {};
}
increaseIntensity = () => { increaseIntensity = () => {
let data = { this.props
dimType: "UP", .buttonDimmerDim(this.props.id, "UP")
id: this.props.device.id, .catch((err) => console.error("button dimmer increase error", err));
};
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
.buttonDimmerDim(this.props.id, "DOWN")
.catch((err) => console.error("button dimmer decrease error", err));
};
render() { render() {
return ( return (
<ButtonDimmerContainer> <ButtonDimmerContainer>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<img alt="icon" src="/img/buttonDimmer.svg" /> <img alt="icon" src="/img/buttonDimmer.svg" />
<span className="knob"> <span className="knob">Button Dimmer</span>
{this.props.device.name} ({this.props.device.id})
</span>
<PlusPanel name="UP" onClick={this.increaseIntensity}> <PlusPanel name="UP" onClick={this.increaseIntensity}>
<span>&#43;</span> <span>&#43;</span>
</PlusPanel> </PlusPanel>
@ -85,49 +59,51 @@ export class ButtonDimmer extends Component {
} }
} }
export class KnobDimmer extends Component { export class KnobDimmerComponent extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
pointingDevices: [], intensity: this.props.device.intensity || 0,
value: 1, timeout: null,
}; };
this.saveIntensity = this.saveIntensity.bind(this);
this.setIntensity = this.setIntensity.bind(this);
} }
setIntensity = (newValue) => { setIntensity(intensity) {
let val = Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100); intensity *= 100;
let data = {
id: this.props.device.id, if (this.state.timeout) {
intensity: val, clearTimeout(this.state.timeout);
}; }
call.deviceUpdate(data, "knobDimmer/dimTo").then((res) => {
if (res.status === 200) {
this.setState({
value: val,
});
}
});
};
componentDidMount() {
this.setState({ this.setState({
value: 1, intensity,
timeout: setTimeout(() => {
this.saveIntensity();
this.setState({
intensity: this.state.intensity,
timeout: null,
});
}, 100),
}); });
} }
saveIntensity() {
const val = Math.round(this.state.intensity);
this.props
.knobDimmerDimTo(this.props.id, val)
.catch((err) => console.error("knob dimmer set intensity error", err));
}
render() { render() {
return ( return (
<div style={knobContainer}> <div style={knobContainer}>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<CircularInput <CircularInput
style={KnobDimmerStyle} style={KnobDimmerStyle}
value={+(Math.round(this.state.value / 100 + "e+2") + "e-2")} value={+(Math.round(this.state.intensity / 100 + "e+2") + "e-2")}
onChange={this.setIntensity} onChange={this.setIntensity}
> >
<text <text
@ -138,10 +114,10 @@ export class KnobDimmer 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.state.intensity + 0.1 }}
/> />
<CircularThumb style={CircularThumbStyle} /> <CircularThumb style={CircularThumbStyle} />
<ThumbText color={"#1a2849"} /> <ThumbText color={"#1a2849"} />
@ -151,3 +127,11 @@ export class KnobDimmer extends Component {
); );
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const conn = connect(mapStateToProps, RemoteService);
export const KnobDimmer = conn(KnobDimmerComponent);
export const ButtonDimmer = conn(ButtonDimmerComponent);

View file

@ -15,7 +15,6 @@ import {
BottomPanel, BottomPanel,
ThumbText, ThumbText,
} from "./styleComponents"; } from "./styleComponents";
import Settings from "./DeviceSettings";
import { Image } from "semantic-ui-react"; import { Image } from "semantic-ui-react";
import { import {
CircularInput, CircularInput,
@ -31,77 +30,73 @@ import {
CircularThumbStyle, CircularThumbStyle,
knobIcon, knobIcon,
} from "./LightStyle"; } from "./LightStyle";
import { call } from "../../../client_server"; import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
export default class Light extends Component { class Light extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = { intensity: this.props.device.intensity, timeout: null };
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) => { this.setIntensity = this.setIntensity.bind(this);
this.setState( }
Object.assign(this.state, {
intensity: e.intensity,
turnedOn: e.on,
})
);
};
call.socketSubscribe(this.props.device.id, this.stateCallback); get turnedOn() {
return this.props.device.on;
}
get intensity() {
return this.props.device.intensity || 0;
} }
onClickDevice = () => { onClickDevice = () => {
this.props.device.on = !this.state.turnedOn; const on = !this.turnedOn;
call.deviceUpdate(this.props.device, "regularLight").then((res) => { this.props
if (res.status === 200) { .saveDevice({ ...this.props.device, on })
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn })); .catch((err) => console.error("regular light update error", err));
}
});
}; };
getIcon = () => { getIcon = () => {
if (this.state.turnedOn) { return this.turnedOn ? this.iconOn : this.iconOff;
return this.iconOn; };
setIntensity(intensity) {
intensity *= 100;
if (this.state.timeout) {
clearTimeout(this.state.timeout);
} }
return this.iconOff;
};
setIntensity = (newValue) => { this.setState({
this.props.device.intensity = intensity,
Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100); timeout: setTimeout(() => {
call.deviceUpdate(this.props.device, "dimmableLight").then((res) => { this.saveIntensity();
if (res.status === 200) {
this.setState({ this.setState({
intensity: intensity: this.state.intensity,
Math.round(newValue * 100) <= 1 ? 1 : Math.round(newValue * 100), timeout: null,
}); });
} }, 100),
}); });
};
get intensity() {
return isNaN(this.state.intensity) ? 0 : this.state.intensity;
} }
saveIntensity = () => {
const intensity = Math.round(this.state.intensity);
this.props
.saveDevice({ ...this.props.device, intensity })
.catch((err) => console.error("intensity light update error", err));
};
render() { render() {
const intensityLightView = ( const intensityLightView = (
<div style={LightDimmerContainer}> <div style={LightDimmerContainer}>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<CircularInput <CircularInput
style={LightDimmerStyle} style={LightDimmerStyle}
value={+(Math.round(this.intensity / 100 + "e+2") + "e-2")} value={+(Math.round(this.state.intensity / 100 + "e+2") + "e-2")}
onChange={this.setIntensity} onChange={this.setIntensity}
onMouseUp={this.saveIntensity}
> >
<text <text
style={textStyle} style={textStyle}
@ -111,12 +106,12 @@ export default 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={{
...KnobProgress, ...KnobProgress,
opacity: this.intensity / 100 + 0.3, opacity: this.state.intensity / 100 + 0.3,
}} }}
/> />
<CircularThumb style={CircularThumbStyle} /> <CircularThumb style={CircularThumbStyle} />
@ -128,19 +123,10 @@ export default class Light extends Component {
const normalLightView = ( const normalLightView = (
<StyledDiv> <StyledDiv>
<Settings <div onClick={this.onClickDevice}>
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
<div onClick={this.props.edit.mode ? () => {} : this.onClickDevice}>
<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}>Light</h5>
{this.props.device.name} ({this.props.device.id})
</h5>
</BottomPanel> </BottomPanel>
</div> </div>
</StyledDiv> </StyledDiv>
@ -155,3 +141,9 @@ export default class Light extends Component {
); );
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const LightContainer = connect(mapStateToProps, RemoteService)(Light);
export default LightContainer;

View file

@ -9,6 +9,8 @@ import {
Input, Input,
Modal, Modal,
} from "semantic-ui-react"; } from "semantic-ui-react";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
const StyledDiv = styled.div` const StyledDiv = styled.div`
background-color: #505bda; background-color: #505bda;
@ -29,7 +31,7 @@ const StyledDiv = styled.div`
} }
`; `;
export default class NewDevice extends Component { class NewDevice extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
@ -86,65 +88,58 @@ export default class NewDevice extends Component {
this.setState({ lightsAttached: d.value }); this.setState({ lightsAttached: d.value });
}; };
createDevice() { async createDevice() {
// Connect to the backend and create device here. // Connect to the backend and create device here.
const data = { const data = {
params: { id: null,
name: this.state.deviceName, roomId: this.props.activeRoom,
}, name: this.state.deviceName,
device: this.state.motion ? "motionSensor" : this.state.typeOfDevice, kind: this.state.motion ? "motionSensor" : this.state.typeOfDevice,
};
let outputs = null;
const defaultNames = {
regularLight: "New regular light",
dimmableLight: "New intensity light",
smartPlug: "New smart Plug",
sensor: "New sensor",
switch: "New switch",
buttonDimmer: "New button dimmer",
knobDimmer: "New knob dimmer",
}; };
if (this.state.deviceName === "") {
data.name = defaultNames[this.state.typeOfDevice];
}
switch (this.state.typeOfDevice) { switch (this.state.typeOfDevice) {
case "regularLight":
if (this.state.deviceName === "") {
data.params["name"] = "Regular Light";
}
break;
case "smartPlug":
if (this.state.deviceName === "") {
data.params["name"] = "Smart Plug";
}
break;
case "dimmableLight": case "dimmableLight":
if (this.state.deviceName === "") { data.intensity = 0;
data.params["name"] = "Dimmable Light";
}
data.params["intensity"] = 0;
break; break;
case "sensor": case "sensor":
if (this.state.deviceName === "") {
data.params["name"] = "Sensor";
}
if (!this.state.motion) { if (!this.state.motion) {
data.params["sensor"] = this.state.typeOfSensor; data.sensor = this.state.typeOfSensor;
data.params["value"] = 0; data.value = 0;
} }
break; break;
case "switch": case "switch":
if (this.state.deviceName === "") {
data.params["name"] = "Switch";
}
data.params["lights"] = this.state.lightsAttached;
break;
case "buttonDimmer": case "buttonDimmer":
if (this.state.deviceName === "") {
data.params["name"] = "Button Dimmer";
}
data.params["lights"] = this.state.lightsAttached;
break;
case "knobDimmer": case "knobDimmer":
if (this.state.deviceName === "") { outputs = this.state.lightsAttached;
data.params["name"] = "Knob Dimmer";
}
data.params["lights"] = this.state.lightsAttached;
break; break;
default: default:
break; break;
} }
this.props.addDevice(data); try {
this.resetState(); let newDevice = await this.props.saveDevice(data);
if (outputs) {
await this.props.connectOutputs(newDevice, outputs);
}
this.resetState();
} catch (e) {
console.error("device creation error: ", e);
}
} }
render() { render() {
@ -376,3 +371,10 @@ export default class NewDevice extends Component {
); );
} }
} }
const mapStateToProps = (state, _) => ({
devices: Object.values(state.devices),
activeRoom: state.active.activeRoom,
});
const NewDeviceContainer = connect(mapStateToProps, RemoteService)(NewDevice);
export default NewDeviceContainer;

View file

@ -35,11 +35,11 @@ import {
humiditySensorColors, humiditySensorColors,
iconSensorStyle, iconSensorStyle,
} from "./SensorStyle"; } from "./SensorStyle";
import Settings from "./DeviceSettings";
import { call } from "../../../client_server";
import { Image } from "semantic-ui-react"; import { Image } from "semantic-ui-react";
import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
export default class Sensor extends Component { class Sensor extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
@ -53,12 +53,6 @@ export default 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 = () => {
@ -131,13 +125,6 @@ export default class Sensor extends Component {
return ( return (
<div style={container}> <div style={container}>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
{this.state.motion ? ( {this.state.motion ? (
<MotionSensor /> <MotionSensor />
) : ( ) : (
@ -185,3 +172,9 @@ export default class Sensor extends Component {
); );
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const SensorContainer = connect(mapStateToProps, RemoteService)(Sensor);
export default SensorContainer;

View file

@ -5,13 +5,7 @@
The user can reset this value. The user can reset this value.
**/ **/
import React, { Component } from "react"; import React, { Component } from "react";
import { import { BottomPanel, StyledDiv } from "./styleComponents";
BottomPanel,
StyledDiv,
editModeIconStyle,
editModeStyleLeft,
} from "./styleComponents";
import Settings from "./DeviceSettings";
import { Image } from "semantic-ui-react"; import { Image } from "semantic-ui-react";
import { import {
energyConsumedStyle, energyConsumedStyle,
@ -19,99 +13,58 @@ import {
kwhStyle, kwhStyle,
nameStyle, nameStyle,
} from "./SmartPlugStyle"; } from "./SmartPlugStyle";
import { call } from "../../../client_server"; import { RemoteService } from "../../../remote";
import { connect } from "react-redux";
export default 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
if (res.status === 200) { .saveDevice({ ...this.props.device, on })
this.setState((prevState) => ({ turnedOn: !prevState.turnedOn })); .catch((err) => console.error("smart plug update error", err));
}
});
};
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.props.edit.mode ? () => {} : this.onClickDevice}> <StyledDiv onClick={this.onClickDevice}>
<Settings
deviceId={this.props.device.id}
edit={this.props.edit}
onChangeData={(id, newSettings) =>
this.props.onChangeData(id, newSettings)
}
/>
{this.props.edit.mode ? (
<span style={editModeStyleLeft} onClick={this.resetSmartPlug}>
<img src="/img/refresh.svg" alt="" style={editModeIconStyle} />
</span>
) : (
""
)}
<Image src={this.getIcon()} style={imageStyle} /> <Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}> <span style={nameStyle}>Smart Plug</span>
{this.props.device.name} ({this.props.device.id})
</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>
); );
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const SmartPlugContainer = connect(mapStateToProps, RemoteService)(SmartPlug);
export default SmartPlugContainer;

View file

@ -7,82 +7,56 @@
import React, { Component } from "react"; import React, { Component } from "react";
import { BottomPanel, StyledDiv } from "./styleComponents"; import { BottomPanel, StyledDiv } from "./styleComponents";
import Settings from "./DeviceSettings";
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 { connect } from "react-redux";
export default 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";
} }
get turnedOn() {
return this.props.device.on;
}
getIcon = () => { getIcon = () => {
if (this.state.turnedOn) { return this.turnedOn ? this.iconOn : this.iconOff;
return this.iconOn;
}
return 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
state = "ON"; .switchOperate(this.props.id, type)
} else { .catch((err) => console.error("switch operate failed", err));
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.props.edit.mode ? () => {} : this.onClickDevice}> <StyledDiv onClick={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} /> <Image src={this.getIcon()} style={imageStyle} />
<span style={nameStyle}> <span style={nameStyle}>Switch</span>
{this.props.device.name} ({this.props.device.id})
</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.turnedOn ? "ON" : "OFF"}</span>
{this.state.turnedOn ? "ON" : "OFF"}
</span>
</BottomPanel> </BottomPanel>
</StyledDiv> </StyledDiv>
); );
} }
} }
const mapStateToProps = (state, ownProps) => ({
device: state.devices[ownProps.id],
});
const SwitchContainer = connect(mapStateToProps, RemoteService)(Switch);
export default SwitchContainer;

19
smart-hut/src/endpoint.js Normal file
View file

@ -0,0 +1,19 @@
/**
* Returns the endpoint URL (SmartHut backend URL)
* @returns {String} endpoint URL
*/
export function endpointURL() {
return window.BACKEND_URL !== "__BACKEND_URL__"
? window.BACKEND_URL
: "http://localhost:8080";
}
export function socketURL(token) {
const httpURL = new URL(endpointURL());
const isSecure = httpURL.protocol === "https:";
const protocol = isSecure ? "wss:" : "ws:";
const port = httpURL.port || (isSecure ? 443 : 80);
const url = `${protocol}//${httpURL.hostname}:${port}/sensor-socket?token=${token}`;
console.log("socket url: ", url);
return url;
}

View file

@ -2,10 +2,14 @@ import React from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import App from "./App"; import App from "./App";
import * as serviceWorker from "./serviceWorker"; import * as serviceWorker from "./serviceWorker";
//React Router import { Provider } from "react-redux";
//import { BrowserRouter, Route, Switch } from "react-router-dom"; import smartHutStore from "./store";
const index = <App />; const index = (
<Provider store={smartHutStore}>
<App />
</Provider>
);
ReactDOM.render(index, document.getElementById("root")); ReactDOM.render(index, document.getElementById("root"));
serviceWorker.unregister(); serviceWorker.unregister();

549
smart-hut/src/remote.js Normal file
View file

@ -0,0 +1,549 @@
import smartHutStore from "./store";
import actions from "./storeActions";
import axios from "axios";
import { endpointURL, socketURL } from "./endpoint";
import { connect, disconnect } from "@giantmachines/redux-websocket";
/**
* An object returned by promise rejections in remoteservice
* @typedef {Error} RemoteError
* @property {String[]} messages a list of user-friendly error messages to show;
*/
class RemoteError extends Error {
messages;
constructor(messages) {
super(messages.join(" - "));
this.messages = messages;
}
}
const Endpoint = {
axiosInstance: axios.create({
baseURL: endpointURL(),
validateStatus: (status) => status >= 200 && status < 300,
}),
/**
* Returns token for current session, null if logged out
* @returns {String|null} the token
*/
get token() {
return smartHutStore.getState().login.token;
},
/**
* Performs an authenticated request
* @param {get|post|put|delete} the desired method
* @param {String} route the desired route (e.g. "/rooms/1/devices")
* @param {[String]String} query query ('?') parameters (no params by default)
* @param {any} body the JSON request body
*/
send: (method, route, query = {}, body = null) => {
if (!Endpoint.token) {
throw new Error("No token while performing authenticated request");
}
return Endpoint.axiosInstance(route, {
method: method,
params: query,
data: ["put", "post"].indexOf(method) !== -1 ? body : null,
headers: {
Authorization: `Bearer ${Endpoint.token}`,
},
}).then((res) => {
if (!res.data && method !== "delete") {
console.error("Response body is empty");
return null;
} else {
return res;
}
});
},
/**
* Performs login
* @param {String} usernameOrEmail
* @param {String} password
* @returns {Promise<String, *>} promise that resolves to the token string
* and rejects to the axios error.
*/
login: (usernameOrEmail, password) => {
return Endpoint.axiosInstance
.post(`/auth/login`, {
usernameOrEmail,
password,
})
.then((res) => {
localStorage.setItem("token", res.data.jwttoken);
localStorage.setItem("exp", new Date().getTime() + 5 * 60 * 60 * 1000);
return res.data.jwttoken;
});
},
/**
* Returns an immediately resolved promise for the socket logouts
* @return {Promise<Undefined, _>} An always-resolved promise
*/
logout: () => {
localStorage.removeItem("token");
localStorage.removeItem("exp");
return Promise.resolve(void 0);
},
/**
* Performs an authenticated GET request
* @param {String} route the desired route (e.g. "/rooms/1/devices")
* @param {[String]String} query query ('?') parameters (no params by default)
* @returns {Promise<*, *>} The Axios-generated promise
*/
get(route, query = {}) {
return this.send("get", route, query);
},
/**
* Performs an authenticated POST request
* @param {String} route the desired route (e.g. "/rooms/1/devices")
* @param {[String]String} query query ('?') parameters (no params by default)
* @param {any} body the JSON request body
* @returns {Promise<*, *>} The Axios-generated promise
*/
post(route, query, body) {
return this.send("post", route, query, body);
},
/**
* Performs an authenticated PUT request
* @param {String} route the desired route (e.g. "/rooms/1/devices")
* @param {[String]String} query query ('?') parameters (no params by default)
* @param {any} body the JSON request body
* @returns {Promise<*, *>} The Axios-generated promise
*/
put(route, query = {}, body = {}) {
return this.send("put", route, query, body);
},
/**
* Performs an authenticated DELETE request
* @param {get|post|put|delete} the desired method
* @param {String} route the desired route (e.g. "/rooms/1/devices")
* @param {[String]String} query query ('?') parameters (no params by default)
* @returns {Promise<*, *>} The Axios-generated promise
*/
delete(route, query = {}) {
return this.send("delete", route, query);
},
};
/**
* Given an error response, returns an array of user
* friendly messages to display to the user
* @param {*} err the Axios error reponse object
* @returns {RemoteError} user friendly error messages
*/
function parseValidationErrors(err) {
if (
err.response &&
err.response.status === 400 &&
err.response.data &&
Array.isArray(err.response.data.errors)
) {
throw new RemoteError([
...new Set(err.response.data.errors.map((e) => e.defaultMessage)),
]);
} else {
console.warn("Non validation error", err);
throw new RemoteError(["Network error"]);
}
}
export const RemoteService = {
/**
* Performs login
* @param {String} usernameOrEmail
* @param {String} password
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
login: (usernameOrEmail, password) => {
return (dispatch) => {
return Endpoint.login(usernameOrEmail, password)
.then((token) => {
dispatch(actions.loginSuccess(token));
dispatch(connect(socketURL(token)));
})
.catch((err) => {
console.warn("login error", err);
throw new RemoteError([
err.response && err.response.status === 401
? "Wrong credentials"
: "An error occurred while logging in",
]);
});
};
},
/**
* Performs logout
*/
logout: () => {
return (dispatch) =>
Endpoint.logout().then(() => {
dispatch(disconnect());
dispatch(actions.logout());
});
},
/**
* Fetches user information via REST calls, if it is logged in
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
fetchUserInfo: () => {
return (dispatch) => {
return Endpoint.get("/auth/profile")
.then((res) => void dispatch(actions.userInfoUpdate(res.data)))
.catch((err) => {
console.warn("Fetch user info error", err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Fetches all rooms that belong to this user. This call does not
* populate the devices attribute in rooms.
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
fetchAllRooms: () => {
return (dispatch) => {
return Endpoint.get("/room")
.then((res) => void dispatch(actions.roomsUpdate(res.data)))
.catch((err) => {
console.error("Fetch all rooms error", err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Fetches all devices in a particular room, or fetches all devices.
* This also updates the devices attribute on values in the map rooms.
* @param {Number|null} roomId the room to which fetch devices
* from, null to fetch from all rooms
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
fetchDevices: (roomId = null) => {
return (dispatch) => {
return Endpoint.get(roomId ? `/room/${roomId}/device` : "/device")
.then((res) => void dispatch(actions.devicesUpdate(roomId, res.data)))
.catch((err) => {
console.error(`Fetch devices roomId=${roomId} error`, err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Creates/Updates a room with the given data
* @param {String} data.name the room's name,
* @param {String} data.icon the room's icon name in SemanticUI icons
* @param {String} data.image ths room's image, as base64
* @param {Number|null} roomId the room's id if update, null for creation
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
saveRoom: (data, roomId = null) => {
return (dispatch) => {
data = {
name: data.name,
icon: data.icon,
image: data.image,
};
return (roomId
? Endpoint.put(`/room/${roomId}`, {}, data)
: Endpoint.post(`/room`, {}, data)
)
.then((res) => void dispatch(actions.roomSave(res.data)))
.catch(parseValidationErrors);
};
},
/**
* Creates/Updates a device with the given data. If
* data.id is truthy, then a update call is performed,
* otherwise a create call is performed. The update URL
* is computed based on data.kind when data.flowType =
* 'OUTPUT', otherwise the PUT "/device" endpoint
* is used for updates and the POST "/<device.kind>"
* endpoints are used for creation.
* @param {Device} data the device to update.
* @returns {Promise<Device, RemoteError>} promise that resolves to the saved device and rejects
* with user-fiendly errors as a RemoteError
*/
saveDevice: (data) => {
return (dispatch) => {
let url = "/device";
if ((data.id && data.flowType === "OUTPUT") || !data.id) {
url = "/" + data.kind;
}
return Endpoint[data.id ? "put" : "post"](url, {}, data)
.then((res) => {
dispatch(actions.deviceSave(res.data));
return res.data;
})
.catch((err) => {
console.warn("Update device: ", data, "error: ", err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Connetcs a series of output devices to an input device.
* Output devices for Switch input can be: Normal Light, Dimmable Light, Smart Plug.
* Output devices for Dimmers input can be: Dimmable Light.
*
* @typedef {"switch" | "buttonDimmer" | "knobDimmer"} ConnectableInput
*
* @param {ConnectableInput} newDevice.kind kind of the input device
* @param {Integer} newDevice.id id of the input device
* @param {Integer[]} outputs ids of the output device
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
connectOutputs: (newDevice, outputs) => {
return (dispatch) => {
let url = `/${newDevice.kind}/${newDevice.id}/lights`;
return Endpoint.post(url, {}, outputs)
.then((res) => {
dispatch(actions.deviceOperationUpdate(res.data));
return res.data;
})
.catch((err) => {
console.warn(
"ConnectOutputs of ",
newDevice.id,
" with outputs: ",
outputs,
"error: ",
err
);
throw new RemoteError(["Network error"]);
});
};
},
_operateInput: (url, getUrl, action) => {
return (dispatch) => {
return Endpoint.put(url, {}, action)
.then(async (res) => {
const inputDevice = await Endpoint.get(getUrl);
delete inputDevice.outputs;
dispatch(
actions.deviceOperationUpdate([...res.data, inputDevice.data])
);
})
.catch((err) => {
console.warn(`${url} error`, err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Changes the state of a switch, by turning it on, off or toggling it.
*
* @typedef {"ON" | "OFF" | "TOGGLE"} SwitchOperation
*
* @param {Number} switchId the switch device id
* @param {SwitchOperation} type the operation to perform on the switch
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
switchOperate: (switchId, type) => {
return RemoteService._operateInput(
"/switch/operate",
`/switch/${switchId}`,
{
type: type.toUpperCase(),
id: switchId,
}
);
},
/**
* Turns a knob dimmer to a specific amount
*
* @param {Number} dimmerId the knob dimmer id
* @param {number} intensity the absolute intensity to dim to. Must be >=0 and <= 100.
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
knobDimmerDimTo: (dimmerId, intensity) => {
return RemoteService._operateInput(
"/knobDimmer/dimTo",
`/knobDimmer/${dimmerId}`,
{
intensity,
id: dimmerId,
}
);
},
/**
* Turns a button dimmer up or down
*
* @typedef {"UP" | "DOWN"} ButtonDimmerDimType
*
* @param {Number} dimmerId the button dimmer id
* @param {ButtonDimmerDimType} dimType the type of dim to perform
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
buttonDimmerDim: (dimmerId, dimType) => {
return RemoteService._operateInput(
"/buttonDimmer/dim",
`/buttonDimmer/${dimmerId}`,
{
dimType,
id: dimmerId,
}
);
},
/**
* Resets the meter on a smart plug
*
* @param {Number} smartPlugId the smart plug to reset
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
smartPlugReset(smartPlugId) {
return (dispatch) => {
return Endpoint.delete(`/smartPlug/${smartPlugId}/meter`)
.then((res) => dispatch(actions.deviceOperationUpdate([res.data])))
.catch((err) => {
console.warn(`Smartplug reset error`, err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Deletes a room
* @param {Number} roomId the id of the room to delete
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
deleteRoom: (roomId) => {
return (dispatch) => {
return Endpoint.delete(`/room/${roomId}`)
.then((_) => dispatch(actions.roomDelete(roomId)))
.catch((err) => {
console.warn("Room deletion error", err);
throw new RemoteError(["Network error"]);
});
};
},
/**
* Deletes a device
* @param {Device} device the device to delete
* @returns {Promise<Undefined, RemoteError>} promise that resolves to void and rejects
* with user-fiendly errors as a RemoteError
*/
deleteDevice: (device) => {
return (dispatch) => {
return Endpoint.delete(`/${device.kind}/${device.id}`)
.then((_) => dispatch(actions.deviceDelete(device.id)))
.catch((err) => {
console.warn("Device deletion error", err);
throw new RemoteError(["Network error"]);
});
};
},
};
for (const key in RemoteService) {
RemoteService[key] = RemoteService[key].bind(RemoteService);
}
export class Forms {
/**
* Attempts to create a new user from the given data.
* This method does not update the global state,
* please check its return value.
* @param {String} data.username the chosen username
* @param {String} data.password the chosen password
* @param {String} data.email the chosen email
* @param {String} data.name the chosen full name
* @returns {Promise<Undefined, String[]>} promise that resolves to void and rejects
* with validation errors as a String array
*/
static submitRegistration(data) {
return Endpoint.post(
"/register",
{},
{
username: data.username,
password: data.password,
name: data.name,
email: data.email,
}
)
.then((_) => void 0)
.catch(parseValidationErrors);
}
/**
* Sends a request to perform a password reset.
* This method does not update the global state,
* please check its return value.
* @param {String} email the email to which perform the reset
* @returns {Promise<Undefined, String[]>} promise that resolves to void and rejects
* with validation errors as a String array
*/
static submitInitResetPassword(email) {
return Endpoint.post(
"/register/init-reset-password",
{},
{
email: email,
}
)
.then((_) => void 0)
.catch((err) => {
console.warn("Init reset password failed", err);
throw new RemoteError(["Network error"]);
});
}
/**
* Sends the password for the actual password reset, haviug already
* 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(confirmationToken, password) {
return Endpoint.post(
"/register/reset-password",
{},
{
confirmationToken,
password,
}
)
.then((_) => void 0)
.catch(parseValidationErrors);
}
}

299
smart-hut/src/store.js Normal file
View file

@ -0,0 +1,299 @@
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import update from "immutability-helper";
import reduxWebSocket, { connect } from "@giantmachines/redux-websocket";
import { socketURL } from "./endpoint";
function reducer(previousState, action) {
let newState, change;
const createOrUpdateRoom = (room) => {
if (!newState.rooms[room.id]) {
newState = update(newState, {
rooms: { [room.id]: { $set: { ...room, devices: new Set() } } },
});
} else {
newState = update(newState, {
rooms: {
[room.id]: {
name: { $set: room.name },
image: { $set: room.image },
icon: { $set: room.icon },
},
},
});
}
if (newState.pendingJoins.rooms[room.id]) {
newState = update(newState, {
pendingJoins: { rooms: { $unset: [room.id] } },
rooms: {
[room.id]: {
devices: {
$add: [...newState.pendingJoins.rooms[room.id]],
},
},
},
});
}
};
const updateDeviceProps = (device) => {
// In some updates the information regarding a device is incomplete
// due to a fault in the type system and JPA repository management
// in the backend. Therefore to solve this avoid to delete existing
// attributes of this device in the previous state, but just update
// the new ones.
change.devices[device.id] = {};
for (const key in device) {
change.devices[device.id][key] = { $set: device[key] };
}
};
switch (action.type) {
case "LOGIN_UPDATE":
newState = update(previousState, { login: { $set: action.login } });
break;
case "USER_INFO_UPDATE":
newState = update(previousState, { userInfo: { $set: action.userInfo } });
break;
case "ROOMS_UPDATE":
newState = previousState;
for (const room of action.rooms) {
createOrUpdateRoom(room);
}
break;
case "DEVICES_UPDATE":
change = null;
// if room is given, delete all devices in that room
// and remove any join between that room and deleted
// devices
if (action.roomId) {
change = {
rooms: { [action.roomId]: { devices: { $set: new Set() } } },
devices: { $unset: [] },
};
const room = newState.rooms[action.roomId];
for (const deviceId of room.devices) {
change.devices.$unset.push(deviceId);
}
} else if (action.partial) {
// if the update is partial and caused by an operation on an input
// device (like /switch/operate), iteratively remove deleted
// devices and their join with their corresponding room.
change = {
devices: { $unset: [] },
rooms: {},
};
for (const device of action.devices) {
const roomId = previousState.devices[device.id].roomId;
change.rooms[roomId] = change.rooms[roomId] || {
devices: { $remove: [] },
};
change.rooms[roomId].devices.$remove.push(device.id);
change.devices.$unset.push(device.id);
}
} else {
// otherwise, just delete all devices and all joins
// between rooms and devices
change = {
devices: { $set: {} },
rooms: {},
};
for (const room of Object.values(previousState.rooms)) {
if (change.rooms[room.id]) {
change.rooms[room.id].devices = { $set: new Set() };
}
}
}
newState = update(previousState, change);
change = {
devices: {},
rooms: {},
pendingJoins: { rooms: {} },
};
for (const device of action.devices) {
if (!newState.devices[device.id]) {
change.devices[device.id] = { $set: device };
} else {
updateDeviceProps(device);
}
if (device.roomId in newState.rooms) {
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);
} else {
// room does not exist yet, so add to the list of pending
// joins
if (!change.pendingJoins.rooms[device.roomId]) {
change.pendingJoins.rooms[device.roomId] = {
$set: new Set([device.id]),
};
} else {
change.pendingJoins.rooms[device.roomId].$set.add(device.id);
}
}
}
newState = update(newState, change);
break;
case "ROOM_SAVE":
newState = previousState;
createOrUpdateRoom(action.room);
break;
case "DEVICE_SAVE":
change = {
devices: { [action.device.id]: { $set: action.device } },
};
if (previousState.rooms[action.device.roomId]) {
change.rooms = {
[action.device.roomId]: {
devices: {
$add: [action.device.id],
},
},
};
} else {
change.pendingJoins = {
rooms: {
[action.device.roomId]: {
$add: [action.device.id],
},
},
};
}
newState = update(previousState, change);
break;
case "ROOM_DELETE":
if (!(action.roomId in previousState.rooms)) {
console.warn(`Room to delete ${action.roomId} does not exist`);
break;
}
// This update does not ensure the consistent update of switchId/dimmerId properties
// on output devices connected to an input device in this room. Please manually request
// all devices again if consistent update is desired
change = { devices: { $unset: [] } };
for (const id of previousState.rooms[action.roomId].devices) {
change.devices.$unset.push(id);
}
change.rooms = { $unset: [action.roomId] };
if (previousState.active.activeRoom === action.roomId) {
change.active = { activeRoom: { $set: -1 } };
}
newState = update(previousState, change);
break;
case "DEVICE_DELETE":
if (!(action.deviceId in previousState.devices)) {
console.warn(`Device to delete ${action.deviceId} does not exist`);
break;
}
change = {
devices: { $unset: [action.deviceId] },
};
if (previousState.rooms[previousState.devices[action.deviceId].roomId]) {
change.rooms = {
[previousState.devices[action.deviceId].roomId]: {
devices: { $remove: [action.deviceId] },
},
};
}
newState = update(previousState, change);
break;
case "LOGOUT":
newState = update(initState, {});
break;
case "SET_ACTIVE_ROOM":
newState = update(previousState, {
active: {
activeRoom: {
$set: action.activeRoom,
},
},
});
break;
case "REDUX_WEBSOCKET::MESSAGE":
const devices = JSON.parse(action.payload.message);
console.log(devices);
newState = reducer(previousState, {
type: "DEVICES_UPDATE",
partial: true,
devices,
});
break;
default:
console.warn(`Action type ${action.type} unknown`, action);
return previousState;
}
return newState;
}
const initState = {
errors: {},
pendingJoins: {
rooms: {},
},
active: {
activeRoom: -1,
},
login: {
loggedIn: false,
token: null,
},
userInfo: null,
/** @type {[integer]Room} */
rooms: {},
/** @type {[integer]Device} */
devices: {},
};
function createSmartHutStore() {
const token = localStorage.getItem("token");
const exp = localStorage.getItem("exp");
const initialState = update(initState, {
login: {
token: { $set: token },
loggedIn: { $set: !!(token && exp > new Date().getTime()) },
},
});
if (!initialState.login.loggedIn) {
localStorage.removeItem("token");
localStorage.removeItem("exp");
initialState.login.token = null;
}
const store = createStore(
reducer,
initialState,
compose(applyMiddleware(thunk), applyMiddleware(reduxWebSocket()))
);
if (initialState.login.loggedIn) {
store.dispatch(connect(socketURL(token)));
}
return store;
}
const smartHutStore = createSmartHutStore();
export default smartHutStore;

View file

@ -0,0 +1,57 @@
const actions = {
loginSuccess: (token) => ({
type: "LOGIN_UPDATE",
login: {
loggedIn: true,
token,
},
}),
logout: () => ({
type: "LOGOUT",
}),
userInfoUpdate: (userInfo) => ({
type: "USER_INFO_UPDATE",
userInfo,
}),
roomSave: (room) => ({
type: "ROOM_SAVE",
room,
}),
deviceSave: (device) => ({
type: "DEVICE_SAVE",
device,
}),
devicesUpdate: (roomId, devices, partial = false) => ({
type: "DEVICES_UPDATE",
roomId,
devices,
partial,
}),
deviceOperationUpdate: (devices) => ({
type: "DEVICES_UPDATE",
devices,
partial: true,
}),
roomsUpdate: (rooms) => ({
type: "ROOMS_UPDATE",
rooms,
}),
roomDelete: (roomId) => ({
type: "ROOM_DELETE",
roomId,
}),
deviceDelete: (deviceId) => ({
type: "DEVICE_DELETE",
deviceId,
}),
};
export const appActions = {
// -1 for home view
setActiveRoom: (activeRoom = -1) => ({
type: "SET_ACTIVE_ROOM",
activeRoom,
}),
};
export default actions;

View file

@ -2,191 +2,9 @@ import React, { Component } from "react";
import DevicePanel from "../components/dashboard/DevicePanel"; import DevicePanel from "../components/dashboard/DevicePanel";
import Navbar from "./Navbar"; import Navbar from "./Navbar";
import MyHeader from "../components/HeaderController"; import MyHeader from "../components/HeaderController";
import { call } from "../client_server";
import { Grid, Responsive } from "semantic-ui-react"; import { Grid, Responsive } from "semantic-ui-react";
/*
rooms -> actual rooms
activeItem -> the current room in view
devices -> current device in current room view
id of Home is -1
*/
export default class Dashboard extends Component { export default class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
rooms: [],
activeItem: -1,
devices: [],
image: "",
tkn: this.props.tkn,
};
this.addRoom = this.addRoom.bind(this);
this.deleteRoom = this.deleteRoom.bind(this);
this.updateRoom = this.updateRoom.bind(this);
this.addDevice = this.addDevice.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
}
getDevices() {
if (this.state.activeItem === -1) {
call
.getAllDevices()
.then((res) => {
if (res.status === 200) {
//console.log(res.data);
this.setState({
devices: res.data,
});
}
})
.catch((err) => {
//console.log(err);
});
} else {
call
.getAllDevicesByRoom(this.state.activeItem)
.then((res) => {
if (res.status === 200) {
//console.log(res.data);
this.setState({
devices: res.data,
});
}
})
.catch((err) => {});
}
}
getRooms() {
call
.getAllRooms(this.props.tkn)
.then((res) => {
this.setState({
rooms: res.data,
});
})
.catch((err) => {});
}
componentDidMount() {
this.getRooms();
this.getDevices();
}
addRoom(data) {
call
.createRoom(data)
.then((res) => {
if (res.status === 200 && res.data) {
this.getRooms();
this.handleItemClick(-1);
}
})
.catch((err) => {
//console.log(err);
});
}
deleteRoom() {
let data = {
id: this.state.activeItem,
};
call
.deleteRoom(data)
.then((res) => {
//remove room in state.rooms
this.getRooms();
this.setState({
activeItem: -1,
});
this.handleItemClick(-1);
})
.catch((err) => {
//console.log(err);
});
}
updateRoom(data) {
data.id = this.state.activeItem;
call
.updateRoom(data)
.then((res) => {
if (res.status === 200 && res.data) {
this.getRooms();
this.forceUpdate();
}
})
.catch((err) => {});
}
handleItemClick(id) {
this.setState({
activeItem: id,
});
if (id === -1) {
call
.getAllDevices(this.props.tkn)
.then((res) => {
if (res.status === 200) {
this.setState({
devices: res.data,
});
}
})
.catch((err) => {
//console.log(err);
});
} else {
call
.getAllDevicesByRoom(id, this.props.tkn)
.then((res) => {
if (res.status === 200) {
this.setState({
devices: res.data,
});
this.forceUpdate();
}
})
.catch((err) => {
//console.log(err);
});
}
this.state.rooms.forEach((item) => {
if (item.id === id) {
this.setState({ room: item });
}
});
}
addDevice(data) {
data.params["roomId"] = this.state.activeItem;
call
.devicePost(data, this.props.tkn)
.then((res) => {
this.getDevices();
})
.catch((err) => {});
}
updateDeviceUi = (data) => {
let ds = this.state.devices;
ds.forEach((e) => {
if (e.id === data.id) {
e = data;
}
});
this.setState({
devices: ds,
});
return;
};
render() { render() {
return ( return (
<div style={{ height: "110vh", background: "#1b1c1d" }}> <div style={{ height: "110vh", background: "#1b1c1d" }}>
@ -194,29 +12,16 @@ export default class Dashboard extends Component {
<Grid> <Grid>
<Grid.Row color="black"> <Grid.Row color="black">
<Grid.Column> <Grid.Column>
<MyHeader logout={this.props.logout} /> <MyHeader />
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
<Grid.Row color="black"> <Grid.Row color="black">
<Grid.Column width={3}> <Grid.Column width={3}>
<Navbar <Navbar />
activeItem={this.state.activeItem}
addRoom={this.addRoom}
updateRoom={this.updateRoom}
deleteRoom={this.deleteRoom}
rooms={this.state.rooms}
handleItemClick={this.handleItemClick}
/>
</Grid.Column> </Grid.Column>
<Grid.Column width={13}> <Grid.Column width={13}>
<DevicePanel <DevicePanel />
tkn={this.props.tkn}
activeItem={this.state.activeItem}
addDevice={this.addDevice}
devices={this.state.devices}
room={this.state.room}
/>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>
@ -225,32 +30,17 @@ export default class Dashboard extends Component {
<Grid inverted> <Grid inverted>
<Grid.Row color="black"> <Grid.Row color="black">
<Grid.Column> <Grid.Column>
<MyHeader logout={this.props.logout} /> <MyHeader />
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
<Grid.Row color="black"> <Grid.Row color="black">
<Grid.Column color="black"> <Grid.Column color="black">
<Navbar <Navbar />
activeItem={this.state.activeItem}
addRoom={this.addRoom}
updateRoom={this.updateRoom}
deleteRoom={this.deleteRoom}
rooms={this.state.rooms}
handleItemClick={this.handleItemClick}
/>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
<Grid.Row> <Grid.Row>
<Grid.Column> <Grid.Column>
<DevicePanel <DevicePanel />
img={this.state.image}
tkn={this.props.tkn}
activeItem={this.state.activeItem}
addDevice={this.addDevice}
devices={this.state.devices}
updateDev={this.updateDeviceUi}
room={this.state.room}
/>
</Grid.Column> </Grid.Column>
</Grid.Row> </Grid.Row>
</Grid> </Grid>

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,13 @@ 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) =>
if (res.status === 200) { this.setState({
this.setState({ success: true }); error: { state: true, message: err.messages.join(" - ") },
} 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,12 @@ 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) =>
if (res.status === 200) { this.setState({ error: { state: true, message: err.messages } })
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

@ -9,8 +9,11 @@ import {
Icon, Icon,
Input, Input,
} from "semantic-ui-react"; } from "semantic-ui-react";
import { RemoteService } from "../remote";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
export default class Login extends Component { class Login extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
@ -23,31 +26,15 @@ export default class Login extends Component {
handleLogin = (e) => { handleLogin = (e) => {
e.preventDefault(); e.preventDefault();
const params = {
usernameOrEmail: this.state.user,
password: this.state.password,
};
this.props this.props
.auth({ .login(this.state.user, this.state.password)
user: this.state.user, .then(() => this.props.history.push("/dashboard"))
params: params,
})
.then((res) => {
if (res.response.status === 200) {
} else if (res.response.status === 401) {
this.setState({
error: { state: true, message: "Wrong credentials" },
});
} else {
console.log(res);
this.setState({
error: { state: true, message: "An error occurred while logging" },
});
}
})
.catch((err) => { .catch((err) => {
console.log(err); console.log(err);
this.setState({
error: { state: true, message: err.messages.join(" - ") },
});
}); });
}; };
@ -127,3 +114,10 @@ export default class Login extends Component {
); );
} }
} }
const mapStateToProps = (state, _) => ({ loggedIn: state.login.loggedIn });
const LoginContainer = connect(
mapStateToProps,
RemoteService
)(withRouter(Login));
export default LoginContainer;

View file

@ -8,46 +8,55 @@ import {
Dropdown, Dropdown,
} from "semantic-ui-react"; } from "semantic-ui-react";
import { editButtonStyle } from "../components/dashboard/devices/styleComponents"; import { editButtonStyle } from "../components/dashboard/devices/styleComponents";
import ModalWindow from "../components/modalform"; import RoomModal from "../components/RoomModal";
import { RemoteService } from "../remote";
import { connect } from "react-redux";
import { appActions } from "../storeActions";
class Navbar extends Component { class Navbar extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
activeItemName: "Home",
activeItem: -1,
edited: "",
editMode: false, editMode: false,
room: "",
}; };
this.roomRefs = {}; this.toggleEditMode = this.toggleEditMode.bind(this);
this.props.rooms.forEach((e) => { this.selectRoom = this.selectRoom.bind(this);
this.roomRefs[e.id] = React.createRef(); this.openCurrentModalMobile = this.openCurrentModalMobile.bind(this);
});
this.getRooms();
} }
componentDidMount() { getRooms() {
this.setState({ this.props.fetchAllRooms().catch(console.error);
activeItem: this.props.activeItem,
});
} }
editModeController = (e) => get activeItem() {
return this.props.activeRoom;
}
set activeItem(item) {
this.props.setActiveRoom(item);
}
get activeItemName() {
if (this.props.activeRoom === -1) return "Home";
return this.props.rooms[this.props.activeRoom].name;
}
openCurrentModalMobile() {
console.log(this.activeItem, this.props.roomModalRefs);
const currentModal = this.props.roomModalRefs[this.activeItem].current;
currentModal.openModal();
}
toggleEditMode(e) {
this.setState((prevState) => ({ editMode: !prevState.editMode })); this.setState((prevState) => ({ editMode: !prevState.editMode }));
}
handleClick = (e, { id, name }) => { selectRoom(e, { id }) {
const room = this.props.rooms.filter((d) => d.id === id)[0]; this.activeItem = id || -1;
//console.log(room); }
this.setState({
activeItem: id,
activeItemName: name,
});
this.activeRoom = room;
//console.log(this.activeRoom);
this.forceUpdate();
this.props.handleItemClick(id);
};
render() { render() {
return ( return (
@ -55,7 +64,7 @@ class Navbar extends Component {
<Responsive minWidth={768}> <Responsive minWidth={768}>
<Grid> <Grid>
<Grid.Row color="black"> <Grid.Row color="black">
<button style={editButtonStyle} onClick={this.editModeController}> <button style={editButtonStyle} onClick={this.toggleEditMode}>
Edit Edit
</button> </button>
</Grid.Row> </Grid.Row>
@ -63,10 +72,10 @@ class Navbar extends Component {
<Menu inverted fluid vertical> <Menu inverted fluid vertical>
<Menu.Item <Menu.Item
key={-1} key={-1}
id={-1} id={null}
name="Home" name="Home"
active={this.state.activeItem === -1} active={this.activeItem === -1}
onClick={this.handleClick} onClick={this.selectRoom}
> >
<Grid> <Grid>
<Grid.Row> <Grid.Row>
@ -78,46 +87,36 @@ class Navbar extends Component {
</Grid> </Grid>
</Menu.Item> </Menu.Item>
{this.props.rooms {Object.values(this.props.rooms).map((e, i) => {
? this.props.rooms.map((e, i) => { return (
return ( <Menu.Item
<Menu.Item id={e.id}
id={e.id} key={i}
key={i} name={e.name}
name={e.name} active={this.activeItem === e.id}
active={this.state.activeItem === e.id} onClick={this.selectRoom}
onClick={this.handleClick} >
> <Grid>
<Grid> <Grid.Row>
<Grid.Row> <Grid.Column>
<Grid.Column> <Icon name={e.icon} size="small" />
<Icon name={e.icon} size="small" /> </Grid.Column>
</Grid.Column> <Grid.Column width={8}>{e.name}</Grid.Column>
<Grid.Column width={8}>{e.name}</Grid.Column> <Grid.Column floated="right">
<Grid.Column floated="right"> {this.state.editMode ? (
{this.state.editMode ? ( <RoomModal id={e.id} />
<ModalWindow ) : null}
type="modify" </Grid.Column>
idRoom={e} </Grid.Row>
updateRoom={this.props.updateRoom} </Grid>
deleteRoom={this.props.deleteRoom} </Menu.Item>
/> );
) : null} })}
</Grid.Column>
</Grid.Row>
</Grid>
</Menu.Item>
);
})
: null}
<Menu.Item <Menu.Item name="newM">
name="newM"
active={this.state.activeItem === "newM"}
>
<Grid> <Grid>
<Grid.Row centered name="new"> <Grid.Row centered name="new">
<ModalWindow type="new" addRoom={this.props.addRoom} /> <RoomModal id={null} />
</Grid.Row> </Grid.Row>
</Grid> </Grid>
</Menu.Item> </Menu.Item>
@ -128,14 +127,14 @@ class Navbar extends Component {
<Responsive maxWidth={768}> <Responsive maxWidth={768}>
<Menu> <Menu>
<Dropdown item fluid text={this.state.activeItemName}> <Dropdown item fluid text={this.activeItemName}>
<Dropdown.Menu> <Dropdown.Menu>
<Dropdown.Item <Dropdown.Item
key={-1} key={-1}
id={-1} id={null}
name="Home" name="Home"
active={this.state.activeItem === "Home"} active={this.activeItem === -1}
onClick={this.handleClick} onClick={this.selectRoom}
> >
<Grid> <Grid>
<Grid.Row> <Grid.Row>
@ -147,55 +146,46 @@ class Navbar extends Component {
</Grid> </Grid>
</Dropdown.Item> </Dropdown.Item>
{this.props.rooms {Object.values(this.props.rooms).map((e, i) => {
? this.props.rooms.map((e, i) => { return (
if (!this.roomRefs[e.id]) <Dropdown.Item
this.roomRefs[e.id] = React.createRef(); id={e.id}
return ( key={i}
<Dropdown.Item name={e.name}
id={e.id} active={this.activeItem === e.id}
key={i} onClick={this.selectRoom}
name={e.name} >
active={this.state.activeItem === e.id} <Grid>
onClick={this.handleClick} <Grid.Row>
> <Grid.Column width={1}>
<Grid> <Icon name={e.icon} size="small" />
<Grid.Row> </Grid.Column>
<Grid.Column width={1}> <Grid.Column>{e.name}</Grid.Column>
<Icon name={e.icon} size="small" /> </Grid.Row>
</Grid.Column> </Grid>
<Grid.Column>{e.name}</Grid.Column> <RoomModal
</Grid.Row> ref={this.props.roomModalRefs[e.id]}
</Grid> nicolaStop={true}
<ModalWindow id={e.id}
ref={this.roomRefs[e.id]} />
type="modify" </Dropdown.Item>
nicolaStop={true} );
idRoom={e} })}
updateRoom={this.props.updateRoom}
deleteRoom={this.props.deleteRoom}
/>
</Dropdown.Item>
);
})
: null}
</Dropdown.Menu> </Dropdown.Menu>
</Dropdown> </Dropdown>
</Menu> </Menu>
<Grid inverted> <Grid inverted>
<Grid.Row> <Grid.Row>
<Grid.Column width={8}> <Grid.Column width={8}>
<ModalWindow type="new" addRoom={this.props.addRoom} /> <RoomModal id={null} />
</Grid.Column> </Grid.Column>
{this.state.activeItem !== -1 ? ( {this.activeItem !== -1 ? (
<Grid.Column width={8}> <Grid.Column width={8}>
<Button <Button
icon icon
fluid fluid
labelPosition="left" labelPosition="left"
onClick={() => onClick={this.openCurrentModalMobile}
this.roomRefs[this.state.activeItem].current.openModal()
}
> >
<Icon name="pencil" size="small" /> <Icon name="pencil" size="small" />
EDIT ROOM EDIT ROOM
@ -210,4 +200,20 @@ class Navbar extends Component {
} }
} }
export default Navbar; const setActiveRoom = (activeRoom) => {
return (dispatch) => dispatch(appActions.setActiveRoom(activeRoom));
};
const mapStateToProps = (state, _) => ({
rooms: state.rooms,
activeRoom: state.active.activeRoom,
roomModalRefs: Object.keys(state.rooms).reduce(
(acc, key) => ({ ...acc, [key]: React.createRef() }),
{}
),
});
const NavbarContainer = connect(mapStateToProps, {
...RemoteService,
setActiveRoom,
})(Navbar);
export default NavbarContainer;

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,11 @@ export default class Signup extends Component {
username: this.state.username, username: this.state.username,
}; };
call Forms.submitRegistration(params)
.register(params) .then(() => this.setState({ success: true }))
.then((res) => { .catch((err) =>
if (res.status === 200 && res.data) { 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) => {

View file

@ -973,6 +973,13 @@
resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.7.5.tgz#77211291c1900a700b8a78cfafda3160d76949ed" resolved "https://registry.yarnpkg.com/@emotion/unitless/-/unitless-0.7.5.tgz#77211291c1900a700b8a78cfafda3160d76949ed"
integrity sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg== integrity sha512-OWORNpfjMsSSUBVrRBVGECkhWcULOAJz9ZW8uK9qgxD+87M7jHRcvh/A96XXNhXTLmKcoYSQtBEX7lHMO7YRwg==
"@giantmachines/redux-websocket@^1.1.7":
version "1.1.7"
resolved "https://registry.yarnpkg.com/@giantmachines/redux-websocket/-/redux-websocket-1.1.7.tgz#8c045a359cd3f9a73ef141ce722fd14ae754cd1b"
integrity sha512-t90k+NcVInXvppMVpU3c7ZC6i58S/jBPqltckAlKfrtc92YmGZ/He3qYT9OiemlvS+/d+R6P/Ed4yEqKVevYdg==
dependencies:
redux "~4"
"@hapi/address@2.x.x": "@hapi/address@2.x.x":
version "2.1.4" version "2.1.4"
resolved "https://registry.yarnpkg.com/@hapi/address/-/address-2.1.4.tgz#5d67ed43f3fd41a69d4b9ff7b56e7c0d1d0a81e5" resolved "https://registry.yarnpkg.com/@hapi/address/-/address-2.1.4.tgz#5d67ed43f3fd41a69d4b9ff7b56e7c0d1d0a81e5"
@ -5011,7 +5018,7 @@ hmac-drbg@^1.0.0:
minimalistic-assert "^1.0.0" minimalistic-assert "^1.0.0"
minimalistic-crypto-utils "^1.0.1" minimalistic-crypto-utils "^1.0.1"
hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.1.0, hoist-non-react-statics@^3.2.1, hoist-non-react-statics@^3.3.2: hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.1.0, hoist-non-react-statics@^3.2.1, hoist-non-react-statics@^3.3.0, hoist-non-react-statics@^3.3.2:
version "3.3.2" version "3.3.2"
resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45" resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz#ece0acaf71d62c2969c2ec59feff42a4b1a85b45"
integrity sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw== integrity sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==
@ -5228,6 +5235,13 @@ immer@1.10.0:
resolved "https://registry.yarnpkg.com/immer/-/immer-1.10.0.tgz#bad67605ba9c810275d91e1c2a47d4582e98286d" resolved "https://registry.yarnpkg.com/immer/-/immer-1.10.0.tgz#bad67605ba9c810275d91e1c2a47d4582e98286d"
integrity sha512-O3sR1/opvCDGLEVcvrGTMtLac8GJ5IwZC4puPrLuRj3l7ICKvkmA0vGuU9OW8mV9WIBRnaxp5GJh9IEAaNOoYg== integrity sha512-O3sR1/opvCDGLEVcvrGTMtLac8GJ5IwZC4puPrLuRj3l7ICKvkmA0vGuU9OW8mV9WIBRnaxp5GJh9IEAaNOoYg==
immutability-helper@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/immutability-helper/-/immutability-helper-3.0.2.tgz#e9187158b47c93368a92e84c31714c4b3dff30b0"
integrity sha512-fcrJ26wpvUcuGRpoGY4hyQ/JOeR1HAunMmE3C0XYXSe6plAGtgTlB2S4BzueBANCPrDJ7AByL1yrIRLIlVfwpA==
dependencies:
invariant "^2.2.4"
import-cwd@^2.0.0: import-cwd@^2.0.0:
version "2.1.0" version "2.1.0"
resolved "https://registry.yarnpkg.com/import-cwd/-/import-cwd-2.1.0.tgz#aa6cf36e722761285cb371ec6519f53e2435b0a9" resolved "https://registry.yarnpkg.com/import-cwd/-/import-cwd-2.1.0.tgz#aa6cf36e722761285cb371ec6519f53e2435b0a9"
@ -8747,6 +8761,11 @@ react-is@^16.8.1, react-is@^16.8.4:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.12.0.tgz#2cc0fe0fba742d97fd527c42a13bec4eeb06241c" resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.12.0.tgz#2cc0fe0fba742d97fd527c42a13bec4eeb06241c"
integrity sha512-rPCkf/mWBtKc97aLL9/txD8DZdemK0vkA3JMLShjlJB3Pj3s+lpf1KaBzMfQrAmhMQB0n1cU/SUGgKKBCe837Q== integrity sha512-rPCkf/mWBtKc97aLL9/txD8DZdemK0vkA3JMLShjlJB3Pj3s+lpf1KaBzMfQrAmhMQB0n1cU/SUGgKKBCe837Q==
react-is@^16.9.0:
version "16.13.1"
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"
integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==
react-popper@^1.3.4: react-popper@^1.3.4:
version "1.3.7" version "1.3.7"
resolved "https://registry.yarnpkg.com/react-popper/-/react-popper-1.3.7.tgz#f6a3471362ef1f0d10a4963673789de1baca2324" resolved "https://registry.yarnpkg.com/react-popper/-/react-popper-1.3.7.tgz#f6a3471362ef1f0d10a4963673789de1baca2324"
@ -8760,6 +8779,17 @@ react-popper@^1.3.4:
typed-styles "^0.0.7" typed-styles "^0.0.7"
warning "^4.0.2" warning "^4.0.2"
react-redux@^7.2.0:
version "7.2.0"
resolved "https://registry.yarnpkg.com/react-redux/-/react-redux-7.2.0.tgz#f970f62192b3981642fec46fd0db18a074fe879d"
integrity sha512-EvCAZYGfOLqwV7gh849xy9/pt55rJXPwmYvI4lilPM5rUT/1NxuuN59ipdBksRVSvz0KInbPnp4IfoXJXCqiDA==
dependencies:
"@babel/runtime" "^7.5.5"
hoist-non-react-statics "^3.3.0"
loose-envify "^1.4.0"
prop-types "^15.7.2"
react-is "^16.9.0"
react-round-slider@^1.0.1: react-round-slider@^1.0.1:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/react-round-slider/-/react-round-slider-1.0.1.tgz#2f6f14f4e7ce622cc7e450911a163b5841b3fd88" resolved "https://registry.yarnpkg.com/react-round-slider/-/react-round-slider-1.0.1.tgz#2f6f14f4e7ce622cc7e450911a163b5841b3fd88"
@ -8980,6 +9010,19 @@ redent@^3.0.0:
indent-string "^4.0.0" indent-string "^4.0.0"
strip-indent "^3.0.0" strip-indent "^3.0.0"
redux-thunk@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.3.0.tgz#51c2c19a185ed5187aaa9a2d08b666d0d6467622"
integrity sha512-km6dclyFnmcvxhAcrQV2AkZmPQjzPDjgVlQtR0EQjxZPyJ0BnMf3in1ryuR8A2qU0HldVRfxYXbFSKlI3N7Slw==
redux@^4.0.5, redux@~4:
version "4.0.5"
resolved "https://registry.yarnpkg.com/redux/-/redux-4.0.5.tgz#4db5de5816e17891de8a80c424232d06f051d93f"
integrity sha512-VSz1uMAH24DM6MF72vcojpYPtrTUu3ByVWfPL1nPfVRb5mZVTve5GnNCUV53QM/BZ66xfWrm0CTWoM+Xlz8V1w==
dependencies:
loose-envify "^1.4.0"
symbol-observable "^1.2.0"
regenerate-unicode-properties@^8.1.0: regenerate-unicode-properties@^8.1.0:
version "8.1.0" version "8.1.0"
resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz#ef51e0f0ea4ad424b77bf7cb41f3e015c70a3f0e" resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-8.1.0.tgz#ef51e0f0ea4ad424b77bf7cb41f3e015c70a3f0e"
@ -10100,6 +10143,11 @@ svgo@^1.0.0, svgo@^1.2.2:
unquote "~1.1.1" unquote "~1.1.1"
util.promisify "~1.0.0" util.promisify "~1.0.0"
symbol-observable@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804"
integrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==
symbol-tree@^3.2.2: symbol-tree@^3.2.2:
version "3.2.4" version "3.2.4"
resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2" resolved "https://registry.yarnpkg.com/symbol-tree/-/symbol-tree-3.2.4.tgz#430637d248ba77e078883951fb9aa0eed7c63fa2"