This repository has been archived by the owner on Apr 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RscpExampleMain.cpp
971 lines (904 loc) · 32.5 KB
/
RscpExampleMain.cpp
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
/*
Based on RscpExample from E3DC for S10
Modified and extended from Thomas Bella <thomas@bella.network>.
This program fetches the current data from an E3DC S10 device over the RSCP TCP/IP protocol
and deliveres the fetched data into a json file which can be simply parsed by other programs.
Copyright (c) 2018 Thomas Bella <thomas@bella.network>
MIT Licence
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "RscpProtocol.h"
#include "RscpTags.h"
#include "SocketConnection.h"
#include "AES.h"
#include "json.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include "settings.h"
#define AES_KEY_SIZE 32
#define AES_BLOCK_SIZE 32
#ifndef SERVER_IP
printf("SERVER_IP is not defined. Check settings.h within source code")
exit(EXIT_FAILURE);
#endif
static int iSocket = -1;
static int iAuthenticated = 0;
static AES aesEncrypter;
static AES aesDecrypter;
static uint8_t ucEncryptionIV[AES_BLOCK_SIZE];
static uint8_t ucDecryptionIV[AES_BLOCK_SIZE];
static char TAG_EMS_OUT_SERIAL_NUMBER[17];
static bool gotData = false;
static uint8_t gotDataFailed = 0;
static uint16_t printStats = 0;
using json = nlohmann::json;
json mainJSONObject;
using namespace std;
int createRequestExample(SRscpFrameBuffer * frameBuffer) {
RscpProtocol protocol;
SRscpValue rootValue;
// The root container is create with the TAG ID 0 which is not used by any device.
protocol.createContainerValue(&rootValue, 0);
//---------------------------------------------------------------------------------------------------------
// Create a request frame
//---------------------------------------------------------------------------------------------------------
if(iAuthenticated == 0)
{
printf("\nRequest authentication\n");
// authentication request
SRscpValue authenContainer;
protocol.createContainerValue(&authenContainer, TAG_RSCP_REQ_AUTHENTICATION);
protocol.appendValue(&authenContainer, TAG_RSCP_AUTHENTICATION_USER, E3DC_USER);
protocol.appendValue(&authenContainer, TAG_RSCP_AUTHENTICATION_PASSWORD, E3DC_PASSWORD);
// append sub-container to root container
protocol.appendValue(&rootValue, authenContainer);
// free memory of sub-container as it is now copied to rootValue
protocol.destroyValueData(authenContainer);
}
else
{
protocol.appendValue(&rootValue, TAG_INFO_REQ_TIME);
// Only get special results once because they do not change in time
if (strlen(TAG_EMS_OUT_SERIAL_NUMBER) == 0) {
protocol.appendValue(&rootValue, TAG_INFO_REQ_SERIAL_NUMBER);
}
// request power data information
protocol.appendValue(&rootValue, TAG_EMS_REQ_POWER_PV);
protocol.appendValue(&rootValue, TAG_EMS_REQ_POWER_BAT);
protocol.appendValue(&rootValue, TAG_EMS_REQ_POWER_HOME);
protocol.appendValue(&rootValue, TAG_EMS_REQ_POWER_GRID);
protocol.appendValue(&rootValue, TAG_EMS_REQ_POWER_ADD);
protocol.appendValue(&rootValue, TAG_EMS_REQ_AUTARKY);
protocol.appendValue(&rootValue, TAG_EMS_REQ_SELF_CONSUMPTION);
protocol.appendValue(&rootValue, TAG_EMS_REQ_COUPLING_MODE);
protocol.appendValue(&rootValue, TAG_EMS_REQ_GET_IDLE_PERIODS);
// request battery information
SRscpValue batteryContainer;
protocol.createContainerValue(&batteryContainer, TAG_BAT_REQ_DATA);
protocol.appendValue(&batteryContainer, TAG_BAT_INDEX, (uint8_t)0);
protocol.appendValue(&batteryContainer, TAG_BAT_REQ_RSOC);
protocol.appendValue(&batteryContainer, TAG_BAT_REQ_MODULE_VOLTAGE);
protocol.appendValue(&batteryContainer, TAG_BAT_REQ_CURRENT);
protocol.appendValue(&batteryContainer, TAG_BAT_REQ_CHARGE_CYCLES);
protocol.appendValue(&batteryContainer, TAG_BAT_REQ_TRAINING_MODE);
protocol.appendValue(&rootValue, batteryContainer);
protocol.destroyValueData(batteryContainer);
// PVI (PV MPP-Tracker / Strings)
SRscpValue PVIContainer;
protocol.createContainerValue(&PVIContainer, TAG_PVI_REQ_DATA);
protocol.appendValue(&PVIContainer, TAG_PVI_INDEX, (uint8_t)0);
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_ON_GRID);
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_SYSTEM_MODE);
if (PVI_TRACKER == 2)
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_POWER, (uint8_t)1);
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_POWER, (uint8_t)0);
if (PVI_TRACKER == 2)
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_VOLTAGE, (uint8_t)1);
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_VOLTAGE, (uint8_t)0);
if (PVI_TRACKER == 2)
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_CURRENT, (uint8_t)1);
protocol.appendValue(&PVIContainer, TAG_PVI_REQ_DC_CURRENT, (uint8_t)0);
protocol.appendValue(&rootValue, PVIContainer);
protocol.destroyValueData(PVIContainer);
// PM
SRscpValue PMContainer;
protocol.createContainerValue(&PMContainer, TAG_PM_REQ_DATA);
protocol.appendValue(&PMContainer, TAG_PM_INDEX, (uint8_t)0);
protocol.appendValue(&PMContainer, TAG_PM_REQ_DEVICE_STATE);
protocol.appendValue(&PMContainer, TAG_PM_REQ_ACTIVE_PHASES);
protocol.appendValue(&PMContainer, TAG_PM_REQ_POWER_L1);
protocol.appendValue(&PMContainer, TAG_PM_REQ_POWER_L2);
protocol.appendValue(&PMContainer, TAG_PM_REQ_POWER_L3);
protocol.appendValue(&PMContainer, TAG_PM_REQ_VOLTAGE_L1);
protocol.appendValue(&PMContainer, TAG_PM_REQ_VOLTAGE_L2);
protocol.appendValue(&PMContainer, TAG_PM_REQ_VOLTAGE_L3);
protocol.appendValue(&rootValue, PMContainer);
protocol.destroyValueData(PMContainer);
}
// create buffer frame to send data to the S10
protocol.createFrameAsBuffer(frameBuffer, rootValue.data, rootValue.length, true); // true to calculate CRC on for transfer
// the root value object should be destroyed after the data is copied into the frameBuffer and is not needed anymore
protocol.destroyValueData(rootValue);
return 0;
}
int handleResponseValue(RscpProtocol *protocol, SRscpValue *response) {
// check if any of the response has the error flag set and react accordingly
if(response->dataType == RSCP::eTypeError) {
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(response);
printf("Tag 0x%08X received error code %u.\n", response->tag, uiErrorCode);
return -1;
}
// check the SRscpValue TAG to detect which response it is
switch(response->tag) {
case TAG_RSCP_AUTHENTICATION:
{
// It is possible to check the response->dataType value to detect correct data type
// and call the correct function. If data type is known,
// the correct function can be called directly like in this case.
uint8_t ucAccessLevel = protocol->getValueAsUChar8(response);
if(ucAccessLevel > 0) {
iAuthenticated = 1;
}
printf("RSCP authentitication level %i\n", ucAccessLevel);
break;
}
case TAG_EMS_POWER_PV:
{
// response for TAG_EMS_REQ_POWER_PV
int32_t iPower = protocol->getValueAsInt32(response);
mainJSONObject["power"]["pv"] = iPower;
break;
}
case TAG_EMS_POWER_BAT:
{
// response for TAG_EMS_REQ_POWER_BAT
int32_t iPower = protocol->getValueAsInt32(response);
mainJSONObject["power"]["bat"] = iPower;
break;
}
case TAG_EMS_POWER_HOME:
{
// response for TAG_EMS_REQ_POWER_HOME
int32_t iPower = protocol->getValueAsInt32(response);
mainJSONObject["power"]["home"] = iPower;
break;
}
case TAG_EMS_POWER_GRID:
{
// response for TAG_EMS_REQ_POWER_GRID
int32_t iPower = protocol->getValueAsInt32(response);
mainJSONObject["power"]["grid"] = iPower;
break;
}
case TAG_EMS_POWER_ADD:
{
// response for TAG_EMS_REQ_POWER_ADD
int32_t iPower = protocol->getValueAsInt32(response);
mainJSONObject["power"]["add"] = iPower;
break;
}
case TAG_EMS_AUTARKY:
{
// response for TAG_EMS_REQ_AUTARKY
float iPower = protocol->getValueAsFloat32(response);
mainJSONObject["meta"]["autarky"] = iPower;
break;
}
case TAG_EMS_SELF_CONSUMPTION:
{
// response for TAG_EMS_SELF_CONSUMPTION
float iPower = protocol->getValueAsFloat32(response);
mainJSONObject["meta"]["consumption"] = iPower;
break;
}
case TAG_EMS_COUPLING_MODE:
{
// response for TAG_EMS_COUPLING_MODE
uint8_t iPower = protocol->getValueAsUChar8(response);
mainJSONObject["meta"]["operation_mode"] = iPower;
break;
}
case TAG_INFO_TIME:
{
// response for TAG_INFO_REQ_TIME
gotData = true;
int32_t unixTimestamp = protocol->getValueAsInt32(response);
if (unixTimestamp == 0) {
exit(EXIT_FAILURE);
}
mainJSONObject["meta"]["timestamp"] = unixTimestamp;
break;
}
case TAG_INFO_SERIAL_NUMBER:
{
std::string serialNumber = protocol->getValueAsString(response);
strcpy(TAG_EMS_OUT_SERIAL_NUMBER, serialNumber.c_str());
mainJSONObject["meta"]["serial_number"] = TAG_EMS_OUT_SERIAL_NUMBER;
break;
}
case TAG_PM_DATA:
{
// resposne for TAG_PM_REQ_DATA
uint8_t ucPMIndex = 0;
std::vector<SRscpValue> PMData = protocol->getValueAsContainer(response);
for (size_t i = 0; i < PMData.size(); ++i) {
if(PMData[i].dataType == RSCP::eTypeError) {
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&PMData[i]);
printf("Tag 0x%08X received error code %u.\n", PMData[i].tag, uiErrorCode);
return -1;
}
// check each battery sub tag
switch(PMData[i].tag) {
case TAG_PM_INDEX:
{
ucPMIndex = protocol->getValueAsUChar8(&PMData[i]);
break;
}
case TAG_PM_DEVICE_STATE:
{
// response for TAG_PM_REQ_DEVICE_STATE
bool devState = protocol->getValueAsBool(&PMData[i]);
mainJSONObject["pm"]["lm0_state"] = devState;
break;
}
case TAG_PM_ACTIVE_PHASES:
{
// response for TAG_PM_REQ_ACTIVE_PHASES
int32_t activePhases = protocol->getValueAsInt32(&PMData[i]);
mainJSONObject["pm"]["active_phases"] = activePhases;
break;
}
case TAG_PM_POWER_L1:
{
// response for TAG_PM_POWER_L1
double iPower = protocol->getValueAsDouble64(&PMData[i]);
mainJSONObject["pm"]["power1"] = iPower;
break;
}
case TAG_PM_POWER_L2:
{
// response for TAG_PM_POWER_L2
double iPower = protocol->getValueAsDouble64(&PMData[i]);
mainJSONObject["pm"]["power2"] = iPower;
break;
}
case TAG_PM_POWER_L3:
{
// response for TAG_PM_POWER_L3
double iPower = protocol->getValueAsDouble64(&PMData[i]);
mainJSONObject["pm"]["power3"] = iPower;
break;
}
case TAG_PM_VOLTAGE_L1:
{
// response for TAG_PM_VOLTAGE_L1
float iPower = protocol->getValueAsFloat32(&PMData[i]);
mainJSONObject["pm"]["voltage1"] = iPower;
break;
}
case TAG_PM_VOLTAGE_L2:
{
// response for TAG_PM_VOLTAGE_L2
float iPower = protocol->getValueAsFloat32(&PMData[i]);
mainJSONObject["pm"]["voltage2"] = iPower;
break;
}
case TAG_PM_VOLTAGE_L3:
{
// response for TAG_PM_VOLTAGE_L3
float iPower = protocol->getValueAsFloat32(&PMData[i]);
mainJSONObject["pm"]["voltage3"] = iPower;
break;
}
// ...
default:
// default behaviour
printf("Unknown PM tag %08X\n", response->tag);
break;
}
}
protocol->destroyValueData(PMData);
break;
}
case TAG_BAT_DATA:
{
// resposne for TAG_BAT_REQ_DATA
uint8_t ucBatteryIndex = 0;
std::vector<SRscpValue> batteryData = protocol->getValueAsContainer(response);
for (size_t i = 0; i < batteryData.size(); ++i) {
if(batteryData[i].dataType == RSCP::eTypeError) {
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&batteryData[i]);
printf("Tag 0x%08X received error code %u.\n", batteryData[i].tag, uiErrorCode);
return -1;
}
// check each battery sub tag
switch(batteryData[i].tag) {
case TAG_BAT_INDEX:
{
ucBatteryIndex = protocol->getValueAsUChar8(&batteryData[i]);
break;
}
case TAG_BAT_RSOC:
{
// response for TAG_BAT_REQ_RSOC
float fSOC = protocol->getValueAsFloat32(&batteryData[i]);
mainJSONObject["battery"]["charge"] = fSOC;
break;
}
case TAG_BAT_MODULE_VOLTAGE:
{
// response for TAG_BAT_REQ_MODULE_VOLTAGE
float fVoltage = protocol->getValueAsFloat32(&batteryData[i]);
mainJSONObject["battery"]["voltage"] = fVoltage;
break;
}
case TAG_BAT_CURRENT:
{
// response for TAG_BAT_REQ_CURRENT
float fVoltage = protocol->getValueAsFloat32(&batteryData[i]);
mainJSONObject["battery"]["current"] = fVoltage;
break;
}
case TAG_BAT_CHARGE_CYCLES: { // response for TAG_BAT_CHARGE_CYCLES
uint32_t bCycles = protocol->getValueAsUInt32(&batteryData[i]);
mainJSONObject["battery"]["cycles"] = bCycles;
break;
}
case TAG_BAT_TRAINING_MODE:
{
uint32_t trainingMode = protocol->getValueAsUChar8(&batteryData[i]);
mainJSONObject["battery"]["training"] = trainingMode;
break;
}
// ...
default:
// default behaviour
printf("Unknown battery tag %08X\n", response->tag);
break;
}
}
protocol->destroyValueData(batteryData);
break;
}
case TAG_EMS_GET_IDLE_PERIODS:
{
std::vector<SRscpValue> EMSIdlePeriods = protocol->getValueAsContainer(response);
for (size_t i = 0; i < EMSIdlePeriods.size(); ++i)
{
uint8_t idlePeriodDay;
uint8_t idlePeriodType;
uint8_t idlePeriodStartHour;
uint8_t idlePeriodStartMinute;
uint8_t idlePeriodEndHour;
uint8_t idlePeriodEndMinute;
bool idlePeriodActive;
if (EMSIdlePeriods[i].dataType == RSCP::eTypeError)
{
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&EMSIdlePeriods[i]);
printf("Tag 0x%08X received error code %u.\n", EMSIdlePeriods[i].tag, uiErrorCode);
return -1;
}
switch (EMSIdlePeriods[i].tag)
{
case TAG_EMS_IDLE_PERIOD:
{
std::vector<SRscpValue> container = protocol->getValueAsContainer(&EMSIdlePeriods[i]);
for (size_t n = 0; n < container.size(); n++)
{
if (container[n].dataType == RSCP::eTypeError)
{
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&container[n]);
printf("Tag 0x%08X received error code %u.\n", container[n].tag, uiErrorCode);
return -1;
}
switch (container[n].tag) {
case TAG_EMS_IDLE_PERIOD_TYPE:
{
idlePeriodType = protocol->getValueAsUChar8(&container[n]);
break;
}
case TAG_EMS_IDLE_PERIOD_ACTIVE:
{
idlePeriodActive = protocol->getValueAsBool(&container[n]);
break;
}
case TAG_EMS_IDLE_PERIOD_DAY:
{
idlePeriodDay = protocol->getValueAsUChar8(&container[n]);
break;
}
case TAG_EMS_IDLE_PERIOD_START:
{
std::vector<SRscpValue> container2 = protocol->getValueAsContainer(&container[n]);
for (size_t o = 0; o < container2.size(); o++)
{
if (container2[o].dataType == RSCP::eTypeError)
{
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&container2[o]);
printf("Tag 0x%08X received error code %u.\n", container2[o].tag, uiErrorCode);
return -1;
}
else if (container2[o].tag == TAG_EMS_IDLE_PERIOD_HOUR)
{
idlePeriodStartHour = protocol->getValueAsUChar8(&container2[o]);
}
else if (container2[o].tag == TAG_EMS_IDLE_PERIOD_MINUTE)
{
idlePeriodStartMinute = protocol->getValueAsUChar8(&container2[o]);
}
}
protocol->destroyValueData(container2);
break;
}
case TAG_EMS_IDLE_PERIOD_END:
{
std::vector<SRscpValue> container2 = protocol->getValueAsContainer(&container[n]);
for (size_t o = 0; o < container2.size(); o++)
{
if (container2[o].dataType == RSCP::eTypeError)
{
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&container2[o]);
printf("Tag 0x%08X received error code %u.\n", container2[o].tag, uiErrorCode);
return -1;
}
else if (container2[o].tag == TAG_EMS_IDLE_PERIOD_HOUR)
{
idlePeriodEndHour = protocol->getValueAsUChar8(&container2[o]);
}
else if (container2[o].tag == TAG_EMS_IDLE_PERIOD_MINUTE)
{
idlePeriodEndMinute = protocol->getValueAsUChar8(&container2[o]);
}
}
protocol->destroyValueData(container2);
break;
}
default:
{
printf("Found unknown tag 0x%08X on iteration {%i}{%i}\n", container[n].tag, i, n);
break;
}
}
}
protocol->destroyValueData(container);
break;
}
default:
{
printf("Unknown EMS Idle Period tag 0x%08X -> 0x%08X\n", response->tag, EMSIdlePeriods[i].tag);
break;
}
}
std::string name;
if (idlePeriodType == 0) {
name = "charge";
} else {
name = "discharge";
}
name = std::to_string(idlePeriodDay) + "_" + name;
mainJSONObject["idle_block"][name]["day"] = idlePeriodDay;
mainJSONObject["idle_block"][name]["active"] = idlePeriodActive;
mainJSONObject["idle_block"][name]["type"] = idlePeriodType;
mainJSONObject["idle_block"][name]["start"] = std::to_string(idlePeriodStartHour) + ":" + std::to_string(idlePeriodStartMinute);
mainJSONObject["idle_block"][name]["end"] = std::to_string(idlePeriodEndHour) + ":" + std::to_string(idlePeriodEndMinute);
}
protocol->destroyValueData(EMSIdlePeriods);
break;
}
case TAG_PVI_DATA:
{
// resposne for TAG_PVI_REQ_DATA
uint8_t ucPVIIndex = 0;
std::vector<SRscpValue> PVIData = protocol->getValueAsContainer(response);
for (size_t i = 0; i < PVIData.size(); ++i)
{
if (PVIData[i].dataType == RSCP::eTypeError)
{
// handle error for example access denied errors
uint32_t uiErrorCode = protocol->getValueAsUInt32(&PVIData[i]);
printf("Tag 0x%08X received error code %u.\n", PVIData[i].tag, uiErrorCode);
return -1;
}
// check each battery sub tag
switch (PVIData[i].tag)
{
case TAG_PVI_INDEX:
{
ucPVIIndex = protocol->getValueAsUChar8(&PVIData[i]);
break;
}
case TAG_PVI_SYSTEM_MODE:
{
uint8_t systemMode = protocol->getValueAsUChar8(&PVIData[i]);
mainJSONObject["pvi"]["system_mode"] = systemMode;
break;
}
case TAG_PVI_ON_GRID:
{
// response for TAG_PVI_REQ_ON_GRID
bool onGrid = protocol->getValueAsBool(&PVIData[i]);
mainJSONObject["pvi"]["on_grid"] = onGrid;
break;
}
case TAG_PVI_DC_POWER:
{
int index = -1;
float TAG_OUT_PVI_DC_POWER = 0;
std::vector<SRscpValue> container = protocol->getValueAsContainer(&PVIData[i]);
for (size_t n = 0; n < container.size(); n++)
{
if ((container[n].tag == TAG_PVI_INDEX))
{
index = protocol->getValueAsUInt16(&container[n]);
}
else if ((container[n].tag == TAG_PVI_VALUE))
{
TAG_OUT_PVI_DC_POWER = protocol->getValueAsFloat32(&container[n]);
if (index == 0)
{
mainJSONObject["pvi"]["dc0_power"] = TAG_OUT_PVI_DC_POWER;
}
else if (index == 1)
{
mainJSONObject["pvi"]["dc1_power"] = TAG_OUT_PVI_DC_POWER;
}
}
}
protocol->destroyValueData(container);
break;
}
case TAG_PVI_DC_VOLTAGE:
{
int index = -1;
float TAG_OUT_PVI_DC_VOLTAGE = 0;
std::vector<SRscpValue> container = protocol->getValueAsContainer(&PVIData[i]);
for (size_t n = 0; n < container.size(); n++)
{
if ((container[n].tag == TAG_PVI_INDEX))
{
index = protocol->getValueAsUInt16(&container[n]);
}
else if ((container[n].tag == TAG_PVI_VALUE))
{
TAG_OUT_PVI_DC_VOLTAGE = protocol->getValueAsFloat32(&container[n]);
if (index == 0)
{
mainJSONObject["pvi"]["dc0_voltage"] = TAG_OUT_PVI_DC_VOLTAGE;
}
if (index == 1)
{
mainJSONObject["pvi"]["dc1_voltage"] = TAG_OUT_PVI_DC_VOLTAGE;
}
}
}
protocol->destroyValueData(container);
break;
}
case TAG_PVI_DC_CURRENT:
{
int index = -1;
float TAG_OUT_PVI_DC_CURRENT = 0;
std::vector<SRscpValue> container = protocol->getValueAsContainer(&PVIData[i]);
for (size_t n = 0; n < container.size(); n++)
{
if ((container[n].tag == TAG_PVI_INDEX))
{
index = protocol->getValueAsUInt16(&container[n]);
}
else if ((container[n].tag == TAG_PVI_VALUE))
{
TAG_OUT_PVI_DC_CURRENT = protocol->getValueAsFloat32(&container[n]);
if (index == 0)
{
mainJSONObject["pvi"]["dc0_current"] = TAG_OUT_PVI_DC_CURRENT;
}
if (index == 1)
{
mainJSONObject["pvi"]["dc1_current"] = TAG_OUT_PVI_DC_CURRENT;
}
}
}
protocol->destroyValueData(container);
break;
}
// ...
default:
// default behaviour
printf("Unknown PVI tag %08X\n", response->tag);
break;
}
}
protocol->destroyValueData(PVIData);
break;
}
// ...
default:
// default behavior
printf("Unknown tag %08X\n", response->tag);
break;
}
}
static int processReceiveBuffer(const unsigned char * ucBuffer, int iLength)
{
RscpProtocol protocol;
SRscpFrame frame;
int iResult = protocol.parseFrame(ucBuffer, iLength, &frame);
if(iResult < 0) {
// check if frame length error occured
// in that case the full frame length was not received yet
// and the receive function must get more data
if(iResult == RSCP::ERR_INVALID_FRAME_LENGTH) {
return 0;
}
// otherwise a not recoverable error occured and the connection can be closed
else {
return iResult;
}
}
int iProcessedBytes = iResult;
// process each SRscpValue struct seperately
for(unsigned int i; i < frame.data.size(); i++) {
handleResponseValue(&protocol, &frame.data[i]);
}
// Write data to json file if data was correctly received
if (gotData) {
std::ofstream o(TARGET_FILE);
o << std::setw(4) << mainJSONObject << std::endl;
gotData = false;
gotDataFailed = 0;
} else {
// Increase failure counter
++gotDataFailed;
// If failure appeared multiple times in a row we have a basic communication problem with E3DC
// Exit application. Start script should restart this program shortly after exit
if (gotDataFailed > 10) {
printf("Failed to receive data multiple times. Exiting with error");
exit(EXIT_FAILURE);
}
}
// destroy frame data and free memory
protocol.destroyFrameData(frame);
// returned processed amount of bytes
return iProcessedBytes;
}
static void receiveLoop(bool & bStopExecution)
{
//--------------------------------------------------------------------------------------------------------------
// RSCP Receive Frame Block Data
//--------------------------------------------------------------------------------------------------------------
// setup a static dynamic buffer which is dynamically expanded (re-allocated) on demand
// the data inside this buffer is not released when this function is left
static int iReceivedBytes = 0;
static std::vector<uint8_t> vecDynamicBuffer;
// check how many RSCP frames are received, must be at least 1
// multiple frames can only occur in this example if one or more frames are received with a big time delay
// this should usually not occur but handling this is shown in this example
int iReceivedRscpFrames = 0;
while(!bStopExecution && ((iReceivedBytes > 0) || iReceivedRscpFrames == 0))
{
// check and expand buffer
if((vecDynamicBuffer.size() - iReceivedBytes) < 4096) {
// check maximum size
if(vecDynamicBuffer.size() > RSCP_MAX_FRAME_LENGTH) {
// something went wrong and the size is more than possible by the RSCP protocol
printf("Maximum buffer size exceeded %i\n", vecDynamicBuffer.size());
bStopExecution = true;
break;
}
// increase buffer size by 4096 bytes each time the remaining size is smaller than 4096
vecDynamicBuffer.resize(vecDynamicBuffer.size() + 4096);
}
// receive data
int iResult = SocketRecvData(iSocket, &vecDynamicBuffer[0] + iReceivedBytes, vecDynamicBuffer.size() - iReceivedBytes);
if(iResult < 0)
{
// check errno for the error code to detect if this is a timeout or a socket error
if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) {
// receive timed out -> continue with re-sending the initial block
printf("Response receive timeout (retry)\n");
break;
}
// socket error -> check errno for failure code if needed
printf("Socket receive error. errno %i\n", errno);
bStopExecution = true;
break;
}
else if(iResult == 0)
{
// connection was closed regularly by peer
// if this happens on startup each time the possible reason is
// wrong AES password or wrong network subnet (adapt hosts.allow file required)
printf("Connection closed by peer\n");
bStopExecution = true;
break;
}
// increment amount of received bytes
iReceivedBytes += iResult;
// process all received frames
while (!bStopExecution)
{
// round down to a multiple of AES_BLOCK_SIZE
int iLength = ROUNDDOWN(iReceivedBytes, AES_BLOCK_SIZE);
// if not even 32 bytes were received then the frame is still incomplete
if(iLength == 0) {
break;
}
// resize temporary decryption buffer
std::vector<uint8_t> decryptionBuffer;
decryptionBuffer.resize(iLength);
// initialize encryption sequence IV value with value of previous block
aesDecrypter.SetIV(ucDecryptionIV, AES_BLOCK_SIZE);
// decrypt data from vecDynamicBuffer to temporary decryptionBuffer
aesDecrypter.Decrypt(&vecDynamicBuffer[0], &decryptionBuffer[0], iLength / AES_BLOCK_SIZE);
// data was received, check if we received all data
int iProcessedBytes = processReceiveBuffer(&decryptionBuffer[0], iLength);
if(iProcessedBytes < 0) {
// an error occured;
printf("Error parsing RSCP frame: %i\n", iProcessedBytes);
// stop execution as the data received is not RSCP data
bStopExecution = true;
break;
}
else if(iProcessedBytes > 0) {
// round up the processed bytes as iProcessedBytes does not include the zero padding bytes
iProcessedBytes = ROUNDUP(iProcessedBytes, AES_BLOCK_SIZE);
// store the IV value from encrypted buffer for next block decryption
memcpy(ucDecryptionIV, &vecDynamicBuffer[0] + iProcessedBytes - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
// move the encrypted data behind the current frame data (if any received) to the front
memcpy(&vecDynamicBuffer[0], &vecDynamicBuffer[0] + iProcessedBytes, vecDynamicBuffer.size() - iProcessedBytes);
// decrement the total received bytes by the amount of processed bytes
iReceivedBytes -= iProcessedBytes;
// increment a counter that a valid frame was received and
// continue parsing process in case a 2nd valid frame is in the buffer as well
iReceivedRscpFrames++;
}
else {
// iProcessedBytes is 0
// not enough data of the next frame received, go back to receive mode if iReceivedRscpFrames == 0
// or transmit mode if iReceivedRscpFrames > 0
break;
}
}
}
}
void process_mem_usage(double &vm_usage, double &resident_set)
{
vm_usage = 0.0;
resident_set = 0.0;
// the two fields we want
unsigned long vsize;
long rss;
{
std::string ignore;
std::ifstream ifs("/proc/self/stat", std::ios_base::in);
ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> vsize >> rss;
}
long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage = vsize / 1024.0;
resident_set = rss * page_size_kb;
}
static void mainLoop(void)
{
RscpProtocol protocol;
bool bStopExecution = false;
while(!bStopExecution)
{
//--------------------------------------------------------------------------------------------------------------
// RSCP Transmit Frame Block Data
//--------------------------------------------------------------------------------------------------------------
SRscpFrameBuffer frameBuffer;
memset(&frameBuffer, 0, sizeof(frameBuffer));
// create an RSCP frame with requests to some example data
createRequestExample(&frameBuffer);
// check that frame data was created
if(frameBuffer.dataLength > 0)
{
// resize temporary encryption buffer to a multiple of AES_BLOCK_SIZE
std::vector<uint8_t> encryptionBuffer;
encryptionBuffer.resize(ROUNDUP(frameBuffer.dataLength, AES_BLOCK_SIZE));
// zero padding for data above the desired length
memset(&encryptionBuffer[0] + frameBuffer.dataLength, 0, encryptionBuffer.size() - frameBuffer.dataLength);
// copy desired data length
memcpy(&encryptionBuffer[0], frameBuffer.data, frameBuffer.dataLength);
// set continues encryption IV
aesEncrypter.SetIV(ucEncryptionIV, AES_BLOCK_SIZE);
// start encryption from encryptionBuffer to encryptionBuffer, blocks = encryptionBuffer.size() / AES_BLOCK_SIZE
aesEncrypter.Encrypt(&encryptionBuffer[0], &encryptionBuffer[0], encryptionBuffer.size() / AES_BLOCK_SIZE);
// save new IV for next encryption block
memcpy(ucEncryptionIV, &encryptionBuffer[0] + encryptionBuffer.size() - AES_BLOCK_SIZE, AES_BLOCK_SIZE);
// send data on socket
int iResult = SocketSendData(iSocket, &encryptionBuffer[0], encryptionBuffer.size());
if(iResult < 0) {
printf("Socket send error %i. errno %i\n", iResult, errno);
bStopExecution = true;
}
else {
// go into receive loop and wait for response
receiveLoop(bStopExecution);
}
}
// free frame buffer memory
protocol.destroyFrameData(&frameBuffer);
// Print periodic statistics about memory consumption (yeah, looks like we could have a memory-leak)
if (printStats >= 300) {
// Get current memory consumption
double vm, rss;
process_mem_usage(vm, rss);
printStats = 0;
mainJSONObject["prog"]["mem_vm"] = vm;
mainJSONObject["prog"]["mem_rss"] = rss;
} else {
++printStats;
}
// main loop sleep / cycle time before next request
sleep(FETCH_INTERVAL);
}
}
int main(int argc, char *argv[])
{
// endless application which re-connections to server on connection lost
while(true)
{
// connect to server
printf("Connecting to server %s:%i\n", SERVER_IP, SERVER_PORT);
iSocket = SocketConnect(SERVER_IP, SERVER_PORT);
if(iSocket < 0) {
printf("Connection failed\n");
sleep(1);
continue;
}
printf("Connected successfully\n");
// reset authentication flag
iAuthenticated = 0;
// create AES key and set AES parameters
{
// initialize AES encryptor and decryptor IV
memset(ucDecryptionIV, 0xff, AES_BLOCK_SIZE);
memset(ucEncryptionIV, 0xff, AES_BLOCK_SIZE);
// limit password length to AES_KEY_SIZE
int iPasswordLength = strlen(AES_PASSWORD);
if(iPasswordLength > AES_KEY_SIZE)
iPasswordLength = AES_KEY_SIZE;
// copy up to 32 bytes of AES key password
uint8_t ucAesKey[AES_KEY_SIZE];
memset(ucAesKey, 0xff, AES_KEY_SIZE);
memcpy(ucAesKey, AES_PASSWORD, iPasswordLength);
// set encryptor and decryptor parameters
aesDecrypter.SetParameters(AES_KEY_SIZE * 8, AES_BLOCK_SIZE * 8);
aesEncrypter.SetParameters(AES_KEY_SIZE * 8, AES_BLOCK_SIZE * 8);
aesDecrypter.StartDecryption(ucAesKey);
aesEncrypter.StartEncryption(ucAesKey);
}
// enter the main transmit / receive loop
mainLoop();
// close socket connection
SocketClose(iSocket);
iSocket = -1;
}
return 0;
}