forked from Medve01/Shelly-HT
-
Notifications
You must be signed in to change notification settings - Fork 2
/
node_helper.js
85 lines (75 loc) · 2.44 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
var NodeHelper = require("node_helper");
const request = require('request');
module.exports = NodeHelper.create({
start: function() {
},
// Frontend module pings the node helper to fetch data from Shelly PM
socketNotificationReceived: function (notification, payload) {
self = this;
var currentdate = new Date();
var options = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
var printed_date = new Intl.DateTimeFormat('de', options).format(currentdate);
var month = '' + (currentdate.getMonth() + 1);
var day = '' + currentdate.getDate();
var year = currentdate.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
var cloud_date = [year, month, day].join('');
var filter_date = [year, month, day].join('-');
if (notification == "GetShelly"){
//Parameters: notification can be anything (not used), payload must be the URL of the Shelly PM status api
request(payload.uri, {json: true, timeout: 2500 }, (err, res, body) => {
if (err) { return console.log(err); }
payload= {
apower: body['switch:0'].apower,
tmp: body['switch:0'].temperature.tC,
updated: printed_date,
}
//console.log("Sending Shelly data to FE module", payload);
self.sendSocketNotification('ShellyPDData', payload);
});
}
if (notification == "GetShellyCloud") {
// siehe https://www.shelly-support.eu/forum/index.php?thread/10983-cloud-api-abfrage-consumption/&pageNo=2
var dataString = 'channel=0&date_range=day&date=' + cloud_date + '&id=' + payload.deviceId + '&auth_key=' + payload.authKey
const options = {
uri: payload.uri,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: dataString,
json: true,
forever: true,
timeout: 2500
};
// console.log(options);
request.post(options, (err, res, body) => {
if (err) {
return console.log(err);
}
data = body['data']['history']
data = data.filter(function(item) {
if (item.datetime.includes(filter_date)) {
return true;
}
return false
})
var power = 0.0
data.forEach(function(item) {
if (item.consumption < 0.4) {
power -= item.consumption
} else {
power += item.consumption
}
})
payload= {
total: (power/1000).toFixed(3)
}
self.sendSocketNotification('ShellyCloudData', payload)
})
}
}
});