-
Notifications
You must be signed in to change notification settings - Fork 13
/
main.js
1688 lines (1488 loc) · 51.5 KB
/
main.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const utils = require('@iobroker/adapter-core');
const moment = require('moment');
const axios = require('axios').default;
const solcast = require(__dirname + '/lib/solcast');
const CronJob = require('cron').CronJob;
let globalunit = 1000;
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
class Pvforecast extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'pvforecast',
});
this.globalEveryHour = {};
this.reqInterval = 60;
this.hasApiKey = false;
this.longitude = undefined;
this.latitude = undefined;
this.updateServiceDataTimeout = null;
this.updateActualDataCron = null;
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
}
async onReady() {
this.log.debug(`instance config: ${JSON.stringify(this.config)}`);
this.longitude = this.config.longitude;
this.latitude = this.config.latitude;
if (
(!this.longitude && this.longitude !== 0) || isNaN(this.longitude) ||
(!this.latitude && this.latitude !== 0) || isNaN(this.latitude)
) {
this.log.debug('longitude and/or latitude not set, loading system configuration');
try {
const systemConfigState = await this.getForeignObjectAsync('system.config');
if (systemConfigState) {
this.longitude = systemConfigState.common.longitude;
this.latitude = systemConfigState.common.latitude;
if (this.longitude && this.latitude) {
this.log.info(`using system latitude: ${this.latitude} longitude: ${this.longitude}`);
}
}
} catch (err) {
this.log.error(`error white requesting system.config: ${err}`);
}
}
if (
this.longitude == '' || typeof this.longitude == 'undefined' || isNaN(this.longitude) ||
this.latitude == '' || typeof this.latitude == 'undefined' || isNaN(this.latitude)
) {
this.log.error('Please set the longitude and latitude in the adapter (or system) configuration!');
return;
}
if (typeof this.config.devices == 'undefined' || !this.config.devices.length) {
this.log.error('Please set at least one device in the adapter configuration!');
return;
} else {
try {
const plantArray = this.config.devices;
// Validate plants
await asyncForEach(plantArray, async (plant) => {
if (!plant.name) {
throw new Error(`Invalid device configuration: Found plant without name`);
}
if (isNaN(plant.azimuth)) {
throw new Error(`Invalid device configuration: Found plant without azimuth`);
}
if (isNaN(plant.tilt)) {
throw new Error(`Invalid device configuration: Found plant with incorrect tilt`);
}
if (!plant.peakpower || isNaN(plant.peakpower) || plant.peakpower < 0) {
throw new Error(`Invalid device configuration: Found plant without peak power`);
}
if (this.config.influxinstace) {
const cleanPlantId = this.cleanNamespace(plant.name);
this.log.info(`InfluxDB logging is enabled - forecast for plant "${plant.name}" will be available @ "${this.namespace}.plants.${cleanPlantId}.power"`);
}
});
if (this.config.influxinstace) {
this.log.info(`InfluxDB logging is enabled - forecast summary will be available @ "${this.namespace}.summary.power"`);
}
// Get list of valid plants by configuration
const plantsKeep = plantArray.map(d => `${this.namespace}.plants.${this.cleanNamespace(d.name)}`);
const plantDevices = await this.getDevicesAsync();
this.log.debug(`Existing plant devices: ${JSON.stringify(plantDevices)} - configured: ${JSON.stringify(plantsKeep)}`);
await asyncForEach(plantDevices, async (deviceObj) => {
if (plantsKeep.indexOf(deviceObj._id) === -1) {
await this.delObjectAsync(deviceObj._id, { recursive: true });
this.log.info(`Deleted plant with id: ${deviceObj._id} - (not found in configuration)`);
}
});
} catch (err) {
this.log.error(err);
return;
}
}
if (!this.config.interval || this.config.interval < 60) {
this.reqInterval = 60 * 60 * 1000;
this.log.warn('The interval is set to less than 60 minutes. Please set a higher value in the adapter configuration!');
} else {
this.log.debug(`The interval is set to ${this.config.interval} minutes`);
this.reqInterval = this.config.interval * 60 * 1000;
}
// Check if API key is configured
if (typeof this.config.apiKey !== 'undefined' && this.config.apiKey !== '') {
this.hasApiKey = true;
}
if (this.config.service === 'solcast' && !this.hasApiKey) {
this.log.error('Please set the API key for Solcast in the adapter configuration!');
return;
}
if (
this.config.service == 'spa' && (!this.hasApiKey || this.config.apiKey.length < 20)
) {
this.log.error('Please set the API key for SolarPredictionAPI in the adapter configuration!');
return;
}
if (this.config.watt_kw) {
globalunit = 1;
}
await this.subscribeStatesAsync('plants.*');
await this.createAndDeleteStates();
await this.updateServiceDataInterval();
await this.updateActualDataInterval();
let timeZone = 'Europe/Berlin';
try {
timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
this.log.info(`Starting update cron (every 15 Minutes) for timezone: ${timeZone}`);
} catch (err) {
this.log.warn(`Unable to get system timezone - fallback to Europe/Berlin`);
}
this.updateActualDataCron = new CronJob(
'*/15 * * * *',
() => this.updateActualDataInterval(),
() => this.log.debug('stopped updateActualDataInterval'),
true,
timeZone
);
this.log.debug(`[updateActualDataCron] next execution: ${this.updateActualDataCron.nextDates()}`);
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
if (state && !state.ack) {
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
if (id.startsWith(this.namespace)) {
this.getForeignObjectAsync(id)
.then(obj => {
if (obj?.native?.resetId) {
this.log.debug(`state "${id}" changed - resetting "${obj.native.resetId}" to 0`);
return this.setStateAsync(obj.native.resetId, { val: 0, ack: true });
}
})
.then(() => {
this.updateServiceDataInterval();
})
.catch(err => {
this.log.error(err);
});
}
}
}
async updateServiceDataInterval() {
if (this.updateServiceDataTimeout) {
this.clearTimeout(this.updateServiceDataTimeout);
}
await this.updateServiceData();
await this.updateServiceWeatherData();
if (this.config.service === 'solcast') {
this.reqInterval = moment().startOf('day').add(1, 'days').add(1, 'hours').valueOf() - moment().valueOf();
this.log.debug(`updateServiceDataInterval (solcast) - next service refresh in ${this.reqInterval}ms`);
}
this.updateServiceDataTimeout = this.setTimeout(async () => {
this.updateServiceDataTimeout = null;
await this.updateServiceDataInterval();
}, this.reqInterval);
}
async updateActualDataInterval() {
this.log.debug('[updateActualDataInterval] starting update');
const plantArray = this.config.devices || [];
const jsonDataSummary = [];
const jsonTableSummary = [];
const jsonGraphSummary = [];
const jsonGraphLabelSummary = [];
this.globalEveryHour = {};
let totalPowerNow = 0;
let totalPowerInstalled = 0;
let totalEnergyNow = 0;
let totalEnergyToday = 0;
let totalEnergyTomorrow = 0;
await asyncForEach(plantArray, async (plant, index) => {
const cleanPlantId = this.cleanNamespace(plant.name);
this.globalEveryHour[cleanPlantId] = [];
const serviceDataState = await this.getStateAsync(`plants.${cleanPlantId}.service.data`);
if (serviceDataState && serviceDataState.val) {
try {
const data = JSON.parse(serviceDataState.val);
// cancel if no data
if (typeof data === 'undefined') {
return;
}
this.log.debug(`[updateActualDataInterval] current service data for plants.${cleanPlantId}.service.data ("${plant.name}"): ${JSON.stringify(data)}`);
for (const time in data.watts) {
if (this.config.everyhourEnabled) {
this.saveEveryHour(cleanPlantId, `plants.${cleanPlantId}.power.hoursToday`, moment().date(), time, data.watts[time] / globalunit);
this.saveEveryHour(cleanPlantId, `plants.${cleanPlantId}.power.hoursTomorrow`, moment().add(1, 'days').date(), time, data.watts[time] / globalunit);
}
// add to InfluxDB
await this.addToInfluxDB(`plants.${cleanPlantId}.power`, moment(time).valueOf(), data.watts[time] / globalunit);
}
const powerNow = Object.keys(data.watts)
.filter((timeStr) => moment(timeStr).valueOf() < moment().valueOf())
.map(key => data.watts[key])
.pop() || 0;
const energyToday = data.watt_hours_day[moment().format('YYYY-MM-DD')];
const energyTomorrow = data.watt_hours_day[moment().add(1, 'days').format('YYYY-MM-DD')];
const energyNow = Object.keys(data.watt_hours)
.filter((timeStr) => moment(timeStr).valueOf() < moment().valueOf())
.map(key => data.watt_hours[key])
.pop() || 0;
totalPowerNow += powerNow;
totalPowerInstalled += plant.peakpower;
totalEnergyNow += energyNow;
totalEnergyToday += energyToday;
totalEnergyTomorrow += energyTomorrow;
await this.setStateChangedAsync(`plants.${cleanPlantId}.power.now`, { val: Number(powerNow / globalunit), ack: true });
await this.setStateChangedAsync(`plants.${cleanPlantId}.power.installed`, { val: plant.peakpower, ack: true });
await this.setStateChangedAsync(`plants.${cleanPlantId}.energy.now`, { val: Number(energyNow / globalunit), ack: true });
await this.setStateChangedAsync(`plants.${cleanPlantId}.energy.today`, { val: Number(energyToday / globalunit), ack: true });
await this.setStateChangedAsync(`plants.${cleanPlantId}.energy.tomorrow`, { val: Number(energyTomorrow / globalunit), ack: true });
await this.setStateChangedAsync(`plants.${cleanPlantId}.name`, { val: plant.name, ack: true });
if (this.config.everyhourEnabled) {
this.saveEveryHourEmptyStates(cleanPlantId, `plants.${cleanPlantId}.power.hoursToday`, moment().date());
this.saveEveryHourEmptyStates(cleanPlantId, `plants.${cleanPlantId}.power.hoursTomorrow`, moment().add(1, 'days').date());
}
// JSON Data
const jsonData = [];
for (const time in data.watts) {
const power = data.watts[time] / globalunit;
const timestamp = moment(time).valueOf();
jsonData.push(
{
t: timestamp,
y: power
}
);
if (jsonDataSummary?.[timestamp] === undefined) {
jsonDataSummary[timestamp] = 0;
}
jsonDataSummary[timestamp] += power;
}
this.log.debug(`generated JSON data of "${plant.name}": ${JSON.stringify(jsonData)}`);
await this.setStateAsync(`plants.${cleanPlantId}.JSONData`, { val: JSON.stringify(jsonData), ack: true });
// JSON Table
const jsonTable = [];
let wattindex = 0;
for (const time in data.watts) {
const power = data.watts[time] / globalunit;
jsonTable.push(
{
Time: time,
Power: this.formatValue(power, this.config.watt_kw ? 0 : 3)
}
);
if (index === 0) {
jsonTableSummary[wattindex] = { 'Time': time };
jsonTableSummary[wattindex]['Total'] = power;
} else {
jsonTableSummary[wattindex]['Total'] = jsonTableSummary[wattindex]['Total'] + power;
}
jsonTableSummary[wattindex][plant.name] = this.formatValue(power, this.config.watt_kw ? 0 : 3);
wattindex++;
}
this.log.debug(`generated JSON table of "${plant.name}": ${JSON.stringify(jsonTable)}`);
await this.setStateAsync(`plants.${cleanPlantId}.JSONTable`, { val: JSON.stringify(jsonTable), ack: true });
// JSON Graph
if (this.config.chartingEnabled) {
const jsonGraphData = [];
const jsonGraphLabels = [];
for (const time in data.watts) {
const timeMoment = moment(time);
if (!this.config.chartingJustToday || timeMoment.date() === moment().date()) {
const timeInCustomFormat = timeMoment.format(this.config.chartingLabelFormat);
// Add label if not exists
if (jsonGraphLabelSummary.indexOf(timeInCustomFormat) < 0) {
jsonGraphLabelSummary.push(timeInCustomFormat);
}
jsonGraphLabels.push(timeInCustomFormat);
jsonGraphData.push(data.watts[time] / globalunit);
}
}
// https://github.com/Scrounger/ioBroker.vis-materialdesign/blob/master/README.md
const jsonGraph = {
// graph
data: jsonGraphData,
type: 'bar',
legendText: plant.name,
displayOrder: index + 1,
color: plantArray[index].graphcolor,
tooltip_AppendText: this.config.watt_kw ? 'W' : 'kW',
//datalabel_append: this.config.watt_kw ? 'W' : 'kW',
datalabel_show: true,
datalabel_rotation: this.config.chartingRoation,
datalabel_color: plantArray[index].labelcolor,
datalabel_fontSize: this.config.chartingLabelSize,
// graph bar chart spfeicifc
barIsStacked: true,
barStackId: 1,
// graph y-Axis
yAxis_id: 0,
yAxis_position: 'left',
yAxis_show: true,
yAxis_appendix: this.config.watt_kw ? 'W' : 'kW',
yAxis_step: this.config.chartingAxisStepY,
};
jsonGraphSummary.push(jsonGraph);
this.log.debug(`generated JSON graph of "${plant.name}": ${JSON.stringify(jsonGraph)}`);
await this.setStateAsync(`plants.${cleanPlantId}.JSONGraph`, { val: JSON.stringify({ 'graphs': [jsonGraph], 'axisLabels': jsonGraphLabels }), ack: true });
} else {
await this.setStateAsync(`plants.${cleanPlantId}.JSONGraph`, { val: JSON.stringify({}), ack: true });
}
await this.setStateAsync(`plants.${cleanPlantId}.lastUpdated`, { val: moment().valueOf(), ack: true });
this.log.debug(`finished plant update: "${plant.name}"`);
} catch (err) {
this.log.debug(`unable to update "${plant.name}": ${err}`);
}
}
});
this.log.debug('finished plants update');
if (this.config.everyhourEnabled) {
await this.saveEveryHourSummary('summary.power.hoursToday', moment().date());
await this.saveEveryHourSummary('summary.power.hoursTomorrow', moment().add(1, 'days').date());
this.log.debug(`global time: ${JSON.stringify(this.globalEveryHour)}`);
}
await this.setStateChangedAsync('summary.power.now', { val: Number(totalPowerNow / globalunit), ack: true });
await this.setStateChangedAsync('summary.power.installed', { val: totalPowerInstalled, ack: true });
await this.setStateChangedAsync('summary.energy.now', { val: Number(totalEnergyNow / globalunit), ack: true });
await this.setStateChangedAsync('summary.energy.today', { val: Number(totalEnergyToday / globalunit), ack: true });
await this.setStateChangedAsync('summary.energy.tomorrow', { val: Number(totalEnergyTomorrow / globalunit), ack: true });
// add summary to InfluxDB
await asyncForEach(Object.keys(jsonDataSummary), async (time) => {
await this.addToInfluxDB(`summary.power`, Number(time), jsonDataSummary[time]);
});
// JSON Data
const jsonDataSummaryFormat = Object.keys(jsonDataSummary).map(time => {
return {
t: Number(time),
y: jsonDataSummary[time]
};
});
await this.setStateAsync('summary.JSONData', { val: JSON.stringify(jsonDataSummaryFormat), ack: true });
// JSON Table
const jsonTableSummaryFormat = jsonTableSummary.map(row => {
row['Total'] = this.formatValue(row['Total'], this.config.watt_kw ? 0 : 3);
return row;
});
await this.setStateAsync('summary.JSONTable', { val: JSON.stringify(jsonTableSummaryFormat), ack: true });
// JSON Graph
if (this.config.chartingEnabled) {
await this.setStateAsync('summary.JSONGraph', { val: JSON.stringify({ 'graphs': jsonGraphSummary, 'axisLabels': jsonGraphLabelSummary }), ack: true });
} else {
await this.setStateAsync('summary.JSONGraph', { val: JSON.stringify({}), ack: true });
}
await this.setStateAsync('summary.lastUpdated', { val: moment().valueOf(), ack: true });
await this.updateActualWeatherData();
}
async updateActualWeatherData() {
if (this.hasApiKey && this.config.weatherEnabled) {
try {
const serviceDataState = await this.getStateAsync('weather.service.data');
if (serviceDataState && serviceDataState.val) {
const data = JSON.parse(serviceDataState.val);
const weatherNow = data
.filter((weather) => moment(weather.datetime).valueOf() < moment().valueOf())
.pop();
if (weatherNow) {
this.log.debug(`[updateActualWeatherData] filling states with weather info from: ${JSON.stringify(weatherNow)}`);
await this.setStateChangedAsync('weather.sky', { val: Number(weatherNow.sky), ack: true });
await this.setStateChangedAsync('weather.datetime', { val: moment(weatherNow.datetime).valueOf(), ack: true });
await this.setStateChangedAsync('weather.temperature', { val: Number(weatherNow.temperature), ack: true });
await this.setStateChangedAsync('weather.condition', { val: weatherNow.condition, ack: true });
await this.setStateChangedAsync('weather.icon', { val: weatherNow.icon, ack: true });
await this.setStateChangedAsync('weather.wind_speed', { val: Number(weatherNow.wind_speed), ack: true });
await this.setStateChangedAsync('weather.wind_degrees', { val: Number(weatherNow.wind_degrees), ack: true });
await this.setStateChangedAsync('weather.wind_direction', { val: weatherNow.wind_direction, ack: true });
}
}
} catch (err) {
this.log.error(`[updateActualWeatherData] failed to update weather data: ${err}`);
}
}
}
async updateServiceWeatherData() {
try {
if (this.hasApiKey && this.config.weatherEnabled) {
if (this.config.service === 'forecastsolar') {
// https://api.forecast.solar/:key/weather/:lat/:lon (Professional account only)
const url = `https://api.forecast.solar/${this.config.apiKey}/weather/${this.latitude}/${this.longitude}`;
this.log.debug(`[updateServiceWeatherData] url (professional account only): ${url}`);
try {
const serviceResponse = await axios.get(url);
this.log.debug(`[updateServiceWeatherData] received data: ${JSON.stringify(serviceResponse.data)}`);
if (serviceResponse) {
await this.setStateAsync('weather.service.data', { val: JSON.stringify(serviceResponse.data.result), ack: true });
await this.setStateAsync(`weather.service.lastUpdated`, { val: moment().valueOf(), ack: true });
}
} catch (error) {
if (error === 'Error: Request failed with status code 429') {
this.log.error('too many data requests');
} else if (error === 'Error: Request failed with status code 400') {
this.log.error('entry out of range (check the notes in settings) => check azimuth, tilt, longitude,latitude');
} else {
this.log.error('Axios Error ' + error);
}
}
} else {
this.log.warn(`[updateServiceWeatherData] weather data is just available for "forecastsolar"`);
}
}
} catch (err) {
this.log.error(`[updateServiceWeatherData] error: ${err}`);
}
}
async updateServiceData() {
const plantArray = this.config.devices || [];
await asyncForEach(plantArray, async (plant) => {
const cleanPlantId = this.cleanNamespace(plant.name);
let url = '';
let requestHeader = {};
if (this.config.service === 'forecastsolar') {
if (this.hasApiKey) {
// https://api.forecast.solar/:apikey/estimate/:lat/:lon/:dec/:az/:kwp
url = `https://api.forecast.solar/${this.config.apiKey}/estimate/${this.latitude}/${this.longitude}/${plant.tilt}/${plant.azimuth}/${plant.peakpower}`;
} else {
// https://api.forecast.solar/estimate/:lat/:lon/:dec/:az/:kwp
url = `https://api.forecast.solar/estimate/${this.latitude}/${this.longitude}/${plant.tilt}/${plant.azimuth}/${plant.peakpower}`;
}
} else if (this.config.service === 'solcast') {
url = `https://api.solcast.com.au/world_pv_power/forecasts?format=json&hours=48&loss_factor=1&latitude=${this.latitude}&longitude=${this.longitude}&tilt=${plant.tilt}&azimuth=${this.convertAzimuth(plant.azimuth)}&capacity=${plant.peakpower}&api_key=${this.config.apiKey}`;
} else if (this.config.service === 'spa') {
url = `https://solarenergyprediction.p.rapidapi.com/v2.0/solar/prediction?decoration=forecast.solar&lat=${this.latitude}&lon=${this.longitude}°=${plant.tilt}&az=${plant.azimuth}&wp=${plant.peakpower*1000}`;
if (this.hasApiKey) {
requestHeader = {
headers: {
'X-RapidAPI-Key': this.config.apiKey,
'X-RapidAPI-Host': 'solarenergyprediction.p.rapidapi.com'
}
};
}
}
if (url) {
// Force update when url changed
const serviceDataUrlState = await this.getStateAsync(`plants.${cleanPlantId}.service.url`);
const lastUrl = (serviceDataUrlState && serviceDataUrlState.val) ? serviceDataUrlState.val : '';
const serviceDataLastUpdatedState = await this.getStateAsync(`plants.${cleanPlantId}.service.lastUpdated`);
const lastUpdate = (serviceDataLastUpdatedState && serviceDataLastUpdatedState.val) ? Number(serviceDataLastUpdatedState.val) : 0;
this.log.debug(`plant "${plant.name}" - last update: ${lastUpdate}, service url: ${url}`);
if (lastUrl !== url || !lastUpdate || moment().valueOf() - lastUpdate > 60 * 60 * 1000) {
try {
this.log.debug(`Starting update of ${plant.name}`);
const serviceResponse = await axios.get(url, requestHeader);
this.log.debug(`received "${this.config.service}" data for plant "${plant.name}": ${JSON.stringify(serviceResponse.data)}`);
let data;
let message;
if (this.config.service === 'forecastsolar') {
data = serviceResponse.data.result;
message = serviceResponse.data.message;
this.log.debug(`rate limit for forecastsolar API: ${message.ratelimit.limit} (${message.ratelimit.remaining} left in period)`);
} else if (this.config.service === 'solcast') {
data = solcast.convertToForecast(serviceResponse.data);
this.log.debug(`[parseSolcastToForecast] converted JSON: ${JSON.stringify(data)}`);
message = { 'info': { 'place': '-' }, 'type': 'Solcast' };
} else if (this.config.service === 'spa') {
data = serviceResponse.data.result;
message = serviceResponse.data.message;
}
await this.setStateAsync(`plants.${cleanPlantId}.service.url`, { val: url, ack: true });
await this.setStateAsync(`plants.${cleanPlantId}.service.data`, { val: JSON.stringify(data), ack: true });
await this.setStateAsync(`plants.${cleanPlantId}.service.lastUpdated`, { val: moment().valueOf(), ack: true });
await this.setStateAsync(`plants.${cleanPlantId}.service.message`, { val: message.type, ack: true });
await this.setStateAsync(`plants.${cleanPlantId}.place`, { val: message.info.place, ack: true });
} catch (error) {
if (error === 'Error: Request failed with status code 429') {
this.log.error('too many data requests');
} else if (error === 'Error: Request failed with status code 400') {
this.log.error('entry out of range (check the notes in settings) => check azimuth, tilt, longitude,latitude');
} else if (error === 'Error: Request failed with status code 404') {
this.log.error('Error: Not Found');
} else if (error === 'Error: Request failed with status code 502') {
this.log.error('Error: Bad Gateway');
} else {
this.log.error('Axios Error ' + error);
}
}
} else {
this.log.debug(`Last update of "${plant.name}" is within refresh interval - skipping`);
}
this.log.debug('received all data');
}
});
}
async saveEveryHour(cleanPlantId, prefix, dayOfMonth, timeStr, value) {
// timeStr example: "2022-05-23 17:30:00"
const timeObj = moment(timeStr);
const hourKey = timeObj.format('HH:mm:ss');
if (this.getValidHourKeys().includes(hourKey) && dayOfMonth === moment(timeStr).date()) {
this.log.debug(`[saveEveryHour] found time ${prefix}.${hourKey} - value: ${value}`);
await this.setStateChangedAsync(`${prefix}.${hourKey}`, { val: Number(value), ack: true });
this.globalEveryHour[cleanPlantId].push({dayOfMonth: dayOfMonth, time: hourKey, value: Number(value) });
} else {
this.log.silly(`[saveEveryHour] no match for plant "${cleanPlantId}" at "${timeStr}" (${moment().date()} !== ${moment(timeStr).date()})`);
}
}
async saveEveryHourEmptyStates(cleanPlantId, prefix, dayOfMonth) {
const validHourKeys = this.getValidHourKeys();
const filledHourKeys = this.globalEveryHour[cleanPlantId].filter(e => e.dayOfMonth == dayOfMonth).map(e => e.time);
const unfilledHourKeys = validHourKeys.filter(hourKey => filledHourKeys.indexOf(hourKey) < 0);
this.log.debug(`[saveEveryHourEmptyStates] ${unfilledHourKeys.length} items missing - please check if your license allows to request all values`);
// Fill all hours with 0 (which were not included in the service data)
await asyncForEach(unfilledHourKeys, async (hourKey) => {
await this.setStateChangedAsync(`${prefix}.${hourKey}`, { val: 0, ack: true, q: 0x02 });
});
}
async saveEveryHourSummary(prefix, dayOfMonth) {
const plantArray = this.config.devices || [];
const validHourKeys = this.getValidHourKeys();
await asyncForEach(validHourKeys, async (hourKey) => {
let totalPower = 0;
await asyncForEach(plantArray, async (plant) => {
const cleanPlantId = this.cleanNamespace(plant.name);
totalPower += this.globalEveryHour[cleanPlantId]
.filter(e => e.dayOfMonth == dayOfMonth && e.time === hourKey)
.reduce((pv, cv) => pv + cv.value, 0);
});
await this.setStateChangedAsync(`${prefix}.${hourKey}`, { val: totalPower, ack: true });
});
}
async addToInfluxDB(datapoint, timestamp, value) {
try {
let influxInstance = this.config.influxinstace;
if (!influxInstance) return;
// Fallback for older instance configs
if (!influxInstance.startsWith('influxdb.')) {
influxInstance = `influxdb.${influxInstance}`;
}
this.log.silly(`[addToInfluxDB] storeState into "${influxInstance}": value "${value}" (${typeof value}) of "${this.namespace}.${datapoint}" with timestamp ${timestamp}`);
const result = await this.sendToAsync(influxInstance, 'storeState', {
id: `${this.namespace}.${datapoint}`,
state: {
ts: timestamp,
val: value,
ack: true,
from: `system.adapter.${this.namespace}`,
//q: 0
}
});
this.log.silly(`[addToInfluxDB] storeState result: ${JSON.stringify(result)}`);
} catch (err) {
this.log.error(`[addToInfluxDB] storeState error: ${err}`);
}
}
async createAndDeleteStates() {
try {
if (this.hasApiKey && this.config.weatherEnabled) {
this.log.debug('creating states for weather');
await this.setObjectNotExistsAsync('weather', {
type: 'channel',
common: {
name: {
en: 'Weather',
de: 'Wetter',
ru: 'Погода',
pt: 'Clima',
nl: 'Het weer',
fr: 'Temps',
it: 'Tempo metereologico',
es: 'Tiempo',
pl: 'Pogoda',
'zh-cn': '天气'
}
},
native: {}
});
await this.setObjectNotExistsAsync('weather.service', {
type: 'channel',
common: {
name: {
en: 'API',
de: 'API',
ru: 'API',
pt: 'API',
nl: 'API',
fr: 'API',
it: 'API',
es: 'API',
pl: 'API',
'zh-cn': 'API'
}
},
native: {}
});
await this.setObjectNotExistsAsync('weather.service.data', {
type: 'state',
common: {
name: {
en: 'Weather data from service',
de: 'Wetterdaten vom Dienst',
ru: 'Данные о погоде от сервиса',
pt: 'Dados meteorológicos do serviço',
nl: 'Weergegevens van service',
fr: 'Données météorologiques du service',
it: 'Dati meteorologici dal servizio',
es: 'Datos meteorológicos del servicio',
pl: 'Dane pogodowe z serwisu',
'zh-cn': '来自服务的天气数据'
},
type: 'string',
role: 'weather.json',
read: true,
write: false,
def: '{}'
},
native: {}
});
await this.setObjectNotExistsAsync(`weather.service.lastUpdated`, {
type: 'state',
common: {
name: {
en: 'Last update (service)',
de: 'Letztes Update (Service)',
ru: 'Последнее обновление (сервис)',
pt: 'Última atualização (serviço)',
nl: 'Laatste update (service)',
fr: 'Dernière mise à jour (service)',
it: 'Ultimo aggiornamento (servizio)',
es: 'Última actualización (servicio)',
pl: 'Ostatnia aktualizacja (usługa)',
'zh-cn': '最后更新(服务)'
},
type: 'number',
role: 'value.time',
read: true,
write: false,
def: 0
},
native: {}
});
await this.setObjectNotExistsAsync('weather.datetime', {
type: 'state',
common: {
name: {
en: 'Timestamp',
de: 'Zeitstempel',
ru: 'Отметка времени',
pt: 'Carimbo de data e hora',
nl: 'Tijdstempel',
fr: 'Horodatage',
it: 'Timestamp',
es: 'marca de tiempo',
pl: 'Znak czasu',
'zh-cn': '时间戳'
},
type: 'number',
role: 'value.time',
read: true,
write: false
},
native: {}
});
await this.setObjectNotExistsAsync('weather.sky', {
type: 'state',
common: {
name: {
en: 'Sky',
de: 'Himmel',
ru: 'Небо',
pt: 'Céu',
nl: 'Lucht',
fr: 'Ciel',
it: 'Cielo',
es: 'Cielo',
pl: 'Niebo',
'zh-cn': '天空'
},
type: 'number',
role: 'value',
read: true,
write: false,
def: 0
},
native: {}
});
await this.setObjectNotExistsAsync('weather.temperature', {
type: 'state',
common: {
name: {
en: 'Temperature',
de: 'Temperatur',
ru: 'Температура',
pt: 'Temperatura',
nl: 'Temperatuur',
fr: 'Température',
it: 'Temperatura',
es: 'Temperatura',
pl: 'Temperatura',
'zh-cn': '温度'
},
type: 'number',
role: 'value.temperature',
unit: '°C',
read: true,
write: false,
def: 0
},
native: {}
});
await this.setObjectNotExistsAsync('weather.condition', {
type: 'state',
common: {
name: {
en: 'Weather condition',
de: 'Wetterlage',
ru: 'Погодные условия',
pt: 'Condições meteorológicas',
nl: 'Weerconditie',
fr: 'Les conditions météorologiques',
it: 'Condizioni metereologiche',
es: 'Condición climática',
pl: 'Stan pogody',
'zh-cn': '气候条件'
},
type: 'string',
role: 'value.condition',
read: true,
write: false,
def: ''
},
native: {}
});
await this.setObjectNotExistsAsync('weather.icon', {
type: 'state',
common: {
name: {
en: 'Icon',
de: 'Symbol',
ru: 'Значок',
pt: 'Ícone',
nl: 'Icoon',
fr: 'Icône',
it: 'Icona',
es: 'Icono',
pl: 'Ikona',
'zh-cn': '图标'
},
type: 'string',
role: 'weather.icon',
read: true,
write: false,
def: ''
},
native: {}
});
await this.setObjectNotExistsAsync('weather.wind_speed', {
type: 'state',
common: {
name: {
en: 'Wind speed',
de: 'Windgeschwindigkeit',
ru: 'Скорость ветра',
pt: 'Velocidade do vento',
nl: 'Windsnelheid',
fr: 'Vitesse du vent',
it: 'Velocità del vento',
es: 'Velocidad del viento',
pl: 'Prędkość wiatru',
'zh-cn': '风速'
},
type: 'number',
role: 'value.speed.wind',
unit: 'km/h',
read: true,
write: false,
def: 0
},
native: {}
});
await this.setObjectNotExistsAsync('weather.wind_degrees', {
type: 'state',
common: {
name: {
en: 'Wind direction (degrees)',
de: 'Windrichtung (Grad)',
ru: 'Направление ветра (градусы)',
pt: 'Direção do vento (graus)',
nl: 'Windrichting (graden)',
fr: 'Direction du vent (degrés)',
it: 'Direzione del vento (gradi)',
es: 'Dirección del viento (grados)',
pl: 'Kierunek wiatru (stopnie)',
'zh-cn': '风向(度)'
},
type: 'number',
role: 'value',
unit: '°',
read: true,
write: false,
def: 0
},
native: {}
});
await this.setObjectNotExistsAsync('weather.wind_direction', {
type: 'state',
common: {
name: {
en: 'Wind direction',
de: 'Windrichtung',
ru: 'Направление ветра',
pt: 'Direção do vento',
nl: 'Windrichting',
fr: 'Direction du vent',
it: 'La direzione del vento',
es: 'Dirección del viento',
pl: 'Kierunek wiatru',
'zh-cn': '风向'
},
type: 'string',
role: 'value.direction.wind',
read: true,
write: false,
def: ''
},
native: {}
});
} else {
await this.delObjectAsync('weather', { recursive: true });
}