-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvrm.js
207 lines (178 loc) · 6.89 KB
/
vrm.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* node implementation of the most needed VRM API functions
*
* Documentation see https://vrm-api-docs.victronenergy.com/#/
*/
import Logger from './logging.cjs';
import fetch from 'node-fetch';
import dateformat from 'dateformat';
import { encode } from 'html-entities';
import { toZonedTime } from 'date-fns-tz';
import { getStartAndEndFromInterval, dateMask } from './helper.js';
import config from './config.json' assert { type: 'json' };
const log = new Logger('vrm');
const baseUrl = 'https://vrmapi.victronenergy.com/v2';
const authUrl = `${baseUrl}/auth/login`;
function valueFromSeries(series) {
let last = series[series.length - 1];
let kwh = last[1];
return kwh;
}
function groupSeriesByDay(series) {
let grouped = {};
series.reduce((acc, current) => {
if (current.length === 0) return;
if (current[1] === 0) return; // remove 0 values
let timestamp = current[0] * 1000;
let date = toZonedTime(timestamp, 'Europe/Berlin');
let day = dateformat(date, dateMask, { timeZone: 'Europe/Berlin' });
if (grouped[day] === undefined) {
grouped[day] = {};
}
if (grouped[day]['value'] === null) return;
if (grouped[day]['value'] === undefined || grouped[day]['value'] < parseFloat(current[1])) {
grouped[day]['value'] = parseFloat(current[1]);
}
});
return grouped;
}
class VictronApi {
idUser;
token;
config;
accessToken;
constructor(config, idUser, accessToken) {
this.config = config;
this.idUser = idUser;
this.accessToken = accessToken;
log.debug('site id from config:', this.config.idSite);
}
async login(username, password) {
log.debug(`try to login with username ${username}`);
let reqData = {
username,
password,
remember_me: true
};
let response = await fetch(authUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(reqData)
});
let data = await response.json();
this.token = data.token;
this.idUser = data.idUser;
log.debug('received valid data for user:', `idUser: ${this.idUser}`, `token: ${this.token}`);
}
async fetchInstallations() {
if (!this.accessToken) return;
// get installations
const installUrl = `${baseUrl}/users/${this.idUser}/installations`;
let options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-authorization': `Token ${this.accessToken}`
}
};
let response = await fetch(installUrl, options);
let data = await response.json();
log.debug('received data:', data);
return data.records;
}
async fetchSystemOverview() {
if (!this.accessToken) return;
const systemUrl = `${baseUrl}/installations/${this.config.idSite}/system-overview`;
let options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-authorization': `Token ${this.accessToken}`
}
};
let response = await fetch(systemUrl, options);
let data = await response.json();
log.debug('received system overview data:', data);
return data.records;
}
async fetchData() {
// TODO: if idUser and accessToken not present, use login
if (!this.accessToken) return;
let options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-authorization': `Token ${this.accessToken}`
}
};
let data = [];
data.push(dateformat(new Date(), dateMask));
for (const charger of this.config.charger) {
const solarStatusUrl = `${baseUrl}/installations/${this.config.idSite}/widgets/SolarChargerSummary?instance=${charger.instance}`;
let response = await fetch(solarStatusUrl, options);
let chargerData = await response.json();
// log.debug(`all charger data for ${charger.name} (instance=${charger.instance}):`, chargerData);
let production = parseFloat(chargerData.records.data['94'].value);
data.push({
name: encode(charger.name, { mode: 'nonAscii' }),
production
});
// log.debug(`data for charger '${charger.name}' (instance=${charger.instance}): ${production} kWh`);
}
return data;
}
async fetchStats(interval) {
if (!this.accessToken) return;
let [timeStart, timeEnd, formattedStart, formattedEnd] = getStartAndEndFromInterval(interval, true);
let data = {};
for (const charger of this.config.charger) {
let statsUrl = `${baseUrl}/installations/${this.config.idSite}/widgets/Graph?instance=${charger.instance}&pointsPerPixel=1&useMinMax=0&start=${timeStart}&end=${timeEnd}&attributeIds[]=94`;
if (charger.mppts > 1) {
statsUrl += '&attributeIds[]=703&attributeIds[]=704';
}
log.debug('request url for stats:', statsUrl);
let options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json, text/plain, */*',
'x-authorization': `Token ${this.accessToken}`
}
};
try {
let response = await fetch(statsUrl, options);
let stats = await response.json();
//log.debug("complete stats:", stats);
let chargerData = stats.records.data;
let encodedName = encode(charger.name, { mode: 'nonAscii' });
for (let id of ['94', '703', '704']) {
if (chargerData[id] === undefined || chargerData[id].length === 0) continue;
let main = groupSeriesByDay(chargerData[id]);
for (let day of Object.keys(main)) {
if (data[day] === undefined) {
data[day] = {};
}
if (data[day][id] === undefined) {
data[day][id] = [];
}
data[day][id].push({
instance: charger.instance,
name: encodedName,
value: main[day].value
});
}
}
} catch (error) {
log.error('error occurred:', error);
}
}
return {
rows: data,
timeframe: {
start: formattedStart,
end: formattedEnd
}
};
}
}
export default VictronApi;