forked from FrankZZ/torque-obd-to-influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
89 lines (76 loc) · 2.61 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
const Influx = require('influx');
const Restify = require('restify');
const restify = Restify.createServer();
const bunyan = require('bunyan');
const log = bunyan.createLogger({
name: 'car-obd',
stream: process.stdout,
level: 'debug'
});
let speed = 10;
const PID_DICT = require('./pid_dictionary.json');
const DATABASE_NAME = process.env.DB_NAME || 'car_obd';
const DATABASE_HOST = process.env.DB_HOST || 'localhost';
const HTTP_PORT = parseInt(process.env.HTTP_PORT || '3001');
const influx = new Influx.InfluxDB({
host: DATABASE_HOST,
database: DATABASE_NAME
});
influx.getDatabaseNames()
.then(names => {
if (!names.includes(DATABASE_NAME)) {
log.info(`Created database "${DATABASE_NAME}".`);
return influx.createDatabase(DATABASE_NAME);
} else {
log.info(`Database "${DATABASE_NAME}" already exists.`);
}
})
.then(() => {
restify.use(Restify.queryParser());
restify.listen(HTTP_PORT, function () {
log.info(`Listening on port ${HTTP_PORT}.`);
});
restify.get('/torque', (req, res, next) => {
log.info({
req: req
}, 'Got /torque');
let keys = {};
for(const k in req.query) {
if (Object.hasOwnProperty.call(req.query, k) && /^k/.test(k)) {
const val = parseFloat(req.query[k]);
const name = PID_DICT[k] || 'not_found';
log.debug({
key: k,
keyName: name,
value: val
}, 'Got Torque queryString parameter');
keys[name] = val;
} else {
log.debug({
key: k,
value: req.query[k]
}, 'Ignored queryString parameter');
}
}
log.debug({
keys: keys
}, 'queryString parameters are parsed');
influx.writeMeasurement('car', [
{
fields: keys,
timestamp: new Date(parseInt(req.query.time))
}
]).then(() => {
log.debug('Wrote points to influx');
}).catch(err => {
log.error(`Error saving data to InfluxDB! ${err}`)
});
res.send(200, 'OK!');
log.debug('Sent response, 200: OK!');
next();
return;
});
})
.catch(err => {
log.error(`Error creating Influx database "${DATABASE_NAME}"!`, err);
});