Repository navigation
Expand file tree
/
Copy pathreadbatt.cpp
More file actions
1136 lines (998 loc) · 44.6 KB
/
Copy pathreadbatt.cpp
File metadata and controls
1136 lines (998 loc) · 44.6 KB
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
/*
reads battery data from the pylontech console connector
* check if we have a working connection by sending '\n' and waiting for a prompt '>'
* send command to get battery data: "bat 1\n" 2,3,4 and so on until there is no more battery
* read the response from the battery (until the prompt) and evaluate the data
sample string from Pylontech:
======================
bat 2
@
Battery Volt Curr Tempr Base State Volt. State Curr. State Temp. State SOC Coulomb BAL
0 3508 0 22100 Idle Normal Normal Normal 100% 73555 mAH N
1 3509 0 22100 Idle Normal Normal Normal 100% 73555 mAH N
2 3511 0 22100 Idle Normal Normal Normal 100% 73555 mAH N
3 3509 0 22100 Idle Normal Normal Normal 100% 73555 mAH N
4 3486 0 22100 Idle Normal Normal Normal 100% 73555 mAH N
5 3509 0 22300 Idle Normal Normal Normal 100% 73555 mAH N
6 3511 0 22300 Idle Normal Normal Normal 100% 73555 mAH N
7 3512 0 22300 Idle Normal Normal Normal 100% 73555 mAH N
8 3511 0 22300 Idle Normal Normal Normal 100% 73555 mAH N
9 3509 0 22300 Idle Normal Normal Normal 100% 73555 mAH N
10 3508 0 22000 Idle Normal Normal Normal 100% 73555 mAH N
11 3509 0 22000 Idle Normal Normal Normal 100% 73555 mAH N
12 3510 0 22000 Idle Normal Normal Normal 100% 73555 mAH N
13 3509 0 22000 Idle Normal Normal Normal 100% 73555 mAH N
14 3500 0 22000 Idle Normal Normal Normal 100% 73555 mAH N
Command completed successfully
$$
pylon>
*/
#include <termios.h>
#include "pylonmonitor.h"
#include "readbatt.h"
#include "serial.h"
#include <thread>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <fstream>
#include <iostream>
#include <ctime>
#include <jansson.h>
#include "fifo.h"
#include "config.h"
#include "helper.h"
extern double batteryEnergy[16];
extern int batteryCapacity[16];
READBATT::READBATT()
{
// Initialize batteryInfo array
for(int i = 0; i < MAXBATTNUMBER; i++) {
batteryInfo[i].isNewModel = false;
batteryInfo[i].cycleCount = 0;
memset(batteryInfo[i].manufacturer, 0, sizeof(batteryInfo[i].manufacturer));
memset(batteryInfo[i].model, 0, sizeof(batteryInfo[i].model));
memset(batteryInfo[i].boardVersion, 0, sizeof(batteryInfo[i].boardVersion));
memset(batteryInfo[i].board, 0, sizeof(batteryInfo[i].board));
memset(batteryInfo[i].mainSoftVersion, 0, sizeof(batteryInfo[i].mainSoftVersion));
memset(batteryInfo[i].softVersion, 0, sizeof(batteryInfo[i].softVersion));
memset(batteryInfo[i].bootVersion, 0, sizeof(batteryInfo[i].bootVersion));
memset(batteryInfo[i].commVersion, 0, sizeof(batteryInfo[i].commVersion));
memset(batteryInfo[i].releaseDate, 0, sizeof(batteryInfo[i].releaseDate));
memset(batteryInfo[i].serial, 0, sizeof(batteryInfo[i].serial));
memset(batteryInfo[i].specification, 0, sizeof(batteryInfo[i].specification));
memset(batteryInfo[i].cellNumber, 0, sizeof(batteryInfo[i].cellNumber));
memset(batteryInfo[i].maxDischgCurr, 0, sizeof(batteryInfo[i].maxDischgCurr));
memset(batteryInfo[i].maxChargeCurr, 0, sizeof(batteryInfo[i].maxChargeCurr));
memset(batteryInfo[i].eponPortRate, 0, sizeof(batteryInfo[i].eponPortRate));
memset(batteryInfo[i].consolePortRate, 0, sizeof(batteryInfo[i].consolePortRate));
}
// initialize and open the RPI's internal serial interface (Port 1 - always active)
open_serial(B115200);
// Open additional serial ports if enabled
if(port2Enabled && serialPort2.length() > 0) {
printf("Opening Port 2: %s\n", serialPort2.c_str());
open_serial2(B115200);
}
if(port3Enabled && serialPort3.length() > 0) {
printf("Opening Port 3: %s\n", serialPort3.c_str());
open_serial3(B115200);
}
if(port4Enabled && serialPort4.length() > 0) {
printf("Opening Port 4: %s\n", serialPort4.c_str());
open_serial4(B115200);
}
// create a thread that handles reading from the battery
std::thread myThread(&READBATT::batteryhandler_thread,this);
// Detach the thread to allow it to run and exit independently.
myThread.detach();
}
void READBATT::batteryhandler_thread()
{
while(keeprunning) {
// read byttery information of all connected batteries, one by one
loop_pylon();
usleep(50);
}
}
// Function to write formatted text to the serial port.
void READBATT::serial_printf(const char *format, ...)
{
char buffer[1024]; // Defines the maximum size of the formatted string
va_list args;
va_start(args, format);
vsnprintf(buffer, sizeof(buffer), format, args);
va_end(args);
for (int i = 0; buffer[i] != '\0'; ++i) {
uint8_t byte = (uint8_t)buffer[i];
switch(activePort) {
case 1: write_serial(byte); break;
case 2: write_serial2(byte); break;
case 3: write_serial3(byte); break;
case 4: write_serial4(byte); break;
}
}
}
// Helper function to read from the active port
int READBATT::read_active_port()
{
switch(activePort) {
case 1: return read_serial();
case 2: return read_serial2();
case 3: return read_serial3();
case 4: return read_serial4();
default: return -1;
}
}
// Helper function to check write buffer free space on active port
int READBATT::write_buffer_free()
{
switch(activePort) {
case 1: return write_serial_free();
case 2: return write_serial2_free();
case 3: return write_serial3_free();
case 4: return write_serial4_free();
default: return 0;
}
}
// read byttery information of all connected batteries, one by one, every second a battery
void READBATT::loop_pylon()
{
static int timeout = 0;
static int lasttime = 0;
static int acttime = 0;
static int cycleStart = 0;
static bool cycleInProgress = false;
if(pylonState == PYLON_SEARCH) {
// send LF, pylontech should respond with a prompt
printf("search batt on port %d\n", activePort);
timeout = 0;
switch(activePort) {
case 1: write_serial('\n'); break;
case 2: write_serial2('\n'); break;
case 3: write_serial3('\n'); break;
case 4: write_serial4('\n'); break;
}
pylonState = PYLON_ACK;
return;
}
if(pylonState == PYLON_ACK) {
// wait for the prompt from the battery
int data = read_active_port(); // -1 ... no data
if(data != -1) {
// something was received from the battery
uint8_t c = data;
if (c == '>') {
// prompt received
printf("batt found\n");
acttime = 0;
lasttime = -1000; //make first request immediately
pylonState = PYLON_PWR;
return;
}
} else {
// nothing received
if(++timeout > 5000) {
// nothing received within 5s
printf("batt test timeout\n");
pylonState = PYLON_SEARCH;
return;
}
usleep(1000);
return;
}
}
if(pylonState == PYLON_PWR) {
// send pwr command to get battery count
acttime++;
if((acttime - lasttime) < 20) {
usleep(100000);
return;
}
lasttime = acttime;
printf("req pwr\n");
serial_printf("pwr\n");
timeout = 0;
rxidx = 0;
pylonState = PYLON_READ;
return;
}
if(pylonState == PYLON_REQUEST) {
// battery found, request the next batt data
// wait for 1s before making a new request
acttime++;
// wait pollInterval seconds before starting a new cycle
if(cycleInProgress && localBattnum == 1 && activePort == 1) {
if(acttime - cycleStart < pollInterval * 10) {
usleep(100000);
return;
}
cycleInProgress = false;
}
if((acttime - lasttime) < 20) {
// too early for next request
usleep(100000);
return;
}
lasttime = acttime;
// Check if we need to switch to next port
// Calculate how many batteries we've read on this port
if(localBattnum > portBattCount[activePort-1] && portBattCount[activePort-1] > 0) {
// Finished reading all batteries on this port, switch to next port
bool switched = false;
for(int nextPort = activePort + 1; nextPort <= 4; nextPort++) {
bool portEnabled = false;
if(nextPort == 2 && port2Enabled && serialPort2.length() > 0) portEnabled = true;
if(nextPort == 3 && port3Enabled && serialPort3.length() > 0) portEnabled = true;
if(nextPort == 4 && port4Enabled && serialPort4.length() > 0) portEnabled = true;
if(portEnabled) {
activePort = nextPort;
localBattnum = 1;
battnum = portOffset[nextPort-1] + 1;
portCycleComplete = false;
printf("Switching to port %d (local batt %d, global batt %d)\n", activePort, localBattnum, battnum);
pylonState = PYLON_SEARCH;
switched = true;
break;
}
}
if(!switched) {
// All ports done, wait for poll interval
cycleStart = acttime;
cycleInProgress = true;
localBattnum = 1;
battnum = 1;
activePort = 1;
portCycleComplete = true;
pylonState = PYLON_SEARCH;
}
return;
}
printf("req bat %d on port %d (global %d)\n", localBattnum, activePort, battnum);
// if the write buffer is full, restart the search to clear it
if(write_buffer_free() == -1) {
printf("write buffer full, restarting search\n");
acttime = 0;
lasttime = 0;
pylonState = PYLON_SEARCH;
return;
}
serial_printf("bat %d\n", localBattnum);
timeout = 0;
rxidx = 0;
pylonState = PYLON_READ;
return;
}
if(pylonState == PYLON_INFO) {
// Request info from new model batteries
acttime++;
if((acttime - lasttime) < 20) {
usleep(100000);
return;
}
lasttime = acttime;
printf("req info %d on port %d\n", localBattnum, activePort);
if(write_buffer_free() == -1) {
printf("write buffer full, restarting search\n");
acttime = 0;
lasttime = 0;
pylonState = PYLON_SEARCH;
return;
}
serial_printf("info %d\n", localBattnum);
timeout = 0;
rxidx = 0;
pylonState = PYLON_READ;
return;
}
if(pylonState == PYLON_STAT) {
// Request stat from new model batteries to get cycle count
acttime++;
if((acttime - lasttime) < 20) {
usleep(100000);
return;
}
lasttime = acttime;
printf("req stat %d on port %d\n", localBattnum, activePort);
if(write_buffer_free() == -1) {
printf("write buffer full, restarting search\n");
acttime = 0;
lasttime = 0;
pylonState = PYLON_SEARCH;
return;
}
serial_printf("stat %d\n", localBattnum);
timeout = 0;
rxidx = 0;
pylonState = PYLON_READ;
return;
}
if(pylonState == PYLON_READ) {
// read the response from the battery
// read all bytes until the prompt is received
int c = read_active_port();
if(c != -1) {
while(c != -1) {
// char received
timeout = 0;
// store received char
pylon_rxbuf[rxidx++] = c;
pylon_rxbuf[rxidx] = 0;
if(rxidx >= MAXRXBUFLEN - 1) {
// overflow - process what we have and restart
printf("batt read pylon_rxbuf overflow\n");
pylon_rxbuf[MAXRXBUFLEN - 1] = 0;
processBatData();
rxidx = 0;
}
if(strstr(pylon_rxbuf,"Invalid")) {
// this bat num does not exist
// advance to next battery
localBattnum++;
battnum++;
// empty the RX buffer
while(read_active_port() != -1) usleep(100);
acttime = 0;
lasttime =0;
pylonState = PYLON_REQUEST;
return;
}
if (c == '>') {
// prompt received
pylon_rxbuf[rxidx] = 0; // terminate string
bool wasInfoCommand = (strstr(pylon_rxbuf, "info") != NULL);
bool wasStatCommand = (strstr(pylon_rxbuf, "stat") != NULL);
processBatData();
// if we just read pwr data, start with battery 1
if(strstr(pylon_rxbuf, "pwr") != NULL) {
localBattnum = 1;
battnum = portOffset[activePort-1] + 1;
} else if(wasStatCommand) {
// Just read stat, go to next battery
localBattnum++;
battnum++;
} else if(wasInfoCommand) {
// Just read info, check if we need to request stat for this battery
// New models have isNewModel = true
if(battnum <= battnumber && batteryInfo[battnum-1].isNewModel) {
// Request stat for new model battery to get cycle count
pylonState = PYLON_STAT;
return;
} else {
// go to next battery
localBattnum++;
battnum++;
}
} else {
// Just read bat data, check if we need to request info for this battery
// New models have isNewModel = true
if(battnum <= battnumber && batteryInfo[battnum-1].isNewModel) {
// Request info for new model battery
pylonState = PYLON_INFO;
return;
} else {
// go to the next battery (never read more than MAXBATTNUMBER batteries)
localBattnum++;
battnum++;
}
}
acttime = 0;
lasttime =0;
pylonState = PYLON_REQUEST;
return;
}
c = read_active_port();
}
} else {
// nothing received
if(++timeout > 2000) {
// nothing received within 2s
printf("batt read timeout\n");
// repeat with the same battery
acttime = 0;
lasttime = 0;
pylonState = PYLON_REQUEST;
usleep(1000);
}
}
return;
}
}
// Set battery energy and capacity based on detected model
// All Pylontech are 15S, 48V
void READBATT::setBatterySpecs(int battNum, const char* model) {
if (battNum <= 0 || battNum > MAXBATTNUMBER) return;
string m = model;
if (m.find("US5000") != string::npos) {
batteryEnergy[battNum-1] = 4800; // Wh (nominal)
batteryCapacity[battNum-1] = 100; // Ah
printf("Battery %d: US5000C detected (4800 Wh, 100 Ah)\n", battNum);
} else if (m.find("US3000") != string::npos) {
batteryEnergy[battNum-1] = 3552; // Wh (nominal)
batteryCapacity[battNum-1] = 74; // Ah
printf("Battery %d: US3000/C detected (3552 Wh, 74 Ah)\n", battNum);
} else if (m.find("US2000") != string::npos) {
batteryEnergy[battNum-1] = 2400; // Wh (nominal)
batteryCapacity[battNum-1] = 50; // Ah
printf("Battery %d: US2000/C detected (2400 Wh, 50 Ah)\n", battNum);
} else {
printf("Battery %d: Unknown model '%s', energy/capacity not set\n", battNum, model);
}
}
// remove multiple SPCs
string READBATT::shrink(char *text) {
string result = "";
bool lastWasSpace = false;
while (*text) {
if (*text == ' ') {
if (!lastWasSpace) {
result += *text;
lastWasSpace = true;
}
} else {
result += *text;
lastWasSpace = false;
}
text++;
}
return result;
}
void READBATT::processBatData()
{
string s = shrink(pylon_rxbuf);
const char *batteryString = s.c_str();
// Check if this is a stat command response
if(strstr(batteryString, "stat") != NULL) {
// Parse stat response to get cycle count
char *pos = (char *)batteryString;
int battNum = battnum; // Use global battery number
// Find battery number from the first line (after "stat ")
char *statStr = strstr(pos, "stat ");
if (statStr) {
int localNum = atoi(statStr + 5);
// Convert local to global
battNum = portOffset[activePort-1] + localNum;
} else if (pos[0] >= '1' && pos[0] <= '9') {
int localNum = atoi(pos);
battNum = portOffset[activePort-1] + localNum;
}
// Helper function to extract value after colon and trim spaces/newlines
auto extractValue = [](const char *data, const char *fieldName) -> std::string {
const char *field = strstr(data, fieldName);
if (!field) return "";
// Find the colon after the field name
const char *colon = strchr(field, ':');
if (!colon) return "";
// Skip the colon and spaces
const char *value = colon + 1;
while (*value == ' ' || *value == '\t') value++;
// Extract until newline or end of string
std::string result;
while (*value && *value != '\n' && *value != '\r') {
result += *value;
value++;
}
// Trim trailing spaces
while (!result.empty() && (result.back() == ' ' || result.back() == '\t')) {
result.pop_back();
}
return result;
};
// Extract cycle count
std::string cycleStr = extractValue(pos, "CYCLE Times");
if (battNum > 0 && battNum <= MAXBATTNUMBER) {
batteryInfo[battNum-1].cycleCount = atoi(cycleStr.c_str());
}
return;
}
// Check if this is an info command response
if(strstr(batteryString, "info") != NULL) {
// Parse info response to get battery details
// Format is: "Field name : Value"
char *pos = (char *)batteryString;
int battNum = battnum; // Use global battery number
// Find battery number from the first line (after "info ")
char *infoStr = strstr(pos, "info ");
if (infoStr) {
int localNum = atoi(infoStr + 5);
// Convert local to global
battNum = portOffset[activePort-1] + localNum;
} else if (pos[0] >= '1' && pos[0] <= '9') {
int localNum = atoi(pos);
battNum = portOffset[activePort-1] + localNum;
}
// Helper function to extract value after colon and trim spaces/newlines
auto extractValue = [](const char *data, const char *fieldName) -> std::string {
const char *field = strstr(data, fieldName);
if (!field) return "";
// Find the colon after the field name
const char *colon = strchr(field, ':');
if (!colon) return "";
// Skip the colon and spaces
const char *value = colon + 1;
while (*value == ' ' || *value == '\t') value++;
// Extract until newline or end of string
std::string result;
while (*value && *value != '\n' && *value != '\r') {
result += *value;
value++;
}
// Trim trailing spaces
while (!result.empty() && (result.back() == ' ' || result.back() == '\t')) {
result.pop_back();
}
return result;
};
// Extract all fields
std::string manufacturer = extractValue(pos, "Manufacturer");
std::string model = extractValue(pos, "Device name");
std::string boardVersion = extractValue(pos, "Board version");
std::string board = extractValue(pos, "Board");
std::string mainSoftVersion = extractValue(pos, "Main Soft version");
std::string softVersion = extractValue(pos, "Soft version");
std::string bootVersion = extractValue(pos, "Boot version");
std::string commVersion = extractValue(pos, "Comm version");
std::string releaseDate = extractValue(pos, "Release Date");
std::string serial = extractValue(pos, "Barcode");
std::string specification = extractValue(pos, "Specification");
std::string cellNumber = extractValue(pos, "Cell Number");
std::string maxDischgCurr = extractValue(pos, "Max Dischg Curr");
std::string maxChargeCurr = extractValue(pos, "Max Charge Curr");
std::string eponPortRate = extractValue(pos, "EPONPort rate");
std::string consolePortRate = extractValue(pos, "Console Port rate");
// Store the fields
if (battNum > 0 && battNum <= MAXBATTNUMBER) {
snprintf(batteryInfo[battNum-1].manufacturer, sizeof(batteryInfo[battNum-1].manufacturer), "%s", manufacturer.c_str());
snprintf(batteryInfo[battNum-1].model, sizeof(batteryInfo[battNum-1].model), "%s", model.c_str());
setBatterySpecs(battNum, model.c_str());
snprintf(batteryInfo[battNum-1].boardVersion, sizeof(batteryInfo[battNum-1].boardVersion), "%s", boardVersion.c_str());
snprintf(batteryInfo[battNum-1].board, sizeof(batteryInfo[battNum-1].board), "%s", board.c_str());
snprintf(batteryInfo[battNum-1].mainSoftVersion, sizeof(batteryInfo[battNum-1].mainSoftVersion), "%s", mainSoftVersion.c_str());
snprintf(batteryInfo[battNum-1].softVersion, sizeof(batteryInfo[battNum-1].softVersion), "%s", softVersion.c_str());
snprintf(batteryInfo[battNum-1].bootVersion, sizeof(batteryInfo[battNum-1].bootVersion), "%s", bootVersion.c_str());
snprintf(batteryInfo[battNum-1].commVersion, sizeof(batteryInfo[battNum-1].commVersion), "%s", commVersion.c_str());
snprintf(batteryInfo[battNum-1].releaseDate, sizeof(batteryInfo[battNum-1].releaseDate), "%s", releaseDate.c_str());
snprintf(batteryInfo[battNum-1].serial, sizeof(batteryInfo[battNum-1].serial), "%s", serial.c_str());
snprintf(batteryInfo[battNum-1].specification, sizeof(batteryInfo[battNum-1].specification), "%s", specification.c_str());
snprintf(batteryInfo[battNum-1].cellNumber, sizeof(batteryInfo[battNum-1].cellNumber), "%s", cellNumber.c_str());
snprintf(batteryInfo[battNum-1].maxDischgCurr, sizeof(batteryInfo[battNum-1].maxDischgCurr), "%s", maxDischgCurr.c_str());
snprintf(batteryInfo[battNum-1].maxChargeCurr, sizeof(batteryInfo[battNum-1].maxChargeCurr), "%s", maxChargeCurr.c_str());
snprintf(batteryInfo[battNum-1].eponPortRate, sizeof(batteryInfo[battNum-1].eponPortRate), "%s", eponPortRate.c_str());
snprintf(batteryInfo[battNum-1].consolePortRate, sizeof(batteryInfo[battNum-1].consolePortRate), "%s", consolePortRate.c_str());
}
return;
}
// Check if this is a pwr command response
if(strstr(batteryString, "pwr") != NULL) {
// Parse pwr response to get battery count and detect new/old model
// Count lines that have battery data (not "Absent")
int count = 0;
int lineNum = 0;
char *pos = (char *)batteryString;
while (*pos) {
// Find end of line
char *eol = strchr(pos, '\n');
if (eol) {
*eol = '\0'; // Temporarily null terminate
}
lineNum++;
// Skip header lines (first 2 lines)
if(lineNum > 2) {
// Check if this line contains battery data (not "Absent")
if(strstr(pos, "Absent") == NULL && strstr(pos, "Command") == NULL && strstr(pos, "pylon") == NULL) {
// Check if it starts with a number (battery number)
if(pos[0] >= '1' && pos[0] <= '9') {
int battNum = atoi(pos);
count++;
// Check if the last field is "-" (old model) or a number/word (new model)
// Remove all spaces and newlines and check the last character
char *noSpaces = strdup(pos);
char *write = noSpaces;
for(char *read = noSpaces; *read; read++) {
if(*read != ' ' && *read != '\t' && *read != '\n' && *read != '\r') {
*write++ = *read;
}
}
*write = '\0';
char lastChar = noSpaces[strlen(noSpaces) - 1];
if (lastChar == '-') {
batteryInfo[battNum-1].isNewModel = false;
} else {
batteryInfo[battNum-1].isNewModel = true;
}
free(noSpaces);
}
}
}
if (eol) {
*eol = '\n'; // Restore newline
pos = eol + 1;
} else {
break;
}
}
if(count > 0) {
portBattCount[activePort-1] = count;
printf("Battery count from pwr on port %d: %d\n", activePort, count);
// Calculate offset for this port based on previous ports
int offset = 0;
for(int i = 0; i < activePort-1; i++) {
offset += portBattCount[i];
}
portOffset[activePort-1] = offset;
// Update battnum to start from the correct offset
battnum = offset + 1;
// Update total battery count
totalBattCount = offset + count;
battnumber = totalBattCount;
printf("Port %d: offset=%d, total batteries=%d\n", activePort, offset, totalBattCount);
}
return;
}
//printf("RXed:\n{%s}\n",batteryString);
//printf("installed batts: %d\n",battnumber);
// Split string by lines
char *line = strtok((char *)batteryString, "\n");
int cellCount = 0;
int headerLinesCount = 0;
int batNumber = 0;
while (line) {
if(headerLinesCount == 0) {
sscanf(line, "bat %d", &batNumber);
// Convert local battery number to global
if(batNumber > 0) {
batNumber = portOffset[activePort-1] + batNumber - 1;
}
} else if(headerLinesCount >= 3 && cellCount < 15 && sscanf(line, "%d %lf %lf %lf %s %s %s %s %d%% %lf mAH %c",
&cells[batNumber][cellCount].cellNumber, &cells[batNumber][cellCount].voltage, &cells[batNumber][cellCount].current,
&cells[batNumber][cellCount].temperature, cells[batNumber][cellCount].state, cells[batNumber][cellCount].voltState,
cells[batNumber][cellCount].currState, cells[batNumber][cellCount].tempState, &cells[batNumber][cellCount].soc,
&cells[batNumber][cellCount].coulomb, &cells[batNumber][cellCount].balance) == 11) {
cells[batNumber][cellCount].cellNumber += 1;
cells[batNumber][cellCount].voltage /= 1000;
cells[batNumber][cellCount].current /= 1000;
cells[batNumber][cellCount].temperature /= 1000;
cells[batNumber][cellCount].coulomb /= 1000;
cellCount++;
}
headerLinesCount++;
line = strtok(NULL, "\n");
}
if(battnumber == (batNumber+1)) {
publishBattdata();
}
}
void READBATT::displayCells()
{
for (int i = 0; i < battnumber; ++i) {
//for (int j = 0; j < CELLNUMBER; ++j)
int j=0;
{
printf("Battery %d, Cell %d:", i + 1, j + 1);
printf(" Cell Number: %d", cells[i][j].cellNumber);
printf(" Voltage: %.2f", cells[i][j].voltage);
printf(" Current: %.2f", cells[i][j].current);
printf(" Temperature: %.2f", cells[i][j].temperature);
printf(" State: %s", cells[i][j].state);
printf(" Voltage State: %s", cells[i][j].voltState);
printf(" Current State: %s", cells[i][j].currState);
printf(" Temperature State: %s", cells[i][j].tempState);
printf(" SOC: %d", cells[i][j].soc);
printf(" Coulomb: %.2f", cells[i][j].coulomb);
printf(" Balance: %c\n", cells[i][j].balance);
}
}
}
void READBATT::publishBattdata()
{
// measure the interval and build an average value
static time_t last_execution_time;
time_t current_time;
double elapsed_time;
double sum = 0.0;
int num_measurements = 0;
current_time = time(nullptr);
elapsed_time = difftime(current_time, last_execution_time);
last_execution_time = current_time;
// build average
num_measurements++;
sum += elapsed_time;
int intervall = (int)(sum / num_measurements);
if (num_measurements >= 10) {
sum = 0.0;
num_measurements = 0;
}
// Publish status info (works even without batteries)
json_t *root = json_object();
json_object_set_new(root, "Name", json_string("Pylontech Battery Monitor"));
json_object_set_new(root, "IP", json_string(myLocalIP.c_str()));
json_object_set_new(root, "Interval", json_integer(intervall));
json_object_set_new(root, "temperature", json_real(get_cpu_temperature()));
json_object_set_new(root, "batteryCount", json_integer(battnumber));
char *payload = json_dumps(root, JSON_ENCODE_ANY);
if(payload) {
std::string topic = getMQTTtopic() + "/values";
send_to_mqtt(topic, string(payload));
free(payload);
}
json_decref(root);
// If no batteries, don't publish cell data
if(battnumber == 0)
return;
// create json file for local web page
string batstr_json = convertPylonDataToJson();
std::ofstream outFile("/var/www/html/wxdata/batteryinfo.json");
if (!outFile.is_open()) return;
outFile << batstr_json;
outFile.close();
// publish battery current
for(int battnum = 0; battnum < battnumber; battnum++) {
json_t *root = json_object();
json_object_set_new(root, "current", json_real(cells[battnum][0].current));
// Convert JSON object to string
char *payload = json_dumps(root, JSON_ENCODE_ANY);
if(!payload) {
printf("JSON serialization failed\n");
json_decref(root);
return;
}
std::string topic = getMQTTtopic() + "/current/" + std::to_string(battnum+1);
send_to_mqtt(topic,string(payload));
free(payload);
json_decref(root);
}
// publish battery info (only if model detected)
for(int battnum = 0; battnum < battnumber; battnum++)
{
if(batteryCapacity[battnum] <= 0) continue; // Skip if model not detected
json_t *root = json_object();
json_object_set_new(root, "energy",
json_real(batteryEnergy[battnum]));
json_object_set_new(root, "capacity",
json_integer(batteryCapacity[battnum]));
// Convert JSON object to string
char *payload = json_dumps(root, JSON_ENCODE_ANY);
if(!payload)
{
printf("JSON serialization failed\n");
json_decref(root);
return;
}
std::string topic =
getMQTTtopic() + "/info/" +
std::to_string(battnum + 1);
send_to_mqtt(topic, std::string(payload));
free(payload);
json_decref(root);
}
// Assuming sendJson is similarly adapted to use Jansson
sendJson(0, "voltage");
sendJson(1, "temperature");
sendJson(2, "SoC");
sendJson(3, "charge");
sendJson(4, "bal");
sendJson(5, "status");
sendJson(6, "vstatus");
sendJson(7, "cstatus");
sendJson(8, "tstatus");
// Publish in Home Assistant format if enabled
publishHomeAssistantData();
}
void READBATT::sendJson(int mode, char *name)
{
for(int battnum = 0; battnum < battnumber; battnum++) {
json_t *root = json_object(); // Create a JSON object
json_t *tarr = json_array(); // Create a nested JSON array
for (int cellnum = 0; cellnum < 15; cellnum++) {
switch (mode) {
case 0: json_array_append_new(tarr, json_real(cells[battnum][cellnum].voltage)); break;
case 1: json_array_append_new(tarr, json_real(cells[battnum][cellnum].temperature)); break;
case 2: json_array_append_new(tarr, json_real(cells[battnum][cellnum].soc)); break;
case 3: json_array_append_new(tarr, json_real(cells[battnum][cellnum].coulomb)); break;
case 4: json_array_append_new(tarr, json_integer(cells[battnum][cellnum].balance == 'N' ? 0 : 1)); break;
case 5: json_array_append_new(tarr, json_string(cells[battnum][cellnum].state)); break; // Directly use char array
case 6: json_array_append_new(tarr, json_string(cells[battnum][cellnum].voltState)); break;
case 7: json_array_append_new(tarr, json_string(cells[battnum][cellnum].currState)); break;
case 8: json_array_append_new(tarr, json_string(cells[battnum][cellnum].tempState)); break;
}
}
// Add the array to the root object with the given name
json_object_set_new(root, name, tarr);
// Convert JSON object to string for payload
char *payload = json_dumps(root, JSON_ENCODE_ANY);
if(!payload) {
printf("JSON serialization failed\n");
json_decref(root);
return;
}
std::string topic = getMQTTtopic() + "/" + name + "/" + std::to_string(battnum+1);
send_to_mqtt(topic,string(payload));
free(payload);
json_decref(root);
}
}
string READBATT::convertPylonDataToJson()
{
json_t* root = json_array();
// Add timestamp
char timestamp[50];
time_t now = time(nullptr);
struct tm *tm_info = localtime(&now);
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", tm_info);
json_t* meta = json_object();
json_object_set_new(meta, "timestamp", json_string(timestamp));
json_object_set_new(meta, "batteryCount", json_integer(battnumber));
json_array_append_new(root, meta);
for (int i = 0; i < battnumber; ++i) {
json_t* pylon = json_object();
json_object_set_new(pylon, "battery", json_integer(i));
json_object_set_new(pylon, "current", json_real(cells[i][0].current));
// Add battery info if available
if(batteryInfo[i].isNewModel) {
json_object_set_new(pylon, "isNewModel", json_boolean(true));
json_object_set_new(pylon, "manufacturer", json_string(batteryInfo[i].manufacturer));
json_object_set_new(pylon, "model", json_string(batteryInfo[i].model));
json_object_set_new(pylon, "boardVersion", json_string(batteryInfo[i].boardVersion));
json_object_set_new(pylon, "board", json_string(batteryInfo[i].board));
json_object_set_new(pylon, "mainSoftVersion", json_string(batteryInfo[i].mainSoftVersion));
json_object_set_new(pylon, "softVersion", json_string(batteryInfo[i].softVersion));
json_object_set_new(pylon, "bootVersion", json_string(batteryInfo[i].bootVersion));
json_object_set_new(pylon, "commVersion", json_string(batteryInfo[i].commVersion));
json_object_set_new(pylon, "releaseDate", json_string(batteryInfo[i].releaseDate));
json_object_set_new(pylon, "serial", json_string(batteryInfo[i].serial));
json_object_set_new(pylon, "specification", json_string(batteryInfo[i].specification));
json_object_set_new(pylon, "cellNumber", json_string(batteryInfo[i].cellNumber));
json_object_set_new(pylon, "maxDischgCurr", json_string(batteryInfo[i].maxDischgCurr));
json_object_set_new(pylon, "maxChargeCurr", json_string(batteryInfo[i].maxChargeCurr));
json_object_set_new(pylon, "eponPortRate", json_string(batteryInfo[i].eponPortRate));
json_object_set_new(pylon, "consolePortRate", json_string(batteryInfo[i].consolePortRate));
json_object_set_new(pylon, "cycleCount", json_integer(batteryInfo[i].cycleCount));
} else {
json_object_set_new(pylon, "isNewModel", json_boolean(false));
}
json_t* voltageArray = json_array();
json_t* temperatureArray = json_array();
json_t* SoCArray = json_array();
json_t* chargeArray = json_array();
json_t* balArray = json_array();
for (int j = 0; j < CELLNUMBER; ++j) {
json_array_append_new(voltageArray, json_real(cells[i][j].voltage));
json_array_append_new(temperatureArray, json_real(cells[i][j].temperature));
json_array_append_new(SoCArray, json_integer(cells[i][j].soc));
json_array_append_new(chargeArray, json_real(cells[i][j].coulomb));
json_array_append_new(balArray, json_integer(cells[i][j].balance));
}
json_object_set_new(pylon, "voltage", voltageArray);
json_object_set_new(pylon, "temperature", temperatureArray);
json_object_set_new(pylon, "SoC", SoCArray);
json_object_set_new(pylon, "charge", chargeArray);
json_object_set_new(pylon, "bal", balArray);
json_array_append_new(root, pylon);
}
char* jsonStr = json_dumps(root, JSON_COMPACT | JSON_PRESERVE_ORDER);
string result(jsonStr);
free(jsonStr);
json_decref(root);
return result;
}
void READBATT::publishHomeAssistantData()
{
if(battnumber == 0) return;
// Check if Home Assistant mode is enabled
if(!homeAssistantMode) return;