Added context

This commit is contained in:
kunkliricsi 2020-11-18 09:56:30 +01:00
parent 41bf14a4e5
commit 490f0f3265
17 changed files with 69 additions and 235 deletions

View File

@ -49,8 +49,6 @@
<ItemGroup>
<None Remove="ClientApp\src\common\components\BirdmapTitle.tsx" />
<None Remove="ClientApp\src\common\ErrorDispatcher.ts" />
<None Remove="ClientApp\src\common\ServiceBase.ts" />
<None Remove="ClientApp\src\components\auth\Auth.tsx" />
<None Remove="ClientApp\src\components\auth\AuthClient.ts" />
<None Remove="ClientApp\src\components\auth\AuthService.ts" />
@ -59,10 +57,10 @@
<ItemGroup>
<TypeScriptCompile Include="ClientApp\src\components\auth\Auth.tsx" />
<TypeScriptCompile Include="ClientApp\src\common\components\BirdmapTitle.tsx" />
</ItemGroup>
<ItemGroup>
<Folder Include="ClientApp\src\common\components\" />
<Folder Include="ClientApp\src\components\dashboard\" />
</ItemGroup>

View File

@ -8,20 +8,21 @@ import Typography from '@material-ui/core/Typography';
import { ThemeProvider } from '@material-ui/styles';
import React, { useState, } from 'react';
import { BrowserRouter, NavLink, Redirect, Route, Switch, Link } from 'react-router-dom';
import BirdmapTitle from './common/components/BirdmapTitle';
import BirdmapTitle from './components/appBar/BirdmapTitle';
import Auth from './components/auth/Auth';
import AuthService from './components/auth/AuthService';
import { ClickAwayListener } from '@material-ui/core';
import MapContainer from './components/heatmap/Heatmap';
import Devices from './components/devices/Devices';
import { blueGrey, blue, orange, grey } from '@material-ui/core/colors';
import DevicesContextProvider from './contexts/DevicesContextProvider'
const theme = createMuiTheme({
palette: {
primary: {
main: blue[900],
dark: blueGrey[50],
main: blueGrey[900],
dark: grey[200],
},
secondary: {
main: orange[200],
@ -64,14 +65,16 @@ function App() {
return (
<ThemeProvider theme={theme}>
<BrowserRouter>
<Switch>
<PublicRoute path="/login" component={AuthComponent} />
<BrowserRouter>
<Switch>
<PublicRoute path="/login" component={AuthComponent} />
<DevicesContextProvider>
<PrivateRoute path="/" exact authenticated={authenticated} isAdmin={isAdmin} component={DashboardComponent} />
<PrivateRoute path="/devices/:id?" exact authenticated={authenticated} isAdmin={isAdmin} component={DevicesComponent} />
<PrivateRoute path="/heatmap" exact authenticated={authenticated} isAdmin={isAdmin} component={HeatmapComponent} />
</Switch>
</BrowserRouter>
</DevicesContextProvider>
</Switch>
</BrowserRouter>
</ThemeProvider>
);
}

View File

@ -1,14 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ErrorDispatcher = {
errorHandlers: [],
registerErrorHandler: function (errorHandlerFn) {
this.errorHandlers.push(errorHandlerFn);
},
raiseError: function (errorMessage) {
for (var i = 0; i < this.errorHandlers.length; i++)
this.errorHandlers[i](errorMessage);
}
};
exports.default = ErrorDispatcher;
//# sourceMappingURL=ErrorDispatcher.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ErrorDispatcher.js","sourceRoot":"","sources":["ErrorDispatcher.ts"],"names":[],"mappings":";;AAAA,IAAM,eAAe,GAAG;IACtB,aAAa,EAAE,EAAE;IAEjB,oBAAoB,YAAC,cAAc;QACjC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC1C,CAAC;IAED,UAAU,YAAC,YAAY;QACrB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,EAAE,CAAC,EAAE;YAChD,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC;IACxC,CAAC;CACF,CAAC;AAEF,kBAAe,eAAe,CAAC"}

View File

@ -1,14 +0,0 @@
const ErrorDispatcher = {
errorHandlers: [],
registerErrorHandler(errorHandlerFn) {
this.errorHandlers.push(errorHandlerFn);
},
raiseError(errorMessage) {
for (let i = 0; i < this.errorHandlers.length; i++)
this.errorHandlers[i](errorMessage);
}
};
export default ErrorDispatcher;

View File

@ -1,50 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ErrorDispatcher_1 = require("./ErrorDispatcher");
function get(url) {
var options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('user')
}
};
return makeRequest(url, options);
}
function post(url, request) {
var options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('user')
},
body: "",
};
if (request)
options.body = JSON.stringify(request);
return makeRequest(url, options);
}
function makeRequest(url, options) {
return fetch(url, options)
.then(ensureResponseSuccess)
.catch(errorHandler);
}
function ensureResponseSuccess(response) {
if (!response.ok)
return response.json()
.then(function (data) { return errorHandler(data); });
return response.text()
.then(function (text) { return text.length ? JSON.parse(text) : {}; });
}
function errorHandler(response) {
console.log(response);
if (response && response.Error)
ErrorDispatcher_1.default.raiseError(response.Error);
return Promise.reject();
}
exports.default = {
get: get,
post: post,
makeRequest: makeRequest
};
//# sourceMappingURL=ServiceBase.js.map

View File

@ -1 +0,0 @@
{"version":3,"file":"ServiceBase.js","sourceRoot":"","sources":["ServiceBase.ts"],"names":[],"mappings":";;AAAA,qDAAgD;AAEhD,SAAS,GAAG,CAAC,GAAW;IACpB,IAAI,OAAO,GAAG;QACV,MAAM,EAAE,KAAK;QACb,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;YAClC,eAAe,EAAE,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC;SAClD;KACJ,CAAC;IAEF,OAAO,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AACrC,CAAC;AAED,SAAS,IAAI,CAAC,GAAW,EAAE,OAAY;IACnC,IAAI,OAAO,GAAG;QACV,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;YAClC,eAAe,EAAE,cAAc,CAAC,OAAO,CAAC,MAAM,CAAC;SAClD;QACD,IAAI,EAAE,EAAE;KACX,CAAC;IAEF,IAAI,OAAO;QACP,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAE3C,OAAO,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AACrC,CAAC;AAED,SAAS,WAAW,CAAC,GAAW,EAAE,OAAY;IAC1C,OAAO,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC;SACrB,IAAI,CAAC,qBAAqB,CAAC;SAC3B,KAAK,CAAC,YAAY,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,qBAAqB,CAAC,QAAa;IACxC,IAAI,CAAC,QAAQ,CAAC,EAAE;QACZ,OAAO,QAAQ,CAAC,IAAI,EAAE;aACjB,IAAI,CAAC,UAAC,IAAS,IAAK,OAAA,YAAY,CAAC,IAAI,CAAC,EAAlB,CAAkB,CAAC,CAAC;IAEjD,OAAO,QAAQ,CAAC,IAAI,EAAE;SACjB,IAAI,CAAC,UAAC,IAAS,IAAK,OAAA,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,EAAnC,CAAmC,CAAC,CAAC;AAClE,CAAC;AAED,SAAS,YAAY,CAAC,QAAa;IAC/B,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAEtB,IAAI,QAAQ,IAAI,QAAQ,CAAC,KAAK;QAC1B,yBAAe,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAE/C,OAAO,OAAO,CAAC,MAAM,EAAE,CAAC;AAC5B,CAAC;AAED,kBAAe;IACX,GAAG,KAAA;IACH,IAAI,MAAA;IACJ,WAAW,aAAA;CACd,CAAC"}

View File

@ -1,59 +0,0 @@
import ErrorDispatcher from './ErrorDispatcher';
function get(url: string) {
let options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('user')
}
};
return makeRequest(url, options);
}
function post(url: string, request: any) {
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('user')
},
body: "",
};
if (request)
options.body = JSON.stringify(request);
return makeRequest(url, options);
}
function makeRequest(url: string, options: any) {
return fetch(url, options)
.then(ensureResponseSuccess)
.catch(errorHandler);
}
function ensureResponseSuccess(response: any) {
if (!response.ok)
return response.json()
.then((data: any) => errorHandler(data));
return response.text()
.then((text: any) => text.length ? JSON.parse(text) : {});
}
function errorHandler(response: any) {
console.log(response);
if (response && response.Error)
ErrorDispatcher.raiseError(response.Error);
return Promise.reject();
}
export default {
get,
post,
makeRequest
};

View File

@ -1,11 +1,8 @@
import React, { Component } from 'react'
import DeviceService from './DeviceService'
import Accordion from '@material-ui/core/Accordion';
import DeviceComponent from './DeviceComponent'
import SensorComponent from './DeviceComponent'
import { Box } from '@material-ui/core';
import { withStyles } from '@material-ui/styles';
import { Box } from '@material-ui/core';
import { grey } from '@material-ui/core/colors';
import React from 'react';
import DevicesContext from '../../contexts/DevicesContext';
import DeviceComponent from './DeviceComponent';
const styles = theme => ({
root: {
@ -17,23 +14,16 @@ const styles = theme => ({
class Devices extends React.Component {
constructor(props) {
super(props);
this.state = {
devices: [],
};
}
static contextType = DevicesContext;
componentDidMount() {
new DeviceService().getall().then(result => {
this.setState({ devices: result });
}).catch(ex => {
console.log(ex);
});
}
render() {
const { classes } = this.props;
const Devices = this.state.devices.map((device, index) => (
const Devices = this.context.devices.map((device, index) => (
<DeviceComponent device={device} index={index} key={device.id}/>
));

View File

@ -1,15 +0,0 @@
import React, { Component } from 'react';
import AccordionDetails from '@material-ui/core/AccordionDetails';
export default class SensorComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
);
}
}

View File

@ -1,7 +1,7 @@
/*global google*/
import GoogleMapReact from 'google-map-react';
import React, { Component } from 'react';
import DeviceService from '../devices/DeviceService'
import DeviceService from '../../common/DeviceService'
import DeviceMarker from './DeviceMarker'
import { HubConnectionBuilder } from '@microsoft/signalr';
@ -75,7 +75,7 @@ export default class MapContainer extends Component {
newConnection.on(update_method_name, (id) => {
service.getdevice(id).then(result => {
var index = this.state.devices.findIndex((d => d.id == id));
var index = this.state.devices.findIndex((d => d.id === id));
const newDevices = [...this.state.devices];
newDevices[index] = result;
this.setState({ devices: newDevices });

View File

@ -4,8 +4,5 @@ export default React.createContext({
devices: [],
heatmapPoints: [],
addDevice: () => { },
addPoint: () => { },
addHandler: (_, __) => { },
});

View File

@ -1,41 +1,40 @@
import Context from './DevicesContext'
import { HubConnectionBuilder } from '@microsoft/signalr';
import { DeviceService } from '../components/devices/DeviceService';
import Constants from '../common/Constants'
import DeviceService from '../common/DeviceService';
import C from '../common/Constants'
import React, { Component } from 'react'
const hub_url = '/hubs/devices';
export default class DevicesContextProvider extends Component {
state = {
hubConnection: null,
devices: [],
heatmapPoints: [],
handlers: {},
};
constructor(props) {
super(props);
addPoint = point => {
const updatedPoints = [...this.state.heatmapPoints];
updatedPoints.push(point);
this.setState({ heatmapPoints: updatedPoints });
};
const handlers = {};
for (var property in C) {
handlers[property] = [];
};
addDevice = device => {
const updatedDevices = [...this.state.devices];
updatedDevices.push(device);
this.setState({ devices: updatedDevices });
};
this.state = {
hubConnection: null,
devices: [],
heatmapPoints: [],
handlers: handlers,
};
}
addHandler = (methodName, handler) => {
const updatedHandlers = [...this.state.handlers];
var methodHandlers = updatedHandlers[methodName];
if (methodHandlers == null) {
methodHandlers = [];
};
const updatedMethodHandlers = [...methodHandlers];
updatedMethodHandlers.push(handler);
updatedHandlers[methodName] = updatedMethodHandlers;
updatedHandlers[methodName].push(handler);
this.setState({ handlers: updatedHandlers });
}
removeHandler = (methodName, handler) => {
const updatedHandlers = [...this.state.handlers];
var index = updatedHandlers[methodName].findIndex((h => h === handler));
if (index > 0) {
delete updatedHandlers[index];
}
this.setState({ handlers: updatedHandlers });
}
@ -71,31 +70,34 @@ export default class DevicesContextProvider extends Component {
.then(_ => {
console.log('Hub Connected!');
newConnection.on(Constants.probability_method_name, (id, date, prob) => {
newConnection.on(C.probability_method_name, (id, date, prob) => {
//console.log(method_name + " recieved: [id: " + id + ", date: " + date + ", prob: " + prob + "]");
if (prob > 0.5) {
var device = this.state.devices.filter(function (x) { return x.id === id })[0]
var newPoint = { lat: device.coordinates.latitude, lng: device.coordinates.longitude };
this.setState({
heatmapPoints: [...this.state.heatmapPoints, newPoint]
});
}
var device = this.state.devices.filter(function (x) { return x.id === id })[0]
var newPoint = { lat: device.coordinates.latitude, lng: device.coordinates.longitude, prob: prob, date: date };
this.setState({
heatmapPoints: [...this.state.heatmapPoints, newPoint]
});
this.invokeHandlers(Constants.probability_method_name, { point: newPoint, probability: prob });
this.invokeHandlers(C.probability_method_name, newPoint);
});
newConnection.on(Constants.update_all_method_name, () => {
newConnection.on(C.update_all_method_name, () => {
this.handleAllDevicesUpdated(service);
this.invokeHandlers(Constants.update_all_method_name, null);
this.invokeHandlers(C.update_all_method_name, null);
});
newConnection.on(Constants.update_method_name, (id) => {
newConnection.on(C.update_method_name, (id) => {
service.getdevice(id).then(result => {
var index = this.state.devices.findIndex((d => d.id == id));
const newDevices = [...this.state.devices];
newDevices[index] = result;
this.setState({ devices: newDevices });
this.invokeHandlers(Constants.update_method_name, result);
const updatedDevices = [...this.state.devices];
var index = updatedDevices.findIndex((d => d.id == id));
if (index > 0) {
updatedDevices[index] = result;
}
else {
updatedDevices.push(result);
}
this.setState({ devices: updatedDevices });
this.invokeHandlers(C.update_method_name, result);
}).catch(ex => console.log("Device update failed.", ex));
})
}).catch(e => console.log('Hub Connection failed: ', e));
@ -103,9 +105,9 @@ export default class DevicesContextProvider extends Component {
componentWillUnmount() {
if (this.state.hubConnection != null) {
this.state.hubConnection.off(Constants.probability_method_name);
this.state.hubConnection.off(Constants.update_all_method_name);
this.state.hubConnection.off(Constants.update_method_name);
this.state.hubConnection.off(C.probability_method_name);
this.state.hubConnection.off(C.update_all_method_name);
this.state.hubConnection.off(C.update_method_name);
console.log('Hub Disconnected!');
}
}
@ -116,8 +118,6 @@ export default class DevicesContextProvider extends Component {
value={{
devices: this.state.devices,
heatmapPoints: this.state.heatmapPoints,
addDevice: this.addDevice,
addPoint: this.addPoint,
addHandler: this.addHandler
}}