/
GXDLMSReader.cs
1688 lines (1637 loc) · 63.9 KB
/
GXDLMSReader.cs
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
//---------------------------------------------------------------------------
using Gurux.Common;
using Gurux.DLMS.ASN;
using Gurux.DLMS.Ecdsa;
using Gurux.DLMS.Ecdsa.Enums;
using Gurux.DLMS.Enums;
using Gurux.DLMS.Objects;
using Gurux.DLMS.Objects.Enums;
using Gurux.DLMS.Secure;
using Gurux.Serial;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
namespace Gurux.DLMS.Reader
{
public class GXDLMSReader
{
/// <summary>
/// Wait time in ms.
/// </summary>
public int WaitTime = 5000;
/// <summary>
/// Retry count.
/// </summary>
public int RetryCount = 3;
IGXMedia Media;
TraceLevel Trace;
GXDLMSSecureClient Client;
// Invocation counter (frame counter).
string InvocationCounter = null;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="client">DLMS Client.</param>
/// <param name="media">Media.</param>
/// <param name="trace">Trace level.</param>
/// <param name="invocationCounter">Logical name of invocation counter.</param>
public GXDLMSReader(GXDLMSSecureClient client, IGXMedia media, TraceLevel trace, string invocationCounter)
{
Trace = trace;
Media = media;
Client = client;
//Get ECDSA keys when needed.
Client.OnKeys += Client_OnKeys;
InvocationCounter = invocationCounter;
}
/// <summary>
/// Find ciphering keys.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void Client_OnKeys(object sender, GXCryptoKeyParameter args)
{
try
{
if (args.Encrypt)
{
//Find private key.
string path = GetPath(args.SecuritySuite, args.CertificateType, "Keys", args.SystemTitle);
args.PrivateKey = GXPkcs8.Load(path).PrivateKey;
Console.WriteLine("Client private key:" + args.PrivateKey.ToHex());
}
else
{
//Find public key.
if (args.SystemTitle == null)
{
string path = GetPath(args.SecuritySuite, args.CertificateType, "Certificates", args.SystemTitle);
GXx509Certificate pk = GXx509Certificate.Search(path, args.SystemTitle);
args.PublicKey = pk.PublicKey;
Console.WriteLine("Server public key:" + pk.SerialNumber);
}
else
{
string path = GetPath(args.SecuritySuite, args.CertificateType, "Certificates", args.SystemTitle);
GXx509Certificate pk = GXx509Certificate.Load(path);
args.PublicKey = pk.PublicKey;
Console.WriteLine("Server public key:" + pk.SerialNumber);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Return correct path.
/// </summary>
/// <param name="securitySuite">Security Suite.</param>
/// <param name="type">Certificate type.</param>
/// <param name="path">Folder.</param>
/// <param name="systemTitle">System title.</param>
/// <returns>Path to the certificate file or folder if system title is not given.</returns>
private static string GetPath(SecuritySuite securitySuite, CertificateType type, string path, byte[] systemTitle)
{
string pre;
if (securitySuite == SecuritySuite.Suite2)
{
path = Path.Combine(path, "384");
}
if (systemTitle == null)
{
return path;
}
switch (type)
{
case CertificateType.DigitalSignature:
pre = "D";
break;
case CertificateType.KeyAgreement:
pre = "A";
break;
default:
throw new Exception("Invalid type.");
}
return Path.Combine(path, pre + GXDLMSTranslator.ToHex(systemTitle, false) + ".pem");
}
/// <summary>
/// Generates a new server and client public/private keys and register them and import certificates to the meter.
/// </summary>
/// <param name="logicalName">Logical name of the security setup object.</param>
public void GenerateCertificates(string logicalName)
{
if (!Directory.Exists("Keys"))
{
Directory.CreateDirectory("Keys");
}
if (!Directory.Exists("Certificates"))
{
Directory.CreateDirectory("Certificates");
}
if (!Directory.Exists("Keys384"))
{
Directory.CreateDirectory("Keys384");
}
if (!Directory.Exists("Certificates384"))
{
Directory.CreateDirectory("Certificates384");
}
string address = "https://certificates.gurux.fi/api/CertificateGenerator";
GXx509Certificate[] certs;
if (Client.Authentication < Authentication.Low)
{
throw new Exception("High authentication must be used to change the certificate keys.");
}
GXReplyData reply = new GXReplyData();
InitializeConnection();
GXDLMSSecuritySetup ss = new GXDLMSSecuritySetup(logicalName);
List<GXCertificateRequest> certifications = new List<GXCertificateRequest>();
//Read used security suite.
Read(ss, 3);
//Read client system title.
Read(ss, 4);
//Read server system title.
Read(ss, 5);
byte[] clientST = ss.ClientSystemTitle;
if (clientST == null || clientST.Length != 8)
{
clientST = Client.Ciphering.SystemTitle;
}
//Get client subject.
string subject = GXAsn1Converter.SystemTitleToSubject(clientST);
//Generate new digital signature for the client. In this example P-256 keys are used.
KeyValuePair<GXPublicKey, GXPrivateKey> kp = GXEcdsa.GenerateKeyPair(Ecc.P256);
//Save private key in PKCS #8 format.
GXPkcs8 key = new GXPkcs8(kp);
key.Save(GXAsn1Converter.GetFilePath(Ecc.P256, CertificateType.DigitalSignature, clientST));
//Generate x509 certificates.
GXPkcs10 pkc10 = GXPkcs10.CreateCertificateSigningRequest(kp, subject);
//All certigicates are generated with one request.
certifications.Add(new GXCertificateRequest(CertificateType.DigitalSignature, pkc10));
//Generate new key agreement for the client. In this example P-256 keys are used.
kp = GXEcdsa.GenerateKeyPair(Ecc.P256);
//Save private key in PKCS #8 format.
key = new GXPkcs8(kp);
key.Save(GXAsn1Converter.GetFilePath(Ecc.P256, CertificateType.KeyAgreement, clientST));
//Generate x509 certificates.
pkc10 = GXPkcs10.CreateCertificateSigningRequest(kp, subject);
//All certigicates are generated with one request.
certifications.Add(new GXCertificateRequest(CertificateType.KeyAgreement, pkc10));
//Generate public/private key for digital signature.
if (!ReadDataBlock(ss.GenerateKeyPair(Client, CertificateType.DigitalSignature), reply))
{
throw new GXDLMSException(reply.Error);
}
reply.Clear();
//Generate public/private key for key agreement.
if (!ReadDataBlock(ss.GenerateKeyPair(Client, CertificateType.KeyAgreement), reply))
{
throw new GXDLMSException(reply.Error);
}
reply.Clear();
//Generate certification request.
if (!ReadDataBlock(ss.GenerateCertificate(Client, CertificateType.DigitalSignature), reply))
{
throw new GXDLMSException(reply.Error);
}
//Generate server certification.
pkc10 = new GXPkcs10((byte[])reply.Value);
subject = GXAsn1Converter.SystemTitleToSubject(ss.ServerSystemTitle);
//Validate subject.
if (!pkc10.Subject.Contains(subject))
{
throw new Exception(string.Format("Server system title '{0}' is not the same as in the generated certificate request '{1}'.",
GXDLMSTranslator.ToHex(ss.ServerSystemTitle),
GXAsn1Converter.HexSystemTitleFromSubject(pkc10.Subject)));
}
certifications.Add(new GXCertificateRequest(CertificateType.DigitalSignature, pkc10));
reply.Clear();
//Generate certification request for key agreement.
if (!ReadDataBlock(ss.GenerateCertificate(Client, CertificateType.KeyAgreement), reply))
{
throw new GXDLMSException(reply.Error);
}
//Generate server certification.
pkc10 = new GXPkcs10((byte[])reply.Value);
//Validate subject.
if (!pkc10.Subject.Contains(subject))
{
throw new Exception(string.Format("Server system title '{0}' is not the same as in the generated certificate request '{1}'.",
GXDLMSTranslator.ToHex(ss.ServerSystemTitle),
GXAsn1Converter.HexSystemTitleFromSubject(pkc10.Subject)));
}
certifications.Add(new GXCertificateRequest(CertificateType.KeyAgreement, pkc10));
reply.Clear();
//Note! There is a limit how many request you can do in a day.
certs = GXPkcs10.GetCertificate(address, certifications);
//Save server certificates.
foreach (GXx509Certificate it in certs)
{
it.Save(GXx509Certificate.GetFilePath(it));
}
reply.Clear();
//Import server certificates.
foreach (GXx509Certificate it in certs)
{
if (!ReadDataBlock(ss.ImportCertificate(Client, it), reply))
{
throw new GXDLMSException(reply.Error);
}
reply.Clear();
}
//Export server certificates and verify it.
foreach (GXx509Certificate it in certs)
{
CertificateEntity entity;
byte[] st;
if (it.Subject.Contains(GXAsn1Converter.SystemTitleToSubject(ss.ServerSystemTitle)))
{
st = ss.ServerSystemTitle;
entity = CertificateEntity.Server;
}
else if (it.Subject.Contains(GXAsn1Converter.SystemTitleToSubject(clientST)))
{
st = clientST;
entity = CertificateEntity.Client;
}
else
{
//This is another certificate.
continue;
}
if (!ReadDataBlock(ss.ExportCertificateByEntity(Client, entity,
GXDLMSConverter.KeyUsageToCertificateType(it.KeyUsage), st), reply))
{
throw new GXDLMSException(reply.Error);
}
//Verify certificate.
GXx509Certificate exported = new GXx509Certificate((byte[])reply.Value);
if (!exported.Equals(it))
{
throw new ArgumentOutOfRangeException("Invalid server certificate.");
}
reply.Clear();
}
//Export server certificates using serial number and verify it.
foreach (GXx509Certificate it in certs)
{
if (!ReadDataBlock(ss.ExportCertificateBySerial(Client, it.SerialNumber,
ASCIIEncoding.ASCII.GetBytes(it.Issuer)), reply))
{
throw new GXDLMSException(reply.Error);
}
//Verify certificate.
GXx509Certificate exported = new GXx509Certificate((byte[])reply.Value);
if (!exported.Equals(it))
{
throw new ArgumentOutOfRangeException("Invalid server certificate.");
}
reply.Clear();
}
}
/// <summary>
/// Export client and server certificates from the meter.
/// </summary>
/// <param name="logicalName">Logical name of the security setup object.</param>
public void ExportMeterCertificates(string logicalName)
{
try
{
InitializeConnection();
GXDLMSSecuritySetup ss = new GXDLMSSecuritySetup(logicalName);
//Read used security suite.
Read(ss, 3);
//Client private keys are saved to this directory.
//Client might be different system title for each meter.
if (!Directory.Exists("Keys"))
{
Directory.CreateDirectory("Keys");
}
if (!Directory.Exists("Certificates"))
{
Directory.CreateDirectory("Certificates");
}
if (!Directory.Exists("Keys384"))
{
Directory.CreateDirectory("Keys384");
}
if (!Directory.Exists("Certificates384"))
{
Directory.CreateDirectory("Certificates384");
}
//Read server system title.
Read(ss, 5);
//Read certificates.
Read(ss, 6);
//Export meter certificates and save them.
GXReplyData reply = new GXReplyData();
foreach (GXDLMSCertificateInfo it in ss.Certificates)
{
reply.Clear();
//Export certification and verify it.
if (!ReadDataBlock(ss.ExportCertificateBySerial(Client, it.SerialNumber, ASCIIEncoding.ASCII.GetBytes(it.Issuer)), reply))
{
throw new GXDLMSException(reply.Error);
}
GXx509Certificate cert = new GXx509Certificate((byte[])reply.Value);
string path = GXAsn1Converter.GetFilePath(cert.PublicKey.Scheme, it.Type, GXAsn1Converter.SystemTitleFromSubject(it.Subject));
cert.Save(path);
}
}
finally
{
Close();
}
}
/// <summary>
/// Read all data from the meter.
/// </summary>
public void ReadAll(string outputFile)
{
try
{
InitializeConnection();
if (GetAssociationView(outputFile))
{
GetScalersAndUnits();
GetProfileGenericColumns();
}
GetReadOut();
GetProfileGenerics();
if (outputFile != null)
{
try
{
Client.Objects.Save(outputFile, new GXXmlWriterSettings() { UseMeterTime = true, IgnoreDefaultValues = false });
}
catch (Exception)
{
//It's OK if this fails.
}
}
}
finally
{
Close();
}
}
/// <summary>
/// Send SNRM Request to the meter.
/// </summary>
public void SNRMRequest()
{
GXReplyData reply = new GXReplyData();
byte[] data;
data = Client.SNRMRequest();
if (data != null)
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
}
ReadDataBlock(data, reply);
if (Trace == TraceLevel.Verbose)
{
Console.WriteLine("Parsing UA reply." + reply.ToString());
}
//Has server accepted client.
Client.ParseUAResponse(reply.Data);
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing UA reply succeeded.");
}
}
}
/// <summary>
/// Send AARQ Request to the meter.
/// </summary>
public void AarqRequest()
{
GXReplyData reply = new GXReplyData();
//Generate AARQ request.
//Split requests to multiple packets if needed.
//If password is used all data might not fit to one packet.
foreach (byte[] it in Client.AARQRequest())
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
}
reply.Clear();
ReadDataBlock(it, reply);
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing AARE reply" + reply.ToString());
}
//Parse reply.
Client.ParseAAREResponse(reply.Data);
reply.Clear();
//Get challenge Is HLS authentication is used.
if (Client.Authentication > Authentication.Low)
{
foreach (byte[] it in Client.GetApplicationAssociationRequest())
{
reply.Clear();
ReadDataBlock(it, reply);
}
Client.ParseApplicationAssociationResponse(reply.Data);
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing AARE reply succeeded.");
}
}
/// <summary>
/// Read Invocation counter (frame counter) from the meter and update it.
/// </summary>
private void UpdateFrameCounter()
{
//Read frame counter if GeneralProtection is used.
if (!string.IsNullOrEmpty(InvocationCounter) && Client.Ciphering != null && Client.Ciphering.Security != Security.None)
{
InitializeOpticalHead();
byte[] data;
GXReplyData reply = new GXReplyData();
Client.ProposedConformance |= Conformance.GeneralProtection;
int add = Client.ClientAddress;
Authentication auth = Client.Authentication;
Security security = Client.Ciphering.Security;
Signing signing = Client.Ciphering.Signing;
byte[] challenge = Client.CtoSChallenge;
try
{
Client.ClientAddress = 16;
Client.Authentication = Authentication.None;
Client.Ciphering.Security = Security.None;
Client.Ciphering.Signing = Signing.None;
data = Client.SNRMRequest();
if (data != null)
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Send SNRM request." + GXCommon.ToHex(data, true));
}
ReadDataBlock(data, reply);
if (Trace == TraceLevel.Verbose)
{
Console.WriteLine("Parsing UA reply." + reply.ToString());
}
//Has server accepted client.
Client.ParseUAResponse(reply.Data);
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing UA reply succeeded.");
}
}
//Generate AARQ request.
//Split requests to multiple packets if needed.
//If password is used all data might not fit to one packet.
foreach (byte[] it in Client.AARQRequest())
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
}
reply.Clear();
ReadDataBlock(it, reply);
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing AARE reply" + reply.ToString());
}
try
{
//Parse reply.
Client.ParseAAREResponse(reply.Data);
reply.Clear();
GXDLMSData d = new GXDLMSData(InvocationCounter);
Read(d, 2);
Client.Ciphering.InvocationCounter = 1 + Convert.ToUInt32(d.Value);
Console.WriteLine("Invocation counter: " + Convert.ToString(Client.Ciphering.InvocationCounter));
reply.Clear();
Disconnect();
}
catch (Exception Ex)
{
Disconnect();
throw Ex;
}
}
finally
{
Client.ClientAddress = add;
Client.Authentication = auth;
Client.Ciphering.Security = security;
Client.CtoSChallenge = challenge;
Client.Ciphering.Signing = signing;
}
}
}
/// <summary>
/// Send IEC disconnect message.
/// </summary>
void DiscIEC()
{
ReceiveParameters<string> p = new ReceiveParameters<string>()
{
AllData = false,
Eop = (byte)0x0A,
WaitTime = WaitTime * 1000
};
string data = (char)0x01 + "B0" + (char)0x03 + "\r\n";
Media.Send(data, null);
p.Eop = "\n";
p.AllData = true;
p.Count = 1;
Media.Receive(p);
}
/// <summary>
/// Initialize optical head.
/// </summary>
void InitializeOpticalHead()
{
if (Client.InterfaceType != InterfaceType.HdlcWithModeE)
{
return;
}
GXSerial serial = Media as GXSerial;
byte Terminator = (byte)0x0A;
Media.Open();
//Some meters need a little break.
Thread.Sleep(1000);
//Query device information.
string data = "/?!\r\n";
if (Trace > TraceLevel.Info)
{
Console.WriteLine("IEC Sending:" + data);
}
ReceiveParameters<string> p = new ReceiveParameters<string>()
{
AllData = false,
Eop = Terminator,
WaitTime = WaitTime * 1000
};
lock (Media.Synchronous)
{
Media.Send(data, null);
if (!Media.Receive(p))
{
//Try to move away from mode E.
try
{
Disconnect();
}
catch (Exception)
{
}
DiscIEC();
string str = "Failed to receive reply from the device in given time.";
if (Trace > TraceLevel.Info)
{
Console.WriteLine(str);
}
Media.Send(data, null);
if (!Media.Receive(p))
{
throw new Exception(str);
}
}
//If echo is used.
if (p.Reply == data)
{
p.Reply = null;
if (!Media.Receive(p))
{
//Try to move away from mode E.
GXReplyData reply = new GXReplyData();
Disconnect();
if (serial != null)
{
DiscIEC();
serial.DtrEnable = serial.RtsEnable = false;
serial.BaudRate = 9600;
serial.DtrEnable = serial.RtsEnable = true;
DiscIEC();
}
data = "Failed to receive reply from the device in given time.";
if (Trace > TraceLevel.Info)
{
Console.WriteLine(data);
}
throw new Exception(data);
}
}
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("IEC received: " + p.Reply);
}
int pos = 0;
//With some meters there might be some extra invalid chars. Remove them.
while (pos < p.Reply.Length && p.Reply[pos] != '/')
{
++pos;
}
if (p.Reply[pos] != '/')
{
p.WaitTime = 100;
Media.Receive(p);
DiscIEC();
throw new Exception("Invalid responce.");
}
string manufactureID = p.Reply.Substring(1 + pos, 3);
char baudrate = p.Reply[4 + pos];
int BaudRate = 0;
switch (baudrate)
{
case '0':
BaudRate = 300;
break;
case '1':
BaudRate = 600;
break;
case '2':
BaudRate = 1200;
break;
case '3':
BaudRate = 2400;
break;
case '4':
BaudRate = 4800;
break;
case '5':
BaudRate = 9600;
break;
case '6':
BaudRate = 19200;
break;
default:
throw new Exception("Unknown baud rate.");
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("BaudRate is : " + BaudRate.ToString());
}
//Send ACK
//Send Protocol control character
// "2" HDLC protocol procedure (Mode E)
byte controlCharacter = (byte)'2';
//Send Baud rate character
//Mode control character
byte ModeControlCharacter = (byte)'2';
//"2" //(HDLC protocol procedure) (Binary mode)
//Set mode E.
byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Moving to mode E.", arr);
}
lock (Media.Synchronous)
{
p.Reply = null;
Media.Send(arr, null);
//Some meters need this sleep. Do not remove.
Thread.Sleep(200);
p.WaitTime = 2000;
//Note! All meters do not echo this.
Media.Receive(p);
if (p.Reply != null)
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Received: " + p.Reply);
}
}
serial.BaudRate = BaudRate;
serial.DataBits = 8;
serial.Parity = Parity.None;
serial.StopBits = StopBits.One;
//Some meters need this sleep. Do not remove.
Thread.Sleep(800);
}
}
/// <summary>
/// Initialize connection to the meter.
/// </summary>
public void InitializeConnection()
{
Console.WriteLine("Standard: " + Client.Standard);
if (Client.Ciphering.Security != Security.None)
{
Console.WriteLine("Security: " + Client.Ciphering.Security);
Console.WriteLine("System title: " + GXCommon.ToHex(Client.Ciphering.SystemTitle, true));
Console.WriteLine("Authentication key: " + GXCommon.ToHex(Client.Ciphering.AuthenticationKey, true));
Console.WriteLine("Block cipher key " + GXCommon.ToHex(Client.Ciphering.BlockCipherKey, true));
if (Client.Ciphering.DedicatedKey != null)
{
Console.WriteLine("Dedicated key: " + GXCommon.ToHex(Client.Ciphering.DedicatedKey, true));
}
}
UpdateFrameCounter();
InitializeOpticalHead();
GXReplyData reply = new GXReplyData();
SNRMRequest();
//Generate AARQ request.
//Split requests to multiple packets if needed.
//If password is used all data might not fit to one packet.
foreach (byte[] it in Client.AARQRequest())
{
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Send AARQ request", GXCommon.ToHex(it, true));
}
reply.Clear();
ReadDataBlock(it, reply);
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing AARE reply" + reply.ToString());
}
//Parse reply.
Client.ParseAAREResponse(reply.Data);
Console.WriteLine("Conformance: " + Client.NegotiatedConformance);
reply.Clear();
//Get challenge Is HLS authentication is used.
if (Client.IsAuthenticationRequired)
{
foreach (byte[] it in Client.GetApplicationAssociationRequest())
{
reply.Clear();
ReadDataBlock(it, reply);
}
Client.ParseApplicationAssociationResponse(reply.Data);
}
if (Trace > TraceLevel.Info)
{
Console.WriteLine("Parsing AARE reply succeeded.");
}
}
/// <summary>
/// This method is used to update meter firmware.
/// </summary>
/// <param name="target"></param>
public void ImageUpdate(GXDLMSImageTransfer target, byte[] identification, byte[] data)
{
//Check that image transfer ia enabled.
GXReplyData reply = new GXReplyData();
ReadDataBlock(Client.Read(target, 5), reply);
Client.UpdateValue(target, 5, reply.Value);
if (!target.ImageTransferEnabled)
{
throw new Exception("Image transfer is not enabled");
}
//Step 1: Read image block size.
ReadDataBlock(Client.Read(target, 2), reply);
Client.UpdateValue(target, 2, reply.Value);
// Step 2: Initiate the Image transfer process.
ReadDataBlock(target.ImageTransferInitiate(Client, identification, data.Length), reply);
// Step 3: Transfers ImageBlocks.
int imageBlockCount;
ReadDataBlock(target.ImageBlockTransfer(Client, data, out imageBlockCount), reply);
//Step 4: Check the completeness of the Image.
ReadDataBlock(Client.Read(target, 3), reply);
Client.UpdateValue(target, 3, reply.Value);
// Step 5: The Image is verified;
ReadDataBlock(target.ImageVerify(Client), reply);
// Step 6: Before activation, the Image is checked;
//Get list to images to activate.
ReadDataBlock(Client.Read(target, 7), reply);
Client.UpdateValue(target, 7, reply.Value);
bool bFound = false;
foreach (GXDLMSImageActivateInfo it in target.ImageActivateInfo)
{
if (GXCommon.EqualBytes(it.Identification, identification))
{
bFound = true;
break;
}
}
//Read image transfer status.
ReadDataBlock(Client.Read(target, 6), reply);
Client.UpdateValue(target, 6, reply.Value);
if (target.ImageTransferStatus != Gurux.DLMS.Objects.Enums.ImageTransferStatus.VerificationSuccessful)
{
throw new Exception("Image transfer status is " + target.ImageTransferStatus.ToString());
}
if (!bFound)
{
throw new Exception("Image not found.");
}
//Step 7: Activate image.
ReadDataBlock(target.ImageActivate(Client), reply);
}
/// <summary>
/// Read association view.
/// </summary>
public bool GetAssociationView(string outputFile)
{
if (outputFile != null)
{
//Save Association view to the cache so it is not needed to retrieve every time.
if (File.Exists(outputFile))
{
try
{
Client.Objects.Clear();
Client.Objects.AddRange(GXDLMSObjectCollection.Load(outputFile));
return false;
}
catch (Exception)
{
if (File.Exists(outputFile))
{
File.Delete(outputFile);
}
}
}
}
GXReplyData reply = new GXReplyData();
ReadDataBlock(Client.GetObjectsRequest(), reply);
Client.ParseObjects(reply.Data, true);
//Access rights must read differently when short Name referencing is used.
if (!Client.UseLogicalNameReferencing)
{
GXDLMSAssociationShortName sn = (GXDLMSAssociationShortName)Client.Objects.FindBySN(0xFA00);
if (sn != null && sn.Version > 0)
{
Read(sn, 3);
}
}
if (outputFile != null)
{
try
{
Client.Objects.Save(outputFile, new GXXmlWriterSettings() { Values = false });
}
catch (Exception)
{
//It's OK if this fails.
return false;
}
}
return true;
}
/// <summary>
/// Read scalers and units.
/// </summary>
public void GetScalersAndUnits()
{
GXDLMSObjectCollection objs = Client.Objects.GetObjects(new ObjectType[] { ObjectType.Register, ObjectType.ExtendedRegister, ObjectType.DemandRegister });
//If trace is info.
if (Trace > TraceLevel.Warning)
{
Console.WriteLine("Read scalers and units from the device.");
}
//Access services are available only for general protection.
if ((Client.NegotiatedConformance & Conformance.Access) != 0 &&
(Client.Ciphering.Security == Security.None ||
(Client.NegotiatedConformance & Conformance.GeneralProtection) != 0))
{
List<GXDLMSAccessItem> list = new List<GXDLMSAccessItem>();
foreach (GXDLMSObject it in objs)
{
if ((it is GXDLMSRegister || it is GXDLMSExtendedRegister) && Client.CanRead(it, 3))
{
list.Add(new GXDLMSAccessItem(AccessServiceCommandType.Get, it, 3));
}
else if (it is GXDLMSDemandRegister && Client.CanRead(it, 4))
{
list.Add(new GXDLMSAccessItem(AccessServiceCommandType.Get, it, 4));
}
}
ReadByAccess(list);
}
else if ((Client.NegotiatedConformance & Gurux.DLMS.Enums.Conformance.MultipleReferences) != 0)
{
List<KeyValuePair<GXDLMSObject, int>> list = new List<KeyValuePair<GXDLMSObject, int>>();
foreach (GXDLMSObject it in objs)
{
if ((it is GXDLMSRegister || it is GXDLMSExtendedRegister) && Client.CanRead(it, 3))
{
list.Add(new KeyValuePair<GXDLMSObject, int>(it, 3));
}
if (it is GXDLMSDemandRegister && Client.CanRead(it, 4))
{
list.Add(new KeyValuePair<GXDLMSObject, int>(it, 4));
}
}
if (list.Count != 0)
{
try
{
ReadList(list);
}
catch (Exception)
{
Client.NegotiatedConformance &= ~Gurux.DLMS.Enums.Conformance.MultipleReferences;
}
}
}
if ((Client.NegotiatedConformance & Gurux.DLMS.Enums.Conformance.MultipleReferences) == 0)
{
//Read values one by one.