-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
95 lines (80 loc) · 2.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
'use strict';
const util = require('util');
const fs = require('fs');
const mqtt = require('mqtt');
const Influx = require('influx');
var mqttClient;
var influxhost = 'localhost';
var influxport = 8086;
var databasename = 'heatingsystem';
var mqtthost = 'localhost';
var mqttport = 1883;
var topics = [];
function connectAndSubscribe() {
mqttClient.on('connect', function () {
topics.forEach(function(topic) {
// subscribeToTopic(topic);
mqttClient.subscribe(topic);
});
});
}
function listenForMessages() {
mqttClient.on('message', function (topic, message) {
var convertedMessage = convertToInfluxPoint(topic, JSON.parse(message));
try {
influx.writePoints([convertedMessage]);
} catch (err) {
console.error("Something went wrong writing to influxdb", e);
}
});
}
function getMeasurementNameFromTopic(topic) {
var parts = topic.split("/");
return parts[parts.length - 1];
}
function extractValue(message) {
switch (message.type) {
case "boolean":
return message.value ? 1 : 0;
case "float":
case "string":
default:
return message.value;
}
}
function convertToInfluxPoint(topic, message) {
var fieldName = getMeasurementNameFromTopic(topic);
var value = extractValue(message);
var fields = {};
fields[fieldName] = value;
return {
measurement: 'otgw',
tags: { measure: fieldName},
fields : fields,
"timestamp" : new Date(message.timestamp)
};
}
function readConfiguration() {
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
console.log(util.format('Loaded config: %s', JSON.stringify(config)));
influxhost = config.influx.host;
influxport = config.influx.port;
mqtthost = config.mqtt.host;
mqttport = config.mqtt.port;
topics = config.mqtt.topics;
}
function start() {
readConfiguration();
const influx = new Influx.InfluxDB({
host: influxhost,
port: influxport,
database: databasename
});
influx.createDatabase('heatingsystem');
mqttClient = mqtt.connect('mqtt://' + mqtthost + ':' + mqttport);
connectAndSubscribe();
listenForMessages();
}
module.exports = function() {
return start();
};