forked from tkoeberl/MMM-homeassistant-sensors
-
Notifications
You must be signed in to change notification settings - Fork 24
/
node_helper.js
65 lines (62 loc) · 1.81 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
var NodeHelper = require('node_helper');
var got = require('got');
module.exports = NodeHelper.create({
start: function () {
if(config.debuglogging) { console.log('MMM-homeassistant-sensors helper started...') };
},
getStats: function (config) {
var self = this;
var url = self.buildUrl(config);
var instance = got.extend({
hooks: {
beforeRequest: [
options => {
if (!options.context || !options.context.token) {
throw new Error('Long Lived Token required');
}
json: true;
options.headers = {'Authorization' : 'Bearer ' + options.context.token}
}
]
}
});
(async () => {
var context = {
token: config.token
};
try {
var response = await instance(url, {context});
if (response.statusCode == 200) {
if(config.debuglogging) { console.log('MMM-homeassistant-sensors response successfull. calling STATS_RESULT') };
self.sendSocketNotification('STATS_RESULT', JSON.parse(response.body));
}
if(config.debuglogging) {
console.log('MMM-homeassistant-sensors Body:', response.body);
console.log('MMM-homeassistant-sensors statusCode:', response.statusCode);
}
} catch (error) {
console.log('MMM-homeassistant-sensors - Connection Failed: ' + error.response.body);
}
})();
},
buildUrl: function(config) {
var url = config.host;
if (config.port) {
url = url + ':' + config.port;
}
url = url + '/api/states'
if (config.https) {
url = 'https://' + url;
} else {
url = 'http://' + url;
}
if(config.debuglogging) { console.error("MMM-homeassistant-sensors - buildUrl:", url);}
return url;
},
//Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
if (notification === 'GET_STATS') {
this.getStats(payload);
}
}
});