-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfronius-modbus.c
1770 lines (1469 loc) · 50.6 KB
/
fronius-modbus.c
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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ansi-color-codes.h>
#include "fronius-config.h"
#include "fronius.h"
#include "tasmota.h"
#include "sunspec.h"
#include "mosmix.h"
#include "utils.h"
#include "mcp.h"
#define MIN_SOC (f10 ? SFI(f10->storage->MinRsvPct, f10->storage->MinRsvPct_SF) * 10 : 0)
#define AKKU_CAPACITY (f10 ? SFI(f10->nameplate->WHRtg, f10->nameplate->WHRtg_SF) : 0)
#define AKKU_CAPACITY_SOC(soc) (AKKU_CAPACITY * (soc) / 1000)
#define EMERGENCY (AKKU_CAPACITY / 10)
#define WAIT_NEXT_RAMP 1
#define WAIT_RESPONSE 3 // TODO reicht manchmal nicht?
#define WAIT_NEXT 1
#define WAIT_AKKU_CHARGE 30
#define WAIT_AKKU_RAMP 10
#define MOSMIX3X24 "FRONIUS mosmix Rad1h/SunD1/RSunD today %d/%d/%d tomorrow %d/%d/%d tomorrow+1 %d/%d/%d"
#define GNUPLOT "/usr/bin/gnuplot -p /home/hje/workspace-cpp/dac/misc/mosmix.gp"
#define POWERFLOW_JSON "{\"common\":{\"datestamp\":\"01.01.2025\",\"timestamp\":\"00:00:00\"},\"inverters\":[{\"BatMode\":1,\"CID\":0,\"DT\":0,\"E_Total\":1,\"ID\":1,\"P\":1,\"SOC\":%f}],\"site\":{\"BackupMode\":false,\"BatteryStandby\":false,\"E_Day\":null,\"E_Total\":1,\"E_Year\":null,\"MLoc\":0,\"Mode\":\"bidirectional\",\"P_Akku\":%d,\"P_Grid\":%d,\"P_Load\":%d,\"P_PV\":%d,\"rel_Autonomy\":100.0,\"rel_SelfConsumption\":100.0},\"version\":\"13\"}"
#define POWERFLOW_FILE "/run/mcp/powerflow.json"
#define SAVE_RUN_DIRECORY "cp -r /run/mcp /tmp"
// program of the day - choosen by mosmix forecast data
static potd_t *potd = 0;
// counter history every hour over one day and access pointers
static counter_t counter_hours[24];
static volatile counter_t *counter = 0;
#define COUNTER_NOW (&counter_hours[now->tm_hour])
#define COUNTER_LAST (&counter_hours[now->tm_hour > 00 ? now->tm_hour - 1 : 23])
#define COUNTER_NEXT (&counter_hours[now->tm_hour < 23 ? now->tm_hour + 1 : 00])
#define COUNTER_0 (&counter_hours[0])
// 24h slots over one week and access pointers
static gstate_t gstate_hours[24 * 7];
static volatile gstate_t *gstate = 0;
#define GSTATE_NOW (&gstate_hours[24 * now->tm_wday + now->tm_hour])
#define GSTATE_LAST (&gstate_hours[24 * now->tm_wday + now->tm_hour - (!now->tm_wday && !now->tm_hour ? 24 * 7 - 1 : 1)])
#define GSTATE_NEXT (&gstate_hours[24 * now->tm_wday + now->tm_hour + (now->tm_wday == 6 && now->tm_hour == 23 ? -24 * 7 + 1 : 1)])
#define GSTATE_HOUR(h) (&gstate_hours[24 * now->tm_wday + (h)])
#define GSTATE_TODAY GSTATE_HOUR(0)
// pstate history every second/minute/hour and access pointers
static pstate_t pstate_seconds[60], pstate_minutes[60], pstate_hours[24];
static volatile pstate_t *pstate = 0;
#define PSTATE_NOW (&pstate_seconds[now->tm_sec])
#define PSTATE_SEC_LAST1 (&pstate_seconds[now->tm_sec > 0 ? now->tm_sec - 1 : 59])
#define PSTATE_SEC_LAST2 (&pstate_seconds[now->tm_sec > 1 ? now->tm_sec - 2 : (now->tm_sec - 2 + 60)])
#define PSTATE_SEC_LAST3 (&pstate_seconds[now->tm_sec > 2 ? now->tm_sec - 3 : (now->tm_sec - 3 + 60)])
#define PSTATE_MIN_NOW (&pstate_minutes[now->tm_min])
#define PSTATE_MIN_LAST1 (&pstate_minutes[now->tm_min > 0 ? now->tm_min - 1 : 59])
#define PSTATE_MIN_LAST2 (&pstate_minutes[now->tm_min > 1 ? now->tm_min - 2 : (now->tm_min - 2 + 60)])
#define PSTATE_MIN_LAST3 (&pstate_minutes[now->tm_min > 2 ? now->tm_min - 3 : (now->tm_min - 3 + 60))
#define PSTATE_HOUR_NOW (&pstate_hours[now->tm_hour])
#define PSTATE_HOUR(h) (&pstate_hours[h])
// SunSpec modbus devices
static sunspec_t *f10 = 0, *f7 = 0, *meter = 0;
static struct tm *lt, now_tm, *now = &now_tm;
static int sock = 0;
static void create_pstate_json() {
// pstate
store_struct_json((int*) pstate, PSTATE_SIZE, PSTATE_HEADER, PSTATE_JSON);
// feed Fronius powerflow web application
FILE *fp = fopen(POWERFLOW_FILE, "w");
fprintf(fp, POWERFLOW_JSON, FLOAT10(pstate->soc), pstate->akku, pstate->grid, pstate->load, pstate->pv);
fflush(fp);
fclose(fp);
}
static void create_gstate_dstate_json() {
// pstate
store_struct_json((int*) gstate, GSTATE_SIZE, GSTATE_HEADER, GSTATE_JSON);
// devices
FILE *fp = fopen(DSTATE_JSON, "w");
fprintf(fp, "[");
int i = 0;
for (device_t **dd = potd->devices; *dd; dd++) {
if (i)
fprintf(fp, ",");
fprintf(fp, "\{");
fprintf(fp, "\"name\":\"%s\",", DD->name);
fprintf(fp, "\"state\":%d,", DD->state);
fprintf(fp, "\"total\":%d,", DD->total);
fprintf(fp, "\"power\":%d,", DD->power);
fprintf(fp, "\"load\":%d", DD == &a1 ? pstate->akku : DD->load);
fprintf(fp, "}");
i++;
}
fprintf(fp, "]");
fflush(fp);
fclose(fp);
}
static void plot() {
// create gstate daily/weekly
store_csv((int*) GSTATE_TODAY, GSTATE_SIZE, 24, GSTATE_HEADER, GSTATE_TODAY_CSV);
store_csv((int*) gstate_hours, GSTATE_SIZE, 24 * 7, GSTATE_HEADER, GSTATE_WEEK_CSV);
// create mosmix history, today, tomorrow csv
mosmix_store_csv();
// plot diagrams
system(GNUPLOT);
}
static device_t* get_by_name(const char *name) {
for (device_t **dd = DEVICES; *dd; dd++)
if (!strcmp(DD->name, name))
return DD;
return 0;
}
// sample grid load from meter
static int grid() {
sunspec_t *ss = sunspec_init("fronius10", 200);
sunspec_read(ss);
ss->common = 0;
float grid;
while (1) {
sunspec_read(ss);
grid = SFF(ss->meter->W, ss->meter->W_SF);
printf("%.1f\n", grid);
msleep(666);
}
return 0;
}
// set charge(-) / discharge(+) limits or reset when 0
static int battery(char *arg) {
sunspec_t *ss = sunspec_init("fronius10", 1);
sunspec_read(ss);
int wh = atoi(arg);
if (wh > 0)
return sunspec_storage_limit_discharge(ss, wh);
if (wh < 0)
return sunspec_storage_limit_charge(ss, wh * -1);
return sunspec_storage_limit_reset(ss);
}
// set minimum SoC
static int minimum(char *arg) {
sunspec_t *ss = sunspec_init("fronius10", 1);
sunspec_read(ss);
int min = atoi(arg);
return sunspec_storage_minimum_soc(ss, min);
}
static int akku_standby(device_t *akku) {
if (akku->state == Standby)
return 0; // continue loop
xdebug("FRONIUS set akku STANDBY");
#ifndef FRONIUS_MAIN
sunspec_storage_limit_both(f10, 0, 0);
#endif
akku->state = Standby;
akku->timer = WAIT_RESPONSE;
akku->power = akku->load = akku->xload = 0; // disable response/standby/steal logic
return 0; // continue loop
}
static int akku_charge(device_t *akku) {
if (akku->state == Charge)
return 0; // continue loop
// enable charging
xdebug("FRONIUS set akku CHARGE");
#ifndef FRONIUS_MAIN
sunspec_storage_limit_discharge(f10, 0);
#endif
akku->state = Charge;
akku->timer = WAIT_AKKU_CHARGE;
akku->load = akku->xload = 0; // disable response/standby/steal logic
akku->power = 1;
return 1; // loop done
}
static int akku_discharge(device_t *akku) {
if (akku->state == Discharge)
return 0; // continue loop
#ifndef FRONIUS_MAIN
// enable discharge
int limit = WINTER && (gstate->survive < 0 || gstate->tomorrow < AKKU_CAPACITY);
if (limit) {
xdebug("FRONIUS set akku DISCHARGE limit BASELOAD");
sunspec_storage_limit_both(f10, 0, BASELOAD);
} else {
xdebug("FRONIUS set akku DISCHARGE");
sunspec_storage_limit_charge(f10, 0);
}
#endif
akku->state = Discharge;
akku->timer = WAIT_RESPONSE;
akku->power = akku->load = akku->xload = 0; // disable response/standby/steal logic
return 1; // loop done
}
static void update_f10(sunspec_t *ss) {
if (!pstate || !counter)
return;
pstate->ac10 = SFI(ss->inverter->W, ss->inverter->W_SF);
pstate->dc10 = SFI(ss->inverter->DCW, ss->inverter->DCW_SF);
pstate->soc = SFF(ss->storage->ChaState, ss->storage->ChaState_SF) * 10;
switch (ss->inverter->St) {
case I_STATUS_MPPT:
pstate->mppt1 = SFI(ss->mppt->DCW1, ss->mppt->DCW_SF);
if (pstate->mppt1 == 1)
pstate->mppt1 = 0; // noise
pstate->mppt2 = SFI(ss->mppt->DCW2, ss->mppt->DCW_SF);
if (pstate->mppt2 == 1)
pstate->mppt2 = 0; // noise
counter->mppt1 = SFUI(ss->mppt->DCWH1, ss->mppt->DCWH_SF);
counter->mppt2 = SFUI(ss->mppt->DCWH2, ss->mppt->DCWH_SF);
ss->sleep = 0;
ss->active = 1;
break;
case I_STATUS_SLEEPING:
// let the inverter sleep
ss->sleep = SLEEP_TIME_SLEEPING;
ss->active = 0;
break;
default:
xdebug("FRONIUS %s inverter St %d W %d DCW %d ", ss->name, ss->inverter->St, ss->inverter->W, ss->inverter->DCW);
ss->sleep = SLEEP_TIME_FAULT;
ss->active = 0;
}
}
static void update_f7(sunspec_t *ss) {
if (!pstate || !counter)
return;
switch (ss->inverter->St) {
case I_STATUS_MPPT:
// only take over values in MPPT state
pstate->ac7 = SFI(ss->inverter->W, ss->inverter->W_SF);
pstate->dc7 = SFI(ss->inverter->DCW, ss->inverter->DCW_SF);
pstate->mppt3 = SFI(ss->mppt->DCW1, ss->mppt->DCW_SF);
if (pstate->mppt3 == 1)
pstate->mppt3 = 0; // noise
pstate->mppt4 = SFI(ss->mppt->DCW2, ss->mppt->DCW_SF);
if (pstate->mppt4 == 1)
pstate->mppt4 = 0; // noise
counter->mppt3 = SFUI(ss->mppt->DCWH1, ss->mppt->DCWH_SF);
counter->mppt4 = SFUI(ss->mppt->DCWH2, ss->mppt->DCWH_SF);
ss->sleep = 0;
ss->active = 1;
break;
case I_STATUS_SLEEPING:
// let the inverter sleep
ss->sleep = SLEEP_TIME_SLEEPING;
ss->active = 0;
break;
default:
// xdebug("FRONIUS %s inverter St %d W %d DCW %d ", ss->name, ss->inverter->St, ss->inverter->W, ss->inverter->DCW);
ss->sleep = SLEEP_TIME_FAULT;
ss->active = 0;
}
}
static void update_meter(sunspec_t *ss) {
if (!pstate || !counter)
return;
counter->produced = SFUI(ss->meter->TotWhExp, ss->meter->TotWh_SF);
counter->consumed = SFUI(ss->meter->TotWhImp, ss->meter->TotWh_SF);
pstate->grid = SFI(ss->meter->W, ss->meter->W_SF);
}
static int collect_load(int from, int hours) {
int load = 0;
char line[LINEBUF], value[25];
strcpy(line, "FRONIUS mosmix load");
for (int i = 0; i < hours; i++) {
int hour = from + i;
if (hour >= 24)
hour -= 24;
int hload = PSTATE_HOUR(hour)->load * -1;
load += hload;
snprintf(value, 25, " %d:%d", hour, hload);
strcat(line, value);
}
xdebug(line);
// adding +10% Dissipation / Reserve
load += load / 10;
return load;
}
static int collect_heating_total() {
int total = 0;
for (device_t **dd = DEVICES; *dd; dd++)
if (!DD->adj)
total += DD->total;
return total;
}
static int check_override(device_t *d, int power) {
if (d->override) {
time_t t = time(NULL);
if (t > d->override) {
xdebug("FRONIUS Override expired for %s", d->name);
d->override = 0;
power = 0;
} else {
xdebug("FRONIUS Override active for %lu seconds on %s", d->override - t, d->name);
power = d->adj ? 100 : 1;
}
}
return power;
}
static void print_gstate() {
char line[512]; // 256 is not enough due to color escape sequences!!!
xlogl_start(line, "FRONIUS");
xlogl_int_b(line, "∑PV", gstate->pv);
xlogl_int_b(line, "PV10", gstate->mppt1 + gstate->mppt2);
xlogl_int_b(line, "PV7", gstate->mppt3 + gstate->mppt4);
xlogl_int(line, 1, 0, "↑Grid", gstate->produced);
xlogl_int(line, 1, 1, "↓Grid", gstate->consumed);
xlogl_int(line, 0, 0, "Today", gstate->today);
xlogl_int(line, 0, 0, "Tomo", gstate->tomorrow);
xlogl_int(line, 0, 0, "Exp", gstate->expected);
xlogl_float(line, 0, 0, "SoC", FLOAT10(gstate->soc));
xlogl_int(line, 0, 0, "Akku", gstate->akku);
xlogl_float(line, 0, 0, "TTL", FLOAT60(gstate->ttl));
xlogl_float(line, 1, gstate->survive < 0, "Survive", 1.0 + FLOAT10(gstate->survive));
xlogl_float(line, 1, gstate->heating < 0, "Heating", 1.0 + FLOAT10(gstate->heating));
strcat(line, " potd:");
strcat(line, potd ? potd->name : "NULL");
xlogl_end(line, strlen(line), 0);
}
static void print_pstate_dstate(device_t *d) {
char line[512], value[16]; // 256 is not enough due to color escape sequences!!!
xlogl_start(line, "FRONIUS");
for (device_t **dd = potd->devices; *dd; dd++) {
if (DD->adj)
snprintf(value, 5, " %3d", DD->power);
else
snprintf(value, 5, " %c", DD->power ? 'X' : '_');
strcat(line, value);
}
strcat(line, " st ");
for (device_t **dd = potd->devices; *dd; dd++) {
snprintf(value, 5, "%d", DD->state);
strcat(line, value);
}
strcat(line, " nr ");
for (device_t **dd = potd->devices; *dd; dd++) {
snprintf(value, 5, "%d", DD->noresponse);
strcat(line, value);
}
strcat(line, " F");
if (f10 && f10->inverter) {
snprintf(value, 16, ":%d", f10->inverter->St);
strcat(line, value);
}
if (f7 && f7->inverter) {
snprintf(value, 16, ":%d", f7->inverter->St);
strcat(line, value);
}
xlogl_bits16(line, " Flags", pstate->flags);
xlogl_int_b(line, "PV10", pstate->mppt1 + pstate->mppt2);
xlogl_int_b(line, "PV7", pstate->mppt3 + pstate->mppt4);
xlogl_int(line, 1, 1, "Grid", pstate->grid);
xlogl_int(line, 1, 1, "Akku", pstate->akku);
xlogl_int(line, 1, 0, "Ramp", pstate->ramp);
xlogl_int(line, 0, 0, "Load", pstate->load);
if (d)
xlogl_int(line, 0, 0, d->name, d->timer);
xlogl_end(line, strlen(line), 0);
}
// call device specific ramp function
static int ramp_device(device_t *d, int power) {
if (power < 0)
xdebug("FRONIUS ramp↓ %d %s", power, d->name);
else if (power > 0)
xdebug("FRONIUS ramp↑ +%d %s", power, d->name);
else
xdebug("FRONIUS ramp 0 %s", d->name);
return (d->ramp)(d, power);
}
static int select_program(const potd_t *p) {
if (potd == p)
return 0;
// potd has changed - reset all devices and wait for new values
a1.power = -1;
for (device_t **dd = DEVICES; *dd; dd++)
ramp_device(DD, DOWN);
xlog("FRONIUS selecting %s program of the day", p->name);
potd = (potd_t*) p;
sleep(WAIT_RESPONSE);
return 0;
}
// choose program of the day
static int choose_program() {
if (!gstate)
return select_program(&MODEST);
// akku is empty - charging akku has priority
if (gstate->soc < 100)
return select_program(&MODEST);
// we will NOT survive - charging akku has priority
if (gstate->survive < 0)
return select_program(&MODEST);
// tomorrow not enough pv - charging akku has priority
if (gstate->tomorrow < AKKU_CAPACITY)
return select_program(&MODEST);
// tomorrow more pv than today - charge akku tommorrow
if (gstate->tomorrow > gstate->today)
return select_program(&GREEDY);
// enough pv available to survive + heating
if (gstate->heating > 0)
return select_program(&PLENTY);
return select_program(&MODEST);
}
static device_t* rampup(int power) {
for (device_t **dd = potd->devices; *dd; dd++)
if (ramp_device(DD, power))
return DD;
return 0;
}
static device_t* rampdown(int power) {
// jump to last entry
device_t **dd = potd->devices;
while (*dd)
dd++;
// now go backward - this gives reverse order
while (dd-- != potd->devices)
if (ramp_device(DD, power))
return DD;
return 0;
}
static device_t* ramp() {
device_t *d;
// prio1: ramp down in reverse order
if (pstate->ramp < 0) {
d = rampdown(pstate->ramp);
if (d)
return d;
}
// prio2: ramp up in order when stable and ramp indicated
if (pstate->ramp > 0 && PSTATE_VALID && (PSTATE_STABLE || pstate->ramp > 1000)) {
d = rampup(pstate->ramp);
if (d)
return d;
}
return 0;
}
static int steal_thief_victim(device_t *t, device_t *v) {
// thief not active or in standby
if (t->state == Disabled || t->state == Standby)
return 0;
// thief already (full) on
if (t->power == (t->adj ? 100 : 1))
return 0;
// we can steal akkus charge power or victims load
int psteal = 0;
if (v == &a1)
psteal = pstate->akku < -100 ? pstate->akku * -0.9 : 0;
else
psteal = v->load;
// nothing to steal
if (!psteal)
return 0;
// not enough to steal
int min = t->adj ? t->total / 100 : t->total; // adjustable: 1% of total, dumb: total
int power = pstate->ramp + psteal;
if (power < min)
return 0;
xdebug("FRONIUS steal %d from %s and provide it to %s with a load of %d min=%d", psteal, v->name, t->name, t->total, min);
// ramp down victim, ramp up thief (akku ramps down itself)
if (v != &a1)
ramp_device(v, v->load * -1);
ramp_device(t, power);
// give akku time to adjust
if (v == &a1)
t->timer = WAIT_AKKU_RAMP;
// no response expected as we put power from one to another device
t->xload = 0;
return 1;
}
static device_t* steal() {
// check flags
if (!PSTATE_STABLE || !PSTATE_VALID || PSTATE_DISTORTION)
return 0;
// jump to end
device_t **tail = potd->devices;
while (*tail)
tail++;
tail--;
// thief goes forward, victim backward till it reaches thief
for (device_t **tt = potd->devices; *tt != 0; tt++)
for (device_t **vv = tail; vv != tt; vv--)
if (steal_thief_victim(*tt, *vv))
return *tt;
return 0;
}
static device_t* perform_standby(device_t *d) {
int power = d->adj ? (d->power < 50 ? +500 : -500) : (d->power ? d->total * -1 : d->total);
xdebug("FRONIUS starting standby check on %s with power=%d", d->name, power);
d->state = Standby_Check;
ramp_device(d, power);
return d;
}
static int force_standby() {
if (SUMMER)
return 1; // summer mode -> off
// force heating independently from temperature
if ((now->tm_mon == 4 || now->tm_mon == 8) && now->tm_hour >= 16) // may/sept begin 16 o'clock
return 0;
else if ((now->tm_mon == 3 || now->tm_mon == 9) && now->tm_hour >= 14) // apr/oct begin 14 o'clock
return 0;
return TEMP_IN > 25; // too hot for heating
}
static device_t* standby() {
// put dumb devices into standby if summer or too hot
if (force_standby()) {
xdebug("FRONIUS month=%d out=%.1f in=%.1f --> forcing standby", now->tm_mon, TEMP_OUT, TEMP_IN);
for (device_t **dd = DEVICES; *dd; dd++) {
if (!DD->adj && DD->state == Active) {
ramp_device(DD, DOWN);
DD->state = Standby;
}
}
}
// check flags
if (!PSTATE_CHECK_STANDBY || !PSTATE_STABLE || !PSTATE_VALID || PSTATE_DISTORTION || pstate->pv < BASELOAD * 2)
return 0;
// try first active powered adjustable device with noresponse counter > 0
for (device_t **dd = DEVICES; *dd; dd++)
if (DD->state == Active && DD->power && DD->adj && DD->noresponse > 0)
return perform_standby(DD);
// try first active powered device with noresponse counter > 0
for (device_t **dd = DEVICES; *dd; dd++)
if (DD->state == Active && DD->power && DD->noresponse > 0)
return perform_standby(DD);
// try first active powered adjustable device
for (device_t **dd = DEVICES; *dd; dd++)
if (DD->state == Active && DD->power && DD->adj)
return perform_standby(DD);
// try first active powered device
for (device_t **dd = DEVICES; *dd; dd++)
if (DD->state == Active && DD->power)
return perform_standby(DD);
return 0;
}
static device_t* response(device_t *d) {
// ramp timer not yet expired -> continue main loop
if (d->timer > 0) {
d->timer--;
return d;
}
// no expected delta load - no response to check
if (!d->xload)
return 0;
int delta = pstate->load - d->aload;
int expected = d->xload;
d->xload = 0; // reset
// valid response is at least 1/3 of expected
int response = expected > 0 ? (delta > expected / 3) : (delta < expected / 3);
// response OK
if (d->state == Active && response) {
xdebug("FRONIUS response OK from %s, delta load expected %d actual %d", d->name, expected, delta);
d->noresponse = 0;
d->timer = 0;
return 0;
}
// standby check was negative - we got a response
if (d->state == Standby_Check && response) {
xdebug("FRONIUS standby check negative for %s, delta load expected %d actual %d", d->name, expected, delta);
d->noresponse = 0;
d->state = Active;
d->timer = 0;
return d;
}
// standby check was positive -> set device into standby
if (d->state == Standby_Check && !response) {
xdebug("FRONIUS standby check positive for %s, delta load expected %d actual %d --> entering standby", d->name, expected, delta);
ramp_device(d, d->total * -1);
d->noresponse = 0;
d->state = Standby;
d->xload = 0; // no response from switch off expected
return d; // recalculate in next round
}
// ignore standby check when power was released
if (expected > 0)
return 0;
// perform standby check when noresponse counter reaches threshold
if (++d->noresponse >= STANDBY_NORESPONSE)
return perform_standby(d);
xdebug("FRONIUS no response from %s count %d/%d", d->name, d->noresponse, STANDBY_NORESPONSE);
return 0;
}
static void calculate_mosmix() {
// update forecasts
if (mosmix_load(MARIENBERG))
return;
// mosmix 24h raw values forecasts today, tomorrow and tomorrow+1
mosmix_csv_t m0, m1, m2;
mosmix_24h(0, &m0);
mosmix_24h(1, &m1);
mosmix_24h(2, &m2);
xdebug(MOSMIX3X24, m0.Rad1h, m0.SunD1, m0.RSunD, m1.Rad1h, m1.SunD1, m1.RSunD, m2.Rad1h, m2.SunD1, m2.RSunD);
// update produced energy this hour and recalculate mosmix factors for each mppt
mosmix_mppt(now, gstate->mppt1, gstate->mppt2, gstate->mppt3, gstate->mppt4);
// collect total expected today, tomorrow and till end of day / start of day
int today, tomorrow, sod, eod;
mosmix_collect(now, &today, &tomorrow, &sod, &eod);
gstate->today = today;
gstate->tomorrow = tomorrow;
gstate->expected = eod;
// calculate survival factor
int hours, from, to;
mosmix_survive(now, BASELOAD / 2, &hours, &from, &to);
int needed = collect_load(from, hours);
int tocharge = needed - gstate->akku;
if (tocharge < 0)
tocharge = 0;
int available = gstate->expected - tocharge;
if (available < 0)
available = 0;
float survive = needed ? (float) (gstate->akku + available) / (float) needed - 1.0 : -1.0;
gstate->survive = survive * 10; // store as x10 scaled
xdebug("FRONIUS survive expected=%d tocharge=%d available=%d akku=%d needed=%d --> %.2f", gstate->expected, tocharge, available, gstate->akku, needed, survive);
// calculate heating factor
int heating_total = collect_heating_total();
mosmix_heating(now, heating_total, &hours, &from, &to);
needed = heating_total * hours;
float heating = needed ? (float) available / (float) needed - 1.0 : -1.0;
gstate->heating = heating * 10; // store as x10 scaled
xdebug("FRONIUS heating expected=%d tocharge=%d available=%d needed=%d --> %.2f", gstate->expected, tocharge, available, needed, heating);
// actual vs. yesterdays expected ratio
int actual = 0;
for (int i = 0; i <= now->tm_hour; i++)
actual += GSTATE_HOUR(i)->pv;
int yesterdays_tomorrow = GSTATE_HOUR(23)->tomorrow;
float error = yesterdays_tomorrow ? (float) actual / (float) yesterdays_tomorrow : 0;
xdebug("FRONIUS yesterdays forecast for today %d, actual %d, error %.2f", yesterdays_tomorrow, actual, error);
// dump todays history
mosmix_dump_history_today(now);
}
static void calculate_gstate() {
// take over SoC
gstate->soc = pstate->soc;
// get previous values to calculate deltas
counter_t *c = COUNTER_LAST, *c0 = COUNTER_0;
gstate_t *g = GSTATE_LAST;
// pv / consumed / produced -> day total
gstate->pv = 0;
gstate->pv += counter->mppt1 && c0->mppt1 ? counter->mppt1 - c0->mppt1 : 0;
gstate->pv += counter->mppt2 && c0->mppt2 ? counter->mppt2 - c0->mppt2 : 0;
gstate->pv += counter->mppt3 && c0->mppt3 ? counter->mppt3 - c0->mppt3 : 0;
gstate->pv += counter->mppt4 && c0->mppt4 ? counter->mppt4 - c0->mppt4 : 0;
gstate->produced = counter->produced && c0->produced ? counter->produced - c0->produced : 0;
gstate->consumed = counter->consumed && c0->consumed ? counter->consumed - c0->consumed : 0;
// mppt's -> last hour
gstate->mppt1 = counter->mppt1 && c->mppt1 ? counter->mppt1 - c->mppt1 : 0;
gstate->mppt2 = counter->mppt2 && c->mppt2 ? counter->mppt2 - c->mppt2 : 0;
gstate->mppt3 = counter->mppt3 && c->mppt3 ? counter->mppt3 - c->mppt3 : 0;
gstate->mppt4 = counter->mppt4 && c->mppt4 ? counter->mppt4 - c->mppt4 : 0;
// calculate akku energy and delta (+)charge (-)discharge when soc between 10-90% and estimate time to live when discharging
int range_ok = gstate->soc > 100 && gstate->soc < 900 && g->soc > 100 && g->soc < 900;
gstate->akku = gstate->soc > MIN_SOC ? AKKU_CAPACITY_SOC(gstate->soc - MIN_SOC) : 0;
gstate->dakku = range_ok ? AKKU_CAPACITY_SOC(gstate->soc - g->soc) : 0;
if (gstate->dakku < BASELOAD / -2)
gstate->ttl = gstate->akku * 60 / gstate->dakku * -1; // in discharge phase - use current discharge rate (minutes)
else if (gstate->soc > MIN_SOC)
gstate->ttl = gstate->akku * 60 / BASELOAD; // not yet in discharge phase - use BASELOAD (minutes)
else
gstate->ttl = 0;
}
static void calculate_pstate() {
// clear all flags
pstate->flags = 0;
// get history states
pstate_t *m1 = PSTATE_MIN_LAST1;
pstate_t *m2 = PSTATE_MIN_LAST2;
pstate_t *s1 = PSTATE_SEC_LAST1;
pstate_t *s2 = PSTATE_SEC_LAST2;
pstate_t *s3 = PSTATE_SEC_LAST3;
// total PV produced by both inverters
pstate->pv = pstate->mppt1 + pstate->mppt2 + pstate->mppt3 + pstate->mppt4;
pstate->dpv = pstate->pv - s1->pv;
pstate->sdpv += abs(pstate->dpv);
// grid, delta grid and sum
pstate->dgrid = pstate->grid - s1->grid;
pstate->sdgrid += abs(pstate->dgrid);
if (abs(pstate->dgrid) < NOISE)
pstate->dgrid = 0; // shape dgrid
// calculate load, delta load + sum
pstate->load = (pstate->ac10 + pstate->ac7 + pstate->grid) * -1;
pstate->dload = pstate->load - s1->load;
pstate->sdload += abs(pstate->dload);
if (abs(pstate->dload) < NOISE)
pstate->dload = 0; // shape dload
// check if we have delta ac power anywhere
if (abs(pstate->grid - s1->grid) > NOISE)
pstate->flags |= FLAG_DELTA;
if (abs(pstate->ac10 - s1->ac10) > NOISE)
pstate->flags |= FLAG_DELTA;
if (abs(pstate->ac7 - s1->ac7) > NOISE)
pstate->flags |= FLAG_DELTA;
// akku power is Fronius10 DC power minus PV
pstate->akku = pstate->dc10 - (pstate->mppt1 + pstate->mppt2);
// offline mode when 3x not enough PV production
if (pstate->pv < MINIMUM && s1->pv < MINIMUM && s2->pv < MINIMUM && s3->pv < MINIMUM) {
int burnout_time = !SUMMER && (now->tm_hour == 6 || now->tm_hour == 7 || now->tm_hour == 8);
int burnout_possible = TEMP_IN < 20 && pstate->soc > 150;
if (burnout_time && burnout_possible && AKKU_BURNOUT)
pstate->flags |= FLAG_BURNOUT; // akku burnout between 6 and 9 o'clock when possible
else
pstate->flags |= FLAG_OFFLINE; // offline
pstate->ramp = pstate->xload = pstate->dxload = pstate->pv = pstate->dpv = pstate->mppt1 = pstate->mppt2 = pstate->mppt3 = pstate->mppt4 = 0;
return;
}
// emergency shutdown when last minute extreme akku discharge or grid download
if (EMERGENCY && (m1->akku > EMERGENCY || m1->grid > EMERGENCY)) {
pstate->flags |= FLAG_EMERGENCY;
return;
}
// calculate ramp up/down power
pstate->ramp = pstate->grid * -1;
// stable when grid between -RAMP_WINDOW..+NOISE
if (-RAMP_WINDOW < pstate->grid && pstate->grid <= NOISE)
pstate->ramp = 0;
// ramp down as soon as grid goes above NOISE
if (NOISE < pstate->grid && pstate->grid <= RAMP_WINDOW)
pstate->ramp = -RAMP_WINDOW;
// when akku is charging it regulates around 0, so set stable window between -RAMP_WINDOW..+RAMP_WINDOW
if (pstate->akku < -NOISE && -RAMP_WINDOW < pstate->grid && pstate->grid <= RAMP_WINDOW)
pstate->ramp = 0;
// 50% more ramp down when pv tendency is falling
if (pstate->ramp < 0 && m1->dpv < 0)
pstate->ramp += pstate->ramp / 2;
// state is stable when we have three times no grid changes
if (!s1->dgrid && !s2->dgrid && !s3->dgrid)
pstate->flags |= FLAG_STABLE;
// distortion when current sdpv is too big or aggregated last two sdpv's are too big
int d0 = pstate->sdpv > m1->pv;
int d1 = m1->sdpv > m1->pv + m1->pv / 2;
int d2 = m2->sdpv > m2->pv + m2->pv / 2;
if (d0 || d1 || d2)
pstate->flags |= FLAG_DISTORTION;
if (PSTATE_DISTORTION)
xdebug("FRONIUS set FLAG_DISTORTION 0=%d/%d 1=%d/%d 2=%d/%d", pstate->sdpv, m1->pv, m1->sdpv, m1->pv, m2->sdpv, m2->pv);
// device loop:
// - expected load
// - active devices
// - all devices in standby
pstate->flags |= FLAG_ALL_STANDBY;
pstate->xload = BASELOAD;
for (device_t **dd = DEVICES; *dd; dd++) {
pstate->xload += DD->load;
if (DD->power > 0 && DD != &a1) // excl. akku; -1 when unitialized!
pstate->flags |= FLAG_ACTIVE;
if (DD->state != Standby)
pstate->flags &= ~FLAG_ALL_STANDBY;
}
pstate->xload *= -1;
// indicate standby check when deviation between actual load and calculated load is three times above 33%
pstate->dxload = pstate->load < -BASELOAD ? (pstate->xload - pstate->load) * 100 / pstate->xload : 0;
if (s1->dxload > 33 && s2->dxload > 33 && s3->dxload > 33)
pstate->flags |= FLAG_CHECK_STANDBY;
if (PSTATE_CHECK_STANDBY)
xdebug("FRONIUS set FLAG_CHECK_STANDBY load=%d xload=%d dxload=%d", pstate->load, pstate->xload, pstate->dxload);
// clear flag when values not valid
pstate->flags |= FLAG_VALID;
int sum = pstate->grid + pstate->akku + pstate->load + pstate->pv;
if (abs(sum) > SUSPICIOUS) {
xdebug("FRONIUS suspicious values detected: sum=%d", sum); // probably inverter power dissipations (?)
pstate->flags &= ~FLAG_VALID;
}
if (pstate->load > 0) {
xdebug("FRONIUS positive load detected");
pstate->flags &= ~FLAG_VALID;
}
if (pstate->grid < -NOISE && pstate->akku > NOISE) {
int waste = abs(pstate->grid) < pstate->akku ? abs(pstate->grid) : pstate->akku;
xdebug("FRONIUS wasting %d akku -> grid power", waste);
pstate->flags &= ~FLAG_VALID;
}
if (pstate->dgrid > BASELOAD * 2) { // e.g. refrigerator starts !!!
xdebug("FRONIUS grid spike detected %d: %d -> %d", pstate->grid - s1->grid, s1->grid, pstate->grid);
pstate->flags &= ~FLAG_VALID;
}
if (!f10->active) {
// xlog("FRONIUS Fronius10 is not active!");
pstate->flags &= ~FLAG_VALID;
}
if (f7 && !f7->active) {
// xlog("FRONIUS Fronius7 is not active!");
}
}
static void emergency() {
xlog("FRONIUS emergency shutdown at akku=%d grid=%d ", pstate->akku, pstate->grid);
for (device_t **dd = DEVICES; *dd; dd++)
ramp_device(DD, DOWN);
}
static void offline() {
// xlog("FRONIUS offline soc=%.1f temp=%.1f", FLOAT10(pstate->soc), TEMP_IN);
}
// burn out akku between 7 and 9 o'clock if we can re-charge it completely by day
static void burnout() {
xlog("FRONIUS burnout soc=%.1f temp=%.1f", FLOAT10(gstate->soc), TEMP_IN);
// fronius_override_seconds("plug5", WAIT_OFFLINE);
// fronius_override_seconds("plug6", WAIT_OFFLINE);
// fronius_override_seconds("plug7", WAIT_OFFLINE); // makes no sense due to ventilate sleeping room
// fronius_override_seconds("plug8", WAIT_OFFLINE);
}
static void daily(time_t now_ts) {
xlog("FRONIUS executing daily tasks...");
// aggregate 24 pstate hours into one day
pstate_t pd;
aggregate((int*) &pd, (int*) pstate_hours, PSTATE_SIZE, 24);
dump_table((int*) pstate_hours, PSTATE_SIZE, 24, -1, "FRONIUS pstate_hours", PSTATE_HEADER);
dump_struct((int*) &pd, PSTATE_SIZE, "[ØØ]", 0);
// aggregate 24 gstate hours into one day
gstate_t gd;
aggregate((int*) &gd, (int*) GSTATE_TODAY, GSTATE_SIZE, 24);
dump_table((int*) GSTATE_TODAY, GSTATE_SIZE, 24, -1, "FRONIUS gstate_hours", GSTATE_HEADER);
dump_struct((int*) &gd, GSTATE_SIZE, "[ØØ]", 0);
// dump high noon mosmix slots
mosmix_dump_history_noon();
#ifndef FRONIUS_MAIN
store_blob(GSTATE_FILE, gstate_hours, sizeof(gstate_hours));
store_blob(COUNTER_FILE, counter_hours, sizeof(counter_hours));
store_blob(PSTATE_H_FILE, pstate_hours, sizeof(pstate_hours));
store_blob(PSTATE_M_FILE, pstate_minutes, sizeof(pstate_minutes));
#endif
}
static void hourly(time_t now_ts) {
xlog("FRONIUS executing hourly tasks...");
// resetting noresponse counters and standby states
for (device_t **dd = DEVICES; *dd; dd++) {
DD->noresponse = 0;
if (DD->state == Standby)
DD->state = Active;
}
// force all devices off when offline
if (PSTATE_OFFLINE)
for (device_t **dd = DEVICES; *dd; dd++)
ramp_device(DD, DOWN);
// aggregate 59 minutes into current hour
// dump_table((int*) pstate_minutes, PSTATE_SIZE, 60, -1, "FRONIUS pstate_minutes", PSTATE_HEADER);
pstate_t *ph = PSTATE_HOUR_NOW;
aggregate((int*) ph, (int*) pstate_minutes, PSTATE_SIZE, 60);
// dump_struct((int*) PSTATE_HOUR_NOW, PSTATE_SIZE, "[ØØ]", 0);
// recalculate mosmix and choose potd
calculate_mosmix();
choose_program();
// compare gstate (counter) vs. pstate (1h aggregated) mppt's
xlog("FRONIUS gstate/pstate mppt1 %d/%d mppt2 %d/%d mppt3 %d/%d", gstate->mppt1, ph->mppt1, gstate->mppt2, ph->mppt2, gstate->mppt3, ph->mppt3);
// copy gstate and counters to next hour (Fronius7 goes into sleep mode - no updates overnight)
memcpy(COUNTER_NEXT, (void*) counter, sizeof(counter_t));
memcpy(GSTATE_NEXT, (void*) gstate, sizeof(gstate_t));
// storage strategy: standard 5%, winter and tomorrow not much pv expected 10%
int min = WINTER && gstate->tomorrow < AKKU_CAPACITY && gstate->soc > 111 ? 10 : 5;