-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
68 lines (56 loc) · 1.99 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
const restify = require('restify');
const request = require('request-promise-native');
const moment = require('moment');
const mqtt = require('mqtt');
const logger = require('./logger');
const config = require('./env');
const consoleConfig = { ...config };
logger.info('environment variables:\n', consoleConfig);
// api settings
const server = restify.createServer();
server.server.setTimeout(config.SERVER_TIMEOUT);
server
.use(restify.plugins.queryParser({ mapParams: false }))
.use(restify.plugins.bodyParser({ mapParams: false }));
// mqtt settings
const client = mqtt.connect({ port: config.MQTT_PORT, host: config.MQTT_HOST });
// some handling
server.on('error', (err) => {
logger.error('server encountered an error', err);
process.exit(1); // if in docker it should be restarted automatically
});
// router
server.post('/data', async (req, res) => {
logger.logRequest('fitbit-ifttt-webhook-to-influx.data.post');
try {
const data = req.body;
data.epoch = moment(data.date, 'MMMM D, YYYY at hh:mmA').valueOf();
logger.debug(data);
postValuesToInflux(data);
postValuesToMQTT(data);
res.send(201);
} catch (err) {
logger.error(err);
res.send(500, { code: 500, message: `an internal error occurred ${err}` });
}
});
server.listen(config.SERVER_PORT, () => {
logger.info(`fitbit-ifttt-webhook-to-influx listening on port ${config.SERVER_PORT}`);
});
function postValuesToInflux(data) {
const body = `fitbit,device=aria bmi=${data.bmi},weight=${data.weight} ${data.epoch}`;
return request({
url: `http://${config.DB_HOST}:${config.DB_PORT}/api/v2/write?bucket=${config.DB_NAME}&precision=ms`,
method: 'POST',
body
})
.catch((err) => {
logger.error('could not post fitbit data to influx', err);
throw new Error('could not post fitbit data to influx');
});
}
function postValuesToMQTT(data) {
client.publish(`${config.MQTT_TOPIC}/weight`, `${data.weight}`);
client.publish(`${config.MQTT_TOPIC}/bmi`, `${data.bmi}`);
client.publish(`${config.MQTT_TOPIC}/date`, `${data.epoch}`);
}