/
GXDLMSReader.java
1412 lines (1359 loc) · 57.7 KB
/
GXDLMSReader.java
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
//
//---------------------------------------------------------------------------
//
// DESCRIPTION
//
// This file is a part of Gurux Device Framework.
//
// Gurux Device Framework is Open Source software; you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
// Gurux Device Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// More information of Gurux products: http://www.gurux.org
//
// This code is licensed under the GNU General Public License v2.
// Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
//---------------------------------------------------------------------------
package gurux.dlms.client;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import gurux.common.GXCommon;
import gurux.common.IGXMedia;
import gurux.common.ReceiveParameters;
import gurux.common.enums.TraceLevel;
import gurux.dlms.GXByteBuffer;
import gurux.dlms.GXDLMSAccessItem;
import gurux.dlms.GXDLMSConverter;
import gurux.dlms.GXDLMSException;
import gurux.dlms.GXDLMSTranslator;
import gurux.dlms.GXDateTime;
import gurux.dlms.GXReplyData;
import gurux.dlms.GXSimpleEntry;
import gurux.dlms.TranslatorOutputType;
import gurux.dlms.asn.GXAsn1Converter;
import gurux.dlms.asn.GXCertificateRequest;
import gurux.dlms.asn.GXPkcs10;
import gurux.dlms.asn.GXPkcs8;
import gurux.dlms.asn.GXx509Certificate;
import gurux.dlms.asn.enums.Ecc;
import gurux.dlms.asn.enums.KeyUsage;
import gurux.dlms.ecdsa.GXEcdsa;
import gurux.dlms.enums.AccessServiceCommandType;
import gurux.dlms.enums.Authentication;
import gurux.dlms.enums.Conformance;
import gurux.dlms.enums.DataType;
import gurux.dlms.enums.ErrorCode;
import gurux.dlms.enums.InterfaceType;
import gurux.dlms.enums.ObjectType;
import gurux.dlms.enums.Security;
import gurux.dlms.enums.Signing;
import gurux.dlms.objects.GXDLMSAssociationShortName;
import gurux.dlms.objects.GXDLMSCaptureObject;
import gurux.dlms.objects.GXDLMSCertificateInfo;
import gurux.dlms.objects.GXDLMSData;
import gurux.dlms.objects.GXDLMSDemandRegister;
import gurux.dlms.objects.GXDLMSObject;
import gurux.dlms.objects.GXDLMSObjectCollection;
import gurux.dlms.objects.GXDLMSProfileGeneric;
import gurux.dlms.objects.GXDLMSRegister;
import gurux.dlms.objects.GXDLMSSecuritySetup;
import gurux.dlms.objects.GXXmlWriterSettings;
import gurux.dlms.objects.IGXDLMSBase;
import gurux.dlms.objects.enums.CertificateEntity;
import gurux.dlms.objects.enums.CertificateType;
import gurux.io.BaudRate;
import gurux.io.Parity;
import gurux.io.StopBits;
import gurux.serial.GXSerial;
public class GXDLMSReader {
IGXMedia Media;
TraceLevel Trace;
GXDLMSSecureClient2 dlms;
java.nio.ByteBuffer replyBuff;
int waitTime = 60000;
final PrintWriter logFile;
// Invocation counter (frame counter).
String invocationCounter = null;
public GXDLMSReader(GXDLMSSecureClient2 client, IGXMedia media, TraceLevel trace,
final String frameCounter) throws Exception {
Files.deleteIfExists(Paths.get("trace.txt"));
logFile = new PrintWriter(new BufferedWriter(new FileWriter("logFile.txt")));
Trace = trace;
Media = media;
dlms = client;
invocationCounter = frameCounter;
if (trace.ordinal() > TraceLevel.WARNING.ordinal()) {
System.out.println("Authentication: " + dlms.getAuthentication());
System.out.println("ClientAddress: 0x" + Integer.toHexString(dlms.getClientAddress()));
System.out.println("ServerAddress: 0x" + Integer.toHexString(dlms.getServerAddress()));
}
if (dlms.getInterfaceType() == InterfaceType.WRAPPER) {
replyBuff = java.nio.ByteBuffer.allocate(8 + 1024);
} else {
replyBuff = java.nio.ByteBuffer.allocate(100);
}
}
void disconnect() throws Exception {
if (Media != null && Media.isOpen()) {
System.out.println("DisconnectRequest");
GXReplyData reply = new GXReplyData();
readDLMSPacket(dlms.disconnectRequest(), reply);
}
}
void release() throws Exception {
if (Media != null && Media.isOpen()) {
GXReplyData reply = new GXReplyData();
try {
// Release is call only for secured connections.
// All meters are not supporting Release and it's causing
// problems.
if (dlms.getInterfaceType() == InterfaceType.WRAPPER
|| (dlms.getInterfaceType() == InterfaceType.HDLC
&& dlms.getCiphering().getSecurity() != Security.NONE)) {
System.out.println("release");
readDataBlock(dlms.releaseRequest(), reply);
}
} catch (Exception e) {
// All meters don't support release.
}
}
}
void close() throws Exception {
if (Media != null && Media.isOpen()) {
System.out.println("DisconnectRequest");
GXReplyData reply = new GXReplyData();
try {
// Release is call only for secured connections.
// All meters are not supporting Release and it's causing
// problems.
if (dlms.getInterfaceType() == InterfaceType.WRAPPER
|| (dlms.getInterfaceType() == InterfaceType.HDLC
&& dlms.getCiphering().getSecurity() != Security.NONE)) {
readDataBlock(dlms.releaseRequest(), reply);
}
} catch (Exception e) {
// All meters don't support release.
}
reply.clear();
readDLMSPacket(dlms.disconnectRequest(), reply);
Media.close();
}
}
String now() {
return new SimpleDateFormat("HH:mm:ss.SSS")
.format(java.util.Calendar.getInstance().getTime());
}
void writeTrace(String line, TraceLevel level) {
if (Trace.ordinal() >= level.ordinal()) {
System.out.println(line);
}
PrintWriter logFile = null;
try {
logFile = new PrintWriter(new BufferedWriter(new FileWriter("trace.txt", true)));
logFile.println(line);
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage());
} finally {
if (logFile != null) {
logFile.close();
}
}
}
public void readDLMSPacket(byte[][] data) throws Exception {
GXReplyData reply = new GXReplyData();
for (byte[] it : data) {
reply.clear();
readDLMSPacket(it, reply);
}
}
/**
* Handle received notify messages.
*
* @param reply
* Received data.
* @throws Exception
*/
private void handleNotifyMessages(final GXReplyData reply) throws Exception {
List<Entry<GXDLMSObject, Integer>> items = new ArrayList<Entry<GXDLMSObject, Integer>>();
Object value = dlms.parseReport(reply, items);
// If Event notification or Information report.
if (value == null) {
for (Entry<GXDLMSObject, Integer> it : items) {
System.out.println(it.getKey().toString() + " Value:"
+ it.getKey().getValues()[it.getValue() - 1]);
}
} else // Show data notification.
{
if (value instanceof List<?>) {
for (Object it : (List<?>) value) {
System.out.println("Value:" + String.valueOf(it));
}
} else {
System.out.println("Value:" + String.valueOf(value));
}
}
reply.clear();
}
/**
* Read DLMS Data from the device. If access is denied return null.
*/
public void readDLMSPacket(byte[] data, GXReplyData reply) throws Exception {
if (!reply.getStreaming() && (data == null || data.length == 0)) {
return;
}
GXReplyData notify = new GXReplyData();
reply.setError((short) 0);
Object eop = (byte) 0x7E;
// In network connection terminator is not used.
if (dlms.getInterfaceType() != InterfaceType.HDLC
&& dlms.getInterfaceType() != InterfaceType.HDLC_WITH_MODE_E) {
eop = null;
}
GXByteBuffer rd = new GXByteBuffer();
int pos = 0;
boolean succeeded = false;
ReceiveParameters<byte[]> p = new ReceiveParameters<byte[]>(byte[].class);
p.setEop(eop);
p.setCount(dlms.getFrameSize(rd));
p.setWaitTime(waitTime);
synchronized (Media.getSynchronous()) {
while (!succeeded) {
if (!reply.isStreaming()) {
writeTrace("TX: " + now() + "\t" + GXCommon.bytesToHex(data),
TraceLevel.VERBOSE);
Media.send(data, null);
}
succeeded = Media.receive(p);
if (!succeeded) {
if (p.getEop() == null) {
p.setCount(dlms.getFrameSize(rd));
}
// Try to read again...
if (pos++ == 3) {
throw new RuntimeException(
"Failed to receive reply from the device in given time.");
}
System.out.println(
"Data send failed. Try to resend " + String.valueOf(pos) + "/3");
}
}
rd = new GXByteBuffer(p.getReply());
int msgPos = 0;
// Loop until whole DLMS packet is received.
try {
while (!dlms.getData(rd, reply, notify)) {
p.setReply(null);
if (notify.getData().getData() != null) {
// Handle notify.
if (!notify.isMoreData()) {
// Show received push message as XML.
GXDLMSTranslator t =
new GXDLMSTranslator(TranslatorOutputType.SIMPLE_XML);
String xml = t.dataToXml(notify.getData());
System.out.println(xml);
notify.clear();
msgPos = rd.position();
}
continue;
}
if (p.getEop() == null) {
p.setCount(dlms.getFrameSize(rd));
}
while (!Media.receive(p)) {
// If echo.
if (reply.isEcho()) {
Media.send(data, null);
}
// Try to read again...
if (++pos == 3) {
throw new Exception(
"Failed to receive reply from the device in given time.");
}
System.out.println(
"Data send failed. Try to resend " + String.valueOf(pos) + "/3");
}
rd.position(msgPos);
rd.set(p.getReply());
}
} catch (Exception e) {
writeTrace("RX: " + now() + "\t" + rd.toString(), TraceLevel.ERROR);
throw e;
}
}
writeTrace("RX: " + now() + "\t" + rd.toString(), TraceLevel.VERBOSE);
if (reply.getError() != 0) {
if (reply.getError() == ErrorCode.REJECTED.getValue()) {
Thread.sleep(1000);
readDLMSPacket(data, reply);
} else {
throw new GXDLMSException(reply.getError());
}
}
}
boolean readDataBlock(byte[][] data, GXReplyData reply) throws Exception {
if (data != null) {
for (byte[] it : data) {
reply.clear();
readDataBlock(it, reply);
}
}
return reply.getError() == 0;
}
/**
* Reads next data block.
*
* @param data
* @return
* @throws Exception
*/
void readDataBlock(byte[] data, GXReplyData reply) throws Exception {
if (data != null && data.length != 0) {
readDLMSPacket(data, reply);
while (reply.isMoreData()) {
if (reply.isStreaming()) {
data = null;
} else {
data = dlms.receiverReady(reply);
}
readDLMSPacket(data, reply);
}
}
}
/**
* Read Invocation counter (frame counter) from the meter and update it.
*
* @throws Exception
*/
private void updateFrameCounter() throws Exception {
// Read frame counter if GeneralProtection is used.
if (invocationCounter != null && dlms.getCiphering() != null
&& dlms.getCiphering().getSecurity() != Security.NONE) {
initializeOpticalHead();
byte[] data;
GXReplyData reply = new GXReplyData();
reply.clear();
int add = dlms.getClientAddress();
Authentication auth = dlms.getAuthentication();
Security security = dlms.getCiphering().getSecurity();
Signing signing = dlms.getCiphering().getSigning();
byte[] challenge = dlms.getCtoSChallenge();
try {
dlms.setClientAddress(16);
dlms.setAuthentication(Authentication.NONE);
dlms.getCiphering().setSecurity(Security.NONE);
dlms.getCiphering().setSigning(Signing.NONE);
data = dlms.snrmRequest();
if (data != null) {
readDLMSPacket(data, reply);
// Has server accepted client.
dlms.parseUAResponse(reply.getData());
// Allocate buffer to same size as transmit buffer of the
// meter.
// Size of replyBuff is payload and frame (Bop, EOP, crc).
int size = (int) ((((Number) dlms.getHdlcSettings().getMaxInfoTX()).intValue()
& 0xFFFFFFFFL) + 40);
replyBuff = java.nio.ByteBuffer.allocate(size);
}
// Generate AARQ request.
// Split requests to multiple packets if needed.
// If password is used all data might not fit to one packet.
reply.clear();
readDataBlock(dlms.aarqRequest(), reply);
try {
// Parse reply.
dlms.parseAareResponse(reply.getData());
reply.clear();
GXDLMSData d = new GXDLMSData(invocationCounter);
read(d, 2);
long iv = ((Number) d.getValue()).longValue();
iv += 1;
dlms.getCiphering().setInvocationCounter(iv);
writeTrace("Invocation counter: " + String.valueOf(iv), TraceLevel.INFO);
reply.clear();
disconnect();
} catch (Exception Ex) {
disconnect();
throw Ex;
}
} finally {
dlms.setClientAddress(add);
dlms.setAuthentication(auth);
dlms.getCiphering().setSecurity(security);
dlms.setCtoSChallenge(challenge);
dlms.getCiphering().setSigning(signing);
}
}
}
void initializeOpticalHead() throws Exception {
if (dlms.getInterfaceType() != InterfaceType.HDLC_WITH_MODE_E) {
return;
}
ReceiveParameters<byte[]> p = new ReceiveParameters<byte[]>(byte[].class);
p.setAllData(false);
p.setEop((byte) '\n');
p.setWaitTime(waitTime);
String data;
String replyStr;
synchronized (Media.getSynchronous()) {
data = "/?!\r\n";
writeTrace("TX: " + now() + "\t" + GXCommon.bytesToHex(data.getBytes("ASCII")),
TraceLevel.VERBOSE);
Media.send(data, null);
if (!Media.receive(p)) {
throw new RuntimeException("Failed to received reply from the media.");
}
writeTrace("RX: " + now() + "\t" + GXCommon.bytesToHex(p.getReply()),
TraceLevel.VERBOSE);
// If echo is used.
replyStr = new String(p.getReply());
if (data.equals(replyStr)) {
p.setReply(null);
if (!Media.receive(p)) {
throw new Exception("Failed to received reply from the media.");
}
writeTrace("RX: " + now() + "\t" + GXCommon.bytesToHex(p.getReply()),
TraceLevel.VERBOSE);
replyStr = new String(p.getReply());
}
}
if (replyStr.length() == 0 || replyStr.charAt(0) != '/') {
throw new Exception("Invalid responce : " + replyStr);
}
int bitrate = 0;
char baudrate = replyStr.charAt(4);
switch (baudrate) {
case '0':
bitrate = 300;
break;
case '1':
bitrate = 600;
break;
case '2':
bitrate = 1200;
break;
case '3':
bitrate = 2400;
break;
case '4':
bitrate = 4800;
break;
case '5':
bitrate = 9600;
break;
case '6':
bitrate = 19200;
break;
default:
throw new Exception("Unknown baud rate.");
}
System.out.println("Bitrate is : " + bitrate);
// Send ACK
// Send Protocol control character
byte controlCharacter = (byte) '2';// "2" HDLC protocol
// procedure (Mode E)
// Send Baudrate character
// Mode control character
byte ModeControlCharacter = (byte) '2';// "2" //(HDLC protocol
// procedure) (Binary
// mode)
// Set mode E.
byte[] tmp = new byte[] { 0x06, controlCharacter, (byte) baudrate, ModeControlCharacter, 13,
10 };
p.setReply(null);
synchronized (Media.getSynchronous()) {
Media.send(tmp, null);
writeTrace("RX: " + now() + "\t" + GXCommon.bytesToHex(tmp), TraceLevel.VERBOSE);
p.setWaitTime(100);
if (Media.receive(p)) {
writeTrace("RX: " + now() + "\t" + GXCommon.bytesToHex(p.getReply()),
TraceLevel.VERBOSE);
}
Media.close();
// This sleep make sure that all meters can be read.
Thread.sleep(400);
GXSerial serial = (GXSerial) Media;
serial.setDataBits(8);
serial.setParity(Parity.NONE);
serial.setStopBits(StopBits.ONE);
serial.setBaudRate(BaudRate.forValue(bitrate));
Media.open();
serial.setDtrEnable(true);
serial.setRtsEnable(true);
Thread.sleep(400);
}
}
/**
* Initializes connection.
*
* @param port
* @throws InterruptedException
* @throws Exception
*/
void initializeConnection() throws Exception, InterruptedException {
if (Media instanceof GXSerial) {
GXSerial serial = (GXSerial) Media;
serial.setDtrEnable(true);
serial.setRtsEnable(true);
}
System.out.println("Standard: " + dlms.getStandard().toString());
if (dlms.getCiphering().getSecurity() != Security.NONE) {
System.out.println("Security: " + dlms.getCiphering().getSecurity());
System.out.println(
"System title: " + GXCommon.bytesToHex(dlms.getCiphering().getSystemTitle()));
System.out.println("Authentication key: "
+ GXCommon.bytesToHex(dlms.getCiphering().getAuthenticationKey()));
System.out.println("Block cipher key "
+ GXCommon.bytesToHex(dlms.getCiphering().getBlockCipherKey()));
if (dlms.getCiphering().getDedicatedKey() != null) {
System.out.println("Dedicated key: "
+ GXCommon.bytesToHex(dlms.getCiphering().getDedicatedKey()));
}
}
updateFrameCounter();
initializeOpticalHead();
GXReplyData reply = new GXReplyData();
byte[] data = dlms.snrmRequest();
if (data.length != 0) {
readDLMSPacket(data, reply);
// Has server accepted client.
dlms.parseUAResponse(reply.getData());
// Allocate buffer to same size as transmit buffer of the meter.
// Size of replyBuff is payload and frame (Bop, EOP, crc).
int size = (int) ((((Number) dlms.getHdlcSettings().getMaxInfoTX()).intValue()
& 0xFFFFFFFFL) + 40);
replyBuff = java.nio.ByteBuffer.allocate(size);
}
reply.clear();
readDataBlock(dlms.aarqRequest(), reply);
// Parse reply.
dlms.parseAareResponse(reply.getData());
reply.clear();
System.out.println("----------------------------");
System.out.println("Proposed conformance:");
System.out.println(dlms.getProposedConformance());
System.out.println("Negotiated conformance:");
System.out.println(dlms.getNegotiatedConformance());
System.out.println("MaxReceivePDUSize: " + dlms.getMaxReceivePDUSize());
// Get challenge Is HLS authentication is used.
if (dlms.getAuthentication().getValue() > Authentication.LOW.getValue()) {
// Update public key certificate and private key.
if (dlms.getAuthentication() == Authentication.HIGH_ECDSA) {
Path path = Paths.get("Keys",
"D" + GXDLMSTranslator.toHex(dlms.getCiphering().getSystemTitle(), false)
+ ".pem");
if (!Files.exists(path)) {
throw new IllegalArgumentException("Client Private key file is missing. "
+ GXDLMSTranslator.toHex(dlms.getCiphering().getSystemTitle(), false));
}
GXPkcs8 key = GXPkcs8.load(path);
// Load public key of the server.
path = Paths.get("Certificates",
"D" + GXDLMSTranslator.toHex(dlms.getSourceSystemTitle(), false) + ".pem");
GXx509Certificate cert = GXx509Certificate.load(path);
dlms.getCiphering()
.setSigningKeyPair(new KeyPair(cert.getPublicKey(), key.getPrivateKey()));
}
for (byte[] it : dlms.getApplicationAssociationRequest()) {
readDLMSPacket(it, reply);
}
dlms.parseApplicationAssociationResponse(reply.getData());
}
}
/**
* Reads selected DLMS object with selected attribute index.
*
* @param item
* @param attributeIndex
* @return
* @throws Exception
*/
public Object read(GXDLMSObject item, int attributeIndex) throws Exception {
byte[][] data = dlms.read(item.getName(), item.getObjectType(), attributeIndex);
GXReplyData reply = new GXReplyData();
readDataBlock(data, reply);
// Update data type on read.
if (item.getDataType(attributeIndex) == DataType.NONE) {
item.setDataType(attributeIndex, reply.getValueType());
}
return dlms.updateValue(item, attributeIndex, reply.getValue());
}
/*
* Read list of attributes.
*/
public void readList(List<Entry<GXDLMSObject, Integer>> list) throws Exception {
if (!list.isEmpty()) {
byte[][] data = dlms.readList(list);
GXReplyData reply = new GXReplyData();
List<Object> values = new ArrayList<Object>(list.size());
for (byte[] it : data) {
readDataBlock(it, reply);
// Value is null if data is send in multiple frames.
if (reply.getValue() != null) {
values.addAll((List<?>) reply.getValue());
}
reply.clear();
}
if (values.size() != list.size()) {
throw new Exception("Invalid reply. Read items count do not match.");
}
dlms.updateValues(list, values);
}
}
/**
* Writes value to DLMS object with selected attribute index.
*
* @param item
* @param attributeIndex
* @throws Exception
*/
public void writeObject(GXDLMSObject item, int attributeIndex) throws Exception {
byte[][] data = dlms.write(item, attributeIndex);
readDLMSPacket(data);
}
/*
* Returns columns of profile Generic.
*/
public List<Entry<GXDLMSObject, GXDLMSCaptureObject>> GetColumns(GXDLMSProfileGeneric pg)
throws Exception {
Object entries = read(pg, 7);
System.out.println("Reading Profile Generic: " + pg.getLogicalName() + " "
+ pg.getDescription() + " entries:" + entries.toString());
GXReplyData reply = new GXReplyData();
byte[] data = dlms.read(pg.getName(), pg.getObjectType(), 3)[0];
readDataBlock(data, reply);
dlms.updateValue((GXDLMSObject) pg, 3, reply.getValue());
return pg.getCaptureObjects();
}
/**
* Read Profile Generic's data by entry start and count.
*
* @param pg
* @param index
* @param count
* @return
* @throws Exception
*/
public Object[] readRowsByEntry(GXDLMSProfileGeneric pg, int index, int count)
throws Exception {
byte[][] data = dlms.readRowsByEntry(pg, index, count);
GXReplyData reply = new GXReplyData();
readDataBlock(data, reply);
return (Object[]) dlms.updateValue(pg, 2, reply.getValue());
}
/**
* Read Profile Generic's data by range (start and end time).
*
* @param pg
* @param sortedItem
* @param start
* @param end
* @return
* @throws Exception
*/
public Object[] readRowsByRange(final GXDLMSProfileGeneric pg, final Date start, final Date end)
throws Exception {
GXReplyData reply = new GXReplyData();
byte[][] data = dlms.readRowsByRange(pg, start, end);
readDataBlock(data, reply);
return (Object[]) dlms.updateValue(pg, 2, reply.getValue());
}
/**
* Read Profile Generic's data by range (start and end time).
*
* @param pg
* @param sortedItem
* @param start
* @param end
* @return
* @throws Exception
*/
public Object[] readRowsByRange(final GXDLMSProfileGeneric pg, final GXDateTime start,
final GXDateTime end) throws Exception {
GXReplyData reply = new GXReplyData();
byte[][] data = dlms.readRowsByRange(pg, start, end);
readDataBlock(data, reply);
return (Object[]) dlms.updateValue(pg, 2, reply.getValue());
}
/*
* Read Scalers and units from the register objects.
*/
void readScalerAndUnits() throws Exception {
GXDLMSObjectCollection objs = dlms.getObjects().getObjects(new ObjectType[] {
ObjectType.REGISTER, ObjectType.DEMAND_REGISTER, ObjectType.EXTENDED_REGISTER });
try {
if (dlms.getNegotiatedConformance().contains(Conformance.ACCESS)) {
List<GXDLMSAccessItem> list = new ArrayList<GXDLMSAccessItem>();
for (GXDLMSObject it : objs) {
if (it instanceof GXDLMSRegister) {
list.add(new GXDLMSAccessItem(AccessServiceCommandType.GET, it, 3));
}
if (it instanceof GXDLMSDemandRegister) {
list.add(new GXDLMSAccessItem(AccessServiceCommandType.GET, it, 4));
}
}
readByAccess(list);
} else if (dlms.getNegotiatedConformance().contains(Conformance.MULTIPLE_REFERENCES)) {
List<Entry<GXDLMSObject, Integer>> list =
new ArrayList<Entry<GXDLMSObject, Integer>>();
for (GXDLMSObject it : objs) {
if (it instanceof GXDLMSRegister) {
list.add(new GXSimpleEntry<GXDLMSObject, Integer>(it, 3));
}
if (it instanceof GXDLMSDemandRegister) {
list.add(new GXSimpleEntry<GXDLMSObject, Integer>(it, 4));
}
}
readList(list);
}
} catch (Exception e) {
// Some meters are set multiple references, but don't support it.
dlms.getNegotiatedConformance().remove(Conformance.MULTIPLE_REFERENCES);
}
if (!dlms.getNegotiatedConformance().contains(Conformance.MULTIPLE_REFERENCES)) {
for (GXDLMSObject it : objs) {
try {
if (it instanceof GXDLMSRegister) {
read(it, 3);
} else if (it instanceof GXDLMSDemandRegister) {
read(it, 4);
}
} catch (Exception e) {
// Actaric SL7000 can return error here. Continue reading.
}
}
}
}
/*
* Read profile generic columns from the meter.
*/
void getProfileGenericColumns() {
GXDLMSObjectCollection profileGenerics =
dlms.getObjects().getObjects(ObjectType.PROFILE_GENERIC);
for (GXDLMSObject it : profileGenerics) {
writeTrace("Profile Generic " + it.getName() + "Columns:", TraceLevel.INFO);
GXDLMSProfileGeneric pg = (GXDLMSProfileGeneric) it;
// Read columns.
try {
read(pg, 3);
if (Trace.ordinal() > TraceLevel.WARNING.ordinal()) {
boolean first = true;
StringBuilder sb = new StringBuilder();
for (Entry<GXDLMSObject, GXDLMSCaptureObject> col : pg.getCaptureObjects()) {
if (!first) {
sb.append(" | ");
}
sb.append(col.getKey().getName());
sb.append(" ");
String desc = col.getKey().getDescription();
if (desc != null) {
sb.append(desc);
}
first = false;
}
writeTrace(sb.toString(), TraceLevel.INFO);
}
} catch (Exception ex) {
writeTrace("Err! Failed to read columns:" + ex.getMessage(), TraceLevel.ERROR);
// Continue reading.
}
}
}
/**
* Read all data from the meter except profile generic (Historical) data.
*/
void getReadOut() {
for (GXDLMSObject it : dlms.getObjects()) {
if (!(it instanceof IGXDLMSBase)) {
// If interface is not implemented.
System.out.println("Unknown Interface: " + it.getObjectType().toString());
continue;
}
if (it instanceof GXDLMSProfileGeneric) {
// Profile generic are read later
// because it might take so long time
// and this is only a example.
continue;
}
writeTrace("-------- Reading " + it.getClass().getSimpleName() + " "
+ it.getName().toString() + " " + it.getDescription(), TraceLevel.INFO);
for (int pos : ((IGXDLMSBase) it).getAttributeIndexToRead(true)) {
try {
if (pos == 1) {
continue;
}
Object val = read(it, pos);
showValue(pos, val);
} catch (Exception ex) {
writeTrace("Error! Index: " + pos + " " + ex.getMessage(), TraceLevel.ERROR);
writeTrace(ex.toString(), TraceLevel.ERROR);
// Continue reading.
}
}
}
}
void showValue(final int pos, final Object value) {
Object val = value;
if (val instanceof byte[]) {
val = GXCommon.bytesToHex((byte[]) val);
} else if (val instanceof Double) {
NumberFormat formatter = NumberFormat.getNumberInstance();
val = formatter.format(val);
} else if (val instanceof List) {
StringBuilder sb = new StringBuilder();
for (Object tmp : (List<?>) val) {
if (sb.length() != 0) {
sb.append(", ");
}
if (tmp instanceof byte[]) {
sb.append(GXCommon.bytesToHex((byte[]) tmp));
} else {
sb.append(String.valueOf(tmp));
}
}
val = sb.toString();
} else if (val != null && val.getClass().isArray()) {
StringBuilder sb = new StringBuilder();
for (int pos2 = 0; pos2 != Array.getLength(val); ++pos2) {
if (sb.length() != 0) {
sb.append(", ");
}
Object tmp = Array.get(val, pos2);
if (tmp instanceof byte[]) {
sb.append(GXCommon.bytesToHex((byte[]) tmp));
} else {
sb.append(String.valueOf(tmp));
}
}
val = sb.toString();
}
writeTrace("Index: " + pos + " Value: " + String.valueOf(val), TraceLevel.INFO);
}
/**
* Read profile generic (Historical) data.
*/
void getProfileGenerics() throws Exception {
Object[] cells;
GXDLMSObjectCollection profileGenerics =
dlms.getObjects().getObjects(ObjectType.PROFILE_GENERIC);
for (GXDLMSObject it : profileGenerics) {
writeTrace("-------- Reading " + it.getClass().getSimpleName() + " "
+ it.getName().toString() + " " + it.getDescription(), TraceLevel.INFO);
long entriesInUse = ((Number) read(it, 7)).longValue();
long entries = ((Number) read(it, 8)).longValue();
writeTrace("Entries: " + String.valueOf(entriesInUse) + "/" + String.valueOf(entries),
TraceLevel.INFO);
GXDLMSProfileGeneric pg = (GXDLMSProfileGeneric) it;
// If there are no columns.
if (entriesInUse == 0 || pg.getCaptureObjects().isEmpty()) {
continue;
}
///////////////////////////////////////////////////////////////////
// Read first item.
try {
cells = readRowsByEntry(pg, 1, 1);
if (Trace.ordinal() > TraceLevel.WARNING.ordinal()) {
for (Object rows : cells) {
StringBuilder sb = new StringBuilder();
for (Object cell : (Object[]) rows) {
if (cell instanceof byte[]) {
sb.append(GXCommon.bytesToHex((byte[]) cell));
sb.append(" | ");
} else {
sb.append(String.valueOf(cell));
sb.append(" | ");
}
}
writeTrace(sb.toString(), TraceLevel.INFO);
}
}
} catch (Exception ex) {
writeTrace("Error! Failed to read first row: " + ex.getMessage(), TraceLevel.ERROR);
// Continue reading if device returns access denied error.
}
///////////////////////////////////////////////////////////////////
// Read last day.
try {
java.util.Calendar start = java.util.Calendar.getInstance();
start.set(java.util.Calendar.HOUR_OF_DAY, 0); // set hour to
// midnight
start.set(java.util.Calendar.MINUTE, 0); // set minute in
// hour
start.set(java.util.Calendar.SECOND, 0); // set second in
// minute
start.set(java.util.Calendar.MILLISECOND, 0);
start.add(java.util.Calendar.DATE, -1);
java.util.Calendar end = java.util.Calendar.getInstance();
end.set(java.util.Calendar.MINUTE, 0); // set minute in hour
end.set(java.util.Calendar.SECOND, 0); // set second in
// minute
end.set(java.util.Calendar.MILLISECOND, 0);
GXDateTime s = new GXDateTime(start);
GXDateTime e = new GXDateTime(end);
cells = readRowsByRange((GXDLMSProfileGeneric) it, s, e);
for (Object rows : cells) {
StringBuilder sb = new StringBuilder();
for (Object cell : (Object[]) rows) {
if (cell instanceof byte[]) {
sb.append(GXCommon.bytesToHex((byte[]) cell));
sb.append(" | ");
} else {
sb.append(String.valueOf(cell));
sb.append(" | ");
}
}
writeTrace(sb.toString(), TraceLevel.INFO);
}
} catch (Exception ex) {
writeTrace("Error! Failed to read last day: " + ex.getMessage(), TraceLevel.ERROR);
// Continue reading if device returns access denied error.
}
}
}
/**
* Read association view.
*
* @throws Exception
*/
public void getAssociationView() throws Exception {
GXReplyData reply = new GXReplyData();
// Get Association view from the meter.
readDataBlock(dlms.getObjectsRequest(), reply);
dlms.parseObjects(reply.getData(), true);
// Access rights must read differently when short Name referencing is
// used.
if (!dlms.getUseLogicalNameReferencing()) {
GXDLMSAssociationShortName sn =
(GXDLMSAssociationShortName) dlms.getObjects().findBySN(0xFA00);
if (sn != null && sn.getVersion() > 0) {
read(sn, 3);
}
}
}