-
Notifications
You must be signed in to change notification settings - Fork 0
/
bike.js
69 lines (55 loc) · 1.42 KB
/
bike.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const express = require('express');
const axios = require('axios');
const IP_ADDRESS = '127.0.0.1';
const MANAGEMENT_APPLICATION_HOST = 'localhost:3000';
const PING_INTERVAL = 60000;
const [a, b, SYSTEM_ID, PORT] = process.argv;
let state = {
locked: true,
status: 'N/A',
light: 'off',
ip: `${IP_ADDRESS}:${PORT}`,
};
const updateModel = async (data) => {
try {
const response = await axios.patch(
`http://${MANAGEMENT_APPLICATION_HOST}/bicycles/${SYSTEM_ID}`,
data,
);
return response;
} catch (e) {
console.error('No connection to management application');
}
};
const app = express();
app.use(express.json());
const getCurrentLocation = () => `RANDOM LOCATION${new Date()}`;
const turnOn = async () => {
console.log('Bike is starting...');
state.status = 'free';
app.listen(PORT);
console.log(`Bike is listening on port: ${PORT}`);
await updateModel(state);
setInterval(async () => {
console.log('Sending current status to management application');
await updateModel({
...state,
location: getCurrentLocation(),
});
}, PING_INTERVAL);
};
app.get('/', (req, res) => {
res.send(state);
});
app.post('/', async (req, res) => {
try {
console.log('Updating bike status from management application...');
const {body} = req;
state = {...state, ...body};
res.send(state);
} catch (e) {
console.error(e);
res.send(e);
}
});
turnOn();