forked from dekinet/MMM-Growatt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
60 lines (53 loc) · 1.83 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
const NodeHelper = require('node_helper');
const api = require('growatt');
const getJSONCircularReplacer = () => {
const seen = new WeakMap();
return (key, val) => {
const value = val;
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return `loop on ${seen.get(value)}`;
}
seen.set(value, key);
}
return value;
};
};
module.exports = NodeHelper.create({
start: function() {
console.log("Starting node helper: " + this.name);
},
socketNotificationReceived: async function(notification, payload) {
let self = this;
const options = { weather: false, historyLast: false };
if (notification === "GROWATT_GET_DATA") {
console.log(self.name + ': GROWATT_GET_DATA');
const growatt = new api({});
let data = [];
let login = await growatt.login(payload.config.user, payload.config.password).catch(e => {console.log(e)});
let getAllPlantData = await growatt.getAllPlantData(options).catch(e => {console.log(e)});
if (getAllPlantData) {
const keys = Object.keys(getAllPlantData);
keys.forEach(key => {
let { devices, ...rest } = getAllPlantData[key];
const serialNumbers = Object.keys(devices);
let devicesData = [];
serialNumbers.forEach(sn => {
devicesData.push({
sn: sn,
data: devices[sn],
});
});
data.push({
plantid: key,
data: { ...rest, devicesData }
})
});
// console.log(this.name + " GOT DATA", JSON.stringify(self, getJSONCircularReplacer(), 2));
console.log('Publishing GROWATT data');
self.sendSocketNotification("GROWATT_GOT_DATA", JSON.stringify(data));
await growatt.logout().catch(e => {console.log(e)});
}
}
}
});