-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathkm200mqtt.js
executable file
·203 lines (183 loc) · 5.5 KB
/
km200mqtt.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
#!/usr/bin/env node
var pkg = require('./package.json');
var request = require('request');
var async = require('async');
var MCrypt = require('mcrypt').MCrypt;
var buffertrim = require('buffertrim');
var Mqtt = require('mqtt');
var log = require('yalm');
var config = require('./config.js');
require('require-yaml');
var mqttConnected;
var km200Connected;
log.setLevel(config.verbosity);
log.info(pkg.name + ' ' + pkg.version + ' starting');
log.info('mqtt trying to connect', config.url);
var mqtt = Mqtt.connect(config.url,
{
will: { topic: config.name + '/connected', payload: '0', retain: true },
rejectUnauthorized: !config.insecure
}
);
mqtt.on('connect', function () {
mqttConnected = true;
log.info('mqtt connected', config.url);
mqtt.publish(config.name + '/connected', '1', { retain: true });
log.info('mqtt subscribe', config.name + '/set/#');
mqtt.subscribe(config.name + '/set/#');
checkKM200();
setInterval(checkKM200, 60000);
});
mqtt.on('close', function () {
if (mqttConnected) {
mqttConnected = false;
log.info('mqtt closed ' + config.url);
}
});
mqtt.on('error', function (err) {
log.error('mqtt', err);
});
log.info('Config file: ' + config.config);
var measurements = require(config.config).measurements;
log.debug(measurements);
var key = Buffer.from(config.passcode, 'hex');
log.debug(key);
var desEcb = new MCrypt('rijndael-128', 'ecb');
desEcb.open(key);
var km200host = config.km200;
log.info(km200host);
var writables = {};
var meta = {};
function mnemonizeWritable(result) {
if (result.writeable === 1) {
log.debug('mnemonizeWritable', result);
if (writables[result.id] === undefined) {
storeWritable(result);
}
}
}
function storeWritable(result) {
if (result.allowedValues) {
log.info('Writable: ' + result.id + ' (' + result.type + '): ' + JSON.stringify(result.allowedValues));
} else if (result.minValue) {
log.info('Writable: ' + result.id + ' (' + result.type + '): ' + result.minValue + ' - ' + result.maxValue);
} else {
return;
}
var writable = {
valueType: result.type,
minValue: result.minValue,
maxValue: result.maxValue,
allowedValues: result.allowedValues
};
writables[result.id] = writable;
}
function mnemonizeMeta(result) {
log.debug('mnemonizeMeta', result);
if (!meta[result.id]) {
publishMeta(result);
meta[result.id] = true;
}
}
function publishMeta(result) {
if (typeof (result.id) === 'string') {
if (endsWith(result.id, 'flameCurrent')) {
result.unitOfMeasure = 'µA';
}
var topic = 'km200/meta' + result.id;
var metaData = {
native: JSON.parse(JSON.stringify(result))
};
metaData.native.value = undefined;
metaData.native.id = undefined;
mqtt.publish(topic, JSON.stringify(metaData), { retain: true }, function () {
log.debug('meta', topic, metaData);
});
}
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
mqtt.on('message', (topic, message) => {
log.info(topic, message.toString())
const topicPrefix = config.name + '/set/';
if (topic.startsWith(topicPrefix)) {
let url = topic.substring(topicPrefix.length - 1);
let value = message.toString();
let writable = writables[url];
if (writable) {
if ((writable.valueType === 'stringValue' && writable.allowedValues.indexOf(value) !== -1) ||
(writable.valueType === 'floatValue' && parseFloat(value) >= writable.minValue && parseFloat(value) <= writable.maxValue)) {
log.info('WRITE: ' + value);
const postValue = desEcb.encrypt(JSON.stringify({
value: writable.valueType === 'stringValue' ? value : parseFloat(value)
})).toString('base64');
var options = {
url: 'http://' + km200host + url,
body: postValue,
headers: {
'Content-type': 'application/json',
'User-Agent': 'TeleHeater/2.2.3'
}
};
request.post(options, function (error, response, body) {
if (!error) {
getKM200(url, function done() { });
}
//log.info(error, response);
});
} else {
log.info('Invalid value: ' + value);
}
} else {
log.info(url + ' not writable!');
}
}
});
function getKM200(url, done) {
var options = {
url: 'http://' + km200host + url,
headers: {
'Content-type': 'application/json',
'User-Agent': 'TeleHeater/2.2.3'
}
};
request.get(options, function (error, response, body) {
if (!error && response.statusCode === 200) {
if (!km200Connected) {
km200Connected = true;
mqtt.publish(config.name + '/connected', '2', { retain: true });
}
var result = JSON.parse(buffertrim.trimEnd(desEcb.decrypt(Buffer.from(body, 'base64'), 'base64')).toString());
mnemonizeWritable(result);
mnemonizeMeta(result);
var topic = 'km200/status' + result.id;
var state = {
ts: Math.floor(new Date() / 1000),
val: result.value,
km200_unitOfMeasure: result.unitOfMeasure
};
mqtt.publish(topic, JSON.stringify(state), { retain: true }, function () {
log.debug(topic, state);
});
done(null);
} else {
done(null);
}
});
}
function checkKM200() {
log.debug('Start checking');
async.eachSeries(measurements,
function (measurement, cb) {
getKM200(measurement.url, function (done) {
cb(done);
});
},
function (err, result) {
if (err) {
console.error(err);
}
}
);
}