-
Notifications
You must be signed in to change notification settings - Fork 91
Expand file tree
/
Copy pathGXDLMSClient.py
More file actions
1668 lines (1538 loc) · 60.6 KB
/
Copy pathGXDLMSClient.py
File metadata and controls
1668 lines (1538 loc) · 60.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# --------------------------------------------------------------------------
# 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
# ---------------------------------------------------------------------------
from __future__ import print_function
from .GXDLMSSettings import GXDLMSSettings
from .enums import (
Authentication,
InterfaceType,
SourceDiagnostic,
DataType,
Conformance,
)
from .ConnectionState import ConnectionState
from .GXByteBuffer import GXByteBuffer
from .GXHdlcSettings import GXHdlcSettings
from .enums import Command, ObjectType
from .GXDLMS import GXDLMS
from ._GXAPDU import _GXAPDU
from ._HDLCInfo import _HDLCInfo
from .GXDLMSLNParameters import GXDLMSLNParameters
from .ActionRequestType import ActionRequestType
from .internal._GXCommon import _GXCommon
from .GetCommandType import GetCommandType
from .objects import GXDLMSObject, GXDLMSObjectCollection, GXDLMSData
from .internal._GXDataInfo import _GXDataInfo
from .ValueEventArgs import ValueEventArgs
from .GXDateTime import GXDateTime
from .SetRequestType import SetRequestType
from .GXDLMSSNParameters import GXDLMSSNParameters
from .VariableAccessSpecification import VariableAccessSpecification
from .GXSecure import GXSecure
from .GXDLMSConverter import GXDLMSConverter
from .GXDLMSLNCommandHandler import GXDLMSLNCommandHandler
from .GXDLMSSNCommandHandler import GXDLMSSNCommandHandler
from .enums.AccessServiceCommandType import AccessServiceCommandType
from .enums.ErrorCode import ErrorCode
from .GXDLMSTranslatorStructure import GXDLMSTranslatorStructure
from .enums.RequestTypes import RequestTypes
from .SerialnumberCounter import SerialNumberCounter
from ._GXObjectFactory import _GXObjectFactory
from .enums.AccessMode import AccessMode
from .enums.MethodAccessMode import MethodAccessMode
from .enums.AccessMode3 import AccessMode3
from .enums.MethodAccessMode3 import MethodAccessMode3
from .internal._GXLocalizer import _GXLocalizer
from .ecdsa.GXEcdsa import GXEcdsa
# pylint:disable=bad-option-value,too-many-instance-attributes,too-many-arguments,too-many-public-methods,useless-object-inheritance
class GXDLMSClient(object):
"""
GXDLMS implements methods to communicate with DLMS/COSEM metering devices.
"""
#
# Constructor.
#
# useLogicalNameReferencing: Is Logical Name referencing used.
# clientAddress: Server address.
# serverAddress: Client address.
# forAuthentication: Authentication type.
# password: Password if authentication is used.
# interfaceType: Interface type.
def __init__(
self,
useLogicalNameReferencing=True,
clientAddress=16,
serverAddress=1,
forAuthentication=Authentication.NONE,
password=None,
interfaceType=InterfaceType.HDLC,
):
# DLMS settings.
self.settings = GXDLMSSettings(False, self)
self.manufacturerId = None
self.settings.setUseLogicalNameReferencing(useLogicalNameReferencing)
self.clientAddress = clientAddress
self.serverAddress = serverAddress
self.authentication = forAuthentication
if not password:
self.password = None
elif isinstance(password, str):
self.password = _GXCommon.getBytes(password)
elif isinstance(password, (bytes, bytearray)):
self.password = password
self.interfaceType = interfaceType
self.translator = None
self.throwExceptions = True
self.obisCodes = None
# Is authentication required.
self.isAuthenticationRequired = False
# Auto increase Invoke ID.
self.autoIncreaseInvokeID = False
# If protected release is used release is including a ciphered xDLMS
# Initiate request.
self.useProtectedRelease = False
# Initialize challenge that is restored after the connection is closed.
self.initializeChallenge = None
# Initialize PDU size that is restored after the connection is closed.
self.initializePduSize = 0
# Initialize Max HDLC transmission size that is restored after the connection is closed.
self.initializeMaxInfoTX = 0
# Initialize Max HDLC receive size that is restored after the connection is closed.
self.initializeMaxInfoRX = 0
# Initialize max HDLC window size in transmission that is restored after the connection is closed.
self.initializeWindowSizeTX = 0
# Initialize max HDLC window size in receive that is restored after the connection is closed.
self.initializeWindowSizeRX = 0
def getObjects(self):
return self.settings.objects
objects = property(getObjects)
#
# Set starting packet index. Default is One based, but some meters
# use Zero
# based value. Usually this is not used.
#
# value
# Zero based starting index.
#
def setStartingPacketIndex(self, value):
self.settings.setStartingPacketIndex(value)
def getUserId(self):
return self.settings.userId
def setUserId(self, value):
if value < -1 or value > 255:
raise ValueError("Invalid user Id.")
self.settings.userId = value
#
# User id is the identifier of the user. This value is used if user
# list on Association LN is used.
userId = property(getUserId, setUserId)
def getClientAddress(self):
return self.settings.clientAddress
def setClientAddress(self, value):
self.settings.clientAddress = value
#
# Client address.
#
clientAddress = property(getClientAddress, setClientAddress)
def __getServerAddress(self):
# pylint: disable=unused-private-member
return self.settings.serverAddress
def __setServerAddress(self, value):
# pylint: disable=unused-private-member
self.settings.serverAddress = value
#
# Server Address.
#
serverAddress = property(__getServerAddress, __setServerAddress)
@property
def compressionOptions(self):
"""
Gets the compression options used for data transmission.
"""
return self.settings.compressionOptions
@compressionOptions.setter
def compressionOptions(self, value):
self.settings.compressionOptions = value
def getServerAddressSize(self):
return self.settings.serverAddressSize
def setServerAddressSize(self, value):
self.settings.serverAddressSize = value
#
# Server address size in bytes. If it is Zero it is counted
# automatically.
#
serverAddressSize = property(getServerAddressSize, setServerAddressSize)
def getSourceSystemTitle(self):
return self.settings.sourceSystemTitle
#
# Source system title.
# Meter returns system title when ciphered connection is made or GMAC
# authentication is used.
#
sourceSystemTitle = property(getSourceSystemTitle)
def getGbtWindowSize(self):
return self.settings.gbtWindowSize
def setGbtWindowSize(self, value):
self.settings.gbtWindowSize = value
#
# GBT window size.
#
gbtWndowSize = property(getGbtWindowSize, setGbtWindowSize)
def getMaxReceivePDUSize(self):
return self.settings.maxPduSize
def setMaxReceivePDUSize(self, value):
self.settings.maxPduSize = value
#
# Retrieves the maximum size of received PDU. PDU size tells
# maximum size
# of PDU packet. Value can be from 0 to 0xFFFF. By default the
# value is
# 0xFFFF.
#
# @see GXDLMSClient.clientAddress
# @see GXDLMSClient.serverAddress
# @see GXDLMSClient.useLogicalNameReferencing
# Maximum size of received PDU.
#
maxReceivePDUSize = property(getMaxReceivePDUSize, setMaxReceivePDUSize)
def getUseLogicalNameReferencing(self):
return self.settings.getUseLogicalNameReferencing()
def setUseLogicalNameReferencing(self, value):
self.settings.setUseLogicalNameReferencing(value)
#
# Determines, whether Logical, or Short name, referencing is used.
# Referencing depends on the device to communicate with. Normally,
# a device
# supports only either Logical or Short name referencing. The
# referencing
# is defined by the device manufacturer. If the referencing is
# wrong, the
# SNMR message will fail.
#
# Is Logical Name referencing used.
#
useLogicalNameReferencing = property(
getUseLogicalNameReferencing, setUseLogicalNameReferencing
)
def getCtoSChallenge(self):
return self.settings.ctoSChallenge
def setCtoSChallenge(self, value):
self.settings.useCustomChallenge = value is not None
self.settings.ctoSChallenge = value
#
# Client to Server custom challenge.
# This is for debugging purposes. Reset custom challenge settings
# CtoSChallenge to null.
#
# Client to Server custom challenge.
#
# Client to Server custom challenge.
#
ctoSChallenge = property(getCtoSChallenge, setCtoSChallenge)
def getUseUtc2NormalTime(self):
return self.settings.useUtc2NormalTime
def setUseUtc2NormalTime(self, value):
self.settings.useUtc2NormalTime = value
#
# Standard says that Time zone is from normal time to UTC in minutes.
# If meter is configured to use UTC time (UTC to normal time) set this to
# true.
#
# True, if UTC time is used.
#
useUtc2NormalTime = property(getUseUtc2NormalTime, setUseUtc2NormalTime)
def getIncreaseInvocationCounterForGMacAuthentication(self):
return self.settings.increaseInvocationCounterForGMacAuthentication
def setIncreaseInvocationCounterForGMacAuthentication(self, value):
self.settings.increaseInvocationCounterForGMacAuthentication = value
increaseInvocationCounterForGMacAuthentication = property(
getIncreaseInvocationCounterForGMacAuthentication,
setIncreaseInvocationCounterForGMacAuthentication,
)
"""Some meters expect that Invocation Counter is increased for GMAC Authentication when connection is established."""
def getDateTimeSkips(self):
return self.settings.dateTimeSkips
def setDateTimeSkips(self, value):
self.settings.dateTimeSkips = value
dateTimeSkips = property(getDateTimeSkips, setDateTimeSkips)
"""Skipped date time fields. This value can be used if meter can't handle deviation or status."""
def getStandard(self):
return self.settings.standard
def setStandard(self, value):
self.settings.standard = value
#
# Used standard.
#
standard = property(getStandard, setStandard)
def getPassword(self):
return self.settings.password
def setPassword(self, value):
self.settings.password = value
#
# Retrieves the password that is used in communication. If
# authentication
# is set to none, password is not used.
#
# @see GXDLMSClient#getAuthentication
# Used password.
#
password = property(getPassword, setPassword)
def getNegotiatedConformance(self):
return self.settings.negotiatedConformance
def setNegotiatedConformance(self, value):
self.settings.negotiatedConformance = value
#
# Functionality what server offers.
#
negotiatedConformance = property(getNegotiatedConformance, setNegotiatedConformance)
def getProposedConformance(self):
return self.settings.proposedConformance
def setProposedConformance(self, value):
self.settings.proposedConformance = value
#
# When connection is made client tells what kind of services
# it want's to use.
#
proposedConformance = property(getProposedConformance, setProposedConformance)
def getAuthentication(self):
return self.settings.authentication
def setAuthentication(self, value):
self.settings.authentication = value
#
# Retrieves the authentication used in communicating with the
# device. By
# default authentication is not used. If authentication is used,
# set the
# password with the Password property.
#
# @see GXDLMSClient#getPassword
# @see GXDLMSClient#getClientAddress
# Used authentication.
#
authentication = property(getAuthentication, setAuthentication)
def getPriority(self):
return self.settings.priority
def setPriority(self, value):
self.settings.priority = value
#
# Used Priority.
#
priority = property(getPriority, setPriority)
def getServiceClass(self):
return self.settings.serviceClass
def setServiceClass(self, value):
self.settings.serviceClass = value
#
# Used service class.
#
serviceClass = property(getServiceClass, setServiceClass)
def getInvokeID(self):
return self.settings.invokeId
def setInvokeID(self, value):
self.settings.invokeID = value
#
# Invoke ID.
#
invokeID = property(getInvokeID, setInvokeID)
def getInterfaceType(self):
return self.settings.interfaceType
def setInterfaceType(self, value):
self.settings.interfaceType = value
#
# Interface type.
#
interfaceType = property(getInterfaceType, setInterfaceType)
"""Interface type."""
#
# Information from the connection size that server can
# handle.
#
@property
def limits(self):
"""Obsolete. Use hdlcSettings instead."""
return self.settings.hdlc
#
# HDLC framing settings.
#
@property
def hdlcSettings(self):
return self.settings.hdlc
def getGateway(self):
return self.settings.gateway
def setGateway(self, value):
self.settings.gateway = value
#
# Gateway settings.
#
gateway = property(getGateway, setGateway)
def getProtocolVersion(self):
return self.settings.protocolVersion
def setProtocolVersion(self, value):
self.settings.protocolVersion = value
#
# Protocol version.
#
protocolVersion = property(getProtocolVersion, setProtocolVersion)
#
# Generates SNRM request. his method is used to generate send
# SNRMRequest.
# Before the SNRM request can be generated, at least the following
# properties must be set:
# <ul>
# <li>ClientAddress</li>
# <li>ServerAddress</li>
# </ul>
# <b>Note! </b>According to IEC 62056-47: when communicating using
# TCP/IP,
# the SNRM request is not send.
#
# @see GXDLMSClient#getClientAddress
# @see GXDLMSClient#getServerAddress
# @see GXDLMSClient#parseUAResponse
# SNRM request as byte array.
#
def snrmRequest(self):
# Save default values.
self.initializeMaxInfoTX = self.hdlcSettings.maxInfoTX
self.initializeMaxInfoRX = self.hdlcSettings.maxInfoRX
self.initializeWindowSizeTX = self.hdlcSettings.windowSizeTX
self.initializeWindowSizeRX = self.hdlcSettings.windowSizeRX
self.settings.connected = ConnectionState.NONE
self.isAuthenticationRequired = False
# SNRM request is not used in network connections.
if self.interfaceType == InterfaceType.WRAPPER:
return None
data = GXByteBuffer(25)
data.setUInt8(0x81)
# FromatID
data.setUInt8(0x80)
# GroupID
data.setUInt8(0)
# Length.
# If custom HDLC parameters are used.
if GXHdlcSettings.DEFAULT_MAX_INFO_TX != self.hdlcSettings.maxInfoTX:
data.setUInt8(_HDLCInfo.MAX_INFO_TX)
GXDLMS.appendHdlcParameter(data, self.hdlcSettings.maxInfoTX)
if GXHdlcSettings.DEFAULT_MAX_INFO_RX != self.hdlcSettings.maxInfoRX:
data.setUInt8(_HDLCInfo.MAX_INFO_RX)
GXDLMS.appendHdlcParameter(data, self.hdlcSettings.maxInfoRX)
if GXHdlcSettings.DEFAULT_WINDOWS_SIZE_TX != self.hdlcSettings.windowSizeTX:
data.setUInt8(_HDLCInfo.WINDOW_SIZE_TX)
data.setUInt8(4)
data.setUInt32(self.hdlcSettings.windowSizeTX)
if GXHdlcSettings.DEFAULT_WINDOWS_SIZE_RX != self.hdlcSettings.windowSizeRX:
data.setUInt8(_HDLCInfo.WINDOW_SIZE_RX)
data.setUInt8(4)
data.setUInt32(self.hdlcSettings.windowSizeRX)
# If default HDLC parameters are not used.
if data.size != 3:
data.setUInt8(len(data) - 3, 2)
else:
data = None
return GXDLMS.getHdlcFrame(self.settings, Command.SNRM, data)
#
# Parses UAResponse from byte array.
#
# data: # Received message from the server.
# @see GXDLMSClient#snrmRequest
#
def parseUAResponse(self, data):
if not isinstance(data, GXByteBuffer):
data = GXByteBuffer(data)
GXDLMS.parseSnrmUaResponse(data, self.settings.hdlc)
self.settings.connected = ConnectionState.HDLC
#
# Generate AARQ request. Because all_ meters can't read all_ data in
# one
# packet, the packet must be split first, by using
# SplitDataToPackets
# method.
#
# AARQ request as byte array.
# @see GXDLMSClient#parseAareResponse
#
def aarqRequest(self):
# pylint: disable=bad-option-value,redefined-variable-type
# Save default values.
self.initializePduSize = self.maxReceivePDUSize
self.initializeChallenge = self.settings.getStoCChallenge()
self.settings.connected = self.settings.connected & ~ConnectionState.DLMS
buff = GXByteBuffer(20)
self.settings.resetBlockIndex()
GXDLMS.checkInit(self.settings)
self.settings.setStoCChallenge(None)
if self.autoIncreaseInvokeID:
self.settings.setInvokeID(0)
else:
self.settings.setInvokeID(1)
# If authentication or ciphering is used.
if self.authentication > Authentication.LOW:
if not self.settings.useCustomChallenge:
self.settings.ctoSChallenge = GXSecure.generateChallenge()
else:
self.settings.setCtoSChallenge(None)
_GXAPDU.generateAarq(self.settings, self.settings.cipher, None, buff)
reply = None
if self.settings.getUseLogicalNameReferencing():
p = GXDLMSLNParameters(self.settings, 0, Command.AARQ, 0, buff, None, 0xFF)
reply = GXDLMS.getLnMessages(p)
else:
p = GXDLMSSNParameters(self.settings, Command.AARQ, 0, 0, None, buff)
reply = GXDLMS.getSnMessages(p)
return reply
#
# Parses the AARE response. Parse method will update the following
# data:
# <ul>
# <li>DLMSVersion</li>
# <li>MaxReceivePDUSize</li>
# <li>UseLogicalNameReferencing</li>
# <li>LNSettings or SNSettings</li>
# </ul>
# LNSettings or SNSettings will be updated, depending on the
# referencing,
# Logical name or Short name.
#
# reply
# Received data.
# @see GXDLMSClient#aarqRequest
# @see GXDLMSClient#useLogicalNameReferencing
# @see GXDLMSClient#negotiatedConformance
# @see GXDLMSClient#proposedConformance
#
def parseAareResponse(self, reply):
self.isAuthenticationRequired = (
_GXAPDU.parsePDU(self.settings, self.settings.cipher, reply, None)
== SourceDiagnostic.AUTHENTICATION_REQUIRED
)
if self.settings.dlmsVersion != 6:
raise ValueError("Invalid DLMS version number.")
if not self.isAuthenticationRequired:
self.settings.connected = self.settings.connected | ConnectionState.DLMS
#
# Is authentication Required.
#
def getIsAuthenticationRequired(self):
return self.isAuthenticationRequired
#
# Get challenge request if HLS authentication is used.
#
def getApplicationAssociationRequest(self):
if (
self.settings.authentication != Authentication.HIGH_ECDSA
and self.settings.authentication != Authentication.HIGH_GMAC
and not self.settings.password
):
raise ValueError("Password is invalid.")
self.settings.resetBlockIndex()
# Count challenge for Landis+Gyr. L+G is using custom way to count the
# challenge.
if (
self.manufacturerId == "LGZ"
and self.settings.authentication == Authentication.HIGH
):
challenge = self.encryptLandisGyrHighLevelAuthentication(
self.settings.password, self.settings.stoCChallenge
)
if self.useLogicalNameReferencing:
return self.__method(
"0.0.40.0.0.255",
ObjectType.ASSOCIATION_LOGICAL_NAME,
1,
challenge,
DataType.OCTET_STRING,
)
return self.__method(
0xFA00,
ObjectType.ASSOCIATION_SHORT_NAME,
8,
challenge,
DataType.OCTET_STRING,
)
if self.settings.authentication == Authentication.HIGH_GMAC:
pw = self.settings.cipher.systemTitle
elif self.settings.authentication == Authentication.HIGH_SHA256:
tmp = GXByteBuffer()
tmp.set(self.settings.password)
tmp.set(self.settings.cipher.systemTitle)
tmp.set(self.settings.sourceSystemTitle)
tmp.set(self.settings.stoCChallenge)
tmp.set(self.settings.ctoSChallenge)
pw = tmp.array()
elif self.settings.authentication == Authentication.HIGH_ECDSA:
tmp = GXByteBuffer()
tmp.set(self.settings.cipher.systemTitle)
tmp.set(self.settings.sourceSystemTitle)
tmp.set(self.settings.stoCChallenge)
tmp.set(self.settings.ctoSChallenge)
pw = tmp.array()
else:
pw = self.settings.password
challenge = GXSecure.secure(
self.settings,
self.settings.cipher,
self.settings.cipher.invocationCounter,
self.settings.getStoCChallenge(),
pw,
)
self.settings.cipher.invocationCounter += 1
if self.useLogicalNameReferencing:
return self.__method(
"0.0.40.0.0.255",
ObjectType.ASSOCIATION_LOGICAL_NAME,
1,
challenge,
DataType.OCTET_STRING,
)
return self.__method(
0xFA00,
ObjectType.ASSOCIATION_SHORT_NAME,
8,
challenge,
DataType.OCTET_STRING,
)
#
# Parse server's challenge if HLS authentication is used.
#
# reply
# Received reply from the server.
#
def parseApplicationAssociationResponse(self, reply):
# Landis+Gyr is not returning StoC.
if (
self.manufacturerId == "LGZ"
and self.settings.authentication == Authentication.HIGH
):
self.settings.connected |= ConnectionState.DLMS
else:
info = _GXDataInfo()
equals = False
ic = 0
value = _GXCommon.getData(self.settings, reply, info)
if value:
if self.settings.authentication == Authentication.HIGH_ECDSA:
if not self.settings.cipher.signingKeyPair:
raise ValueError("SigningKeyPair is empty.")
tmp2 = GXByteBuffer()
tmp2.set(self.settings.sourceSystemTitle)
tmp2.set(self.settings.cipher.systemTitle)
tmp2.set(self.settings.ctoSChallenge)
tmp2.set(self.settings.stoCChallenge)
sig = GXEcdsa(self.settings.cipher.signingKeyPair[0])
equals = sig.verify(value, tmp2.array())
else:
if self.settings.authentication == Authentication.HIGH_GMAC:
secret = self.settings.sourceSystemTitle
bb = GXByteBuffer(value)
bb.getUInt8()
ic = bb.getUInt32()
elif self.settings.authentication == Authentication.HIGH_SHA256:
tmp2 = GXByteBuffer()
tmp2.set(self.settings.password)
tmp2.set(self.settings.sourceSystemTitle)
tmp2.set(self.settings.cipher.systemTitle)
tmp2.set(self.settings.ctoSChallenge)
tmp2.set(self.settings.stoCChallenge)
secret = tmp2.array()
else:
secret = self.settings.password
tmp = GXSecure.secure(
self.settings,
self.settings.cipher,
ic,
self.settings.getCtoSChallenge(),
secret,
)
challenge = GXByteBuffer(tmp)
equals = challenge.compare(value)
if not equals:
print(
"Invalid StoC:"
+ GXByteBuffer.hex(value, True)
+ "-"
+ GXByteBuffer.hex(tmp, True)
)
else:
print("Server did not accept CtoS.")
if not equals:
raise Exception(
"parseApplicationAssociationResponse failed. "
+ " Server to Client do not match."
)
self.settings.connected |= ConnectionState.DLMS
def releaseRequest(self):
if (self.settings.connected & ConnectionState.DLMS) == 0:
return None
buff = GXByteBuffer()
# Restore default values.
self.maxReceivePDUSize = self.initializePduSize
self.settings.setCtoSChallenge(self.initializeChallenge)
if self.useProtectedRelease:
buff.setUInt8(0)
buff.setUInt8(0x80)
buff.setUInt8(1)
buff.setUInt8(0)
# Increase IC.
if self.settings.cipher and self.settings.cipher.isCiphered:
self.settings.cipher.invocationCounter = (
self.settings.cipher.invocationCounter + 1
)
_GXAPDU.generateUserInformation(
self.settings, self.settings.cipher, None, buff
)
buff.setUInt8(len(buff) - 1, 0)
else:
buff.setUInt8(3)
buff.setUInt8(0x80)
buff.setUInt8(1)
buff.setUInt8(0)
if self.useLogicalNameReferencing:
p = GXDLMSLNParameters(
self.settings, 0, Command.RELEASE_REQUEST, 0, buff, None, 0xFF
)
reply = GXDLMS.getLnMessages(p)
else:
reply = GXDLMS.getSnMessages(
GXDLMSSNParameters(
self.settings, Command.RELEASE_REQUEST, 0xFF, 0xFF, None, buff
)
)
self.settings.connected = self.settings.connected & ~ConnectionState.DLMS
return reply
def disconnectRequest(self, force=False):
if not force and self.settings.connected == ConnectionState.NONE:
return None
if GXDLMS.useHdlc(self.interfaceType):
self.settings.connected = ConnectionState.NONE
reply = GXDLMS.getHdlcFrame(self.settings, Command.DISCONNECT_REQUEST, None)
elif force or self.settings.connected == ConnectionState.DLMS:
reply = self.releaseRequest()
if reply:
reply = reply[0]
if GXDLMS.useHdlc(self.settings.interfaceType):
# Restore default HDLC values.
self.hdlcSettings.maxInfoTX = self.initializeMaxInfoTX
self.hdlcSettings.maxInfoRX = self.initializeMaxInfoRX
self.hdlcSettings.windowSizeTX = self.initializeWindowSizeTX
self.hdlcSettings.windowSizeRX = self.initializeWindowSizeRX
# Restore default values.
self.maxReceivePDUSize = self.initializePduSize
self.settings.connected = ConnectionState.NONE
self.settings.resetFrameSequence()
return reply
@classmethod
def __createDLMSObject(
cls, classID, version, baseName, ln, accessRights, lnVersion
):
type_ = classID
obj = cls.createObject(type_)
GXDLMSClient.__updateObjectData(
obj, type_, version, baseName, ln, accessRights, lnVersion
)
return obj
def parseSNObjects(self, buff, onlyKnownObjects, ignoreInactiveObjects):
# pylint: disable=unidiomatic-typecheck
buff.position = 0
size = buff.getUInt8()
if size != 0x01:
raise Exception("Invalid response.")
items = GXDLMSObjectCollection(self)
cnt = _GXCommon.getObjectCount(buff)
info = _GXDataInfo()
objPos = 0
while objPos != cnt:
if buff.position == len(buff):
break
info.count = 0
info.index = 0
info.type_ = DataType.NONE
objects = _GXCommon.getData(self.settings, buff, info)
if len(objects) != 4:
raise Exception("Invalid structure format.")
classID = objects[1]
baseName = int(objects[0]) & 0xFFFF
comp = GXDLMSClient.__createDLMSObject(
classID, objects[2], baseName, objects[3], None, 2
)
if not onlyKnownObjects or type(comp) != GXDLMSObject:
if not ignoreInactiveObjects or comp.logicalName != "0.0.127.0.0.0":
items.append(comp)
else:
print("Unknown object : " + str(classID) + " " + str(baseName))
objPos += 1
return items
@classmethod
def __updateObjectData(
cls, obj, objectType, version, baseName, logicalName, accessRights, lnVersion
):
obj.objectType = objectType
if accessRights:
for attributeAccess in accessRights[0]:
id_ = attributeAccess[0]
if id_ > 0:
mode = attributeAccess[1]
if lnVersion < 3:
obj.setAccess(id_, AccessMode(mode))
else:
obj.setAccess3(id_, AccessMode3(mode))
for methodAccess in accessRights[1]:
id_ = methodAccess[0]
tmp = 0
if isinstance(methodAccess[1], bool):
if bool((methodAccess)[1]):
tmp = 1
else:
tmp = 0
else:
tmp = methodAccess[1]
if lnVersion < 3:
obj.setMethodAccess(id_, MethodAccessMode(tmp))
else:
obj.setMethodAccess3(id_, MethodAccessMode3(tmp))
if baseName is not None:
obj.shortName = int(baseName)
if version is not None:
obj.version = int(version)
obj.logicalName = _GXCommon.toLogicalName(logicalName)
def parseObjects(self, data, onlyKnownObjects=True, ignoreInactiveObjects=True):
if not data:
raise Exception("Invalid parameter.")
objects = None
if self.useLogicalNameReferencing:
objects = self.parseLNObjects(data, onlyKnownObjects, ignoreInactiveObjects)
else:
objects = self.parseSNObjects(data, onlyKnownObjects, ignoreInactiveObjects)
self.settings.objects = objects
c = GXDLMSConverter(self.standard)
c.updateOBISCodeInformation(objects)
return objects
def parseLNObjects(self, buff, onlyKnownObjects, ignoreInactiveObjects):
# pylint: disable=unidiomatic-typecheck
size = buff.getInt8()
if size != 0x01:
raise Exception("Invalid response.")
items = GXDLMSObjectCollection(self)
info = _GXDataInfo()
cnt = _GXCommon.getObjectCount(buff)
lnVersion = 2
objPos = 0
# Find LN Version because some meters don't add LN Association the first object.
pos = buff.position
while objPos != cnt:
if buff.position == len(buff):
break
info.type_ = DataType.NONE
info.index = 0
info.count = 0
objects = _GXCommon.getData(self.settings, buff, info)
if len(objects) != 4:
raise Exception("Invalid structure format.")
ot = objects[0]
# Get LN association version.
if (
ot == int(ObjectType.ASSOCIATION_LOGICAL_NAME)
and _GXCommon.toLogicalName(objects[2]) == "0.0.40.0.0.255"
):
lnVersion = int(objects[1])
break
objPos = 0
buff.position = pos
while objPos != cnt:
if buff.position == len(buff):
break
info.type_ = DataType.NONE
info.index = 0
info.count = 0
objects = _GXCommon.getData(self.settings, buff, info)
if len(objects) != 4:
raise Exception("Invalid structure format.")
classID = objects[0]
if classID > 0:
comp = GXDLMSClient.__createDLMSObject(
classID, objects[1], 0, objects[2], objects[3], lnVersion
)
if not onlyKnownObjects or type(comp) != GXDLMSObject:
if not ignoreInactiveObjects or comp.logicalName != "0.0.127.0.0.0":
items.append(comp)
else:
print(
"Unknown object : "
+ str(classID)
+ " "
+ _GXCommon.toLogicalName(objects[2])
)
objPos += 1
return items
def updateValue(self, target, attributeIndex, value, parameters=None):
if value and target.getDataType(attributeIndex) == DataType.NONE:
target.setDataType(attributeIndex, _GXCommon.getDLMSDataType(value))
if isinstance(value, (bytes, bytearray)):
type_ = target.getUIDataType(attributeIndex)