forked from paphko/mmm-openhabfloorplan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_helper.js
More file actions
65 lines (52 loc) · 2.3 KB
/
Copy pathnode_helper.js
File metadata and controls
65 lines (52 loc) · 2.3 KB
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
const request = require("request");
const NodeHelper = require("node_helper");
const url = require("url");
module.exports = NodeHelper.create({
start: function() {
var self = this;
console.log("Starting node helper: " + this.name);
this.expressApp.get('/openhab', (req, res) => {
var query = url.parse(req.url, true).query;
var payload = { item: query.item, state: query.state, timestamp: new Date() };
if (query.item == null || query.state == null) {
res.send({ status: "failed", error: "item and/or state is missing", payload: payload});
} else {
self.sendSocketNotification("OPENHAB_ITEM", payload);
res.send({ status: "success", payload: payload });
}
});
},
socketNotificationReceived: function(notification, openhab) {
// continue only if it is a get request for an openhab group
if (notification === "GET_OPENHAB_ITEMS") {
// build request params: url and optionally basic authentication
var requestParams = this.buildRequestParams(openhab);
var self = this;
// console.log("Requesting items on openhab server: " + JSON.stringify(requestParams));
request(requestParams, function(error, response, body) {
// console.log("response received: " + JSON.stringify(response));
if (!error && response.statusCode === 200) {
self.sendSocketNotification("OPENHAB_ITEMS", JSON.parse(body));
} else {
console.log("Request on openhab server failed (" + JSON.stringify(response) + "): " + error);
}
});
} else {
console.log("Unknown notification: " + notification);
}
},
buildRequestParams: function(openhab) {
// build url of openhab server to get status of group items in json format
var url = openhab.url;
if (!url.endsWith('/'))
url += '/';
url += "rest/items" + (openhab.version === 1 ? "?type=json" : "");
if (openhab.user && openhab.password) {
// if user and password are set, perform request with basic authentication!
var auth = "Basic " + new Buffer(openhab.user + ":" + openhab.password).toString("base64");
return { url: url, headers: { "Authorization" : auth } };
} else {
return { url: url };
}
},
});