-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
347 lines (313 loc) · 9.29 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// define proxy
process.env.HTTP_PROXY = 'http://ptmproxy.gmv.es:80';
process.env.HTTPS_PROXY = 'http://ptmproxy.gmv.es:80';
var SerialPort = require('serialport');
var morgan = require('morgan');
var express = require('express');
var bodyParser = require('body-parser');
var sqlite3 = require('sqlite3');
// var io = require('socket.io')(http)
// serial port definition
var port = new SerialPort('COM4', {
baudRate: 9600,
encoding: 'ascii',
parser: SerialPort.parsers.readline('\n')
});
// create server
const app = express();
// http server
var http = require('http').Server(app);
// socket io connection
var io = require('socket.io')(http);
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use(morgan('combined'));
// get name
const dns = require('dns');
// dns.reverse('172.22.60.5',(err,a)=>{console.log(a)})
// Simple App State
const STATE = {
angle: 70.0,
offset: 0.0,
lasPetition: new Date(0)
};
/**
* seconds from date1 to date2
*
* @param {Date} date1
* @param {Date} date2
*/
function secsBetween (date1, date2) {
// Get 1 day in milliseconds
var one_sec = 1000;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to seconds and return
return Math.round(difference_ms / one_sec);
}
/**
* seconds from date to now
*
* @param {Date} date
*/
function secsFromNow (date) {
return secsBetween(date, new Date());
}
/**
* seconds from date to now, corrected with server offset
*
* @param {Date} date
*/
function secsFromNowCorrected (date) {
return secsBetween(new Date(date.getTime() + STATE.offset), new Date());
}
// validate a petition to operate the servo
function validatePetition (petition_date) {
// must not be older than 2 seconds
const notOld = (Math.abs(secsFromNowCorrected(petition_date)) < 2);
// must be at least 1 second between petitions
const niceRatio = secsBetween(STATE.lasPetition, petition_date) > 0.5;
// operated at an apporpiate time so no one is waken up
const appropiateTime = petition_date.getHours() > 7 && petition_date.getHours() < 20;
return (notOld && niceRatio && appropiateTime);
}
// send the command to operate the servo to the serial port
function run_servo () {
// adjust integer to 3 figures
angleFixed = ('00' + STATE.angle).slice(-3);
const buf5 = Buffer.from('joke' + angleFixed + '.', 'ascii');
port.write(buf5, function (err) {
if (err) {
return console.log('Error on write: ', err.message);
}
console.log('message written');
});
}
// Request measurements to the serial port
function request_meas () {
const buf5 = Buffer.from('meas.', 'ascii');
port.write(buf5, function (err) {
if (err) {
return console.log('Error on write: ', err.message);
}
});
}
/**
* Parse the measurements
* @param {String} data
* @param {Function} cb
*/
const parseMeasurements = (data, cb) => {
data = data.trim();
try {
parsed_data = JSON.parse(data);
cb(null, parsed_data);
} catch (error) {
cb(error);
}
};
function init_app () {
// app.listen(6969)
http.listen(6969, function () {
console.log('listening on *:6969');
});
// sqlite
var db = new sqlite3.Database('local.db');
db.serialize(function () {
db.run('CREATE TABLE IF NOT EXISTS meas (date INTEGER, type TEXT, value REAL)');
db.run('CREATE TABLE IF NOT EXISTS users (name TEXT, pass TEXT)');
db.run('CREATE TABLE IF NOT EXISTS petitions (date INTEGER, by TEXT)');
});
function cleanDB () {
db.close();
}
function getUserData (name) {
db.get('SELECT * FROM users WHERE name =?', name, function (err, data) {
console.log(data);
});
}
function addTempMeasurement (value,timestamp) {
try {
var stmt = db.prepare('INSERT INTO meas VALUES (?,?,?)');
stmt.run(timestamp, 'Temperature', value);
stmt.finalize();
} catch (e) {
console.log(e);
}
}
function addPetition (petition_source) {
try {
var stmt = db.prepare('INSERT INTO petitions VALUES (?,?)');
const timestamp = new Date().getTime();
stmt.run(timestamp, petition_source);
stmt.finalize();
} catch (e) {
console.log(e);
}
}
function addHumMeasurement (value,timestamp) {
try {
var stmt = db.prepare('INSERT INTO meas VALUES (?,?,?)');
stmt.run(timestamp, 'Humidity', value);
stmt.finalize();
} catch (e) {
console.log(e);
}
}
function getMeasurementsHumid (nb,cb) {
db.serialize(() => {
db.all('SELECT * FROM meas WHERE type is "Humidity" ORDER BY date DESC LIMIT $nb_items ',{$nb_items:nb}, function (err, data) {
// example { timestamp: 12312321, name: 'fdsf', value: 5456 }
cb(null, data);
});
});
}
function getMeasurementsTemp (cb) {
db.serialize(() => {
db.all('SELECT * FROM meas WHERE type is "Temperature" ORDER BY date DESC LIMIT 600 ', function (err, data) {
// example { timestamp: 12312321, name: 'fdsf', value: 5456 }
cb(null, data);
});
});
}
function getScores (cb) {
db.serialize(() => {
db.all('SELECT COUNT(by) as count, by FROM petitions GROUP BY by', function (err, data) {
// example { by: 'fdsf', count: 5456 }
cb(null, data);
});
});
}
function getPetitions (cb) {
db.serialize(() => {
db.all('SELECT * FROM petitions', function (err, data) {
cb(null, data);
});
});
}
// *****************************************************************************************************
app.use('/static', express.static('public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/index.html');
});
app.post('/login', function (req, res) {
const user = req.body.username;
const pass = req.body.password;
res.sendFile(__dirname + '/public/index.html');
});
function getIp (req) {
return req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
}
app.get('/api/run', function (req, res) {
const petition_date = new Date();
var ip = getIp(req);
// clean ip address
ip = ip.replace('::ffff:', '');
console.log('petition at :' + petition_date + ' by ' + ip);
if (validatePetition(petition_date)) {
STATE.lasPetition = petition_date;
run_servo();
res.sendStatus(200);
// add to database
dns.reverse(ip, (err, a) => {
console.log('petition by :' + a);
if (a) {
addPetition(a[0]);
// tell everyone
io.emit('new click', {by: a[0]});
} else {
addPetition('jonhDoe');
// tell everyone
io.emit('new click', {by: 'jonhDoe'});
console.log('*********** Unknown Player ************')
}
});
} else {
console.log('rejected petition');
res.sendStatus(404);
dns.reverse(ip, (err, a) => {
console.log('petition by :' + a);});
}
});
app.get('/api/temp', function (req, res) {
getMeasurementsTemp((err, meas) => {
res.json({'data': meas});
});
});
app.get('/api/humid', function (req, res) {
var items = req.query.nb || 600
getMeasurementsHumid(items,(err, meas) => {
res.json({'data': meas});
});
});
app.get('/api/scores', function (req, res) {
getScores((err, scores) => {
res.json({'data': scores});
});
});
app.get('/api/petitions', function (req, res) {
getPetitions((err, petitions) => {
res.json({'data': petitions});
});
});
// socket io
io.on('connection', function (socket) {
var clientIp = getIp(socket.request);
console.log('a user connected' + clientIp);
});
// handle received data on serial port
port.on('data', function (data) {
parseMeasurements(data, (err, data) => {
if (err) {
console.log('error parsing');
} else {
var timestamp = new Date().getTime()
addTempMeasurement(data['temperature'],timestamp);
addHumMeasurement(data['humidity']),timestamp;
io.emit('new data', {temp:{value:data['temperature'] , date:timestamp}, humidity:{value:data['humidity'] , date:timestamp}});
}
});
});
// handle error data on serial port
port.on('error', function (data) {
console.log('Error in port: ' + data);
});
// request measurements each 5 minutes
setInterval(request_meas, 1000 * 60 * 5);
// clap for readiness
run_servo();
}
// init the serial
port.on('open', function () {
// wait to start properly
setTimeout(() => {
init_app();
}, 2000);
});
// CLEAN UP
function Cleanup (callback) {
// attach user callback to the process event emitter
// if no callback, it will still exit gracefully on Ctrl-C
callback = callback || function () {};
process.on('cleanup', callback);
// do app specific cleaning before exiting
process.on('exit', function () {
process.emit('cleanup');
});
// catch ctrl+c event and exit normally
process.on('SIGINT', function () {
console.log('Ctrl-C...');
process.exit(2);
});
// catch uncaught exceptions, trace, then exit normally
process.on('uncaughtException', function (e) {
console.log('Uncaught Exception...');
console.log(e.stack);
process.exit(99);
});
}