/
main.c
3339 lines (3213 loc) · 107 KB
/
main.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
//
// --------------------------------------------------------------------------
// Gurux Ltd
//
//
//
// Filename: $HeadURL: $
//
// Version: $Revision: $,
// $Date: $
// $Author: $
//
// Copyright (c) Gurux Ltd
//
//---------------------------------------------------------------------------
#include <stdio.h>
#if defined(_WIN32) || defined(_WIN64)//Windows includes
#if _MSC_VER > 1400
#include <crtdbg.h>
#endif
#include <tchar.h>
#include <conio.h>
#include <Winsock2.h> //Add support for sockets
#include <time.h>
#include <process.h>//Add support for threads
#include "../include/getopt.h"
#else //Linux includes.
#define closesocket close
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/socket.h> //Add support for sockets
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <fcntl.h>
#endif
#include "../../development/include/gxmem.h"
#include "../../development/include/dlmssettings.h"
#include "../../development/include/variant.h"
#include "../../development/include/cosem.h"
#include "../../development/include/server.h"
//Add this if you want to send notify messages.
#include "../../development/include/notify.h"
//Add support for serialization.
#include "../../development/include/gxserializer.h"
//DLMS settings.
dlmsServerSettings settings;
GX_TRACE_LEVEL trace = GX_TRACE_LEVEL_OFF;
const static char* FLAG_ID = "GRX";
//Space for client challenge.
static unsigned char C2S_CHALLENGE[64];
//Space for server challenge.
static unsigned char S2C_CHALLENGE[64];
unsigned char testMode = 1;
int socket1 = -1;
uint32_t SERIAL_NUMBER = 123456;
//TODO: Allocate space where profile generic row values are serialized.
#define PDU_MAX_PROFILE_GENERIC_COLUMN_SIZE 100
#define HDLC_HEADER_SIZE 17
#define HDLC_BUFFER_SIZE 128
#define PDU_BUFFER_SIZE 512
#define WRAPPER_BUFFER_SIZE 8 + PDU_BUFFER_SIZE
//Buffer where frames are saved.
static unsigned char frameBuff[HDLC_BUFFER_SIZE + HDLC_HEADER_SIZE];
//Buffer where PDUs are saved.
static unsigned char pduBuff[PDU_BUFFER_SIZE];
static unsigned char replyFrame[HDLC_BUFFER_SIZE + HDLC_HEADER_SIZE];
//Define server system title.
static unsigned char SERVER_SYSTEM_TITLE[8] = { 0 };
static gxByteBuffer reply;
uint32_t time_current(void)
{
//Get current time somewhere.
return (uint32_t)time(NULL);
}
uint32_t time_elapsed(void)
{
return (uint32_t)clock() / (CLOCKS_PER_SEC / 1000);
}
//Don't use clock as a name. Some compilers are using clock as reserved word.
static gxClock clock1;
static gxIecHdlcSetup hdlc;
static gxData ldn;
static gxData eventCode;
static gxData unixTime;
static gxData invocationCounter;
static gxAssociationLogicalName associationNone;
static gxAssociationLogicalName associationLow;
static gxAssociationLogicalName associationHigh;
static gxAssociationLogicalName associationHighGMac;
static gxRegister activePowerL1;
static gxScriptTable scriptTableGlobalMeterReset;
static gxScriptTable scriptTableDisconnectControl;
static gxScriptTable scriptTableActivateTestMode;
static gxScriptTable scriptTableActivateNormalMode;
static gxProfileGeneric eventLog;
static gxActionSchedule actionScheduleDisconnectOpen;
static gxActionSchedule actionScheduleDisconnectClose;
static gxPushSetup pushSetup;
static gxDisconnectControl disconnectControl;
static gxProfileGeneric loadProfile;
static gxSapAssignment sapAssignment;
//Security Setup High is for High authentication.
static gxSecuritySetup securitySetupHigh;
//Security Setup HighGMac is for GMac authentication.
static gxSecuritySetup securitySetupHighGMac;
//static gxObject* NONE_OBJECTS[] = { BASE(associationNone), BASE(ldn), BASE(sapAssignment), BASE(clock1) };
static gxObject* ALL_OBJECTS[] = { BASE(associationNone), BASE(associationLow), BASE(associationHigh), BASE(associationHighGMac), BASE(securitySetupHigh), BASE(securitySetupHighGMac),
BASE(ldn), BASE(sapAssignment), BASE(eventCode),
BASE(clock1), BASE(activePowerL1), BASE(pushSetup), BASE(scriptTableGlobalMeterReset), BASE(scriptTableDisconnectControl),
BASE(scriptTableActivateTestMode), BASE(scriptTableActivateNormalMode), BASE(loadProfile), BASE(eventLog), BASE(hdlc),
BASE(disconnectControl), BASE(actionScheduleDisconnectOpen), BASE(actionScheduleDisconnectClose), BASE(unixTime), BASE(invocationCounter)
};
////////////////////////////////////////////////////
//Define what is serialized to decrease EEPROM usage.
gxSerializerIgnore NON_SERIALIZED_OBJECTS[] = {
//Nothing is saved when authentication is not used.
IGNORE_ATTRIBUTE(BASE(associationNone), GET_ATTRIBUTE_ALL()),
//Only password is saved for low and high authentication.
IGNORE_ATTRIBUTE(BASE(associationLow), GET_ATTRIBUTE_EXCEPT(7)),
IGNORE_ATTRIBUTE(BASE(associationHigh), GET_ATTRIBUTE_EXCEPT(7)),
//Nothing is saved when authentication is not used.
IGNORE_ATTRIBUTE(BASE(associationHighGMac), GET_ATTRIBUTE_ALL()),
//Only scaler and unit are saved for all register objects.
IGNORE_ATTRIBUTE_BY_TYPE(DLMS_OBJECT_TYPE_REGISTER, GET_ATTRIBUTE(2)) };
static uint32_t executeTime = 0;
static uint16_t activePowerL1Value = 0;
typedef enum
{
//Meter is powered.
GURUX_EVENT_CODES_POWER_UP = 0x1,
//User has change the time.
GURUX_EVENT_CODES_TIME_CHANGE = 0x2,
//DST status is changed.
GURUX_EVENT_CODES_DST = 0x4,
//Push message is sent.
GURUX_EVENT_CODES_PUSH = 0x8,
//Meter makes auto connect.
GURUX_EVENT_CODES_AUTO_CONNECT = 0x10,
//User has change the password.
GURUX_EVENT_CODES_PASSWORD_CHANGED = 0x20,
//Wrong password tried 3 times.
GURUX_EVENT_CODES_WRONG_PASSWORD = 0x40,
//Disconnect control state is changed.
GURUX_EVENT_CODES_OUTPUT_RELAY_STATE = 0x80,
//User has reset the meter.
GURUX_EVENT_CODES_GLOBAL_METER_RESET = 0x100
} GURUX_EVENT_CODES;
/////////////////////////////////////////////////////////////////////////////
// Save security settings to the EEPROM.
//
// Only updated value is saved. This is done because write to EEPROM is slow
// and there is a limit how many times value can be written to the EEPROM.
/////////////////////////////////////////////////////////////////////////////
int saveSecurity()
{
int ret = 0;
const char* fileName = "security.raw";
//Save keys to own block in EEPROM.
#if _MSC_VER > 1400
FILE* f = NULL;
fopen_s(&f, fileName, "wb");
#else
FILE* f = fopen(fileName, "wb");
#endif
gxByteBuffer bb;
bb_init(&bb);
bb_capacity(&bb, 56);
if (f != NULL)
{
if ((ret = bb_set(&bb, settings.base.cipher.blockCipherKey.data, 16)) == 0 &&
(ret = bb_set(&bb, settings.base.cipher.authenticationKey.data, 16)) == 0 &&
(ret = bb_set(&bb, settings.base.kek.data, 16)) == 0 &&
//Save server IV.
(ret = bb_setUInt32(&bb, settings.base.cipher.invocationCounter)) == 0 &&
//Save last client IV.
(ret = bb_setUInt32(&bb, securitySetupHighGMac.minimumInvocationCounter)) == 0)
{
fwrite(bb.data, 1, bb.size, f);
}
bb_clear(&bb);
fclose(f);
}
else
{
printf("%s\r\n", "Failed to open keys file.");
}
return ret;
}
/////////////////////////////////////////////////////////////////////////////
// Save data to the EEPROM.
//
// Only updated value is saved. This is done because write to EEPROM is slow
// and there is a limit how many times value can be written to the EEPROM.
/////////////////////////////////////////////////////////////////////////////
int saveSettings()
{
int ret = 0;
const char* fileName = "settings.raw";
//Save keys to own block in EEPROM.
#if _MSC_VER > 1400
FILE* f = NULL;
fopen_s(&f, fileName, "wb");
#else
FILE* f = fopen(fileName, "wb");
#endif
if (f != NULL)
{
gxSerializerSettings serializerSettings;
ser_init(&serializerSettings);
serializerSettings.stream = f;
serializerSettings.ignoredAttributes = NON_SERIALIZED_OBJECTS;
serializerSettings.count = sizeof(NON_SERIALIZED_OBJECTS) / sizeof(NON_SERIALIZED_OBJECTS[0]);
ret = ser_saveObjects(&serializerSettings, ALL_OBJECTS, sizeof(ALL_OBJECTS) / sizeof(ALL_OBJECTS[0]));
fclose(f);
}
else
{
printf("%s\r\n", "Failed to open settings file.");
}
return ret;
}
//Allocate profile generic buffer.
void allocateProfileGenericBuffer(const char* fileName, uint32_t size)
{
uint32_t pos;
FILE* f = NULL;
#if _MSC_VER > 1400
fopen_s(&f, fileName, "ab");
#else
f = fopen(fileName, "ab");
#endif
if (f != NULL)
{
fseek(f, 0, SEEK_END);
if (ftell(f) == 0)
{
for (pos = 0; pos != size; ++pos)
{
if (fputc(0x00, f) != 0)
{
printf("Error Writing to %s\n", fileName);
break;
}
}
}
fclose(f);
}
}
int getProfileGenericFileName(gxProfileGeneric* pg, char* fileName)
{
int ret = hlp_getLogicalNameToString(pg->base.logicalName, fileName);
#if defined(_WIN64)
strcat(fileName, "64.raw");
#else // defined(_WIN32) || defined(__linux__)
strcat(fileName, ".raw");
#endif //defined(_WIN32) || defined(__linux__)
return ret;
}
//Returns profile generic buffer column sizes.
int getProfileGenericBufferColumnSizes(
gxProfileGeneric* pg,
DLMS_DATA_TYPE* dataTypes,
uint8_t* columnSizes,
uint16_t* rowSize)
{
int ret = 0;
uint8_t pos;
gxKey* it;
gxValueEventArg e;
ve_init(&e);
*rowSize = 0;
uint16_t size;
unsigned char type;
//Loop capture columns and get values.
for (pos = 0; pos != pg->captureObjects.size; ++pos)
{
if ((ret = arr_getByIndex(&pg->captureObjects, (uint16_t)pos, (void**)&it)) != 0)
{
break;
}
//Date time is saved in EPOCH to save space.
if (((gxObject*)it->key)->objectType == DLMS_OBJECT_TYPE_CLOCK && ((gxTarget*)it->value)->attributeIndex == 2)
{
type = DLMS_DATA_TYPE_UINT32;
size = 4;
}
else
{
e.target = (gxObject*)it->key;
e.index = ((gxTarget*)it->value)->attributeIndex;
if ((ret = cosem_getValue(&settings.base, &e)) != 0)
{
break;
}
if (bb_size(e.value.byteArr) != 0)
{
if ((ret = bb_getUInt8(e.value.byteArr, &type)) != 0)
{
break;
}
size = bb_available(e.value.byteArr);
}
else
{
type = DLMS_DATA_TYPE_NONE;
size = 0;
}
}
if (dataTypes != NULL)
{
dataTypes[pos] = type;
}
if (columnSizes != NULL)
{
columnSizes[pos] = (uint8_t)size;
}
*rowSize += (uint16_t)size;
ve_clear(&e);
}
ve_clear(&e);
return ret;
}
//Get max row count for allocated buffer.
uint16_t getProfileGenericBufferMaxRowCount(
gxProfileGeneric* pg)
{
uint16_t count = 0;
char fileName[30];
//Allocate space for load profile buffer.
getProfileGenericFileName(pg, fileName);
uint16_t rowSize = 0;
FILE* f = NULL;
#if _MSC_VER > 1400
fopen_s(&f, fileName, "r+b");
#else
f = fopen(fileName, "r+b");
#endif
if (f == NULL)
{
//Allocate space for the profile generic buffer.
allocateProfileGenericBuffer(fileName, 1024);
#if _MSC_VER > 1400
fopen_s(&f, fileName, "r+b");
#else
f = fopen(fileName, "r+b");
#endif
}
if (f != NULL)
{
getProfileGenericBufferColumnSizes(pg, NULL, NULL, &rowSize);
if (rowSize != 0)
{
fseek(f, 0L, SEEK_END);
count = (uint16_t)ftell(f);
//Decrease current index and total amount of the entries.
count -= 4;
count /= rowSize;
}
fclose(f);
}
return count;
}
//Get current row count for allocated buffer.
uint16_t getProfileGenericBufferEntriesInUse(gxProfileGeneric* pg)
{
uint16_t index = 0;
char fileName[30];
getProfileGenericFileName(pg, fileName);
FILE* f = NULL;
#if _MSC_VER > 1400
fopen_s(&f, fileName, "r+b");
#else
f = fopen(fileName, "r+b");
#endif
if (f != NULL)
{
//Load current entry index from the begin of the data.
unsigned char pduBuff[2];
gxByteBuffer pdu;
bb_attach(&pdu, pduBuff, 0, sizeof(pduBuff));
if (fread(pdu.data, 1, 2, f) == 2)
{
pdu.size = 2;
bb_getUInt16(&pdu, &index);
fseek(f, 0, SEEK_SET);
bb_empty(&pdu);
}
fclose(f);
}
return index;
}
int captureProfileGeneric(gxProfileGeneric* pg)
{
unsigned char pos;
gxKey* it;
int ret = 0;
char fileName[30];
getProfileGenericFileName(pg, fileName);
unsigned char pduBuff[PDU_MAX_PROFILE_GENERIC_COLUMN_SIZE];
gxByteBuffer pdu;
bb_attach(&pdu, pduBuff, 0, sizeof(pduBuff));
gxValueEventArg e;
ve_init(&e);
FILE* f = NULL;
#if _MSC_VER > 1400
fopen_s(&f, fileName, "r+b");
#else
f = fopen(fileName, "r+b");
#endif
if (f != NULL)
{
uint16_t dataSize = 0;
uint8_t columnSizes[10];
DLMS_DATA_TYPE dataTypes[10];
//Load current entry index from the begin of the data.
uint16_t index = 0;
if (fread(pdu.data, 1, 2, f) == 2)
{
pdu.size = 2;
bb_getUInt16(&pdu, &index);
fseek(f, 0, SEEK_SET);
bb_empty(&pdu);
}
//Current index in ring buffer.
if (pg->profileEntries != 0)
{
bb_setUInt16(&pdu, (1 + index) % (pg->profileEntries));
}
//Update how many entries is used until buffer is full.
if (ret == 0 && pg->entriesInUse != pg->profileEntries)
{
//Total amount of the entries.
++pg->entriesInUse;
}
bb_setUInt16(&pdu, (uint16_t)pg->entriesInUse);
//Update values to the EEPROM.
fwrite(pdu.data, 1, 4, f);
getProfileGenericBufferColumnSizes(pg, dataTypes, columnSizes, &dataSize);
if (index != 0 && pg->profileEntries != 0)
{
fseek(f, 4 + ((index % pg->profileEntries) * dataSize), SEEK_SET);
}
//Loop capture columns and get values.
for (pos = 0; pos != pg->captureObjects.size; ++pos)
{
if ((ret = arr_getByIndex(&pg->captureObjects, pos, (void**)&it)) != 0)
{
break;
}
bb_clear(&pdu);
//Date time is saved in EPOCH to save space.
if ((((gxObject*)it->key)->objectType == DLMS_OBJECT_TYPE_CLOCK || ((gxObject*)it->key) == BASE(unixTime)) &&
((gxTarget*)it->value)->attributeIndex == 2)
{
e.value.ulVal = time_current();
e.value.vt = DLMS_DATA_TYPE_UINT32;
fwrite(&e.value.bVal, 4, 1, f);
}
else
{
e.target = (gxObject*)it->key;
e.index = ((gxTarget*)it->value)->attributeIndex;
e.value.byteArr = &pdu;
e.value.vt = DLMS_DATA_TYPE_OCTET_STRING;
if ((ret = cosem_getValue(&settings.base, &e)) != 0)
{
break;
}
//Data type is not serialized. For that reason first byte is ignored.
fwrite(&e.value.byteArr->data[1], e.value.byteArr->size - 1, 1, f);
}
}
fclose(f);
if (ret != 0)
{
//Total amount of the entries.
--pg->entriesInUse;
}
}
return ret;
}
void updateState(uint16_t value)
{
GX_UINT16(eventCode.value) = value;
captureProfileGeneric(&eventLog);
}
///////////////////////////////////////////////////////////////////////
// Write trace to the serial port.
//
// This can be used for debugging.
///////////////////////////////////////////////////////////////////////
void GXTRACE(const char* str, const char* data)
{
//Send trace to the serial port in test mode.
if (testMode)
{
if (data == NULL)
{
printf("%s\r\n", str);
}
else
{
printf("%s %s\r\n", str, data);
}
}
}
///////////////////////////////////////////////////////////////////////
// Write trace to the serial port.
//
// This can be used for debugging.
///////////////////////////////////////////////////////////////////////
void GXTRACE_INT(const char* str, int32_t value)
{
char data[10];
sprintf(data, " %ld", value);
GXTRACE(str, data);
}
///////////////////////////////////////////////////////////////////////
// Write trace to the serial port.
//
// This can be used for debugging.
///////////////////////////////////////////////////////////////////////
void GXTRACE_LN(const char* str, uint16_t type, unsigned char* ln)
{
char buff[30];
sprintf(buff, "%d %d.%d.%d.%d.%d.%d", type, ln[0], ln[1], ln[2], ln[3], ln[4], ln[5]);
GXTRACE(str, buff);
}
///////////////////////////////////////////////////////////////////////
//Print detailed information to the serial port.
void svr_trace(const char* str, const char* data)
{
GXTRACE(str, data);
}
///////////////////////////////////////////////////////////////////////
void time_now(
gxtime* value,
unsigned char meterTime)
{
uint32_t offset = time_current();
time_initUnix(value, offset);
//If date time is wanted in meter time, not in utc time.
if (meterTime)
{
clock_utcToMeterTime(&clock1, value);
}
}
///////////////////////////////////////////////////////////////////////
//This method adds example Logical Name Association object.
///////////////////////////////////////////////////////////////////////
int addAssociationNone()
{
int ret;
const unsigned char ln[6] = { 0, 0, 40, 0, 1, 255 };
if ((ret = INIT_OBJECT(associationNone, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
{
//All objects are shown also without authentication.
OA_ATTACH(associationNone.objectList, ALL_OBJECTS);
//Uncomment this if you want to show only part of the objects without authentication.
//OA_ATTACH(associationNone.objectList, NONE_OBJECTS);
associationNone.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_NONE;
associationNone.clientSAP = 0x10;
//Max PDU is half of PDU size. This is for demonstration purposes only.
associationNone.xDLMSContextInfo.maxSendPduSize = associationNone.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE / 2;
associationNone.xDLMSContextInfo.conformance = DLMS_CONFORMANCE_GET;
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds example Logical Name Association object.
///////////////////////////////////////////////////////////////////////
int addAssociationLow()
{
int ret;
const unsigned char ln[6] = { 0, 0, 40, 0, 2, 255 };
if ((ret = INIT_OBJECT(associationLow, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
{
//Only Logical Device Name is add to this Association View.
OA_ATTACH(associationLow.objectList, ALL_OBJECTS);
associationLow.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_LOW;
associationLow.clientSAP = 0x11;
associationLow.xDLMSContextInfo.maxSendPduSize = associationLow.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
associationLow.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
DLMS_CONFORMANCE_SET |
DLMS_CONFORMANCE_SELECTIVE_ACCESS |
DLMS_CONFORMANCE_ACTION |
DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
DLMS_CONFORMANCE_GET);
bb_addString(&associationLow.secret, "Gurux");
associationLow.securitySetup = NULL;
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds example Logical Name Association object for High authentication.
// UA in Indian standard.
///////////////////////////////////////////////////////////////////////
int addAssociationHigh()
{
int ret;
//Dedicated key.
static unsigned char CYPHERING_INFO[20] = { 0 };
const unsigned char ln[6] = { 0, 0, 40, 0, 3, 255 };
if ((ret = INIT_OBJECT(associationHigh, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
{
associationHigh.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_HIGH;
OA_ATTACH(associationHigh.objectList, ALL_OBJECTS);
BB_ATTACH(associationHigh.xDLMSContextInfo.cypheringInfo, CYPHERING_INFO, 0);
associationHigh.clientSAP = 0x12;
associationHigh.xDLMSContextInfo.maxSendPduSize = associationHigh.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
associationHigh.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
DLMS_CONFORMANCE_SET |
DLMS_CONFORMANCE_SELECTIVE_ACCESS |
DLMS_CONFORMANCE_ACTION |
DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
DLMS_CONFORMANCE_GET);
bb_addString(&associationHigh.secret, "Gurux");
#ifndef DLMS_IGNORE_OBJECT_POINTERS
associationHigh.securitySetup = &securitySetupHigh;
#else
memcpy(associationHigh.securitySetupReference, securitySetupHigh.base.logicalName, 6);
#endif //DLMS_IGNORE_OBJECT_POINTERS
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds example Logical Name Association object for GMAC High authentication.
// UA in Indian standard.
///////////////////////////////////////////////////////////////////////
int addAssociationHighGMac()
{
int ret;
const unsigned char ln[6] = { 0, 0, 40, 0, 4, 255 };
if ((ret = INIT_OBJECT(associationHighGMac, DLMS_OBJECT_TYPE_ASSOCIATION_LOGICAL_NAME, ln)) == 0)
{
associationHighGMac.authenticationMechanismName.mechanismId = DLMS_AUTHENTICATION_HIGH_GMAC;
OA_ATTACH(associationHighGMac.objectList, ALL_OBJECTS);
associationHighGMac.clientSAP = 0x1;
associationHighGMac.xDLMSContextInfo.maxSendPduSize = associationHighGMac.xDLMSContextInfo.maxReceivePduSize = PDU_BUFFER_SIZE;
associationHighGMac.xDLMSContextInfo.conformance = (DLMS_CONFORMANCE)(DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_ACTION |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_SET_OR_WRITE |
DLMS_CONFORMANCE_BLOCK_TRANSFER_WITH_GET_OR_READ |
DLMS_CONFORMANCE_SET |
DLMS_CONFORMANCE_SELECTIVE_ACCESS |
DLMS_CONFORMANCE_ACTION |
DLMS_CONFORMANCE_MULTIPLE_REFERENCES |
DLMS_CONFORMANCE_GET);
//GMAC authentication don't need password.
#ifndef DLMS_IGNORE_OBJECT_POINTERS
associationHighGMac.securitySetup = &securitySetupHighGMac;
#else
memcpy(associationHighGMac.securitySetupReference, securitySetupHigh.base.logicalName, 6);
#endif //DLMS_IGNORE_OBJECT_POINTERS
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds security setup object for High authentication.
///////////////////////////////////////////////////////////////////////
int addSecuritySetupHigh()
{
int ret;
//Define client system title.
static unsigned char CLIENT_SYSTEM_TITLE[8] = { 0 };
const unsigned char ln[6] = { 0, 0, 43, 0, 1, 255 };
if ((ret = INIT_OBJECT(securitySetupHigh, DLMS_OBJECT_TYPE_SECURITY_SETUP, ln)) == 0)
{
BB_ATTACH(securitySetupHigh.serverSystemTitle, SERVER_SYSTEM_TITLE, 8);
BB_ATTACH(securitySetupHigh.clientSystemTitle, CLIENT_SYSTEM_TITLE, 8);
securitySetupHigh.securityPolicy = DLMS_SECURITY_POLICY_NOTHING;
securitySetupHigh.securitySuite = DLMS_SECURITY_SUITE_V0;
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds security setup object for High GMAC authentication.
///////////////////////////////////////////////////////////////////////
int addSecuritySetupHighGMac()
{
int ret;
//Define client system title.
static unsigned char CLIENT_SYSTEM_TITLE[8] = { 0 };
const unsigned char ln[6] = { 0, 0, 43, 0, 2, 255 };
if ((ret = INIT_OBJECT(securitySetupHighGMac, DLMS_OBJECT_TYPE_SECURITY_SETUP, ln)) == 0)
{
BB_ATTACH(securitySetupHighGMac.serverSystemTitle, SERVER_SYSTEM_TITLE, 8);
BB_ATTACH(securitySetupHighGMac.clientSystemTitle, CLIENT_SYSTEM_TITLE, 8);
//Only Authenticated encrypted connections are allowed.
securitySetupHighGMac.securityPolicy = DLMS_SECURITY_POLICY_AUTHENTICATED_ENCRYPTED;
securitySetupHighGMac.securitySuite = DLMS_SECURITY_SUITE_V0;
securitySetupHighGMac.minimumInvocationCounter = 1;
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//Add SAP Assignment object.
///////////////////////////////////////////////////////////////////////
int addSapAssignment()
{
int ret;
const unsigned char ln[6] = { 0, 0, 41, 0, 0, 255 };
if ((ret = INIT_OBJECT(sapAssignment, DLMS_OBJECT_TYPE_SAP_ASSIGNMENT, ln)) == 0)
{
char tmp[17];
gxSapItem* it = (gxSapItem*)gxmalloc(sizeof(gxSapItem));
bb_init(&it->name);
ret = sprintf(tmp, "%s%.13lu", FLAG_ID, SERIAL_NUMBER);
bb_addString(&it->name, tmp);
it->id = 1;
ret = arr_push(&sapAssignment.sapAssignmentList, it);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//Add Logical Device Name. 123456 is meter serial number.
///////////////////////////////////////////////////////////////////////
// COSEM Logical Device Name is defined as an octet-string of 16 octets.
// The first three octets uniquely identify the manufacturer of the device and it corresponds
// to the manufacturer's identification in IEC 62056-21.
// The following 13 octets are assigned by the manufacturer.
//The manufacturer is responsible for guaranteeing the uniqueness of these octets.
int addLogicalDeviceName()
{
int ret;
const unsigned char ln[6] = { 0, 0, 42, 0, 0, 255 };
if ((ret = INIT_OBJECT(ldn, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
{
char tmp[17];
sprintf(tmp, "%s%.13lu", FLAG_ID, SERIAL_NUMBER);
var_addBytes(&ldn.value, (unsigned char*)tmp, 16);
}
return ret;
}
//Add event code object.
int addEventCode()
{
int ret;
const unsigned char ln[6] = { 0, 0, 96, 11, 0, 255 };
if ((ret = INIT_OBJECT(eventCode, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
{
GX_UINT16(eventCode.value) = 0;
}
return ret;
}
//Add unix time object.
int addUnixTime()
{
int ret;
const unsigned char ln[6] = { 0, 0, 1, 1, 0, 255 };
if ((ret = INIT_OBJECT(unixTime, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
{
//Set initial value.
GX_UINT32(unixTime.value) = 0;
}
return ret;
}
//Add invocation counter object.
int addInvocationCounter()
{
int ret;
const unsigned char ln[6] = { 0,0,43,1,0,255 };
if ((ret = INIT_OBJECT(invocationCounter, DLMS_OBJECT_TYPE_DATA, ln)) == 0)
{
//Initial invocation counter value.
GX_UINT32_BYREF(invocationCounter.value, securitySetupHighGMac.minimumInvocationCounter);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//Add push setup object. (On Connectivity)
///////////////////////////////////////////////////////////////////////
int addPushSetup()
{
int ret;
const unsigned char ln[6] = { 0, 0, 25, 9, 0, 255 };
if ((ret = INIT_OBJECT(pushSetup, DLMS_OBJECT_TYPE_PUSH_SETUP, ln)) == 0)
{
pushSetup.service = DLMS_SERVICE_TYPE_HDLC;
gxtime* start, * end;
start = (gxtime*)gxmalloc(sizeof(gxtime));
end = (gxtime*)gxmalloc(sizeof(gxtime));
//This push is sent every minute, but max 10 seconds over.
time_init(start, -1, -1, -1, -1, -1, 0, 0, 0);
time_init(end, -1, -1, -1, -1, -1, 10, 0, 0);
arr_push(&pushSetup.communicationWindow, key_init(start, end));
//This push is sent every half minute, but max 40 seconds over.
start = (gxtime*)gxmalloc(sizeof(gxtime));
end = (gxtime*)gxmalloc(sizeof(gxtime));
time_init(start, -1, -1, -1, -1, -1, 30, 0, 0);
time_init(end, -1, -1, -1, -1, -1, 40, 0, 0);
arr_push(&pushSetup.communicationWindow, key_init(start, end));
// Add logical device name.
gxTarget* capture = (gxTarget*)gxmalloc(sizeof(gxTarget));
capture->attributeIndex = 2;
capture->dataIndex = 0;
arr_push(&pushSetup.pushObjectList, key_init(BASE(ldn), capture));
// Add push object logical name. This is needed to tell structure of data to the Push listener.
// Also capture object list can be used here.
capture = (gxTarget*)gxmalloc(sizeof(gxTarget));
capture->attributeIndex = 1;
capture->dataIndex = 0;
arr_push(&pushSetup.pushObjectList, key_init(BASE(pushSetup), capture));
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds example clock object.
///////////////////////////////////////////////////////////////////////
int addClockObject()
{
int ret = 0;
//Add default clock. Clock's Logical Name is 0.0.1.0.0.255.
const unsigned char ln[6] = { 0, 0, 1, 0, 0, 255 };
if ((ret = INIT_OBJECT(clock1, DLMS_OBJECT_TYPE_CLOCK, ln)) == 0)
{
//Set default values.
time_init(&clock1.begin, -1, 3, -1, 2, 0, 0, 0, 0);
clock1.begin.extraInfo = DLMS_DATE_TIME_EXTRA_INFO_LAST_DAY;
time_init(&clock1.end, -1, 10, -1, 3, 0, 0, 0, 0);
clock1.end.extraInfo = DLMS_DATE_TIME_EXTRA_INFO_LAST_DAY;
//Meter is using UTC time zone.
clock1.timeZone = 0;
//Deviation is 60 minutes.
clock1.deviation = 60;
clock1.clockBase = DLMS_CLOCK_BASE_FREQUENCY_50;
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//This method adds example register object.
///////////////////////////////////////////////////////////////////////
int addRegisterObject()
{
int ret;
const unsigned char ln[6] = { 1, 1, 21, 25, 0, 255 };
if ((ret = INIT_OBJECT(activePowerL1, DLMS_OBJECT_TYPE_REGISTER, ln)) == 0)
{
activePowerL1Value = 10;
GX_UINT16_BYREF(activePowerL1.value, activePowerL1Value);
//10 ^ 3 = 1000
activePowerL1.scaler = 3;
activePowerL1.unit = 30;
}
return ret;
}
uint16_t readActivePowerValue()
{
return ++activePowerL1Value;
}
uint16_t readEventCode()
{
return eventCode.value.uiVal;
}
///////////////////////////////////////////////////////////////////////
//Add script table object for meter reset. This will erase the EEPROM.
///////////////////////////////////////////////////////////////////////
int addscriptTableGlobalMeterReset()
{
int ret;
const unsigned char ln[6] = { 0, 0, 10, 0, 0, 255 };
if ((ret = INIT_OBJECT(scriptTableGlobalMeterReset, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
{
gxScript* s = (gxScript*)gxmalloc(sizeof(gxScript));
s->id = 1;
arr_init(&s->actions);
//Add executed script to script list.
arr_push(&scriptTableGlobalMeterReset.scripts, s);
}
return ret;
}
/////////////////////////////////////////////////////////////////////
//Add script table object for disconnect control.
//Action 1 calls remote_disconnect #1 (close).
//Action 2 calls remote_connect #2(open).
///////////////////////////////////////////////////////////////////////
int addscriptTableDisconnectControl()
{
int ret;
const unsigned char ln[6] = { 0, 0, 10, 0, 106, 255 };
if ((ret = INIT_OBJECT(scriptTableDisconnectControl, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
{
gxScript* s = (gxScript*)gxmalloc(sizeof(gxScript));
s->id = 1;
arr_init(&s->actions);
gxScriptAction* a = (gxScriptAction*)gxmalloc(sizeof(gxScriptAction));
a->type = DLMS_SCRIPT_ACTION_TYPE_EXECUTE;
a->target = BASE(disconnectControl);
a->index = 1;
var_init(&a->parameter);
//Action data is Int8 zero.
GX_INT8(a->parameter) = 0;
arr_push(&s->actions, a);
//Add executed script to script list.
arr_push(&scriptTableDisconnectControl.scripts, s);
s = (gxScript*)gxmalloc(sizeof(gxScript));
s->id = 2;
arr_init(&s->actions);
a = (gxScriptAction*)gxmalloc(sizeof(gxScriptAction));
a->type = DLMS_SCRIPT_ACTION_TYPE_EXECUTE;
a->target = BASE(disconnectControl);
a->index = 2;
var_init(&a->parameter);
//Action data is Int8 zero.
GX_INT8(a->parameter) = 0;
arr_push(&s->actions, a);
//Add executed script to script list.
arr_push(&scriptTableDisconnectControl.scripts, s);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//Add script table object for test mode. In test mode meter is sending trace to the serial port.
///////////////////////////////////////////////////////////////////////
int addscriptTableActivateTestMode()
{
int ret;
const unsigned char ln[6] = { 0, 0, 10, 0, 101, 255 };
if ((ret = INIT_OBJECT(scriptTableActivateTestMode, DLMS_OBJECT_TYPE_SCRIPT_TABLE, ln)) == 0)
{
gxScript* s = (gxScript*)gxmalloc(sizeof(gxScript));
s->id = 1;
arr_init(&s->actions);
//Add executed script to script list.
arr_push(&scriptTableActivateTestMode.scripts, s);
}
return ret;
}
///////////////////////////////////////////////////////////////////////
//Add script table object for Normal mode. In normal mode meter is NOT sending trace to the serial port.
///////////////////////////////////////////////////////////////////////
int addscriptTableActivateNormalMode()
{
int ret;