forked from BenRoe/MMM-FHEM
-
Notifications
You must be signed in to change notification settings - Fork 5
/
node_helper.js
executable file
·94 lines (83 loc) · 2.51 KB
/
node_helper.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
'use strict';
/* Magic Mirror
* Module: MMM-ioBroker
*
* By Benjamin Roesner http://benjaminroesner.com
* MIT Licensed.
*/
const NodeHelper = require('node_helper');
var http;
var https;
module.exports = NodeHelper.create({
start: function() {
this.config = {};
},
request: function (url, callback) {
var _http;
if (url.match(/^https:/)) {
_http = https || require('https');
} else {
_http = http || require('http');
}
_http.get(url, function (res) {
var contentType = res.headers['content-type'];
var error;
if (res.statusCode !== 200) {
error = new Error('Request Failed.\n Status Code: ' + res.statusCode);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.Expected application/json but received ' + contentType);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
callback();
return;
}
res.setEncoding('utf8');
var rawData = '';
res.on('data', function (chunk) {
rawData += chunk;
});
res.on('end', function () {
callback(rawData);
});
}).on('error', function (e) {
callback();
console.error('Got error: ' + e.message);
});
},
getIobJson: function (config, callback) {
var count = 0; // works even for node 0.10
var result = {};
var url = 'http' + (config.https ? 's' : '') + '://' + (config.host || 'localhost') + ':' + (config.port || 8082) + '/get/';
var that = this;
for (var i = 0; i < config.devices.length; i++) {
for (var s = 0; s < config.devices[i].deviceStates.length; s++) {
count++;
(function (_id) {
that.request(url + _id, function (body) {
var data = {val: '-'};
try {
data = JSON.parse(body || '{"val": "-"}');
} catch (e) {
console.error('Cannot read value: ' + body + ' => ' + e);
}
result[_id] = data.val;
if (!--count) callback(result);
});
})(config.devices[i].deviceStates[s].id);
}
}
},
// Subclass socketNotificationReceived received.
socketNotificationReceived: function (notification, payload) {
if (notification === 'GETDATA') {
var self = this;
self.config = payload;
this.getIobJson(this.config, function (data) {
self.sendSocketNotification('DATARECEIVED', data);
});
}
}
});