iobroker.pvnode 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +112 -2
- package/admin/coffee.png +0 -0
- package/admin/jsonConfig.json +188 -0
- package/admin/pvnode.png +0 -0
- package/io-package.json +199 -0
- package/lib/api.js +112 -0
- package/lib/compute.js +288 -0
- package/lib/states.js +160 -0
- package/lib/svg.js +242 -0
- package/lib/time.js +133 -0
- package/main.js +734 -0
- package/package.json +61 -4
package/main.js
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* ioBroker.pvnode
|
|
5
|
+
* PV production forecast from pvnode.com (API v2).
|
|
6
|
+
*
|
|
7
|
+
* Polling follows pvnode's integration guidelines:
|
|
8
|
+
* - poll at next_poll_at (+30 s), clamped to 1 min .. 24 h, fallback 1 h
|
|
9
|
+
* - plan features are detected from `available`, never from plan names
|
|
10
|
+
* - variability (paid) is probed once; a 403 for it is not counted
|
|
11
|
+
* - the last payload is persisted and reused after a restart
|
|
12
|
+
* - current power / remaining energy / peak are computed locally every 5 minutes
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const utils = require('@iobroker/adapter-core');
|
|
16
|
+
const { PvnodeApi, PvnodeError } = require('./lib/api');
|
|
17
|
+
const { prepare, computeStates, chartSeries, WEATHER_FIELDS } = require('./lib/compute');
|
|
18
|
+
const { CHANNELS, commonFor } = require('./lib/states');
|
|
19
|
+
const { localDate, isoLocal } = require('./lib/time');
|
|
20
|
+
const { dayChart, daysChart } = require('./lib/svg');
|
|
21
|
+
|
|
22
|
+
const GRACE_MS = 30 * 1000;
|
|
23
|
+
const MIN_DELAY_MS = 60 * 1000;
|
|
24
|
+
const MAX_DELAY_MS = 24 * 3600 * 1000;
|
|
25
|
+
const FALLBACK_DELAY_MS = 3600 * 1000;
|
|
26
|
+
const COMPUTE_INTERVAL_MS = 5 * 60 * 1000;
|
|
27
|
+
const MAX_DAYS = 8;
|
|
28
|
+
const MAX_STRINGS = 8;
|
|
29
|
+
|
|
30
|
+
const OPTIONAL_GROUPS = ['weather', 'irradiance', 'clearsky'];
|
|
31
|
+
|
|
32
|
+
function compass(deg) {
|
|
33
|
+
const names = ['N', 'NO', 'O', 'SO', 'S', 'SW', 'W', 'NW'];
|
|
34
|
+
if (typeof deg !== 'number') {
|
|
35
|
+
return '?';
|
|
36
|
+
}
|
|
37
|
+
return names[Math.round((((deg % 360) + 360) % 360) / 45) % 8];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
class Pvnode extends utils.Adapter {
|
|
41
|
+
constructor(options = {}) {
|
|
42
|
+
super({ ...options, name: 'pvnode' });
|
|
43
|
+
this.pollTimer = null;
|
|
44
|
+
this.computeTimer = null;
|
|
45
|
+
this.computeAlignTimer = null;
|
|
46
|
+
this.api = null;
|
|
47
|
+
this.siteId = '';
|
|
48
|
+
this.prepared = null;
|
|
49
|
+
this.payload = null;
|
|
50
|
+
this.available = null;
|
|
51
|
+
this.variabilityAllowed = undefined;
|
|
52
|
+
this.errorCount = 0;
|
|
53
|
+
this.polling = false;
|
|
54
|
+
this.stopped = false;
|
|
55
|
+
this.created = new Set();
|
|
56
|
+
this.lang = 'de';
|
|
57
|
+
this.stringNames = [];
|
|
58
|
+
|
|
59
|
+
this.on('ready', this.onReady.bind(this));
|
|
60
|
+
this.on('stateChange', this.onStateChange.bind(this));
|
|
61
|
+
this.on('message', this.onMessage.bind(this));
|
|
62
|
+
this.on('unload', this.onUnload.bind(this));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
get userAgent() {
|
|
66
|
+
const v = (this.pack && this.pack.version) || this.version || '0.0.0';
|
|
67
|
+
return `ioBroker.pvnode/${v} ioBroker/js-controller`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// ------------------------------------------------------------------ lifecycle
|
|
71
|
+
|
|
72
|
+
async onReady() {
|
|
73
|
+
await this.setStateAsync('info.connection', false, true);
|
|
74
|
+
await this.createBaseObjects();
|
|
75
|
+
try {
|
|
76
|
+
const sys = await this.getForeignObjectAsync('system.config');
|
|
77
|
+
this.lang = sys && sys.common && sys.common.language === 'de' ? 'de' : 'en';
|
|
78
|
+
} catch {
|
|
79
|
+
this.lang = 'de';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const apiKey = String(this.config.apiKey || '').trim();
|
|
83
|
+
if (!apiKey) {
|
|
84
|
+
this.log.error('No pvnode API key configured. Please enter it in the adapter settings.');
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
this.api = new PvnodeApi(apiKey, this.userAgent);
|
|
88
|
+
this.siteId = String(this.config.siteId || '').trim();
|
|
89
|
+
|
|
90
|
+
// Validate key and load site metadata (does not cost forecast quota)
|
|
91
|
+
try {
|
|
92
|
+
const sites = await this.api.getSites();
|
|
93
|
+
if (!this.siteId) {
|
|
94
|
+
if (sites.length === 1) {
|
|
95
|
+
this.siteId = sites[0].id;
|
|
96
|
+
this.log.info(`No site selected, using the only site "${sites[0].name}" (${this.siteId})`);
|
|
97
|
+
} else if (sites.length === 0) {
|
|
98
|
+
this.log.error('Your pvnode account has no site. Create one at https://pvnode.com/sites/new');
|
|
99
|
+
return;
|
|
100
|
+
} else {
|
|
101
|
+
this.log.error(
|
|
102
|
+
`Several sites found, please select one in the settings: ${sites
|
|
103
|
+
.map(s => `${s.name} (${s.id})`)
|
|
104
|
+
.join(', ')}`,
|
|
105
|
+
);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const site = sites.find(s => s.id === this.siteId);
|
|
110
|
+
if (!site) {
|
|
111
|
+
this.log.error(`Site ${this.siteId} not found in your pvnode account. Please check the settings.`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
await this.writeSiteInfo(site);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (err instanceof PvnodeError && err.status === 401) {
|
|
117
|
+
this.log.error('pvnode API key is invalid or revoked. Please enter a valid key in the settings.');
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
this.log.warn(`Could not load site list (${err.message}), continuing with configured site id`);
|
|
121
|
+
if (!this.siteId) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
await this.cleanupOptionalWeather();
|
|
127
|
+
this.subscribeStates('control.refresh');
|
|
128
|
+
|
|
129
|
+
// Restore cached forecast
|
|
130
|
+
const restored = await this.restoreCache();
|
|
131
|
+
if (restored && restored.nextPollAt && restored.nextPollAt > Date.now()) {
|
|
132
|
+
this.log.info(`Using cached forecast, next poll at ${new Date(restored.nextPollAt).toISOString()}`);
|
|
133
|
+
this.schedulePoll(restored.nextPollAt - Date.now() + GRACE_MS);
|
|
134
|
+
} else {
|
|
135
|
+
await this.poll();
|
|
136
|
+
}
|
|
137
|
+
this.startComputeTimer();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
onUnload(callback) {
|
|
141
|
+
try {
|
|
142
|
+
this.stopped = true;
|
|
143
|
+
if (this.pollTimer) {
|
|
144
|
+
this.clearTimeout(this.pollTimer);
|
|
145
|
+
}
|
|
146
|
+
if (this.computeAlignTimer) {
|
|
147
|
+
this.clearTimeout(this.computeAlignTimer);
|
|
148
|
+
}
|
|
149
|
+
if (this.computeTimer) {
|
|
150
|
+
this.clearInterval(this.computeTimer);
|
|
151
|
+
}
|
|
152
|
+
} finally {
|
|
153
|
+
callback();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async onStateChange(id, state) {
|
|
158
|
+
if (!state || state.ack) {
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (id === `${this.namespace}.control.refresh` && state.val) {
|
|
162
|
+
this.log.info('Manual refresh requested (costs one forecast request)');
|
|
163
|
+
await this.setStateAsync('control.refresh', false, true);
|
|
164
|
+
await this.poll(true);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async onMessage(obj) {
|
|
169
|
+
if (!obj || !obj.command) {
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (obj.command === 'getSites') {
|
|
173
|
+
const msg = obj.message || {};
|
|
174
|
+
const key = String(msg.apiKey || this.config.apiKey || '').trim();
|
|
175
|
+
let result = [];
|
|
176
|
+
if (key) {
|
|
177
|
+
try {
|
|
178
|
+
const api = new PvnodeApi(key, this.userAgent);
|
|
179
|
+
const sites = await api.getSites();
|
|
180
|
+
result = sites.map(s => ({ label: `${s.name} (${s.id})`, value: s.id }));
|
|
181
|
+
} catch (err) {
|
|
182
|
+
result = [{ label: `Error: ${err.message}`, value: '' }];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
if (obj.callback) {
|
|
186
|
+
this.sendTo(obj.from, obj.command, result, obj.callback);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ------------------------------------------------------------------ polling
|
|
192
|
+
|
|
193
|
+
schedulePoll(delayMs) {
|
|
194
|
+
if (this.stopped) {
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const delay = Math.min(Math.max(delayMs, MIN_DELAY_MS), MAX_DELAY_MS);
|
|
198
|
+
if (this.pollTimer) {
|
|
199
|
+
this.clearTimeout(this.pollTimer);
|
|
200
|
+
}
|
|
201
|
+
this.pollTimer = this.setTimeout(() => {
|
|
202
|
+
this.pollTimer = null;
|
|
203
|
+
this.poll().catch(e => this.log.error(`Poll failed: ${e.message}`));
|
|
204
|
+
}, delay);
|
|
205
|
+
this.setState('info.nextPoll', new Date(Date.now() + delay).toISOString(), true);
|
|
206
|
+
this.log.debug(`Next poll in ${Math.round(delay / 60000)} min`);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
buildInclude() {
|
|
210
|
+
const inc = ['default', 'strings'];
|
|
211
|
+
const avail = this.available;
|
|
212
|
+
for (const g of OPTIONAL_GROUPS) {
|
|
213
|
+
const wanted =
|
|
214
|
+
(g === 'weather' && this.config.includeWeather) ||
|
|
215
|
+
(g === 'irradiance' && this.config.includeIrradiance) ||
|
|
216
|
+
(g === 'clearsky' && this.config.includeClearsky);
|
|
217
|
+
if (wanted && (!avail || avail.includes(g))) {
|
|
218
|
+
inc.push(g);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (this.config.useVariability !== false && this.variabilityAllowed !== false) {
|
|
222
|
+
// undefined = fresh install -> probe once (a 403 is not counted)
|
|
223
|
+
inc.push('variability');
|
|
224
|
+
}
|
|
225
|
+
return inc;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
async poll(manual = false) {
|
|
229
|
+
if (this.polling || !this.api || !this.siteId) {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
this.polling = true;
|
|
233
|
+
try {
|
|
234
|
+
let include = this.buildInclude();
|
|
235
|
+
let result;
|
|
236
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
237
|
+
try {
|
|
238
|
+
result = await this.api.getForecast(this.siteId, include, Number(this.config.forecastDays) || 0);
|
|
239
|
+
break;
|
|
240
|
+
} catch (err) {
|
|
241
|
+
if (attempt === 0 && err instanceof PvnodeError && err.status === 403) {
|
|
242
|
+
const detail = err.detail.toLowerCase();
|
|
243
|
+
const dropped = include.filter(g => g !== 'default' && g !== 'strings' && detail.includes(g));
|
|
244
|
+
if (dropped.length) {
|
|
245
|
+
if (dropped.includes('variability')) {
|
|
246
|
+
this.variabilityAllowed = false;
|
|
247
|
+
this.log.info(
|
|
248
|
+
'Variability band is not part of your pvnode plan, continuing without it',
|
|
249
|
+
);
|
|
250
|
+
} else {
|
|
251
|
+
this.log.info(`Plan does not allow ${dropped.join(', ')}, continuing without`);
|
|
252
|
+
this.available = (this.available || []).filter(g => !dropped.includes(g));
|
|
253
|
+
}
|
|
254
|
+
include = include.filter(g => !dropped.includes(g));
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
throw err;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const { body, quota } = result;
|
|
263
|
+
await this.writeQuota(quota);
|
|
264
|
+
this.available = Array.isArray(body.available) ? body.available : this.available;
|
|
265
|
+
if (this.available) {
|
|
266
|
+
this.variabilityAllowed = this.available.includes('variability');
|
|
267
|
+
}
|
|
268
|
+
this.errorCount = 0;
|
|
269
|
+
await this.applyPayload(body, false);
|
|
270
|
+
await this.saveCache(body);
|
|
271
|
+
await this.setStateAsync('info.connection', true, true);
|
|
272
|
+
await this.setStateAsync('info.stale', false, true);
|
|
273
|
+
await this.setStateAsync('info.lastError', '', true);
|
|
274
|
+
|
|
275
|
+
const next = body.next_poll_at ? Date.parse(body.next_poll_at) : NaN;
|
|
276
|
+
this.schedulePoll(Number.isFinite(next) ? next - Date.now() + GRACE_MS : FALLBACK_DELAY_MS);
|
|
277
|
+
if (manual) {
|
|
278
|
+
this.log.info('Manual refresh done');
|
|
279
|
+
}
|
|
280
|
+
} catch (err) {
|
|
281
|
+
await this.handlePollError(err);
|
|
282
|
+
} finally {
|
|
283
|
+
this.polling = false;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async handlePollError(err) {
|
|
288
|
+
const status = err instanceof PvnodeError ? err.status : 0;
|
|
289
|
+
const detail = err instanceof PvnodeError ? err.detail.toLowerCase() : '';
|
|
290
|
+
await this.setStateAsync('info.lastError', String(err.message).slice(0, 500), true);
|
|
291
|
+
if (err instanceof PvnodeError && err.quota) {
|
|
292
|
+
await this.writeQuota(err.quota);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (status === 401) {
|
|
296
|
+
await this.setStateAsync('info.connection', false, true);
|
|
297
|
+
this.log.error(
|
|
298
|
+
'pvnode API key is invalid or revoked. Please enter a new key in the settings. Polling stopped.',
|
|
299
|
+
);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (status === 404) {
|
|
303
|
+
await this.setStateAsync('info.connection', false, true);
|
|
304
|
+
this.log.error(`pvnode site ${this.siteId} not found (deleted?). Please reconfigure. Polling stopped.`);
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (status === 403) {
|
|
308
|
+
await this.setStateAsync('info.connection', false, true);
|
|
309
|
+
if (detail.includes('inactive') || detail.includes('site limit')) {
|
|
310
|
+
this.log.error(`pvnode site is inactive (plan downgrade?): ${err.detail}. Polling stopped.`);
|
|
311
|
+
} else {
|
|
312
|
+
this.log.error(`Your pvnode plan does not allow this request: ${err.detail}. Polling stopped.`);
|
|
313
|
+
}
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (status === 429) {
|
|
317
|
+
const reset = err.quota && err.quota.reset ? Date.parse(err.quota.reset) : NaN;
|
|
318
|
+
const until = Number.isFinite(reset) ? reset : Date.now() + MAX_DELAY_MS;
|
|
319
|
+
this.log.warn(`pvnode monthly request limit reached. Pausing until ${new Date(until).toISOString()}`);
|
|
320
|
+
await this.setStateAsync('info.stale', true, true);
|
|
321
|
+
this.schedulePoll(Math.min(until - Date.now() + GRACE_MS, MAX_DELAY_MS));
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// transient (network, 5xx): keep last forecast, mark stale, back off
|
|
326
|
+
this.errorCount++;
|
|
327
|
+
const delay = Math.min(5 * 60000 * 2 ** (this.errorCount - 1), FALLBACK_DELAY_MS);
|
|
328
|
+
this.log.warn(`pvnode request failed (${err.message}), retry in ${Math.round(delay / 60000)} min`);
|
|
329
|
+
await this.setStateAsync('info.stale', true, true);
|
|
330
|
+
if (!this.payload) {
|
|
331
|
+
await this.setStateAsync('info.connection', false, true);
|
|
332
|
+
}
|
|
333
|
+
this.schedulePoll(delay);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ------------------------------------------------------------------ cache
|
|
337
|
+
|
|
338
|
+
async saveCache(body) {
|
|
339
|
+
const cache = { siteId: this.siteId, savedAt: Date.now(), available: this.available, payload: body };
|
|
340
|
+
await this.setStateAsync('info.cache', JSON.stringify(cache), true);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async restoreCache() {
|
|
344
|
+
try {
|
|
345
|
+
const st = await this.getStateAsync('info.cache');
|
|
346
|
+
if (!st || !st.val) {
|
|
347
|
+
return null;
|
|
348
|
+
}
|
|
349
|
+
const cache = JSON.parse(String(st.val));
|
|
350
|
+
if (!cache || cache.siteId !== this.siteId || !cache.payload) {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
this.available = Array.isArray(cache.available) ? cache.available : null;
|
|
354
|
+
if (this.available) {
|
|
355
|
+
this.variabilityAllowed = this.available.includes('variability');
|
|
356
|
+
}
|
|
357
|
+
await this.applyPayload(cache.payload, true);
|
|
358
|
+
const next = cache.payload.next_poll_at ? Date.parse(cache.payload.next_poll_at) : NaN;
|
|
359
|
+
// if the user changed the requested groups, the cache is not usable for scheduling
|
|
360
|
+
const wanted = this.buildInclude().filter(g => g !== 'variability');
|
|
361
|
+
const included = cache.payload.included || [];
|
|
362
|
+
const complete = included.includes('all') || wanted.every(g => included.includes(g));
|
|
363
|
+
await this.setStateAsync('info.connection', true, true);
|
|
364
|
+
return { nextPollAt: complete && Number.isFinite(next) ? next : null };
|
|
365
|
+
} catch (err) {
|
|
366
|
+
this.log.debug(`Cache not usable: ${err.message}`);
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ------------------------------------------------------------------ data
|
|
372
|
+
|
|
373
|
+
async applyPayload(body, fromCache) {
|
|
374
|
+
this.payload = body;
|
|
375
|
+
this.prepared = prepare(body);
|
|
376
|
+
const tz = this.prepared.tz;
|
|
377
|
+
await this.setStateAsync('info.computedAt', body.computed_at || null, true);
|
|
378
|
+
await this.setStateAsync('info.availableGroups', (body.available || []).join(','), true);
|
|
379
|
+
await this.setStateAsync('info.variability', !!this.prepared.hasVariability, true);
|
|
380
|
+
await this.setStateAsync('info.forecastDays', (body.daily || []).length, true);
|
|
381
|
+
if (!fromCache) {
|
|
382
|
+
await this.setStateAsync('info.lastUpdate', new Date().toISOString(), true);
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// charts are only rebuilt when a new payload arrives
|
|
386
|
+
const now = Date.now();
|
|
387
|
+
const today = localDate(now, tz);
|
|
388
|
+
await this.ensureState('json.forecast', {
|
|
389
|
+
type: 'string',
|
|
390
|
+
role: 'json',
|
|
391
|
+
name: { en: 'Full forecast series', de: 'Komplette Prognosekurve' },
|
|
392
|
+
});
|
|
393
|
+
await this.ensureState('json.today', {
|
|
394
|
+
type: 'string',
|
|
395
|
+
role: 'json',
|
|
396
|
+
name: { en: 'Forecast series today', de: 'Prognosekurve heute' },
|
|
397
|
+
});
|
|
398
|
+
await this.ensureState('json.daily', {
|
|
399
|
+
type: 'string',
|
|
400
|
+
role: 'json',
|
|
401
|
+
name: { en: 'Daily forecast', de: 'Tagesprognose' },
|
|
402
|
+
});
|
|
403
|
+
await this.setStateAsync('json.forecast', JSON.stringify(chartSeries(this.prepared)), true);
|
|
404
|
+
await this.setStateAsync(
|
|
405
|
+
'json.today',
|
|
406
|
+
JSON.stringify(chartSeries(this.prepared, v => localDate(v.t, tz) === today)),
|
|
407
|
+
true,
|
|
408
|
+
);
|
|
409
|
+
await this.setStateAsync('json.daily', JSON.stringify(body.daily || []), true);
|
|
410
|
+
|
|
411
|
+
await this.updateComputed();
|
|
412
|
+
if (!fromCache) {
|
|
413
|
+
this.log.debug(`Forecast applied (computed_at ${body.computed_at}, ${isoLocal(now, tz)})`);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async updateComputed() {
|
|
418
|
+
if (!this.prepared) {
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const states = computeStates(this.prepared, Date.now());
|
|
422
|
+
const dayCount = states._dayCount || 0;
|
|
423
|
+
delete states._dayCount;
|
|
424
|
+
|
|
425
|
+
for (const [id, val] of Object.entries(states)) {
|
|
426
|
+
await this.ensureState(id);
|
|
427
|
+
await this.setStateAsync(id, { val, ack: true });
|
|
428
|
+
}
|
|
429
|
+
await this.removeSurplus('days', dayCount, MAX_DAYS);
|
|
430
|
+
if (this.config.createSvg !== false) {
|
|
431
|
+
await this.updateCharts();
|
|
432
|
+
}
|
|
433
|
+
if (this.prepared.strings.length) {
|
|
434
|
+
await this.removeSurplus('strings', Math.max(...this.prepared.strings.map(s => s.index)) + 1, MAX_STRINGS);
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
async updateCharts() {
|
|
439
|
+
const now = Date.now();
|
|
440
|
+
const p = this.prepared;
|
|
441
|
+
const opt = { lang: this.lang, stringNames: this.stringNames };
|
|
442
|
+
const tomorrow = p.values.map(v => localDate(v.t, p.tz)).find(d => d > localDate(now, p.tz));
|
|
443
|
+
const charts = {
|
|
444
|
+
'html.today': () => dayChart(p, now, opt),
|
|
445
|
+
'html.tomorrow': () => (tomorrow ? dayChart(p, now, { ...opt, day: tomorrow }) : ''),
|
|
446
|
+
'html.days': () => daysChart(p, now, opt),
|
|
447
|
+
};
|
|
448
|
+
for (const [id, fn] of Object.entries(charts)) {
|
|
449
|
+
await this.ensureState(id, { type: 'string', role: 'html', name: this.chartName(id) });
|
|
450
|
+
await this.setStateAsync(id, fn(), true);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
chartName(id) {
|
|
455
|
+
return {
|
|
456
|
+
'html.today': { en: 'SVG chart: power curve today', de: 'SVG-Diagramm: Leistungskurve heute' },
|
|
457
|
+
'html.tomorrow': { en: 'SVG chart: power curve tomorrow', de: 'SVG-Diagramm: Leistungskurve morgen' },
|
|
458
|
+
'html.days': { en: 'SVG chart: daily energy', de: 'SVG-Diagramm: Tagesertrag' },
|
|
459
|
+
}[id];
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
startComputeTimer() {
|
|
463
|
+
const now = Date.now();
|
|
464
|
+
const toNext = COMPUTE_INTERVAL_MS - (now % COMPUTE_INTERVAL_MS) + 2000;
|
|
465
|
+
this.computeAlignTimer = this.setTimeout(() => {
|
|
466
|
+
this.computeAlignTimer = null;
|
|
467
|
+
this.updateComputed().catch(e => this.log.warn(`Compute failed: ${e.message}`));
|
|
468
|
+
this.computeTimer = this.setInterval(() => {
|
|
469
|
+
this.updateComputed().catch(e => this.log.warn(`Compute failed: ${e.message}`));
|
|
470
|
+
}, COMPUTE_INTERVAL_MS);
|
|
471
|
+
}, toNext);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// ------------------------------------------------------------------ objects
|
|
475
|
+
|
|
476
|
+
async createBaseObjects() {
|
|
477
|
+
for (const [ch, name] of Object.entries(CHANNELS)) {
|
|
478
|
+
await this.setObjectNotExistsAsync(ch, { type: 'channel', common: { name }, native: {} });
|
|
479
|
+
}
|
|
480
|
+
const info = {
|
|
481
|
+
'info.connection': {
|
|
482
|
+
type: 'boolean',
|
|
483
|
+
role: 'indicator.connected',
|
|
484
|
+
name: { en: 'Connected to pvnode', de: 'Verbunden mit pvnode' },
|
|
485
|
+
},
|
|
486
|
+
'info.stale': {
|
|
487
|
+
type: 'boolean',
|
|
488
|
+
role: 'indicator',
|
|
489
|
+
name: {
|
|
490
|
+
en: 'Forecast is outdated (last request failed)',
|
|
491
|
+
de: 'Prognose veraltet (letzte Abfrage fehlgeschlagen)',
|
|
492
|
+
},
|
|
493
|
+
},
|
|
494
|
+
'info.lastError': { type: 'string', role: 'text', name: { en: 'Last error', de: 'Letzter Fehler' } },
|
|
495
|
+
'info.lastUpdate': {
|
|
496
|
+
type: 'string',
|
|
497
|
+
role: 'date',
|
|
498
|
+
name: { en: 'Last successful request', de: 'Letzte erfolgreiche Abfrage' },
|
|
499
|
+
},
|
|
500
|
+
'info.computedAt': {
|
|
501
|
+
type: 'string',
|
|
502
|
+
role: 'text',
|
|
503
|
+
name: { en: 'Forecast computed at (pvnode)', de: 'Prognose berechnet um (pvnode)' },
|
|
504
|
+
},
|
|
505
|
+
'info.nextPoll': { type: 'string', role: 'date', name: { en: 'Next request', de: 'Nächste Abfrage' } },
|
|
506
|
+
'info.requestsLimit': {
|
|
507
|
+
type: 'mixed',
|
|
508
|
+
role: 'value',
|
|
509
|
+
name: { en: 'Monthly request limit', de: 'Monatliches Anfragelimit' },
|
|
510
|
+
},
|
|
511
|
+
'info.requestsUsed': {
|
|
512
|
+
type: 'number',
|
|
513
|
+
role: 'value',
|
|
514
|
+
name: { en: 'Requests used this month', de: 'Anfragen diesen Monat verbraucht' },
|
|
515
|
+
},
|
|
516
|
+
'info.requestsRemaining': {
|
|
517
|
+
type: 'mixed',
|
|
518
|
+
role: 'value',
|
|
519
|
+
name: { en: 'Requests remaining this month', de: 'Verbleibende Anfragen diesen Monat' },
|
|
520
|
+
},
|
|
521
|
+
'info.requestsReset': {
|
|
522
|
+
type: 'string',
|
|
523
|
+
role: 'date',
|
|
524
|
+
name: { en: 'Request counter reset', de: 'Zurücksetzung des Anfragezählers' },
|
|
525
|
+
},
|
|
526
|
+
'info.availableGroups': {
|
|
527
|
+
type: 'string',
|
|
528
|
+
role: 'text',
|
|
529
|
+
name: { en: 'Data groups allowed by plan', de: 'Vom Plan erlaubte Datengruppen' },
|
|
530
|
+
},
|
|
531
|
+
'info.variability': {
|
|
532
|
+
type: 'boolean',
|
|
533
|
+
role: 'indicator',
|
|
534
|
+
name: { en: 'Variability band available', de: 'Schwankungsband verfügbar' },
|
|
535
|
+
},
|
|
536
|
+
'info.forecastDays': {
|
|
537
|
+
type: 'number',
|
|
538
|
+
role: 'value',
|
|
539
|
+
name: { en: 'Number of forecast days', de: 'Anzahl Prognosetage' },
|
|
540
|
+
},
|
|
541
|
+
'info.cache': {
|
|
542
|
+
type: 'string',
|
|
543
|
+
role: 'json',
|
|
544
|
+
name: { en: 'Cached forecast (internal)', de: 'Zwischengespeicherte Prognose (intern)' },
|
|
545
|
+
},
|
|
546
|
+
'site.name': { type: 'string', role: 'text', name: { en: 'Site name', de: 'Name des Standorts' } },
|
|
547
|
+
'site.id': { type: 'string', role: 'text', name: { en: 'Site ID', de: 'Standort-ID' } },
|
|
548
|
+
'site.power_kw': {
|
|
549
|
+
type: 'number',
|
|
550
|
+
role: 'value',
|
|
551
|
+
unit: 'kWp',
|
|
552
|
+
name: { en: 'Installed power', de: 'Installierte Leistung' },
|
|
553
|
+
},
|
|
554
|
+
};
|
|
555
|
+
for (const [id, c] of Object.entries(info)) {
|
|
556
|
+
await this.ensureState(id, c);
|
|
557
|
+
}
|
|
558
|
+
await this.setObjectNotExistsAsync('control.refresh', {
|
|
559
|
+
type: 'state',
|
|
560
|
+
common: {
|
|
561
|
+
name: {
|
|
562
|
+
en: 'Refresh forecast now (costs one request)',
|
|
563
|
+
de: 'Prognose jetzt abrufen (kostet eine Anfrage)',
|
|
564
|
+
},
|
|
565
|
+
type: 'boolean',
|
|
566
|
+
role: 'button',
|
|
567
|
+
read: false,
|
|
568
|
+
write: true,
|
|
569
|
+
def: false,
|
|
570
|
+
},
|
|
571
|
+
native: {},
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
async ensureState(id, override) {
|
|
576
|
+
if (this.created.has(id)) {
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
const parts = id.split('.');
|
|
580
|
+
// intermediate channels (e.g. days.0, strings.1)
|
|
581
|
+
for (let i = 2; i < parts.length; i++) {
|
|
582
|
+
const ch = parts.slice(0, i).join('.');
|
|
583
|
+
if (!this.created.has(ch)) {
|
|
584
|
+
await this.setObjectNotExistsAsync(ch, {
|
|
585
|
+
type: 'channel',
|
|
586
|
+
common: { name: this.channelName(ch) },
|
|
587
|
+
native: {},
|
|
588
|
+
});
|
|
589
|
+
this.created.add(ch);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
const common = { ...commonFor(id), ...(override || {}) };
|
|
593
|
+
common.read = true;
|
|
594
|
+
common.write = false;
|
|
595
|
+
await this.extendObjectAsync(id, { type: 'state', common, native: {} });
|
|
596
|
+
this.created.add(id);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
channelName(ch) {
|
|
600
|
+
const [root, idx] = ch.split('.');
|
|
601
|
+
if (root === 'days') {
|
|
602
|
+
const n = Number(idx);
|
|
603
|
+
if (n === 0) {
|
|
604
|
+
return { en: 'Today', de: 'Heute' };
|
|
605
|
+
}
|
|
606
|
+
if (n === 1) {
|
|
607
|
+
return { en: 'Tomorrow', de: 'Morgen' };
|
|
608
|
+
}
|
|
609
|
+
return { en: `In ${n} days`, de: `In ${n} Tagen` };
|
|
610
|
+
}
|
|
611
|
+
if (root === 'strings') {
|
|
612
|
+
return { en: `String ${Number(idx) + 1}`, de: `String ${Number(idx) + 1}` };
|
|
613
|
+
}
|
|
614
|
+
return ch;
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
async removeSurplus(root, count, max) {
|
|
618
|
+
for (let i = count; i < max; i++) {
|
|
619
|
+
const id = `${root}.${i}`;
|
|
620
|
+
const obj = await this.getObjectAsync(id);
|
|
621
|
+
if (obj) {
|
|
622
|
+
await this.delObjectAsync(id, { recursive: true });
|
|
623
|
+
for (const k of [...this.created]) {
|
|
624
|
+
if (k === id || k.startsWith(`${id}.`)) {
|
|
625
|
+
this.created.delete(k);
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
async cleanupOptionalWeather() {
|
|
633
|
+
const wanted = new Set();
|
|
634
|
+
if (this.config.includeWeather) {
|
|
635
|
+
[
|
|
636
|
+
'temp',
|
|
637
|
+
'weather_code',
|
|
638
|
+
'wind_speed',
|
|
639
|
+
'relative_humidity',
|
|
640
|
+
'precipitation_mm',
|
|
641
|
+
'snow_water_equivalent',
|
|
642
|
+
].forEach(f => wanted.add(f));
|
|
643
|
+
}
|
|
644
|
+
if (this.config.includeIrradiance) {
|
|
645
|
+
['ghi', 'dhi', 'bni'].forEach(f => wanted.add(f));
|
|
646
|
+
}
|
|
647
|
+
for (const f of WEATHER_FIELDS) {
|
|
648
|
+
if (!wanted.has(f)) {
|
|
649
|
+
const obj = await this.getObjectAsync(`weather.${f}`);
|
|
650
|
+
if (obj) {
|
|
651
|
+
await this.delObjectAsync(`weather.${f}`);
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
if (!this.config.includeClearsky) {
|
|
656
|
+
for (const id of ['now.power_clearsky']) {
|
|
657
|
+
if (await this.getObjectAsync(id)) {
|
|
658
|
+
await this.delObjectAsync(id);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
for (let i = 0; i < MAX_DAYS; i++) {
|
|
662
|
+
if (await this.getObjectAsync(`days.${i}.energy_clearsky`)) {
|
|
663
|
+
await this.delObjectAsync(`days.${i}.energy_clearsky`);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
async writeSiteInfo(site) {
|
|
670
|
+
await this.setStateAsync('site.name', site.name || '', true);
|
|
671
|
+
await this.setStateAsync('site.id', site.id || '', true);
|
|
672
|
+
const strings = Array.isArray(site.strings) ? site.strings : [];
|
|
673
|
+
const total = strings.reduce((a, s) => a + (Number(s.power_kw) || 0), 0);
|
|
674
|
+
await this.setStateAsync('site.power_kw', Math.round(total * 100) / 100, true);
|
|
675
|
+
const dirDe = {
|
|
676
|
+
N: 'Nord',
|
|
677
|
+
NO: 'Nordost',
|
|
678
|
+
O: 'Ost',
|
|
679
|
+
SO: 'Südost',
|
|
680
|
+
S: 'Süd',
|
|
681
|
+
SW: 'Südwest',
|
|
682
|
+
W: 'West',
|
|
683
|
+
NW: 'Nordwest',
|
|
684
|
+
};
|
|
685
|
+
const dirEn = {
|
|
686
|
+
N: 'North',
|
|
687
|
+
NO: 'Northeast',
|
|
688
|
+
O: 'East',
|
|
689
|
+
SO: 'Southeast',
|
|
690
|
+
S: 'South',
|
|
691
|
+
SW: 'Southwest',
|
|
692
|
+
W: 'West',
|
|
693
|
+
NW: 'Northwest',
|
|
694
|
+
};
|
|
695
|
+
this.stringNames = strings.map(st => {
|
|
696
|
+
const c = compass(st.orientation);
|
|
697
|
+
return `${(this.lang === 'de' ? dirDe : dirEn)[c] || c} ${Number(st.power_kw).toLocaleString(this.lang === 'de' ? 'de-DE' : 'en-US')} kWp`;
|
|
698
|
+
});
|
|
699
|
+
for (let i = 0; i < strings.length && i < MAX_STRINGS; i++) {
|
|
700
|
+
const s = strings[i];
|
|
701
|
+
const ch = `strings.${i}`;
|
|
702
|
+
await this.extendObjectAsync(ch, {
|
|
703
|
+
type: 'channel',
|
|
704
|
+
common: {
|
|
705
|
+
name: `String ${i + 1}: ${compass(s.orientation)} ${s.orientation}°, ${s.slope}° Neigung, ${s.power_kw} kWp`,
|
|
706
|
+
},
|
|
707
|
+
native: { string_id: s.id },
|
|
708
|
+
});
|
|
709
|
+
this.created.add(ch);
|
|
710
|
+
await this.ensureState(`${ch}.string_id`);
|
|
711
|
+
await this.setStateAsync(`${ch}.string_id`, s.id || '', true);
|
|
712
|
+
for (const k of ['orientation', 'slope', 'power_kw']) {
|
|
713
|
+
await this.ensureState(`${ch}.${k}`);
|
|
714
|
+
await this.setStateAsync(`${ch}.${k}`, typeof s[k] === 'number' ? s[k] : null, true);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
async writeQuota(q) {
|
|
720
|
+
if (!q) {
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
await this.setStateAsync('info.requestsLimit', q.limit ?? null, true);
|
|
724
|
+
await this.setStateAsync('info.requestsUsed', typeof q.used === 'number' ? q.used : null, true);
|
|
725
|
+
await this.setStateAsync('info.requestsRemaining', q.remaining ?? null, true);
|
|
726
|
+
await this.setStateAsync('info.requestsReset', q.reset || null, true);
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
if (require.main !== module) {
|
|
731
|
+
module.exports = options => new Pvnode(options);
|
|
732
|
+
} else {
|
|
733
|
+
new Pvnode();
|
|
734
|
+
}
|