Compare commits
12 Commits
feature/pr
...
70c4c91035
Author | SHA1 | Date | |
---|---|---|---|
70c4c91035 | |||
aa39597541 | |||
bcbab1383a | |||
bab0984c30 | |||
0667c6ec39 | |||
0d71899ce1 | |||
966d8bd79e | |||
5b42ce9f43 | |||
85320d3cf3 | |||
9d55c39e33 | |||
d75e9d378d | |||
3cdaa2dc35 |
25
.dockerignore
Normal file
25
.dockerignore
Normal file
@ -0,0 +1,25 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/docs
|
||||
**/bin
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
@ -8,6 +8,9 @@
|
||||
<SpaRoot>ClientApp\</SpaRoot>
|
||||
<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
|
||||
<AssemblyName>Birdmap.API</AssemblyName>
|
||||
<UserSecretsId>a919c854-b332-49ee-8e38-96549f828836</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
|
||||
@ -31,6 +34,7 @@
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.9" />
|
||||
<PackageReference Include="MQTTnet" Version="3.0.13" />
|
||||
<PackageReference Include="MQTTnet.AspNetCore" Version="3.0.13" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
|
||||
|
@ -1,23 +1,17 @@
|
||||
import { Box, Container, IconButton, Menu, MenuItem, MenuList, Paper, Grow, Popper } from '@material-ui/core';
|
||||
import AccountCircle from '@material-ui/icons/AccountCircle';
|
||||
import AppBar from '@material-ui/core/AppBar';
|
||||
import { positions } from '@material-ui/system';
|
||||
import { Box, Paper } from '@material-ui/core';
|
||||
import { blueGrey, grey, orange } from '@material-ui/core/colors';
|
||||
import { createMuiTheme, createStyles, makeStyles, Theme } from '@material-ui/core/styles';
|
||||
import Toolbar from '@material-ui/core/Toolbar';
|
||||
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 './components/appBar/BirdmapTitle';
|
||||
import React, { useState } from 'react';
|
||||
import { BrowserRouter, Redirect, Route, Switch } from 'react-router-dom';
|
||||
import BirdmapBar from './components/appBar/BirdmapBar';
|
||||
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'
|
||||
import Dashboard from './components/dashboard/Dashboard';
|
||||
|
||||
import Devices from './components/devices/Devices';
|
||||
import MapContainer from './components/heatmap/Heatmap';
|
||||
import Logs from './components/logs/Logs';
|
||||
import DevicesContextProvider from './contexts/DevicesContextProvider';
|
||||
|
||||
const theme = createMuiTheme({
|
||||
palette: {
|
||||
@ -26,14 +20,13 @@ const theme = createMuiTheme({
|
||||
dark: grey[400],
|
||||
},
|
||||
secondary: {
|
||||
main: orange[200],
|
||||
main: blueGrey[700],
|
||||
dark: blueGrey[50],
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
function App() {
|
||||
|
||||
const [authenticated, setAuthenticated] = useState(AuthService.isAuthenticated());
|
||||
const [isAdmin, setIsAdmin] = useState(AuthService.isAdmin());
|
||||
|
||||
@ -48,6 +41,10 @@ function App() {
|
||||
);
|
||||
}
|
||||
|
||||
const LogsComponent = () => {
|
||||
return <Logs/>
|
||||
}
|
||||
|
||||
const DashboardComponent = () => {
|
||||
return <Dashboard isAdmin={isAdmin}/>;
|
||||
};
|
||||
@ -56,6 +53,7 @@ function App() {
|
||||
return <Devices isAdmin={isAdmin}/>;
|
||||
|
||||
};
|
||||
|
||||
const HeatmapComponent = () => {
|
||||
return (
|
||||
<Paper elevation={0}>
|
||||
@ -64,15 +62,46 @@ function App() {
|
||||
);
|
||||
};
|
||||
|
||||
const HeaderComponent = () => {
|
||||
return (
|
||||
<BirdmapBar onLogout={AuthService.logout} isAdmin={isAdmin} isAuthenticated={authenticated}/>
|
||||
);
|
||||
}
|
||||
|
||||
const PredicateRoute = ({ component: Component, predicate: Predicate, ...rest }: { [x: string]: any, component: any, predicate: any }) => {
|
||||
return (
|
||||
<PredicateRouteInternal {...rest} header={HeaderComponent} body={Component} predicate={Predicate}/>
|
||||
);
|
||||
}
|
||||
|
||||
const PublicRoute = ({ component: Component, ...rest }: { [x: string]: any, component: any }) => {
|
||||
return (
|
||||
<PredicateRoute {...rest} component={Component} predicate={true}/>
|
||||
);
|
||||
}
|
||||
|
||||
const PrivateRoute = ({ component: Component, ...rest }: { [x: string]: any, component: any }) => {
|
||||
return (
|
||||
<PredicateRoute {...rest} component={Component} predicate={authenticated}/>
|
||||
);
|
||||
}
|
||||
|
||||
const AdminRoute = ({ component: Component, ...rest }: { [x: string]: any, component: any }) => {
|
||||
return (
|
||||
<PredicateRoute {...rest} component={Component} predicate={authenticated && isAdmin}/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProvider theme={theme}>
|
||||
<BrowserRouter>
|
||||
<Switch>
|
||||
<PublicRoute path="/login" component={AuthComponent} />
|
||||
<PublicRoute exact path="/login" component={AuthComponent} />
|
||||
<AdminRoute exact path="/logs" component={LogsComponent} />
|
||||
<DevicesContextProvider>
|
||||
<PrivateRoute path="/" exact authenticated={authenticated} component={DashboardComponent} />
|
||||
<PrivateRoute path="/devices/:id?" exact authenticated={authenticated} component={DevicesComponent} />
|
||||
<PrivateRoute path="/heatmap" exact authenticated={authenticated} component={HeatmapComponent} />
|
||||
<PrivateRoute exact path="/" component={DashboardComponent} />
|
||||
<PrivateRoute exact path="/devices/:id?" component={DevicesComponent} />
|
||||
<PrivateRoute exact path="/heatmap" component={HeatmapComponent} />
|
||||
</DevicesContextProvider>
|
||||
</Switch>
|
||||
</BrowserRouter>
|
||||
@ -82,112 +111,26 @@ function App() {
|
||||
|
||||
export default App;
|
||||
|
||||
const PublicRoute = ({ component: Component, ...rest }: { [x: string]: any, component: any}) => {
|
||||
const PredicateRouteInternal = ({ header: HeaderComponent, body: BodyComponent, predicate: Predicate, ...rest }: { [x: string]: any, header: any, body: any, predicate: any }) => {
|
||||
return (
|
||||
<Route {...rest} render={matchProps => (
|
||||
<DefaultLayout component={Component} authenticated={false} isAdmin={false} {...matchProps} />
|
||||
)} />
|
||||
);
|
||||
}
|
||||
|
||||
const PrivateRoute = ({ component: Component, authenticated: Authenticated, ...rest }: { [x: string]: any, component: any, authenticated: any }) => {
|
||||
return (
|
||||
<Route {...rest} render={matchProps => (
|
||||
Authenticated
|
||||
? <DefaultLayout component={Component} authenticated={Authenticated} {...matchProps} />
|
||||
Predicate
|
||||
? <DefaultLayoutInternal header={HeaderComponent} body={BodyComponent} {...matchProps} />
|
||||
: <Redirect to='/login' />
|
||||
)} />
|
||||
);
|
||||
};
|
||||
|
||||
const DefaultLayout = ({ component: Component, authenticated: Authenticated, ...rest }: { [x: string]: any, component: any, authenticated: any }) => {
|
||||
const DefaultLayoutInternal = ({ header: HeaderComponent, body: BodyComponent, ...rest }: { [x: string]: any, header: any, body: any }) => {
|
||||
const classes = useDefaultLayoutStyles();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const anchorRef = React.useRef<HTMLButtonElement>(null);
|
||||
|
||||
const handleToggle = () => {
|
||||
setOpen((prevOpen) => !prevOpen);
|
||||
};
|
||||
|
||||
const handleClose = (event: React.MouseEvent<EventTarget>) => {
|
||||
if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleLogout = (event: React.MouseEvent<EventTarget>) => {
|
||||
if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
AuthService.logout();
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
function handleListKeyDown(event: React.KeyboardEvent) {
|
||||
if (event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
const prevOpen = React.useRef(open);
|
||||
React.useEffect(() => {
|
||||
if (prevOpen.current === true && open === false) {
|
||||
anchorRef.current!.focus();
|
||||
}
|
||||
|
||||
prevOpen.current = open;
|
||||
}, [open]);
|
||||
|
||||
|
||||
const renderNavLinks = () => {
|
||||
return Authenticated
|
||||
? <Container className={classes.nav_menu}>
|
||||
<NavLink exact to="/" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Dashboard</NavLink>
|
||||
<NavLink to="/devices" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Devices</NavLink>
|
||||
<NavLink exact to="/heatmap" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Heatmap</NavLink>
|
||||
<IconButton className={classes.nav_menu_icon}
|
||||
ref={anchorRef}
|
||||
aria-haspopup="true"
|
||||
aria-controls={open ? 'menu-list-grow' : undefined}
|
||||
aria-label="account of current user"
|
||||
onClick={handleToggle}>
|
||||
<AccountCircle/>
|
||||
</IconButton>
|
||||
<Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
|
||||
{({ TransitionProps, placement }) => (
|
||||
<Grow
|
||||
{...TransitionProps}
|
||||
style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}>
|
||||
<Paper>
|
||||
<ClickAwayListener onClickAway={handleClose}>
|
||||
<MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
|
||||
<MenuItem onClick={handleLogout} component={Link} {...{ to: '/login' }}>Logout</MenuItem>
|
||||
</MenuList>
|
||||
</ClickAwayListener>
|
||||
</Paper>
|
||||
</Grow>
|
||||
)}
|
||||
</Popper>
|
||||
</Container>
|
||||
: null;
|
||||
};
|
||||
|
||||
return (
|
||||
<React.Fragment>
|
||||
<AppBar position="static" className={classes.bar_root}>
|
||||
<Toolbar>
|
||||
<BirdmapTitle />
|
||||
<Typography component={'span'} className={classes.typo}>
|
||||
{renderNavLinks()}
|
||||
</Typography>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<Box zIndex="modal" className={classes.box_root}>
|
||||
<Component {...rest} />
|
||||
<Box className={classes.header}>
|
||||
<HeaderComponent />
|
||||
</Box>
|
||||
<Box className={classes.body}>
|
||||
<BodyComponent {...rest} />
|
||||
</Box>
|
||||
</React.Fragment>
|
||||
);
|
||||
@ -195,46 +138,12 @@ const DefaultLayout = ({ component: Component, authenticated: Authenticated, ...
|
||||
|
||||
const useDefaultLayoutStyles = makeStyles((theme: Theme) =>
|
||||
createStyles({
|
||||
bar_root: {
|
||||
header: {
|
||||
height: '7%',
|
||||
},
|
||||
box_root: {
|
||||
body: {
|
||||
backgroundColor: theme.palette.primary.dark,
|
||||
height: '93%',
|
||||
},
|
||||
typo: {
|
||||
marginLeft: 'auto',
|
||||
color: 'white',
|
||||
},
|
||||
nav_menu: {
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
nav_menu_icon: {
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
nav_menu_item: {
|
||||
textDecoration: 'none',
|
||||
fontWeight: 'normal',
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
nav_menu_item_active: {
|
||||
textDecoration: 'underline',
|
||||
fontWeight: 'bold',
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
@ -1,5 +1,5 @@
|
||||
export default {
|
||||
probability_method_name: 'NotifyDeviceAsync',
|
||||
probability_method_name: 'NotifyMessagesAsync',
|
||||
update_method_name: 'NotifyDeviceUpdatedAsync',
|
||||
update_all_method_name: 'NotifyAllUpdatedAsync',
|
||||
};
|
136
Birdmap.API/ClientApp/src/components/appBar/BirdmapBar.tsx
Normal file
136
Birdmap.API/ClientApp/src/components/appBar/BirdmapBar.tsx
Normal file
@ -0,0 +1,136 @@
|
||||
import { ClickAwayListener, Container, createStyles, Grow, IconButton, makeStyles, MenuItem, MenuList, Paper, Popper, Theme } from '@material-ui/core';
|
||||
import AppBar from '@material-ui/core/AppBar';
|
||||
import Toolbar from '@material-ui/core/Toolbar';
|
||||
import Typography from '@material-ui/core/Typography';
|
||||
import AccountCircle from '@material-ui/icons/AccountCircle';
|
||||
import React from 'react';
|
||||
import { Link, NavLink } from 'react-router-dom';
|
||||
import BirdmapTitle from './BirdmapTitle';
|
||||
|
||||
export default function BirdmapBar(props: { onLogout: () => void; isAuthenticated: any; isAdmin: any; }) {
|
||||
const classes = useAppbarStyles();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const anchorRef = React.useRef<HTMLButtonElement>(null);
|
||||
|
||||
const handleToggle = () => {
|
||||
setOpen((prevOpen) => !prevOpen);
|
||||
};
|
||||
|
||||
const handleClose = (event: React.MouseEvent<EventTarget>) => {
|
||||
if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleLogout = (event: React.MouseEvent<EventTarget>) => {
|
||||
if (anchorRef.current && anchorRef.current.contains(event.target as HTMLElement)) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onLogout();
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
function handleListKeyDown(event: React.KeyboardEvent) {
|
||||
if (event.key === 'Tab') {
|
||||
event.preventDefault();
|
||||
setOpen(false);
|
||||
}
|
||||
}
|
||||
|
||||
const prevOpen = React.useRef(open);
|
||||
React.useEffect(() => {
|
||||
if (prevOpen.current === true && open === false) {
|
||||
anchorRef.current!.focus();
|
||||
}
|
||||
|
||||
prevOpen.current = open;
|
||||
}, [open]);
|
||||
|
||||
const renderNavLinks = () => {
|
||||
return props.isAuthenticated
|
||||
? <Container className={classes.nav_menu}>
|
||||
<NavLink exact to="/" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Dashboard</NavLink>
|
||||
{props.isAdmin ? <NavLink exact to="/logs" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Logs</NavLink> : null}
|
||||
<NavLink to="/devices" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Devices</NavLink>
|
||||
<NavLink exact to="/heatmap" className={classes.nav_menu_item} activeClassName={classes.nav_menu_item_active}>Heatmap</NavLink>
|
||||
<IconButton className={classes.nav_menu_icon}
|
||||
ref={anchorRef}
|
||||
aria-haspopup="true"
|
||||
aria-controls={open ? 'menu-list-grow' : undefined}
|
||||
aria-label="account of current user"
|
||||
onClick={handleToggle}>
|
||||
<AccountCircle />
|
||||
</IconButton>
|
||||
<Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
|
||||
{({ TransitionProps, placement }) => (
|
||||
<Grow
|
||||
{...TransitionProps}
|
||||
style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}>
|
||||
<Paper>
|
||||
<ClickAwayListener onClickAway={handleClose}>
|
||||
<MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
|
||||
<MenuItem onClick={handleLogout} component={Link} {...{ to: '/login' }}>Logout</MenuItem>
|
||||
</MenuList>
|
||||
</ClickAwayListener>
|
||||
</Paper>
|
||||
</Grow>
|
||||
)}
|
||||
</Popper>
|
||||
</Container>
|
||||
: null;
|
||||
};
|
||||
|
||||
return (
|
||||
<AppBar position="static">
|
||||
<Toolbar>
|
||||
<BirdmapTitle />
|
||||
<Typography component={'span'} className={classes.typo}>
|
||||
{renderNavLinks()}
|
||||
</Typography>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
)
|
||||
};
|
||||
|
||||
|
||||
const useAppbarStyles = makeStyles((theme: Theme) =>
|
||||
createStyles({
|
||||
typo: {
|
||||
marginLeft: 'auto',
|
||||
color: 'white',
|
||||
},
|
||||
nav_menu: {
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
nav_menu_icon: {
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
nav_menu_item: {
|
||||
textDecoration: 'none',
|
||||
fontWeight: 'normal',
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
nav_menu_item_active: {
|
||||
textDecoration: 'underline',
|
||||
fontWeight: 'bold',
|
||||
color: 'inherit',
|
||||
marginLeft: '24px',
|
||||
'&:hover': {
|
||||
color: 'inherit',
|
||||
}
|
||||
},
|
||||
}),
|
||||
);
|
@ -57,6 +57,9 @@ class Dashboard extends Component {
|
||||
componentWillUnmount() {
|
||||
this.context.removeHandler(C.update_all_method_name, this.updateSeries);
|
||||
this.context.removeHandler(C.update_method_name, this.updateSeries);
|
||||
if (this.updateTimer) {
|
||||
clearTimeout(this.updateTimer);
|
||||
}
|
||||
}
|
||||
|
||||
getItemsWithStatus(iterate, status) {
|
||||
@ -125,7 +128,7 @@ class Dashboard extends Component {
|
||||
barDevicePoints[d.id] = Array(3).fill(0);
|
||||
}
|
||||
|
||||
const processMethod = (items, index) => {
|
||||
const processHeatmapItem = (items, index) => {
|
||||
const p = items[index];
|
||||
if (p.date > minuteAgo) {
|
||||
var seconds = Math.floor((p.date.getTime() - minuteAgo.getTime()) / 1000);
|
||||
@ -164,7 +167,7 @@ class Dashboard extends Component {
|
||||
}
|
||||
}
|
||||
|
||||
const finishMethod = () => {
|
||||
const onFinished = () => {
|
||||
const minuteHeatmapSeries = [];
|
||||
|
||||
var i = 0;
|
||||
@ -236,21 +239,24 @@ class Dashboard extends Component {
|
||||
return categories;
|
||||
}
|
||||
|
||||
this.setState({
|
||||
heatmapSecondsSeries: minuteHeatmapSeries,
|
||||
heatmapMinutesSeries: hourHeatmapSeries,
|
||||
barSeries: barSeries,
|
||||
barCategories: getBarCategories(),
|
||||
lineSeries: lineSeries,
|
||||
});
|
||||
const toUpdate = [
|
||||
{ heatmapSecondsSeries: minuteHeatmapSeries },
|
||||
{ heatmapMinutesSeries: hourHeatmapSeries },
|
||||
{ barSeries: barSeries },
|
||||
{ barCategories: getBarCategories() },
|
||||
{ lineSeries: lineSeries }
|
||||
];
|
||||
|
||||
setTimeout(this.updateDynamic, 1000);
|
||||
//Set states must be done separately otherwise ApexChart's UI update freezes the page.
|
||||
this.performTask(toUpdate, 2, 300, (list, index) => {
|
||||
this.setState(list[index]);
|
||||
},
|
||||
() => {
|
||||
this.updateTimer = setTimeout(this.updateDynamic, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
const processHeatmapItem = processMethod.bind(this);
|
||||
const onFinished = finishMethod.bind(this)
|
||||
|
||||
this.performTask(this.context.heatmapPoints, Math.ceil(this.context.heatmapPoints.length / 100), 10,
|
||||
this.performTask(this.context.heatmapPoints, Math.ceil(this.context.heatmapPoints.length / 50), 20,
|
||||
processHeatmapItem, onFinished);
|
||||
}
|
||||
|
||||
|
@ -8,6 +8,21 @@ export class HeatmapChart extends Component {
|
||||
|
||||
this.state = {
|
||||
options: {
|
||||
chart: {
|
||||
animations: {
|
||||
enabled: true,
|
||||
easing: 'linear',
|
||||
speed: 250,
|
||||
animateGradually: {
|
||||
enabled: false,
|
||||
speed: 250,
|
||||
},
|
||||
dynamicAnimation: {
|
||||
enabled: true,
|
||||
speed: 250
|
||||
}
|
||||
}
|
||||
},
|
||||
dataLabels: {
|
||||
enabled: false
|
||||
},
|
||||
|
@ -1,4 +1,5 @@
|
||||
/*global google*/
|
||||
import { Box, withStyles } from '@material-ui/core';
|
||||
import GoogleMapReact from 'google-map-react';
|
||||
import React, { Component } from 'react';
|
||||
import C from '../../common/Constants';
|
||||
@ -8,7 +9,14 @@ import DeviceMarker from './DeviceMarker';
|
||||
const lat_offset = 0.000038;
|
||||
const lng_offset = -0.000058;
|
||||
|
||||
export default class MapContainer extends Component {
|
||||
const styles = theme => ({
|
||||
root: {
|
||||
height: '93vh',
|
||||
width: '100%',
|
||||
}
|
||||
});
|
||||
|
||||
class MapContainer extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
@ -20,11 +28,18 @@ export default class MapContainer extends Component {
|
||||
};
|
||||
|
||||
this.probabilityHandler = this.probabilityHandler.bind(this);
|
||||
this.handlePoint = this.handlePoint.bind(this);
|
||||
}
|
||||
|
||||
static contextType = DevicesContext;
|
||||
|
||||
probabilityHandler(point) {
|
||||
probabilityHandler(points) {
|
||||
for (var point of points) {
|
||||
this.handlePoint(point);
|
||||
}
|
||||
}
|
||||
|
||||
handlePoint(point) {
|
||||
if (point.prob > 0.5) {
|
||||
|
||||
this.setState({
|
||||
@ -57,6 +72,8 @@ export default class MapContainer extends Component {
|
||||
}
|
||||
|
||||
render() {
|
||||
const {classes} = this.props;
|
||||
|
||||
const heatMapData = {
|
||||
positions: this.state.heatmapPoints,
|
||||
options: {
|
||||
@ -85,7 +102,7 @@ export default class MapContainer extends Component {
|
||||
));
|
||||
|
||||
return (
|
||||
<div style={{ height: '93vh', width: '100%' }}>
|
||||
<Box className={classes.root}>
|
||||
<GoogleMapReact
|
||||
bootstrapURLKeys={{
|
||||
key: ["AIzaSyCZ51VFfxqZ2GkCmVrcNZdUKsM0fuBQUCY"],
|
||||
@ -99,7 +116,9 @@ export default class MapContainer extends Component {
|
||||
defaultCenter={this.state.center}>
|
||||
{Markers}
|
||||
</GoogleMapReact>
|
||||
</div>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(MapContainer);
|
208
Birdmap.API/ClientApp/src/components/logs/LogService.js
Normal file
208
Birdmap.API/ClientApp/src/components/logs/LogService.js
Normal file
@ -0,0 +1,208 @@
|
||||
"use strict";
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
//----------------------
|
||||
// <auto-generated>
|
||||
// Generated using the NSwag toolchain v13.8.2.0 (NJsonSchema v10.2.1.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
|
||||
// </auto-generated>
|
||||
//----------------------
|
||||
// ReSharper disable InconsistentNaming
|
||||
var __extends = (this && this.__extends) || (function () {
|
||||
var extendStatics = function (d, b) {
|
||||
extendStatics = Object.setPrototypeOf ||
|
||||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
|
||||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
|
||||
return extendStatics(d, b);
|
||||
};
|
||||
return function (d, b) {
|
||||
extendStatics(d, b);
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.ApiException = exports.HttpStatusCode = void 0;
|
||||
var LogService = /** @class */ (function () {
|
||||
function LogService(baseUrl, http) {
|
||||
this.jsonParseReviver = undefined;
|
||||
this.http = http ? http : window;
|
||||
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "api/logs";
|
||||
}
|
||||
LogService.prototype.getAll = function () {
|
||||
var _this = this;
|
||||
var url_ = this.baseUrl + "/all";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
var options_ = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
'Authorization': sessionStorage.getItem('user')
|
||||
}
|
||||
};
|
||||
return this.http.fetch(url_, options_).then(function (_response) {
|
||||
return _this.processGetAll(_response);
|
||||
});
|
||||
};
|
||||
LogService.prototype.processGetAll = function (response) {
|
||||
var _this = this;
|
||||
var status = response.status;
|
||||
var _headers = {};
|
||||
if (response.headers && response.headers.forEach) {
|
||||
response.headers.forEach(function (v, k) { return _headers[k] = v; });
|
||||
}
|
||||
;
|
||||
if (status === 200) {
|
||||
return response.text().then(function (_responseText) {
|
||||
var result200 = null;
|
||||
var resultData200 = _responseText === "" ? null : JSON.parse(_responseText, _this.jsonParseReviver);
|
||||
if (Array.isArray(resultData200)) {
|
||||
result200 = [];
|
||||
for (var _i = 0, resultData200_1 = resultData200; _i < resultData200_1.length; _i++) {
|
||||
var item = resultData200_1[_i];
|
||||
result200.push(item);
|
||||
}
|
||||
}
|
||||
return result200;
|
||||
});
|
||||
}
|
||||
else if (status !== 200 && status !== 204) {
|
||||
return response.text().then(function (_responseText) {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
};
|
||||
LogService.prototype.getFiles = function (filenames) {
|
||||
var _this = this;
|
||||
var url_ = this.baseUrl + "?";
|
||||
if (filenames !== undefined && filenames !== null)
|
||||
filenames && filenames.forEach(function (item) { url_ += "filenames=" + encodeURIComponent("" + item) + "&"; });
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
var options_ = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/octet-stream",
|
||||
'Authorization': sessionStorage.getItem('user')
|
||||
}
|
||||
};
|
||||
return this.http.fetch(url_, options_).then(function (_response) {
|
||||
return _this.processGetFiles(_response);
|
||||
});
|
||||
};
|
||||
LogService.prototype.processGetFiles = function (response) {
|
||||
var status = response.status;
|
||||
var _headers = {};
|
||||
if (response.headers && response.headers.forEach) {
|
||||
response.headers.forEach(function (v, k) { return _headers[k] = v; });
|
||||
}
|
||||
;
|
||||
if (status === 200 || status === 206) {
|
||||
var contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
|
||||
var fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
|
||||
var fileName_1 = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
|
||||
return response.blob().then(function (blob) { return { fileName: fileName_1, data: blob, status: status, headers: _headers }; });
|
||||
}
|
||||
else if (status !== 200 && status !== 204) {
|
||||
return response.text().then(function (_responseText) {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve(null);
|
||||
};
|
||||
return LogService;
|
||||
}());
|
||||
exports.default = LogService;
|
||||
var HttpStatusCode;
|
||||
(function (HttpStatusCode) {
|
||||
HttpStatusCode["Continue"] = "Continue";
|
||||
HttpStatusCode["SwitchingProtocols"] = "SwitchingProtocols";
|
||||
HttpStatusCode["Processing"] = "Processing";
|
||||
HttpStatusCode["EarlyHints"] = "EarlyHints";
|
||||
HttpStatusCode["OK"] = "OK";
|
||||
HttpStatusCode["Created"] = "Created";
|
||||
HttpStatusCode["Accepted"] = "Accepted";
|
||||
HttpStatusCode["NonAuthoritativeInformation"] = "NonAuthoritativeInformation";
|
||||
HttpStatusCode["NoContent"] = "NoContent";
|
||||
HttpStatusCode["ResetContent"] = "ResetContent";
|
||||
HttpStatusCode["PartialContent"] = "PartialContent";
|
||||
HttpStatusCode["MultiStatus"] = "MultiStatus";
|
||||
HttpStatusCode["AlreadyReported"] = "AlreadyReported";
|
||||
HttpStatusCode["IMUsed"] = "IMUsed";
|
||||
HttpStatusCode["MultipleChoices"] = "Ambiguous";
|
||||
HttpStatusCode["Ambiguous"] = "Ambiguous";
|
||||
HttpStatusCode["MovedPermanently"] = "Moved";
|
||||
HttpStatusCode["Moved"] = "Moved";
|
||||
HttpStatusCode["Found"] = "Redirect";
|
||||
HttpStatusCode["Redirect"] = "Redirect";
|
||||
HttpStatusCode["SeeOther"] = "RedirectMethod";
|
||||
HttpStatusCode["RedirectMethod"] = "RedirectMethod";
|
||||
HttpStatusCode["NotModified"] = "NotModified";
|
||||
HttpStatusCode["UseProxy"] = "UseProxy";
|
||||
HttpStatusCode["Unused"] = "Unused";
|
||||
HttpStatusCode["TemporaryRedirect"] = "TemporaryRedirect";
|
||||
HttpStatusCode["RedirectKeepVerb"] = "TemporaryRedirect";
|
||||
HttpStatusCode["PermanentRedirect"] = "PermanentRedirect";
|
||||
HttpStatusCode["BadRequest"] = "BadRequest";
|
||||
HttpStatusCode["Unauthorized"] = "Unauthorized";
|
||||
HttpStatusCode["PaymentRequired"] = "PaymentRequired";
|
||||
HttpStatusCode["Forbidden"] = "Forbidden";
|
||||
HttpStatusCode["NotFound"] = "NotFound";
|
||||
HttpStatusCode["MethodNotAllowed"] = "MethodNotAllowed";
|
||||
HttpStatusCode["NotAcceptable"] = "NotAcceptable";
|
||||
HttpStatusCode["ProxyAuthenticationRequired"] = "ProxyAuthenticationRequired";
|
||||
HttpStatusCode["RequestTimeout"] = "RequestTimeout";
|
||||
HttpStatusCode["Conflict"] = "Conflict";
|
||||
HttpStatusCode["Gone"] = "Gone";
|
||||
HttpStatusCode["LengthRequired"] = "LengthRequired";
|
||||
HttpStatusCode["PreconditionFailed"] = "PreconditionFailed";
|
||||
HttpStatusCode["RequestEntityTooLarge"] = "RequestEntityTooLarge";
|
||||
HttpStatusCode["RequestUriTooLong"] = "RequestUriTooLong";
|
||||
HttpStatusCode["UnsupportedMediaType"] = "UnsupportedMediaType";
|
||||
HttpStatusCode["RequestedRangeNotSatisfiable"] = "RequestedRangeNotSatisfiable";
|
||||
HttpStatusCode["ExpectationFailed"] = "ExpectationFailed";
|
||||
HttpStatusCode["MisdirectedRequest"] = "MisdirectedRequest";
|
||||
HttpStatusCode["UnprocessableEntity"] = "UnprocessableEntity";
|
||||
HttpStatusCode["Locked"] = "Locked";
|
||||
HttpStatusCode["FailedDependency"] = "FailedDependency";
|
||||
HttpStatusCode["UpgradeRequired"] = "UpgradeRequired";
|
||||
HttpStatusCode["PreconditionRequired"] = "PreconditionRequired";
|
||||
HttpStatusCode["TooManyRequests"] = "TooManyRequests";
|
||||
HttpStatusCode["RequestHeaderFieldsTooLarge"] = "RequestHeaderFieldsTooLarge";
|
||||
HttpStatusCode["UnavailableForLegalReasons"] = "UnavailableForLegalReasons";
|
||||
HttpStatusCode["InternalServerError"] = "InternalServerError";
|
||||
HttpStatusCode["NotImplemented"] = "NotImplemented";
|
||||
HttpStatusCode["BadGateway"] = "BadGateway";
|
||||
HttpStatusCode["ServiceUnavailable"] = "ServiceUnavailable";
|
||||
HttpStatusCode["GatewayTimeout"] = "GatewayTimeout";
|
||||
HttpStatusCode["HttpVersionNotSupported"] = "HttpVersionNotSupported";
|
||||
HttpStatusCode["VariantAlsoNegotiates"] = "VariantAlsoNegotiates";
|
||||
HttpStatusCode["InsufficientStorage"] = "InsufficientStorage";
|
||||
HttpStatusCode["LoopDetected"] = "LoopDetected";
|
||||
HttpStatusCode["NotExtended"] = "NotExtended";
|
||||
HttpStatusCode["NetworkAuthenticationRequired"] = "NetworkAuthenticationRequired";
|
||||
})(HttpStatusCode = exports.HttpStatusCode || (exports.HttpStatusCode = {}));
|
||||
var ApiException = /** @class */ (function (_super) {
|
||||
__extends(ApiException, _super);
|
||||
function ApiException(message, status, response, headers, result) {
|
||||
var _this = _super.call(this) || this;
|
||||
_this.isApiException = true;
|
||||
_this.message = message;
|
||||
_this.status = status;
|
||||
_this.response = response;
|
||||
_this.headers = headers;
|
||||
_this.result = result;
|
||||
return _this;
|
||||
}
|
||||
ApiException.isApiException = function (obj) {
|
||||
return obj.isApiException === true;
|
||||
};
|
||||
return ApiException;
|
||||
}(Error));
|
||||
exports.ApiException = ApiException;
|
||||
function throwException(message, status, response, headers, result) {
|
||||
if (result !== null && result !== undefined)
|
||||
throw result;
|
||||
else
|
||||
throw new ApiException(message, status, response, headers, null);
|
||||
}
|
||||
//# sourceMappingURL=LogService.js.map
|
File diff suppressed because one or more lines are too long
201
Birdmap.API/ClientApp/src/components/logs/LogService.ts
Normal file
201
Birdmap.API/ClientApp/src/components/logs/LogService.ts
Normal file
@ -0,0 +1,201 @@
|
||||
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
//----------------------
|
||||
// <auto-generated>
|
||||
// Generated using the NSwag toolchain v13.8.2.0 (NJsonSchema v10.2.1.0 (Newtonsoft.Json v12.0.0.0)) (http://NSwag.org)
|
||||
// </auto-generated>
|
||||
//----------------------
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
export default class LogService {
|
||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||
private baseUrl: string;
|
||||
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
||||
|
||||
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
||||
this.http = http ? http : <any>window;
|
||||
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "api/logs";
|
||||
}
|
||||
|
||||
getAll(): Promise<string[]> {
|
||||
let url_ = this.baseUrl + "/all";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_ = <RequestInit>{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json",
|
||||
'Authorization': sessionStorage.getItem('user')
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processGetAll(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processGetAll(response: Response): Promise<string[]> {
|
||||
const status = response.status;
|
||||
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||
if (status === 200) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result200: any = null;
|
||||
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
|
||||
if (Array.isArray(resultData200)) {
|
||||
result200 = [] as any;
|
||||
for (let item of resultData200)
|
||||
result200!.push(item);
|
||||
}
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<string[]>(<any>null);
|
||||
}
|
||||
|
||||
getFiles(filenames: string[] | null | undefined): Promise<FileResponse | null> {
|
||||
let url_ = this.baseUrl + "?";
|
||||
if (filenames !== undefined && filenames !== null)
|
||||
filenames && filenames.forEach(item => { url_ += "filenames=" + encodeURIComponent("" + item) + "&"; });
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_ = <RequestInit>{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/octet-stream",
|
||||
'Authorization': sessionStorage.getItem('user')
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processGetFiles(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processGetFiles(response: Response): Promise<FileResponse | null> {
|
||||
const status = response.status;
|
||||
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
|
||||
if (status === 200 || status === 206) {
|
||||
const contentDisposition = response.headers ? response.headers.get("content-disposition") : undefined;
|
||||
const fileNameMatch = contentDisposition ? /filename="?([^"]*?)"?(;|$)/g.exec(contentDisposition) : undefined;
|
||||
const fileName = fileNameMatch && fileNameMatch.length > 1 ? fileNameMatch[1] : undefined;
|
||||
return response.blob().then(blob => { return { fileName: fileName, data: blob, status: status, headers: _headers }; });
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<FileResponse | null>(<any>null);
|
||||
}
|
||||
}
|
||||
|
||||
export interface FileResponse {
|
||||
data: Blob;
|
||||
status: number;
|
||||
fileName?: string;
|
||||
headers?: { [name: string]: any };
|
||||
}
|
||||
|
||||
export enum HttpStatusCode {
|
||||
Continue = "Continue",
|
||||
SwitchingProtocols = "SwitchingProtocols",
|
||||
Processing = "Processing",
|
||||
EarlyHints = "EarlyHints",
|
||||
OK = "OK",
|
||||
Created = "Created",
|
||||
Accepted = "Accepted",
|
||||
NonAuthoritativeInformation = "NonAuthoritativeInformation",
|
||||
NoContent = "NoContent",
|
||||
ResetContent = "ResetContent",
|
||||
PartialContent = "PartialContent",
|
||||
MultiStatus = "MultiStatus",
|
||||
AlreadyReported = "AlreadyReported",
|
||||
IMUsed = "IMUsed",
|
||||
MultipleChoices = "Ambiguous",
|
||||
Ambiguous = "Ambiguous",
|
||||
MovedPermanently = "Moved",
|
||||
Moved = "Moved",
|
||||
Found = "Redirect",
|
||||
Redirect = "Redirect",
|
||||
SeeOther = "RedirectMethod",
|
||||
RedirectMethod = "RedirectMethod",
|
||||
NotModified = "NotModified",
|
||||
UseProxy = "UseProxy",
|
||||
Unused = "Unused",
|
||||
TemporaryRedirect = "TemporaryRedirect",
|
||||
RedirectKeepVerb = "TemporaryRedirect",
|
||||
PermanentRedirect = "PermanentRedirect",
|
||||
BadRequest = "BadRequest",
|
||||
Unauthorized = "Unauthorized",
|
||||
PaymentRequired = "PaymentRequired",
|
||||
Forbidden = "Forbidden",
|
||||
NotFound = "NotFound",
|
||||
MethodNotAllowed = "MethodNotAllowed",
|
||||
NotAcceptable = "NotAcceptable",
|
||||
ProxyAuthenticationRequired = "ProxyAuthenticationRequired",
|
||||
RequestTimeout = "RequestTimeout",
|
||||
Conflict = "Conflict",
|
||||
Gone = "Gone",
|
||||
LengthRequired = "LengthRequired",
|
||||
PreconditionFailed = "PreconditionFailed",
|
||||
RequestEntityTooLarge = "RequestEntityTooLarge",
|
||||
RequestUriTooLong = "RequestUriTooLong",
|
||||
UnsupportedMediaType = "UnsupportedMediaType",
|
||||
RequestedRangeNotSatisfiable = "RequestedRangeNotSatisfiable",
|
||||
ExpectationFailed = "ExpectationFailed",
|
||||
MisdirectedRequest = "MisdirectedRequest",
|
||||
UnprocessableEntity = "UnprocessableEntity",
|
||||
Locked = "Locked",
|
||||
FailedDependency = "FailedDependency",
|
||||
UpgradeRequired = "UpgradeRequired",
|
||||
PreconditionRequired = "PreconditionRequired",
|
||||
TooManyRequests = "TooManyRequests",
|
||||
RequestHeaderFieldsTooLarge = "RequestHeaderFieldsTooLarge",
|
||||
UnavailableForLegalReasons = "UnavailableForLegalReasons",
|
||||
InternalServerError = "InternalServerError",
|
||||
NotImplemented = "NotImplemented",
|
||||
BadGateway = "BadGateway",
|
||||
ServiceUnavailable = "ServiceUnavailable",
|
||||
GatewayTimeout = "GatewayTimeout",
|
||||
HttpVersionNotSupported = "HttpVersionNotSupported",
|
||||
VariantAlsoNegotiates = "VariantAlsoNegotiates",
|
||||
InsufficientStorage = "InsufficientStorage",
|
||||
LoopDetected = "LoopDetected",
|
||||
NotExtended = "NotExtended",
|
||||
NetworkAuthenticationRequired = "NetworkAuthenticationRequired",
|
||||
}
|
||||
|
||||
export class ApiException extends Error {
|
||||
message: string;
|
||||
status: number;
|
||||
response: string;
|
||||
headers: { [key: string]: any; };
|
||||
result: any;
|
||||
|
||||
constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
|
||||
super();
|
||||
|
||||
this.message = message;
|
||||
this.status = status;
|
||||
this.response = response;
|
||||
this.headers = headers;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
protected isApiException = true;
|
||||
|
||||
static isApiException(obj: any): obj is ApiException {
|
||||
return obj.isApiException === true;
|
||||
}
|
||||
}
|
||||
|
||||
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any {
|
||||
if (result !== null && result !== undefined)
|
||||
throw result;
|
||||
else
|
||||
throw new ApiException(message, status, response, headers, null);
|
||||
}
|
128
Birdmap.API/ClientApp/src/components/logs/Logs.jsx
Normal file
128
Birdmap.API/ClientApp/src/components/logs/Logs.jsx
Normal file
@ -0,0 +1,128 @@
|
||||
import { Box, Button, Checkbox, List, ListItem, ListItemIcon, ListItemText, Paper, withStyles } from '@material-ui/core';
|
||||
import { blueGrey } from '@material-ui/core/colors';
|
||||
import React, { Component } from 'react';
|
||||
import LogService from './LogService';
|
||||
|
||||
const styles = theme => ({
|
||||
root: {
|
||||
padding: '64px',
|
||||
backgroundColor: theme.palette.primary.dark,
|
||||
},
|
||||
paper: {
|
||||
backgroundColor: blueGrey[50],
|
||||
},
|
||||
});
|
||||
|
||||
class Logs extends Component {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
|
||||
this.state = {
|
||||
service: null,
|
||||
files: [],
|
||||
checked: [],
|
||||
selectAllChecked: false,
|
||||
}
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
var service = new LogService();
|
||||
this.setState({service: service});
|
||||
|
||||
service.getAll().then(result => {
|
||||
this.setState({files: result});
|
||||
}).catch(ex => console.log(ex));
|
||||
}
|
||||
|
||||
handleToggle = (value) => {
|
||||
const currentIndex = this.state.checked.indexOf(value);
|
||||
const newChecked = [...this.state.checked];
|
||||
|
||||
if (currentIndex === -1) {
|
||||
newChecked.push(value);
|
||||
} else {
|
||||
newChecked.splice(currentIndex, 1);
|
||||
}
|
||||
|
||||
this.setState({checked: newChecked});
|
||||
}
|
||||
|
||||
handleSelectAllToggle = () => {
|
||||
this.setState({selectAllChecked: !this.state.selectAllChecked});
|
||||
if (this.state.selectAllChecked) {
|
||||
this.setState({checked: []});
|
||||
} else {
|
||||
const newChecked = [...this.state.files];
|
||||
this.setState({checked: newChecked});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
onDownload = () => {
|
||||
this.state.service.getFiles(this.state.checked)
|
||||
.then(result => {
|
||||
const filename = `Logs-${new Date().toISOString()}.zip`;
|
||||
const textUrl = URL.createObjectURL(result.data);
|
||||
const element = document.createElement('a');
|
||||
element.setAttribute('href', textUrl);
|
||||
element.setAttribute('download', filename);
|
||||
element.style.display = 'none';
|
||||
document.body.appendChild(element);
|
||||
element.click();
|
||||
document.body.removeChild(element);
|
||||
this.setState({checked: []});
|
||||
this.setState({selectAllChecked: false});
|
||||
})
|
||||
.catch(ex => console.log(ex));
|
||||
}
|
||||
|
||||
render() {
|
||||
const { classes } = this.props;
|
||||
|
||||
const Files = this.state.files.map((value) => {
|
||||
const labelId = `checkbox-list-label-${value}`;
|
||||
|
||||
return (
|
||||
<ListItem key={value} role={undefined} dense button onClick={() => this.handleToggle(value)}>
|
||||
<ListItemIcon>
|
||||
<Checkbox
|
||||
edge="start"
|
||||
checked={this.state.checked.indexOf(value) !== -1}
|
||||
tabIndex={-1}
|
||||
disableRipple
|
||||
inputProps={{ 'aria-labelledby': labelId }}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
<ListItemText id={labelId} primary={`${value}`} />
|
||||
</ListItem>
|
||||
);
|
||||
})
|
||||
|
||||
return (
|
||||
<Box className={classes.root}>
|
||||
<Paper className={classes.paper}>
|
||||
<List className={classes.paper}>
|
||||
<ListItem key="Select-all" role={undefined} dense button onClick={this.handleSelectAllToggle}>
|
||||
<ListItemIcon>
|
||||
<Checkbox
|
||||
edge="start"
|
||||
checked={this.state.selectAllChecked}
|
||||
tabIndex={-1}
|
||||
disableRipple
|
||||
inputProps={{ 'aria-labelledby': "Select-all" }}
|
||||
/>
|
||||
</ListItemIcon>
|
||||
<ListItemText id="checkbox-list-label-Select-all" primary={(this.state.selectAllChecked ? "Uns" : "S") + "elect all"} />
|
||||
</ListItem>
|
||||
{Files}
|
||||
</List>
|
||||
<Button onClick={this.onDownload}>
|
||||
Download
|
||||
</Button>
|
||||
</Paper>
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export default withStyles(styles)(Logs);
|
@ -99,15 +99,19 @@ export default class DevicesContextProvider extends Component {
|
||||
.then(_ => {
|
||||
console.log('Devices hub Connected!');
|
||||
|
||||
newConnection.on(C.probability_method_name, (id, date, prob) => {
|
||||
newConnection.on(C.probability_method_name, (messages) => {
|
||||
//console.log(method_name + " recieved: [id: " + id + ", date: " + date + ", prob: " + prob + "]");
|
||||
var device = this.state.devices.filter(function (x) { return x.id === id })[0]
|
||||
var newPoint = { deviceId: device.id, lat: device.coordinates.latitude, lng: device.coordinates.longitude, prob: prob, date: new Date(date) };
|
||||
const newPoints = [];
|
||||
for (var message of messages) {
|
||||
var device = this.state.devices.filter(function (x) { return x.id === message.deviceId })[0]
|
||||
var newPoint = { deviceId: device.id, lat: device.coordinates.latitude, lng: device.coordinates.longitude, prob: message.probability, date: new Date(message.date) };
|
||||
newPoints.push(newPoint);
|
||||
}
|
||||
this.setState({
|
||||
heatmapPoints: [...this.state.heatmapPoints, newPoint]
|
||||
heatmapPoints: this.state.heatmapPoints.concat(newPoints)
|
||||
});
|
||||
|
||||
this.invokeHandlers(C.probability_method_name, newPoint);
|
||||
this.invokeHandlers(C.probability_method_name, newPoints);
|
||||
});
|
||||
|
||||
newConnection.on(C.update_all_method_name, () => {
|
||||
|
66
Birdmap.API/Controllers/LogsController.cs
Normal file
66
Birdmap.API/Controllers/LogsController.cs
Normal file
@ -0,0 +1,66 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Birdmap.API.Controllers
|
||||
{
|
||||
[Authorize(Roles = "Admin")]
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class LogsController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<LogsController> _logger;
|
||||
private readonly string _logFolderPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Logs");
|
||||
|
||||
public LogsController(ILogger<LogsController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet("all")]
|
||||
public ActionResult<List<string>> GetAll()
|
||||
{
|
||||
_logger.LogInformation($"Getting all log filenames from folder: '{_logFolderPath}'...");
|
||||
|
||||
return Directory.EnumerateFiles(_logFolderPath, "*.log")
|
||||
.Select(f => Path.GetFileName(f))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> GetFiles([FromQuery] params string[] filenames)
|
||||
{
|
||||
if (!filenames.Any())
|
||||
return null;
|
||||
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var zipStream = new MemoryStream();
|
||||
|
||||
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(_logFolderPath, "*.log"))
|
||||
{
|
||||
var filename = Path.GetFileName(file);
|
||||
|
||||
if (filenames.Contains(filename))
|
||||
{
|
||||
zip.CreateEntryFromFile(file, filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
zipStream.Position = 0;
|
||||
|
||||
return File(zipStream, "application/octet-stream");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
27
Birdmap.API/Dockerfile
Normal file
27
Birdmap.API/Dockerfile
Normal file
@ -0,0 +1,27 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
|
||||
WORKDIR /app
|
||||
RUN apt-get update && apt-get install -y curl
|
||||
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash -
|
||||
RUN apt-get update && apt-get install -y nodejs
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
|
||||
RUN apt-get update && apt-get install -y curl
|
||||
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash -
|
||||
RUN apt-get update && apt-get install -y nodejs
|
||||
WORKDIR /src
|
||||
COPY ["Birdmap.API/Birdmap.API.csproj", "Birdmap.API/"]
|
||||
COPY ["Birdmap.BLL/Birdmap.BLL.csproj", "Birdmap.BLL/"]
|
||||
COPY ["Birdmap.Common/Birdmap.Common.csproj", "Birdmap.Common/"]
|
||||
COPY ["Birdmap.DAL/Birdmap.DAL.csproj", "Birdmap.DAL/"]
|
||||
RUN dotnet restore "Birdmap.API/Birdmap.API.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/Birdmap.API"
|
||||
RUN dotnet build "Birdmap.API.csproj" -c Release -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
RUN dotnet publish "Birdmap.API.csproj" -c Release -o /app/publish
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "Birdmap.API.dll"]
|
@ -1,5 +1,6 @@
|
||||
using Birdmap.DAL;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@ -39,6 +40,10 @@ namespace Birdmap.API
|
||||
|
||||
public static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureAppConfiguration((hostingContext, config) =>
|
||||
{
|
||||
config.AddEnvironmentVariables(prefix: "Birdmap_");
|
||||
})
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
@ -53,8 +58,8 @@ namespace Birdmap.API
|
||||
private static void SeedDatabase(IHost host)
|
||||
{
|
||||
using var scope = host.Services.CreateScope();
|
||||
var dbInitializer = scope.ServiceProvider.GetRequiredService<DbInitializer>();
|
||||
|
||||
var dbInitializer = scope.ServiceProvider.GetRequiredService<DbInitializer>();
|
||||
dbInitializer.Initialize();
|
||||
}
|
||||
}
|
||||
|
@ -1,7 +1,11 @@
|
||||
{
|
||||
{
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iis": {
|
||||
"applicationUrl": "http://localhost/Birdmap.API",
|
||||
"sslPort": 0
|
||||
},
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:63288",
|
||||
"sslPort": 44331
|
||||
@ -12,16 +16,24 @@
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"environmentVariables": {
|
||||
"Birdmap_LocalDbConnectionString": "Data Source=DESKTOP-3600;Initial Catalog=birdmap2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Birdmap": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"applicationUrl": "https://localhost:5001;http://localhost:5000"
|
||||
},
|
||||
"Docker": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
}
|
||||
}
|
@ -1,11 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Birdmap.API.Services
|
||||
{
|
||||
public record Message(Guid DeviceId, DateTime Date, double Probability);
|
||||
|
||||
public interface IDevicesHubClient
|
||||
{
|
||||
Task NotifyDeviceAsync(Guid deviceId, DateTime date, double probability);
|
||||
Task NotifyMessagesAsync(IEnumerable<Message> messages);
|
||||
Task NotifyDeviceUpdatedAsync(Guid deviceId);
|
||||
Task NotifyAllUpdatedAsync();
|
||||
}
|
||||
|
@ -9,9 +9,11 @@ using MQTTnet.Client.Disconnecting;
|
||||
using MQTTnet.Client.Options;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
namespace Birdmap.API.Services.Mqtt
|
||||
{
|
||||
@ -22,6 +24,9 @@ namespace Birdmap.API.Services.Mqtt
|
||||
private readonly ILogger<MqttClientService> _logger;
|
||||
private readonly IInputService _inputService;
|
||||
private readonly IHubContext<DevicesHub, IDevicesHubClient> _hubContext;
|
||||
private readonly Timer _hubTimer;
|
||||
private readonly List<Message> _messages = new();
|
||||
private readonly object _messageLock = new();
|
||||
|
||||
public bool IsConnected => _mqttClient.IsConnected;
|
||||
|
||||
@ -31,10 +36,30 @@ namespace Birdmap.API.Services.Mqtt
|
||||
_logger = logger;
|
||||
_inputService = inputService;
|
||||
_hubContext = hubContext;
|
||||
_hubTimer = new Timer()
|
||||
{
|
||||
AutoReset = true,
|
||||
Interval = 1000,
|
||||
};
|
||||
_hubTimer.Elapsed += SendMqttMessagesWithSignalR;
|
||||
|
||||
_mqttClient = new MqttFactory().CreateMqttClient();
|
||||
ConfigureMqttClient();
|
||||
}
|
||||
|
||||
private void SendMqttMessagesWithSignalR(object sender, System.Timers.ElapsedEventArgs e)
|
||||
{
|
||||
lock (_messageLock)
|
||||
{
|
||||
if (_messages.Any())
|
||||
{
|
||||
_logger.LogInformation($"Sending ({_messages.Count}) messages: {string.Join(" | ", _messages)}");
|
||||
_hubContext.Clients.All.NotifyMessagesAsync(_messages);
|
||||
_messages.Clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ConfigureMqttClient()
|
||||
{
|
||||
_mqttClient.ConnectedHandler = this;
|
||||
@ -55,7 +80,7 @@ namespace Birdmap.API.Services.Mqtt
|
||||
{
|
||||
var message = eventArgs.ApplicationMessage.ConvertPayloadToString();
|
||||
|
||||
_logger.LogInformation($"Recieved [{eventArgs.ClientId}] " +
|
||||
_logger.LogDebug($"Recieved [{eventArgs.ClientId}] " +
|
||||
$"Topic: {eventArgs.ApplicationMessage.Topic} | Payload: {message} | QoS: {eventArgs.ApplicationMessage.QualityOfServiceLevel} | Retain: {eventArgs.ApplicationMessage.Retain}");
|
||||
|
||||
try
|
||||
@ -63,7 +88,10 @@ namespace Birdmap.API.Services.Mqtt
|
||||
var payload = JsonConvert.DeserializeObject<Payload>(message);
|
||||
var inputResponse = await _inputService.GetInputAsync(payload.TagID);
|
||||
|
||||
await _hubContext.Clients.All.NotifyDeviceAsync(inputResponse.Message.Device_id, inputResponse.Message.Date.UtcDateTime, payload.Probability);
|
||||
lock (_messageLock)
|
||||
{
|
||||
_messages.Add(new Message(inputResponse.Message.Device_id, inputResponse.Message.Date.UtcDateTime, payload.Probability));
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -79,6 +107,7 @@ namespace Birdmap.API.Services.Mqtt
|
||||
_logger.LogInformation($"Connected. Auth result: {eventArgs.AuthenticateResult}. Subscribing to topic: {topic}");
|
||||
|
||||
await _mqttClient.SubscribeAsync(topic);
|
||||
_hubTimer.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -88,17 +117,18 @@ namespace Birdmap.API.Services.Mqtt
|
||||
|
||||
public async Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs eventArgs)
|
||||
{
|
||||
_logger.LogWarning(eventArgs.Exception, $"Disconnected. Reason {eventArgs.ReasonCode}. Auth result: {eventArgs.AuthenticateResult}. Reconnecting...");
|
||||
_logger.LogDebug(eventArgs.Exception, $"Disconnected. Reason {eventArgs.ReasonCode}. Auth result: {eventArgs.AuthenticateResult}. Reconnecting...");
|
||||
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
|
||||
try
|
||||
{
|
||||
_hubTimer.Stop();
|
||||
await _mqttClient.ConnectAsync(_options, CancellationToken.None);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"Reconnect failed...");
|
||||
_logger.LogDebug(ex, $"Reconnect failed...");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -5,5 +5,50 @@
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"Kestrel": {
|
||||
"Certificates": {
|
||||
"Default": {
|
||||
"Password": "certpass123",
|
||||
"Path": "C:\\Users\\Ricsi\\AppData\\Roaming\\ASP.NET\\Https\\aspnetapp.pfx"
|
||||
}
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Secret": "7vj.3KW.hYE!}4u6",
|
||||
// "LocalDbConnectionString": "Data Source=DESKTOP-3600\\SQLEXPRESS;Initial Catalog=birdmap;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
|
||||
"LocalDbConnectionString": "Data Source=DESKTOP-3600;Initial Catalog=birdmap2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
|
||||
"Defaults": {
|
||||
"Services": {
|
||||
"Local Database": "https://localhost:44331/health",
|
||||
"KMLabz Services": "https://birb.k8s.kmlabz.com/devices"
|
||||
},
|
||||
"Users": [
|
||||
{
|
||||
"Name": "admin",
|
||||
"Password": "pass",
|
||||
"Role": "Admin"
|
||||
},
|
||||
{
|
||||
"Name": "user",
|
||||
"Password": "pass",
|
||||
"Role": "User"
|
||||
}
|
||||
]
|
||||
},
|
||||
"UseDummyServices": true,
|
||||
"ServicesBaseUrl": "https://birb.k8s.kmlabz.com/",
|
||||
"Mqtt": {
|
||||
"BrokerHostSettings": {
|
||||
"Host": "localhost",
|
||||
"Port": 1883
|
||||
},
|
||||
|
||||
"ClientSettings": {
|
||||
"Id": "ASP.NET Core client",
|
||||
"Username": "username",
|
||||
"Password": "password",
|
||||
"Topic": "devices/output"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -6,40 +6,35 @@
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"Kestrel": {
|
||||
"Certificates": {
|
||||
"Default": {
|
||||
"Password": "",
|
||||
"Path": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Secret": "7vj.3KW.hYE!}4u6",
|
||||
// "LocalDbConnectionString": "Data Source=DESKTOP-3600\\SQLEXPRESS;Initial Catalog=birdmap;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
|
||||
"LocalDbConnectionString": "Data Source=DESKTOP-3600;Initial Catalog=birdmap;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
|
||||
"Secret": "",
|
||||
"LocalDbConnectionString": "",
|
||||
"Defaults": {
|
||||
"Services": {
|
||||
"Local Database": "https://localhost:44331/health",
|
||||
"KMLabz Services": "https://birb.k8s.kmlabz.com/devices"
|
||||
},
|
||||
"Users": [
|
||||
{
|
||||
"Name": "admin",
|
||||
"Password": "pass",
|
||||
"Role": "Admin"
|
||||
"Users": []
|
||||
},
|
||||
{
|
||||
"Name": "user",
|
||||
"Password": "pass",
|
||||
"Role": "User"
|
||||
}
|
||||
]
|
||||
},
|
||||
"UseDummyServices": true,
|
||||
"UseDummyServices": false,
|
||||
"ServicesBaseUrl": "https://birb.k8s.kmlabz.com/",
|
||||
"Mqtt": {
|
||||
"BrokerHostSettings": {
|
||||
"Host": "localhost",
|
||||
"Host": "",
|
||||
"Port": 1883
|
||||
},
|
||||
|
||||
"ClientSettings": {
|
||||
"Id": "ASP.NET Core client",
|
||||
"Username": "username",
|
||||
"Password": "password",
|
||||
"Topic": "devices/output"
|
||||
"Username": "",
|
||||
"Password": "",
|
||||
"Topic": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,7 @@
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
autoReload="true"
|
||||
internalLogLevel="Info"
|
||||
internalLogFile="${basedir}Log/internal-nlog.txt"
|
||||
internalLogFile="${basedir}Logs/internal-nlog.txt"
|
||||
throwConfigExceptions="true">
|
||||
|
||||
<!-- enable asp.net core layout renderers -->
|
||||
@ -14,17 +14,17 @@
|
||||
<!-- the targets to write to -->
|
||||
<targets async="true">
|
||||
<default-target-parameters xsi:type="File" keepFileOpen="false" maxArchiveFiles="10" archiveAboveSize="1048576"/>
|
||||
<target xsi:type="File" name="allFile" fileName="${basedir}Log/birdmap-all-${shortdate}.log"
|
||||
<target xsi:type="File" name="allFile" fileName="${basedir}Logs/birdmap-all-${shortdate}.log"
|
||||
layout="${longdate} [${threadname:whenEmpty=${threadid}}] ${uppercase:${level}} ${logger} - ${message} ${exception:format=tostring}" />
|
||||
|
||||
<target xsi:type="File" name="mqttFile" fileName="${basedir}Log/birdmap-mqtt-${shortdate}.log"
|
||||
<target xsi:type="File" name="mqttFile" fileName="${basedir}Logs/birdmap-mqtt-${shortdate}.log"
|
||||
layout="${longdate} [${threadname:whenEmpty=${threadid}}] ${uppercase:${level}} ${logger} - ${message} ${exception:format=tostring}" />
|
||||
|
||||
<target xsi:type="File" name="hubsFile" fileName="${basedir}Log/birdmap-hubs-${shortdate}.log"
|
||||
<target xsi:type="File" name="hubsFile" fileName="${basedir}Logs/birdmap-hubs-${shortdate}.log"
|
||||
layout="${longdate} [${threadname:whenEmpty=${threadid}}] ${uppercase:${level}} ${logger} - ${message} ${exception:format=tostring}" />
|
||||
|
||||
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
|
||||
<target xsi:type="File" name="ownFile" fileName="${basedir}Log/birdmap-own-${shortdate}.log"
|
||||
<target xsi:type="File" name="ownFile" fileName="${basedir}Logs/birdmap-own-${shortdate}.log"
|
||||
layout="${longdate} [${threadname:whenEmpty=${threadid}}] ${uppercase:${level}} ${callsite} - ${message} ${exception:format=tostring} (url: ${aspnet-request-url})(action: ${aspnet-mvc-action})" />
|
||||
</targets>
|
||||
|
||||
|
@ -23,8 +23,9 @@ namespace Birdmap.BLL.Services
|
||||
private System.Net.Http.HttpClient _httpClient;
|
||||
private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
|
||||
|
||||
public LiveDummyService(System.Net.Http.HttpClient httpClient)
|
||||
public LiveDummyService(string baseUrl, System.Net.Http.HttpClient httpClient)
|
||||
{
|
||||
_baseUrl = baseUrl;
|
||||
_httpClient = httpClient;
|
||||
_settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings);
|
||||
}
|
||||
|
@ -23,8 +23,9 @@ namespace Birdmap.BLL.Services
|
||||
private System.Net.Http.HttpClient _httpClient;
|
||||
private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
|
||||
|
||||
public LiveInputService(System.Net.Http.HttpClient httpClient)
|
||||
public LiveInputService(string baseUrl, System.Net.Http.HttpClient httpClient)
|
||||
{
|
||||
_baseUrl = baseUrl;
|
||||
_httpClient = httpClient;
|
||||
_settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings);
|
||||
}
|
||||
|
@ -2,6 +2,7 @@
|
||||
using Birdmap.BLL.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace Birdmap.BLL
|
||||
{
|
||||
@ -20,8 +21,20 @@ namespace Birdmap.BLL
|
||||
}
|
||||
else
|
||||
{
|
||||
services.AddTransient<IInputService, LiveInputService>();
|
||||
services.AddTransient<IDeviceService, LiveDummyService>();
|
||||
var baseUrl = configuration.GetValue<string>("ServicesBaseUrl");
|
||||
|
||||
services.AddTransient<IInputService, LiveInputService>(serviceProvider =>
|
||||
{
|
||||
var httpClient = serviceProvider.GetService<HttpClient>();
|
||||
var service = new LiveInputService(baseUrl, httpClient);
|
||||
return service;
|
||||
});
|
||||
services.AddTransient<IDeviceService, LiveDummyService>(serviceProvider =>
|
||||
{
|
||||
var httpClient = serviceProvider.GetService<HttpClient>();
|
||||
var service = new LiveDummyService(baseUrl, httpClient);
|
||||
return service;
|
||||
});
|
||||
}
|
||||
|
||||
return services;
|
||||
|
@ -22,10 +22,17 @@ namespace Birdmap.DAL
|
||||
|
||||
public void Initialize()
|
||||
{
|
||||
EnsureCreated();
|
||||
AddDefaultUsers();
|
||||
AddDefaultServices();
|
||||
}
|
||||
|
||||
private void EnsureCreated()
|
||||
{
|
||||
_logger.LogInformation("Ensuring database is created...");
|
||||
_context.Database.EnsureCreated();
|
||||
}
|
||||
|
||||
private void AddDefaultServices()
|
||||
{
|
||||
_logger.LogInformation("Removing previously added default services...");
|
||||
|
@ -13,6 +13,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Birdmap.Common", "Birdmap.C
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MQTTnet.TestApp.WinForm", "MQTTnet.TestApp.WinForm\MQTTnet.TestApp.WinForm.csproj", "{E1707FE7-4A65-42AC-B71C-6CC1A55FC42A}"
|
||||
EndProject
|
||||
Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "docker-compose.dcproj", "{9443433B-1D13-41F0-B345-B36ACD15EF81}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@ -39,6 +41,10 @@ Global
|
||||
{E1707FE7-4A65-42AC-B71C-6CC1A55FC42A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E1707FE7-4A65-42AC-B71C-6CC1A55FC42A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E1707FE7-4A65-42AC-B71C-6CC1A55FC42A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{9443433B-1D13-41F0-B345-B36ACD15EF81}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{9443433B-1D13-41F0-B345-B36ACD15EF81}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{9443433B-1D13-41F0-B345-B36ACD15EF81}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{9443433B-1D13-41F0-B345-B36ACD15EF81}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
1
MQTTnet.TestApp.WinForm/Retained.json
Normal file
1
MQTTnet.TestApp.WinForm/Retained.json
Normal file
@ -0,0 +1 @@
|
||||
[{"Topic":"devices/output","Payload":"eyJ0YWciOiJkNDhhODAwOC0wYjU2LTRkYzAtODYxMy0zMWY0MDY4OTk0ZDciLCJwcm9iYWJpbGl0eSI6MC4yNTMxNDI4NDgyNjMwOTU1fQ==","QualityOfServiceLevel":1,"Retain":true,"UserProperties":null,"ContentType":null,"ResponseTopic":null,"PayloadFormatIndicator":null,"MessageExpiryInterval":null,"TopicAlias":null,"CorrelationData":null,"SubscriptionIdentifiers":null}]
|
15
docker-compose.dcproj
Normal file
15
docker-compose.dcproj
Normal file
@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" Sdk="Microsoft.Docker.Sdk">
|
||||
<PropertyGroup Label="Globals">
|
||||
<ProjectVersion>2.1</ProjectVersion>
|
||||
<DockerTargetOS>Linux</DockerTargetOS>
|
||||
<ProjectGuid>9443433b-1d13-41f0-b345-b36acd15ef81</ProjectGuid>
|
||||
<DockerLaunchAction>LaunchBrowser</DockerLaunchAction>
|
||||
<DockerServiceUrl>{Scheme}://localhost:{ServicePort}</DockerServiceUrl>
|
||||
<DockerServiceName>birdmap.api</DockerServiceName>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<None Include="docker-compose.yml" />
|
||||
<None Include=".dockerignore" />
|
||||
</ItemGroup>
|
||||
</Project>
|
46
docker-compose.yml
Normal file
46
docker-compose.yml
Normal file
@ -0,0 +1,46 @@
|
||||
version: '3.4'
|
||||
|
||||
services:
|
||||
db:
|
||||
image: "mcr.microsoft.com/mssql/server:2019-latest"
|
||||
environment:
|
||||
- ACCEPT_EULA=Y
|
||||
- SA_PASSWORD=RPSsql12345
|
||||
|
||||
birdmap.api:
|
||||
image: ${DOCKER_REGISTRY-}birdmapapi
|
||||
ports:
|
||||
- "8000:80"
|
||||
- "8001:443"
|
||||
volumes:
|
||||
- ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
|
||||
- ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Birdmap.API/Dockerfile
|
||||
depends_on:
|
||||
- db
|
||||
environment:
|
||||
- ASPNETCORE_ENVIRONMENT=Docker
|
||||
- ASPNETCORE_URLS=https://+;http://+
|
||||
- ASPNETCORE_HTTPS_PORT=8001
|
||||
- Birdmap_Kestrel__Certificates__Default__Password=certpass123
|
||||
- Birdmap_Kestrel__Certificates__Default__Path=/root/.aspnet/https/aspnetapp.pfx
|
||||
- Birdmap_Secret=7gz;]=bQe}n#3~RwC+Y<SrjoE:sHwO
|
||||
- Birdmap_LocalDbConnectionString=Data Source=db;Initial Catalog=birdmap;User=sa;Password=RPSsql12345
|
||||
- Birdmap_Defaults__Users__0__Name=admin
|
||||
- Birdmap_Defaults__Users__0__Password=pass
|
||||
- Birdmap_Defaults__Users__0__Role=Admin
|
||||
- Birdmap_Defaults__Users__1__Name=user
|
||||
- Birdmap_Defaults__Users__1__Password=pass
|
||||
- Birdmap_Defaults__Users__1__Role=User
|
||||
- Birdmap_Defaults__Services__Local-Database=https://localhost:8001/health
|
||||
- Birdmap_Defaults__Services__KMLabz-Service=https://birb.k8s.kmlabz.com/devices
|
||||
- Birdmap_UseDummyServices=true
|
||||
- Birdmap_ServicesBaseUrl=https://birb.k8s.kmlabz.com/
|
||||
- Birdmap_Mqtt__BrokerHostSettings__Host=localhost
|
||||
- Birdmap_Mqtt__BrokerHostSettings__Port=1883
|
||||
- Birdmap_Mqtt__ClientSettings__Id=ASP.NET Core client
|
||||
- Birdmap_Mqtt__ClientSettings__Username=username
|
||||
- Birdmap_Mqtt__ClientSettings__Password=password
|
||||
- Birdmap_Mqtt__ClientSettings__Topic=devices/output
|
Reference in New Issue
Block a user