forked from anerdins/node-red-contrib-nibepi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config_node.js
executable file
·3102 lines (2974 loc) · 172 KB
/
config_node.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
module.exports = function (RED) {
const EventEmitter = require('events').EventEmitter;
require('events').EventEmitter.defaultMaxListeners = 800;
const https = require('https');
//const http = require('http');
const nibeData = new EventEmitter()
const nibe = require('nibepi')
var serialPort = "";
var tcp_host = "";
var tcp_port = "";
let text = require('./language-SE.json')
let translate = require('./translate.json')
var series = "";
var systems = {};
let adjust = [];
let hP;
let weatherOffset = {};
let indoorOffset = {};
let priceOffset = {};
let savedGraph = {};
let savedData = {};
const SunCalc = require('suncalc');
const suncalc = (data) => {
var times = SunCalc.getTimes(data.timestamp, data.lat, data.lon);
return times;
}
const toTimestamp = (strDate) => {
var datum = Date.parse(strDate);
return Number((datum).toFixed());
}
const initiateCore = (host, port, cb) => {
nibe.initiateCore(host, port, (err, data) => {
if (err) console.log(err);
nibe.core = data;
cb(null, true);
});
}
let timer = {};
function updateConfig(category, parameter, data) {
let config = nibe.getConfig();
if (config[category] !== undefined && config[category][parameter] !== undefined) {
if (config[category][parameter] !== data) {
config[category][parameter] = data;
// Config has changed
nibeData.emit(`config_${category}`, config[category]);
nibe.setConfig(config);
}
}
}
const curveAdjust = (type, system, data) => {
let curveadjust;
if (hP !== undefined) {
curveadjust = hP['curveadjust_' + system];
}
var newSystem = true;
for (var i = 0; i < adjust.length; i++) {
if (adjust[i].system === system) {
let newType = true;
let newData = false;
for (var o = 0; o < adjust[i].data.length; o++) {
if (adjust[i].data[o].name === type) {
adjust[i].data[o].data = data;
newType = false;
newData = true;
}
}
if (newType === true) {
adjust[i].data.push({ name: type, data: data });
}
if (newData === true) {
// Set new curveadjust
let out = 0;
let run = false;
if (timer[system] !== undefined && timer[system]._idleTimeout > 0) {
clearTimeout(timer[system]);
run = true;
} else {
run = true;
}
if (run === true) {
timer[system] = setTimeout((i) => {
for (var o = 0; o < adjust[i].data.length; o++) {
out = out + adjust[i].data[o].data;
}
out = out;
nibe.reqData(curveadjust).then(result => {
let config = nibe.getConfig();
if (config.home === undefined) {
config.home = {};
nibe.setConfig(config);
}
if (config.home['adjust_' + system] !== undefined) {
out = out + Number(config.home['adjust_' + system]);
}
if (out > 10) out = 10;
if (out < -10) out = -10;
if (out > (result.data + 0.75)) {
out = Math.round(out);
if (result.data !== (out)) {
nibe.setData(curveadjust, out, (err, result) => {
if (err) return console.log(err);
let save = {
titel: "Curveadjustment",
register: 'curveadjust',
info: "NibePis total adjustment of the curve",
raw_data: out,
data: out,
unit: "°C",
icon_name: "fa-thermometer-three-quarters"
}
savedData['curveadjust'] = save;
saveDataGraph('curveadjust', Date.now(), save.raw_data)
});
}
} else if (out < (result.data - 0.75)) {
out = Math.round(out);
if (result.data !== (out)) {
nibe.setData(curveadjust, out, (err, result) => {
if (err) return console.log(err);
let save = {
titel: "Curveadjustment",
register: 'curveadjust',
info: "NibePis total adjustment of the curve",
raw_data: out,
data: out,
unit: "°C",
icon_name: "fa-thermometer-three-quarters"
}
savedData['curveadjust'] = save;
saveDataGraph('curveadjust', Date.now(), save.raw_data)
});
}
}
}).catch(console.log)
}, 5000, i);
}
}
newSystem = false;
}
}
if (newSystem === true) {
adjust.push({ system: system, data: [{ name: type, data: data }] })
curveAdjust(type, system, data);
}
}
const getList = [];
function clearList(plugin, system) {
const promise = new Promise((resolve, reject) => {
for (var i = 0; i < getList.length; i++) {
if (getList[i].system === system) {
for (var j = 0; j < getList[i].registers.length; j++) {
if (getList[i].registers[j].plugin !== undefined) {
let len = getList[i].registers[j].plugin.length;
for (var k = 0; k < len; k++) {
if (getList[i].registers[j].plugin[k] === plugin) {
getList[i].registers[j].plugin.splice(k, 1);
if (getList[i].registers[j].plugin.length === 0) {
getList[i].registers.splice(j, 1);
}
}
}
}
}
}
}
resolve(true);
});
return promise;
}
async function initiatePlugin(arrData, plugin, system = "s1") {
let arr = arrData.slice();
const promise = new Promise((resolve, reject) => {
clearList(plugin, system).then(result => {
var newSystem = true;
for (var i = 0; i < arr.length; i++) {
if (arr[i].register === undefined) {
arr[i].register = hP[arr[i].topic];
}
for (var o = 0; o < getList.length; o++) {
if (getList[o].system === system) {
// System exists, moving on.
newSystem = false;
// Looking for the register from the incoming array.
let regI = getList[o].registers.findIndex(regI => regI.register == arr[i].register);
if (regI === -1) {
// Register dont exist, adding new register.
let newArr = arr[i];
// Adding the plugin name to the first array
newArr.plugin = [plugin];
getList[o].registers.push(newArr);
} else {
// The register already exists, checking if the plugin is already added and gets the index.
let regP = getList[o].registers[regI].plugin.findIndex(regP => regP == plugin);
if (getList[o].registers[regI].name === undefined) getList[o].registers[regI].name = arr[i].name;
if (getList[o].registers[regI].topic === undefined) getList[o].registers[regI].topic = arr[i].topic;
if (regP === -1) {
getList[o].registers[regI].plugin.push(plugin);
} else {
}
}
}
}
}
let checkReg = hP['supply_' + system];
function checkRMU() {
if (plugin == "rmu") {
nibe.reqData(hP['startHW_rmu_' + system]).then(data => {
if (data !== undefined) {
let regN = getList.findIndex(regN => regN.system == 's1');
if (regN !== -1) {
for (var i = 0; i < arr.length; i = i + 1) {
let regI = getList[regN].registers.findIndex(regI => regI.register == arr[i].register);
if (regI === -1) {
let newArr = arr[i];
newArr.plugin = [plugin];
getList[regN].registers.push(newArr);
} else {
if (getList[regN].registers[regI].topic === undefined) getList[regN].registers[regI].topic = arr[i].topic;
if (getList[regN].registers[regI].name === undefined) getList[regN].registers[regI].name = arr[i].name;
let regP = getList[regN].registers[regI].plugin.findIndex(regP => regP == plugin);
if (regP === -1) {
getList[regN].registers[regI].plugin.push(plugin);
} else {
}
}
}
}
resolve(true)
} else {
return reject(false);
}
}).catch((err) => {
return reject(false)
})
} else {
//sendError('System',`System S${system.replace('s','')} ${text.sys_not_connected}`);
//return reject(false);
}
}
if (newSystem === true) {
let regN = getList.findIndex(regN => regN.system == system);
if (regN === -1) {
checkRMU();
nibe.reqData(checkReg).then(data => {
if (data.data < -3276) {
checkRMU();
return reject(false);
} else {
systems[system] = true;
if (plugin == "fan") {
nibe.reqData(hP.bs1_flow).then(data => {
if (data.data < -3276) {
return reject(false);
} else {
let regN = getList.findIndex(regN => regN.system == system);
if (regN === -1) {
getList.push({ system: system, registers: [] });
for (var i = 0; i < arr.length; i = i + 1) {
let regI = getList.findIndex(regI => regI.system == system);
let newArr = arr[i];
newArr.plugin = [plugin];
getList[regI].registers.push(newArr);
}
} else {
for (var i = 0; i < arr.length; i = i + 1) {
let regI = getList[regN].registers.findIndex(regI => regI.register == arr[i].register);
if (regI === -1) {
let newArr = arr[i];
newArr.plugin = [plugin];
getList[regN].registers.push(newArr);
} else {
if (getList[regN].registers[regI].topic === undefined) getList[regN].registers[regI].topic = arr[i].topic;
if (getList[regN].registers[regI].name === undefined) getList[regN].registers[regI].name = arr[i].name;
let regP = getList[regN].registers[regI].plugin.findIndex(regP => regP == plugin);
if (regP === -1) {
getList[regN].registers[regI].plugin.push(plugin);
} else {
}
}
}
}
resolve(true)
}
}, (error => {
return reject(false);
}));
} else {
let regN = getList.findIndex(regN => regN.system == system);
if (regN === -1) {
getList.push({ system: system, registers: [] });
for (var i = 0; i < arr.length; i = i + 1) {
let regI = getList.findIndex(regI => regI.system == system);
let newArr = arr[i];
newArr.plugin = [plugin];
getList[regI].registers.push(newArr);
}
} else {
for (var i = 0; i < arr.length; i = i + 1) {
let regI = getList[regN].registers.findIndex(regI => regI.register == arr[i].register);
if (regI === -1) {
let newArr = arr[i];
newArr.plugin = [plugin];
getList[regN].registers.push(newArr);
} else {
if (getList[regN].registers[regI].topic === undefined) getList[regN].registers[regI].topic = arr[i].topic;
if (getList[regN].registers[regI].name === undefined) getList[regN].registers[regI].name = arr[i].name;
let regP = getList[regN].registers[regI].plugin.findIndex(regP => regP == plugin);
if (regP === -1) {
getList[regN].registers[regI].plugin.push(plugin);
} else {
}
}
}
}
resolve(true)
}
}
}).catch((err) => {
checkRMU();
return reject(false);
});
} else {
checkRMU();
nibe.reqData(checkReg).then(data => {
if (data.data < -3276) {
checkRMU();
return reject(false);
} else {
systems[system] = true;
if (plugin == "fan") {
nibe.reqData(hP.bs1_flow).then(data => {
if (data.data < -3276) {
return reject(false);
} else {
resolve(true)
}
}).catch((err) => {
return reject(false);
});
} else {
resolve(true)
}
}
}).catch((err) => {
checkRMU();
return reject(false);
});
}
} else {
checkRMU();
nibe.reqData(checkReg).then(data => {
if (data.data < -3276) {
checkRMU();
return reject(false);
} else {
systems[system] = true;
if (plugin == "fan") {
nibe.reqData(hP.bs1_flow).then(data => {
if (data.data < -3276) {
return reject(false);
} else {
}
}, (error => {
return reject(false);
}));
} else {
resolve(true)
}
}
}).catch((err) => {
checkRMU();
return reject(false);
});
}
})
});
return promise;
}
async function updateData(hourly = false) {
let timeNow = Date.now();
/*
Check emitters
let events = nibeData.eventNames()
console.log(JSON.stringify(events,null,2));
for (const item of events) {
let count = nibeData.listenerCount(item)
console.log(`Eventname: ${item}, Count: ${count}`);
}*/
for (const item of getList) {
const array = [];
let result = { timestamp: timeNow };
result.system = item.system;
if (weatherOffset[item.system] === undefined) weatherOffset[item.system] = 0;
if (indoorOffset[item.system] === undefined) indoorOffset[item.system] = 0;
if (priceOffset[item.system] === undefined) priceOffset[item.system] = 0;
result.indoorOffset = indoorOffset[item.system];
result.weatherOffset = weatherOffset[item.system];
result.priceOffset = priceOffset[item.system];
for (var i = 0; i < item.registers.length; i++) {
if (item.registers[i].source !== undefined) {
if (item.registers[i].source == "mqtt") {
await nibe.getMQTTData(item.registers[i].register).then(atad => {
let data = Object.assign({}, atad);
let config = nibe.getConfig();
let sensor_timeout;
if (config.home === undefined) {
config.home = {};
nibe.setConfig(config);
}
if (config.home.sensor_timeout !== undefined && config.home.sensor_timeout !== "" && config.home.sensor_timeout !== 0) {
sensor_timeout = data.timestamp + (config.home.sensor_timeout * 60000);
} else if (config.home.sensor_timeout === 0 || config.home.sensor_timeout === undefined || config.home.sensor_timeout === "") {
sensor_timeout = timeNow;
} else {
sensor_timeout = data.timestamp + (60 * 60000);
}
if (timeNow > sensor_timeout) {
sendError(text.extra_sensor, `${text.extra_sensor} ${item.registers[i].name} ${text.not_updated}`)
} else {
data.system = item.system;
data.timestamp = timeNow;
data.name = item.registers[i].name;
data.topic = item.registers[i].register;
result[item.registers[i].register] = data;
array.push(data)
}
}, (error => {
sendError(text.extra_sensor, `${text.extra_sensor} ${item.registers[i].name} ${text.no_values}`)
}));
} else if (item.registers[i].source == "tibber") {
console.log('Tibber Data request');
} else if (item.registers[i].source == "nibe") {
await getNibeData(item.registers[i].register).then(atad => {
let data = Object.assign({}, atad);
data.system = item.system;
data.name = item.registers[i].name;
data.topic = item.registers[i].topic;
result[item.registers[i].topic] = data;
array.push(data)
}).catch(console.log)
}
}
}
runIndoor(result, array);
runPrice(result, array);
runRMU(result, array);
if (hourly === true) {
result.array = array;
runWeather(result);
} else {
result.array = array;
if (nibe.getConfig().weather['enable_' + item.system] === true) {
nibeData.emit('pluginWeather', result);
}
}
nibeData.emit('updateGraph');
}
}
const checkWind = (array, hours) => {
var output = {};
let config = nibe.getConfig();
if (config.weather === undefined) {
config.weather = {};
nibe.setConfig(config);
}
if (config.weather.wind_enable !== undefined && config.weather.wind_enable === true) {
var wind_speed_arr = [];
var wind_gust_arr = [];
var temp_arr = [];
var feel_arr = [];
var direction_arr = [];
for (var o = 0; o < 49; o++) {
let timestamp = toTimestamp(array[o].validTime)
let speed = array[o].parameters.find(speed => speed.name == "ws");
let dir = array[o].parameters.find(dir => dir.name == "wd");
let gust = array[o].parameters.find(gust => gust.name == "gust");
let temp = array[o].parameters.find(temp => temp.name == "t");
speed = speed.values[0];
gust = gust.values[0];
temp = temp.values[0];
dir = dir.values[0];
let direction = 0;
let factor = 1;
if (((1 <= dir) && (dir <= 45)) || ((315 <= dir) && (dir <= 360))) {
direction = -1;
if (config.weather.wind_factor_n === undefined) config.weather.wind_factor_n = 0; nibe.setConfig(config);
factor = config.weather.wind_factor_n;
} else if (136 <= dir && dir <= 225) {
direction = -2;
if (config.weather.wind_factor_s === undefined) { config.weather.wind_factor_s = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_s;
} else if (226 <= dir && dir <= 314) {
direction = -3;
if (config.weather.wind_factor_w === undefined) { config.weather.wind_factor_w = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_w;
} else if (46 <= dir && dir <= 135) {
direction = -4;
if (config.weather.wind_factor_e === undefined) { config.weather.wind_factor_e = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_e;
}
let v = Math.pow(speed, 0.16);
feel = Number((13.12 + (0.6215 * temp) - (13.956 * v) + (0.48669 * temp * v)).toFixed(2));
if (feel > 0) {
feel = Number((feel / factor).toFixed(2));
if (feel > temp) {
feel = temp;
}
} else {
feel = Number((feel * factor).toFixed(2));
if (feel > temp) {
feel = temp;
}
}
if (speed < 2 || temp > 10 || speed > 35 || direction === 0) feel = temp;
wind_speed_arr.push({ x: timestamp, y: Number(speed) });
wind_gust_arr.push({ x: timestamp, y: Number(gust) });
temp_arr.push({ x: timestamp, y: Number(temp) });
feel_arr.push({ x: timestamp, y: feel });
direction_arr.push({ x: timestamp, y: direction });
if (o === hours) {
output.feel = feel;
}
}
wind_speed_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
wind_gust_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
temp_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
feel_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
direction_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
output.graph = [
{
"series": ["Vindhastighet", "Byvind", "Utomhustemp", "Köldeffekt", "Riktning"],
"data": [wind_speed_arr, wind_gust_arr, temp_arr, feel_arr, direction_arr],
"labels": ["Vindhastighet", "Byvind", "Utomhustemp", "Köldeffekt", "Riktning"]
}];
} else {
output.feel = undefined;
output.graph = [];
}
nibe.log(`Done with checkWind, result: ${JSON.stringify(output)}`, 'weather', 'debug');
return output;
}
const checkWindOWM = (array, hours) => {
var output = {};
let config = nibe.getConfig();
nibe.log(`Executing checkWindOWM with data: ${JSON.stringify(array)} and hours: ${hours}, total length: ${array.length}`, 'weather', 'debug');
if (config.weather === undefined) {
config.weather = {};
nibe.setConfig(config);
}
if (config.weather.wind_enable !== undefined && config.weather.wind_enable === true) {
var wind_speed_arr = [];
var wind_gust_arr = [];
var temp_arr = [];
var feel_arr = [];
var direction_arr = [];
for (var o = 0; o < array.length; o++) {
let timestamp = Number((array[o].dt).toFixed()*1000);
let speed = array[o].wind_speed;
let dir = array[o].wind_deg;
let gust = array[o].wind_gust;
let temp = array[o].temp;
//nibe.log(`[${o}] Time: ${timestamp}, Temperature: ${temp}, Windspeed: ${speed} , Winddirection: ${dir}, Gusts: ${gust}`, 'weather', 'debug');
let direction = 0;
let factor = 1;
if (((1 <= dir) && (dir <= 45)) || ((315 <= dir) && (dir <= 360))) {
direction = -1;
if (config.weather.wind_factor_n === undefined) config.weather.wind_factor_n = 0; nibe.setConfig(config);
factor = config.weather.wind_factor_n;
} else if (136 <= dir && dir <= 225) {
direction = -2;
if (config.weather.wind_factor_s === undefined) { config.weather.wind_factor_s = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_s;
} else if (226 <= dir && dir <= 314) {
direction = -3;
if (config.weather.wind_factor_w === undefined) { config.weather.wind_factor_w = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_w;
} else if (46 <= dir && dir <= 135) {
direction = -4;
if (config.weather.wind_factor_e === undefined) { config.weather.wind_factor_e = 0; nibe.setConfig(config); }
factor = config.weather.wind_factor_e;
}
feel = array[o].feels_like;
wind_speed_arr.push({ x: timestamp, y: Number(speed) });
wind_gust_arr.push({ x: timestamp, y: Number(gust) });
temp_arr.push({ x: timestamp, y: Number(temp) });
feel_arr.push({ x: timestamp, y: feel });
direction_arr.push({ x: timestamp, y: direction });
if (o === hours) {
output.feel = feel;
}
}
wind_speed_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
wind_gust_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
temp_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
feel_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
direction_arr.sort((a, b) => (a.x > b.x) ? 1 : -1)
output.graph = [
{
"series": ["Wind Speed", "Gusts", "Outside temperature", "Chill factor", "Direction"],
"data": [wind_speed_arr, wind_gust_arr, temp_arr, feel_arr, direction_arr],
"labels": ["Wind Speed", "Gusts", "temperature", "Chill factor", "direction"]
}];
} else {
output.feel = undefined;
output.graph = [];
}
nibe.log(`Done with checkWindOWM, result: ${JSON.stringify(output)}`, 'weather', 'debug');
return output;
}
const runWeather = async (val) => {
nibe.log(`Startar Prognosreglering`, 'weather', 'debug');
let timeNow = Date.now();
//var val = Object.assign({}, result);
let config = nibe.getConfig();
if (config.weather === undefined) {
config.weather = {};
nibe.setConfig(config);
}
if (config.weather !== undefined && config.weather['enable_' + val.system] === true) {
if (config.weather.enable_up === undefined) {
config.weather.enable_up = true
nibe.setConfig(config);
}
if (config.weather.enable_down === undefined) {
config.weather.enable_down = true
nibe.setConfig(config);
}
let outside = val.outside.data;
nibe.log(`Current outside temperature: ${outside}`, 'weather', 'debug');
if (val['heatcurve_' + val.system] === undefined) {
console.log('Hämtar värmekurva manuellt.')
val['heatcurve_' + val.system] = await getNibeData(hP['heatcurve_' + val.system]).catch(console.log)
}
let heatcurve = val['heatcurve_' + val.system].data;
nibe.log(`Current heat curve: ${heatcurve}`, 'weather', 'debug');
let setOffset = val.weatherOffset;
let lon = config.home.lon;
let lat = config.home.lat;
let weatherkey = config.home.weatherkey;
nibe.log(`Koordinater: (Latitud: ${config.home.lat}, Longitud: ${config.home.lon}), WeatherKey: ${weatherkey}`, 'weather', 'debug');
//weatherkey = "";
if (lon !== undefined && lat !== undefined && lon != "" && lat != "") {
//weatherkey = "";
if (weatherkey !== undefined && weatherkey !== "") {
let requestAddress = `https://api.openweathermap.org/data/3.0/onecall?lat=${lat}&lon=${lon}&exclude=minutely,daily,alerts&appid=${weatherkey}&units=metric`;
nibe.log(`Running OWM Service, trying URL: ${requestAddress}`, 'weather', 'info');
https.get(requestAddress, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
if (resp.statusCode === 200) {
nibe.log(`Successfully retreived URL ${requestAddress}`, 'weather', 'debug');
let hours = config.home['hours_' + val.system];
let time = Number((Date.now()).toFixed()) + (hours * 3600000);
const astro = suncalc({ lat: lat, lon: lon, timestamp: time })
var sunrise = toTimestamp(astro.sunrise) / 1000;
var sunset = toTimestamp(astro.sunset) / 1000;
var sunTime = Number((Date.now() / 1000).toFixed()) + (hours * 3600);
let sun;
if (sunTime > sunrise && sunTime < sunset) {
nibe.log(`Prognosis received for the day`, 'weather', 'debug');
sun = true;
} else {
nibe.log(`Prognosis received for night`, 'weather', 'debug');
sun = false;
}
nibe.log(`Data: ${data}`, 'weather', 'debug');
data = JSON.parse(data);
nibe.log(`Calling checkWindOWM with hours: ${hours}`, 'weather', 'debug');
let wind = checkWindOWM(data.hourly, hours);
let windSet = wind.feel;
var tempNow = data.current.temp;
var weatherPredicted = data.hourly[hours].weather.id;
var tempPredicted = data.hourly[hours].temp;
weatherPredicted = data.hourly[hours].weather.id;
var sunFactor = 0;
if (config.weather.sun_enable !== undefined && config.weather.sun_enable === true) {
nibe.log(`Sunfactor activated`, 'weather', 'debug');
if (weatherPredicted === 800 && sun === true) { // clear sky
if (config.weather.clear === undefined) { config.weather.clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.clear;
} else if (weatherPredicted === 801 && sun === true) { // few clouds (11-25%)
if (config.weather.mostly_clear === undefined) { config.weather.mostly_clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.mostly_clear;
} else if (weatherPredicted === 802 && sun === true) { // scattered clouds (25-50%)
if (config.weather.half_clear === undefined) { config.weather.half_clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.half_clear;
}
nibe.log(`Current sun factor is: ${sunFactor}`, 'weather', 'info');
}
if (outside === undefined || heatcurve === undefined) {
if (outside === undefined) nibe.log(`Missing value from outside temperature sensor`, 'weather', 'error');
if (heatcurve === undefined) nibe.log(`Missing value for heatcurve`, 'weather', 'error');
return;
}
if (heatcurve === 0) {
nibe.log(`Forecast adaption does not work with own custom heatcurve`, 'weather', 'error');
return;
}
if (config.weather.forecast_adjust === undefined) {
config.weather.forecast_adjust = false;
nibe.setConfig(config);
}
if (config.weather.forecast_adjust === true) {
val.unfiltredTemp = { payload: tempPredicted, timestamp: Number((data.hourly[hours].dt).toFixed()*1000) };
saveDataGraph('weather_unfilterd_' + val.system, Number((data.hourly[hours].dt).toFixed()*1000), tempPredicted, true)
tempPredicted = Number(((outside - (tempNow)) + tempPredicted).toFixed(2));
if (windSet !== undefined) windSet = Number(((outside - tempNow) + windSet).toFixed(2));
}
if (config.weather.wind_enable !== undefined && config.weather.wind_enable === true) {
nibe.log(`Wind adaption activated, chill factor: ${windSet} degrees`, 'weather', 'debug');
setOffset = Number(((outside - windSet - sunFactor) * (heatcurve * 1.2 / 10) / ((heatcurve / 10) + 1)).toFixed(2));
} else {
setOffset = Number(((outside - tempPredicted - sunFactor) * (heatcurve * 1.2 / 10) / ((heatcurve / 10) + 1)).toFixed(2));
}
// Lock adaption
nibe.log(`Check if curve adaption is allowed`, 'weather', 'debug');
if (setOffset > 0) {
if (config.weather.enable_up === false) {
nibe.log(`Increase is not allowed.`, 'weather', 'debug');
setOffset = 0
}
} else {
if (config.weather.enable_down === false) {
nibe.log(`Decrease is now allowed.`, 'weather', 'debug');
setOffset = 0
}
}
nibe.log(`Adjusting curve with value ${setOffset}`, 'weather', 'debug');
curveAdjust('weather', val.system, setOffset);
val.windGraph = wind.graph;
val.weatherOffset = setOffset;
weatherOffset[val.system] = setOffset;
val.predictedNow = { payload: tempNow, timestamp: Number((data.hourly[hours].dt).toFixed()*1000) };
val.predictedLater = { payload: tempPredicted, timestamp: Number((data.hourly[hours].dt).toFixed()*1000) };
saveDataGraph('weather_forecast_' + val.system, Number((data.hourly[hours].dt).toFixed()*1000), tempPredicted, true);
nibe.log(`Saving value for forecast (${tempPredicted} degrees)`, 'weather', 'debug');
saveDataGraph('weather_offset_' + val.system, timeNow, val.weatherOffset, true);
nibe.log(`Saving value for curve adjustment. (${val.weatherOffset})`, 'weather', 'debug');
let inside;
if (config.weather['sensor_' + val.system] !== undefined && config.weather['sensor_' + val.system] !== "") {
let index = val.array.findIndex(i => i.name == config.weather['sensor_' + val.system]);
if (index !== -1) {
inside = val.array[index];
}
}
if (inside === undefined) inside = val['inside_' + val.system];
if (inside === undefined || inside.data < -3276) {
nibe.log(`No inside temperature sensor selected or invalid value`, 'weather', 'debug');
//server.sendError('Prognosreglering',`Inomhusgivare saknas (${data.system}).`);
}
val.weatherSensor = inside;
if (inside === undefined) inside = val['inside_' + val.system];
if (inside !== undefined && inside.data > -3276) {
nibe.log(`Saving value for selected indoor temperature sensor (${inside.data} grader)`, 'weather', 'debug');
saveDataGraph('weather_sensor_' + val.system, timeNow, inside.data, true);
}
nibeData.emit('pluginWeather', val);
} else { // ResponseCode is not 200
nibe.log(`There was an issue with receiving the weather data. Response code: ${resp.statusCode}`, 'weather', 'error');
if (weatherOffset[val.system] !== 0) {
nibe.log(`Setting curve adjustment to 0`, 'weather', 'debug');
curveAdjust('weather', val.system, 0);
weatherOffset[val.system] = 0;
}
saveDataGraph('weather_offset_' + val.system, timeNow, 0, true);
}
});
}).on("error", (err) => {
nibe.log(err.message, 'weather', 'error');
});
}
else {
https.get(`https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/${lon}/lat/${lat}/data.json`, (resp) => {
let data = '';
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
if (resp.statusCode === 200) {
let hours = config.home['hours_' + val.system];
let time = Number((Date.now()).toFixed()) + (hours * 3600000);
const astro = suncalc({ lat: lat, lon: lon, timestamp: time })
var sunrise = toTimestamp(astro.sunrise) / 1000;
var sunset = toTimestamp(astro.sunset) / 1000;
var sunTime = Number((Date.now() / 1000).toFixed()) + (hours * 3600);
let sun;
if (sunTime > sunrise && sunTime < sunset) {
nibe.log(`När prognosen infaller är det dag.`, 'weather', 'debug');
sun = true;
} else {
nibe.log(`När prognosen infaller är det inte dag.`, 'weather', 'debug');
sun = false;
}
data = JSON.parse(data);
let wind = checkWind(data.timeSeries, hours);
let windSet = wind.feel;
var tempPredicted = data.timeSeries[hours].parameters.find(tempPredicted => tempPredicted.name == "t");
var tempNow = data.timeSeries[0].parameters.find(tempNow => tempNow.name == "t");
var weatherPredicted = data.timeSeries[hours].parameters.find(weatherPredicted => weatherPredicted.name == "Wsymb2");
tempPredicted = tempPredicted.values[0];
weatherPredicted = Number(weatherPredicted.values[0]);
var sunFactor = 0;
if (config.weather.sun_enable !== undefined && config.weather.sun_enable === true) {
nibe.log(`Solfaktor aktiverad`, 'weather', 'debug');
if (weatherPredicted === 1 && sun === true) {
if (config.weather.clear === undefined) { config.weather.clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.clear;
} else if (weatherPredicted === 2 && sun === true) {
if (config.weather.mostly_clear === undefined) { config.weather.mostly_clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.mostly_clear;
} else if (weatherPredicted === 3 && sun === true) {
if (config.weather.half_clear === undefined) { config.weather.half_clear = 0; nibe.setConfig(config); }
sunFactor = config.weather.half_clear;
}
nibe.log(`Aktuell solfaktor är: ${sunFactor}`, 'weather', 'debug');
}
if (outside === undefined || heatcurve === undefined) {
if (outside === undefined) nibe.log(`Saknar värde från utomhusgivare`, 'weather', 'error');
if (heatcurve === undefined) nibe.log(`Saknar värde från värmekurva`, 'weather', 'error');
return;
}
if (heatcurve === 0) {
nibe.log(`Prognosreglering fungerar inte med egen värmekurva.`, 'weather', 'error');
return;
}
if (config.weather.forecast_adjust === undefined) {
config.weather.forecast_adjust = false;
nibe.setConfig(config);
}
if (config.weather.forecast_adjust === true) {
val.unfiltredTemp = { payload: tempPredicted, timestamp: toTimestamp(data.timeSeries[hours].validTime) };
saveDataGraph('weather_unfilterd_' + val.system, toTimestamp(data.timeSeries[hours].validTime), tempPredicted, true)
tempPredicted = Number(((outside - (tempNow.values[0])) + tempPredicted).toFixed(2));
if (windSet !== undefined) windSet = Number(((outside - tempNow.values[0]) + windSet).toFixed(2));
}
if (config.weather.wind_enable !== undefined && config.weather.wind_enable === true) {
nibe.log(`Vindstyrning aktiverad. Köldeffekt: ${windSet} grader`, 'weather', 'debug');
setOffset = Number(((outside - windSet - sunFactor) * (heatcurve * 1.2 / 10) / ((heatcurve / 10) + 1)).toFixed(2));
} else {
setOffset = Number(((outside - tempPredicted - sunFactor) * (heatcurve * 1.2 / 10) / ((heatcurve / 10) + 1)).toFixed(2));
}
// Lägg in blockering om höjning eller sänkning
nibe.log(`Kollar om det är tillåtet att sänkas eller höjas.`, 'weather', 'debug');
if (setOffset > 0) {
if (config.weather.enable_up === false) {
nibe.log(`Ej tillåtet att höja.`, 'weather', 'debug');
setOffset = 0
}
} else {
if (config.weather.enable_down === false) {
nibe.log(`Ej tillåtet att sänka.`, 'weather', 'debug');
setOffset = 0
}
}
nibe.log(`Utför kurvjustering, värde: ${setOffset}`, 'weather', 'debug');
curveAdjust('weather', val.system, setOffset);
val.windGraph = wind.graph;
val.weatherOffset = setOffset;
weatherOffset[val.system] = setOffset;
val.predictedNow = { payload: tempNow.values[0], timestamp: toTimestamp(data.timeSeries[0].validTime) };
val.predictedLater = { payload: tempPredicted, timestamp: toTimestamp(data.timeSeries[hours].validTime) };
saveDataGraph('weather_forecast_' + val.system, toTimestamp(data.timeSeries[hours].validTime), tempPredicted, true);
nibe.log(`Sparar värde för prognos. (${tempPredicted} grader)`, 'weather', 'debug');
saveDataGraph('weather_offset_' + val.system, timeNow, val.weatherOffset, true);
nibe.log(`Sparar värde för kurvjustering. (${val.weatherOffset})`, 'weather', 'debug');
let inside;
if (config.weather['sensor_' + val.system] !== undefined && config.weather['sensor_' + val.system] !== "") {
let index = val.array.findIndex(i => i.name == config.weather['sensor_' + val.system]);
if (index !== -1) {
inside = val.array[index];
}
}
if (inside === undefined) inside = val['inside_' + val.system];
if (inside === undefined || inside.data < -3276) {
nibe.log(`Ingen inomhusgivare vald eller felaktigt värde.`, 'weather', 'debug');
//server.sendError('Prognosreglering',`Inomhusgivare saknas (${data.system}).`);
}
val.weatherSensor = inside;
if (inside === undefined) inside = val['inside_' + val.system];
if (inside !== undefined && inside.data > -3276) {
nibe.log(`Sparar värde för vald inomhusgivare (${inside.data} grader)`, 'weather', 'debug');
saveDataGraph('weather_sensor_' + val.system, timeNow, inside.data, true);
}
nibeData.emit('pluginWeather', val);
} else {
nibe.log(`Väderleverantör svarar inte, problem med uppkopplingen eller felaktigt angivna koordinater`, 'weather', 'error');
if (weatherOffset[val.system] !== 0) {
nibe.log(`Sätter kurvjustering till 0`, 'weather', 'debug');
curveAdjust('weather', val.system, 0);
weatherOffset[val.system] = 0;
}
saveDataGraph('weather_offset_' + val.system, timeNow, 0, true);
}
});
}).on("error", (err) => {
nibe.log(err.message, 'weather', 'error');
});
}
} else {
nibe.log(`Inga koordinater inlagda.`, 'weather', 'error');
if (weatherOffset[val.system] !== 0) {
nibe.log(`Sätter kurvjustering till 0`, 'weather', 'debug');
curveAdjust('weather', val.system, 0);
weatherOffset[val.system] = 0;
}
saveDataGraph('weather_offset_' + val.system, timeNow, 0, true);
}
} else {
nibe.log(`Prognosreglering inte aktiverat`, 'weather', 'debug');
if (weatherOffset[val.system] !== 0) {
nibe.log(`Sätter kurvjustering till 0`, 'weather', 'debug');
curveAdjust('weather', val.system, 0);
weatherOffset[val.system] = 0;
}
saveDataGraph('weather_offset_' + val.system, timeNow, 0, true);
}
}
const indoorArray = [];
const runIndoor = (data, array) => {
var timeNow = Date.now();
//let data = Object.assign({}, result);
let conf = nibe.getConfig();
let inside_enable = data['inside_enable_' + data.system];
let inside;
if (conf.indoor === undefined) {
conf.indoor = {};
nibe.setConfig(conf);
}
if ((inside_enable !== undefined && inside_enable.data !== undefined && inside_enable.data === 1) || (conf.indoor['enable_' + data.system] !== undefined && conf.indoor['enable_' + data.system] === true)) {
if (conf.indoor['enable_' + data.system] !== undefined && conf.indoor['enable_' + data.system] === true) {
if (conf.indoor['sensor_' + data.system] !== undefined && conf.indoor['sensor_' + data.system] !== "") {
let index = array.findIndex(i => i.name == conf.indoor['sensor_' + data.system]);
if (index !== -1) {
inside = array[index];
}
}
}
if (inside === undefined) inside = data['inside_' + data.system];
if (inside === undefined || inside.data === undefined || inside.data < 4) {
sendError('Inomhusreglering', `Inomhusgivare saknas (${data.system}), avbryter...`);
return;
}
data.indoorSensor = inside;
saveDataGraph('indoor_sensor_' + data.system, timeNow, inside.data, true)
let inside_set = data['inside_set_' + data.system];
let factor = data['inside_factor_' + data.system];
let dM = data.dM;
let dMstart = data.dMstart;
// Calculate setpoint accuracy
if (inside !== undefined) {
indoorArray.unshift({ set: inside_set.data, act: inside.data });
if (indoorArray.length >= 2016) indoorArray.pop();
let sum = 0;
for (const arr of indoorArray) {
sum = sum + (arr.act / arr.set)
}
let result = sum / (indoorArray.length);
data.accuracy = result;
}
// Restore degree minutes if the inside conditions are good.
if (conf.system.pump !== "F370" && conf.system.pump !== "F470") {
if (conf.indoor.dm_reset_enable === true) {
if (conf.indoor.dm_reset_value === undefined) {
conf.indoor.dm_reset_value = -200;