-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
181 lines (141 loc) · 3.73 KB
/
server.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
// noinspection HttpUrlsUsage
'use strict';
const fs = require('fs');
const net = require('net');
const http = require('http');
const HttpDispatcher = require('httpdispatcher');
const mqtt = require('mqtt');
const config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
let status = {};
const dispatcher = new HttpDispatcher();
function leadingZero(num) {
if (num > 9) {
return num;
}
return '0' + num;
}
function logger() {
const dt = new Date;
const args = Array.prototype.slice.apply(arguments);
args.unshift(
'[' +
leadingZero(dt.getDate()) + '.' +
leadingZero(dt.getMonth()) + '.' +
(dt.getFullYear()) + ' ' +
leadingZero(dt.getHours()) + ':' +
leadingZero(dt.getMinutes()) + ':' +
leadingZero(dt.getSeconds()) +
']'
);
console.log.apply(console, args);
}
function buildCollectdCommand(host, plugin, pluginInstance, type, value, timestamp = 'N') {
return `PUTVAL "${host}/${plugin}-${pluginInstance}/${type}" ${timestamp}:${value}`;
}
let collectdSocket;
if (config.collectd) {
collectdSocket = net.connect(config.collectd.socket, function() {
logger('collectd socket connected');
collectdSocket.on('data', function(data) {
logger('collectd socket received', data.toString());
});
});
}
const mqttClient = mqtt.connect(config.mqtt.url);
mqttClient.on('connect', function() {
logger('mqtt connected');
config.mqtt.topics.forEach(function(topic) {
logger('subscribing to ' + topic);
mqttClient.subscribe(topic);
});
});
function parseValue(messageStr, packet) {
try {
const decoded = JSON.parse(messageStr);
if (typeof decoded.timestamp !== 'undefined' && typeof decoded.value !== 'undefined') {
return decoded;
}
// incorrect JSON contents
}
catch {
// not JSON
}
if (packet.retain) {
logger('Skipping retained packet without timestamp');
return false;
}
const value = isFinite(messageStr) ? parseFloat(messageStr) : messageStr;
// backwards compatibility
return {
value,
};
}
mqttClient.on('message', function(topic, message, packet) {
if (!config.mqtt.values.includes(topic)) {
return;
}
const messageStr = message.toString();
logger('[' + topic + '] ' + messageStr);
const parsed = parseValue(messageStr, packet);
if (parsed === false) {
return;
}
let {
timestamp,
value,
} = parsed;
let collectTimestamp;
if (typeof timestamp === 'undefined') {
timestamp = Date.now();
}
else {
collectTimestamp = Math.round(timestamp / 1000);
}
status[topic] = {
timestamp,
value,
};
let topicParts = topic.split('/');
let collectdPluginInstance = topicParts.shift().replace(/-/g, '_');
let type;
if (topicParts[0] === 'relay') {
topicParts[0] = 'state';
type = topicParts.join('-');
}
else {
collectdPluginInstance = topicParts.shift().replace(/-/g, '_');
type = topicParts.pop();
}
const collectdCommand = buildCollectdCommand(
collectdSocket ? config.collectd.host : 'localhost',
collectdSocket ? config.collectd.plugin : 'my_plugin',
collectdPluginInstance,
type,
value,
collectTimestamp,
);
if (collectdSocket) {
collectdSocket.write(collectdCommand + '\n');
}
logger('collectd socket sent', collectdCommand);
});
dispatcher.onGet('/status', function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
});
res.end(JSON.stringify(status));
});
http.createServer(function(req, res) {
const conn = req.connection;
logger('HTTP client connected: ' + conn.remoteAddress + ':' + conn.remotePort);
logger(req.method + ' ' + req.url);
try {
dispatcher.dispatch(req, res);
}
catch(err) {
logger(err);
}
}).listen(config.listen.port, config.listen.hostname, function() {
logger('Server listening on: http://' + config.listen.hostname + ':' + config.listen.port);
});