-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathGXDLMSTranslator.py
More file actions
2671 lines (2627 loc) · 107 KB
/
GXDLMSTranslator.py
File metadata and controls
2671 lines (2627 loc) · 107 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
import logging
import xml.etree.cElementTree as ET
from .internal._GXCommon import _GXCommon
from .GXByteBuffer import GXByteBuffer
from .ActionRequestType import ActionRequestType
from .enums.TranslatorOutputType import TranslatorOutputType
from .TranslatorSimpleTags import TranslatorSimpleTags
from .TranslatorStandardTags import TranslatorStandardTags
from .GXDLMSTranslatorStructure import GXDLMSTranslatorStructure
from .GXDLMSSettings import GXDLMSSettings
from .enums import Command, Security
from .GXCiphering import GXCiphering
from .GXReplyData import GXReplyData
from .GXDLMSLNCommandHandler import GXDLMSLNCommandHandler
from .GXDLMSSNCommandHandler import GXDLMSSNCommandHandler
from ._GXAPDU import _GXAPDU
from .GXDLMS import GXDLMS
from .TranslatorTags import TranslatorTags
from .internal._GXDataInfo import _GXDataInfo
from .GXDLMSXmlSettings import GXDLMSXmlSettings
from .enums.InterfaceType import InterfaceType
from .enums.DataType import DataType
from .GXDLMSLNParameters import GXDLMSLNParameters
from .enums.HdlcFrameType import HdlcFrameType
from .GXDLMSSNParameters import GXDLMSSNParameters
from .enums.BerType import BerType
from .enums.RequestTypes import RequestTypes
from .GXDLMSConverter import GXDLMSConverter
from ._HDLCInfo import _HDLCInfo
from .TranslatorGeneralTags import TranslatorGeneralTags
from .SingleReadResponse import SingleReadResponse
from .VariableAccessSpecification import VariableAccessSpecification
from .enums.AccessServiceCommandType import AccessServiceCommandType
from .enums.Service import Service
from .ServiceError import ServiceError
from .enums.Priority import Priority
from .enums.ServiceClass import ServiceClass
from .GXDateTime import GXDateTime
from .SetResponseType import SetResponseType
from .GetCommandType import GetCommandType
from .SetRequestType import SetRequestType
from .enums.ErrorCode import ErrorCode
from .ActionResponseType import ActionResponseType
from .enums.Authentication import Authentication
from .enums.AssociationResult import AssociationResult
from .enums.SourceDiagnostic import SourceDiagnostic
from .AesGcmParameter import AesGcmParameter
from .GXDLMSException import GXDLMSException
from .enums.Standard import Standard
from .GXDLMSTranslatorMessage import GXDLMSTranslatorMessage
from .plc.enums import PlcSourceAddress, PlcDestinationAddress
# pylint:disable=bad-option-value,too-many-instance-attributes,too-many-function-args,too-many-public-methods,too-many-public-methods,too-many-function-args,too-many-instance-attributes,old-style-class,raise-missing-from
logger = logging.getLogger(__name__)
class GXDLMSTranslator:
"""
This class is used to translate DLMS frame or PDU to xml.
"""
def __init__(self, type_=TranslatorOutputType.SIMPLE_XML):
"""
Constructor.
type_: Translator output type.
"""
self.tags = dict()
self.tagsByName = dict()
# Are numeric values shows as hex.
self.hex = True
# Is string serialized as hex. {@link messageToXml} {@link PduOnly}
self.showStringAsHex = False
# Sending data in multiple frames.
self.multipleFrames = False
# If only PDUs are shown and PDU is received on parts.
self.pduFrames = GXByteBuffer()
# Is only PDU shown when data is parsed with messageToXml.
# {@link messageToXml} {@link CompleatePdu}
self.pduOnly = False
self.outputType = None
# Is XML declaration skipped.
self.omitXmlDeclaration = False
# Is XML name space skipped.
self.omitXmlNameSpace = False
# Add comments.
self.comments = False
# Used security.
self.security = Security.NONE
# System title.
self.systemTitle = "ABCDEFGH".encode()
# Block cipher key.
self.blockCipherKey = bytearray(
(
0x00,
0x01,
0x02,
0x03,
0x04,
0x05,
0x06,
0x07,
0x08,
0x09,
0x0A,
0x0B,
0x0C,
0x0D,
0x0E,
0x0F,
)
)
# Authentication key.
self.authenticationKey = bytearray(
(
0xD0,
0xD1,
0xD2,
0xD3,
0xD4,
0xD5,
0xD6,
0xD7,
0xD8,
0xD9,
0xDA,
0xDB,
0xDC,
0xDD,
0xDE,
0xDF,
)
)
# Invocation Counter.
self.invocationCounter = 0
# Dedicated key.
self.dedicatedKey = None
# Server system title.
self.serverSystemTitle = None
self.outputType = type_
# Is only complete PDU parsed and shown.
self.completePdu = False
self.__getTags(self.outputType, self.tags, self.tagsByName)
self.standard = Standard.DLMS
#
# Find next frame from the string. Position of data is set to the begin of
# new frame. If PDU is None it is not updated.
#
# @param data
# Data where frame is search.
# @param pdu
# PDU of received frame is set here.
# Is new frame found.
def findNextFrame(self, msg, pdu):
if not isinstance(msg, (GXDLMSTranslatorMessage)):
if not isinstance(msg, (GXByteBuffer)):
data = GXByteBuffer(msg)
else:
data = msg
msg = GXDLMSTranslatorMessage()
msg.message = data
msg.sourceAddress = msg.targetAddress = 0
original = msg.message.position
msg.exception = None
data = msg.message
settings = GXDLMSSettings(True, None)
reply = GXReplyData()
reply.moreData = msg.moreData
reply.xml = GXDLMSTranslatorStructure(
self.outputType,
self.omitXmlNameSpace,
self.hex,
self.showStringAsHex,
self.comments,
self.tags,
)
pos = 0
found = False
while data.position < len(data):
if (
msg.interfaceType
in (None, InterfaceType.HDLC, InterfaceType.HDLC_WITH_MODE_E)
and data.getUInt8(data.position) == 0x7E
):
pos = data.position
settings.interfaceType = InterfaceType.HDLC
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif (
msg.interfaceType in (None, InterfaceType.WRAPPER)
and data.getUInt16(data.position) == 0x1
):
pos = data.position
settings.interfaceType = InterfaceType.WRAPPER
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif (
msg.interfaceType in (None, InterfaceType.PLC)
and msg.message.getUInt8(msg.message.position) == 2
):
pos = data.position
settings.interfaceType = InterfaceType.PLC
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif msg.interfaceType in (
None,
InterfaceType.WIRED_MBUS,
) and GXDLMS.isWiredMBusData(msg.message):
pos = data.position
settings.interfaceType = InterfaceType.WIRED_MBUS
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif msg.interfaceType in (
None,
InterfaceType.WIRELESS_MBUS,
) and GXDLMS.isWirelessMBusData(msg.message):
pos = data.position
settings.interfaceType = InterfaceType.WIRELESS_MBUS
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
data.position = data.position + 1
msg.moreData = reply.moreData
msg.sourceAddress = reply.sourceAddress
msg.targetAddress = reply.targetAddress
if pdu:
pdu.clear()
pdu.set(data.data, 0, len(data))
r = data.position != len(data)
if not found:
data.position = original
return r
#
# Find next frame from the string. Position of data is set to the begin of
# new frame. If PDU is None it is not updated.
#
# @param data
# Data where frame is search.
# @param pdu
# PDU of received frame is set here.
# @param type
# Interface type.
# Is new frame found.
#
def findNextFrame_0(self, data, pdu, type_):
settings = GXDLMSSettings(True, None)
settings.iInterfaceType = type_
reply = GXReplyData()
reply.xml = GXDLMSTranslatorStructure(
self.outputType,
self.omitXmlNameSpace,
self.hex,
self.showStringAsHex,
self.comments,
self.tags,
)
pos = int()
found = bool()
try:
while data.position < len(data):
if (
type_ in (InterfaceType.HDLC, InterfaceType.HDLC_WITH_MODE_E)
and data.getUInt8(data.position) == 0x7E
):
pos = data.position
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif (
data.available() > 1
and type_ == InterfaceType.WRAPPER
and data.getUInt16(data.position) == 0x1
):
pos = data.position
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
elif type_ == InterfaceType.WIRELESS_MBUS:
pos = data.position
settings.interfaceType = InterfaceType.WIRELESS_MBUS
found = GXDLMS.getData(settings, data, reply, None)
data.position = pos
if found:
break
data.position = data.position + 1
except Exception:
raise ValueError("Invalid DLMS frame.")
if pdu:
pdu.clear()
pdu.set(data, 0, data.size)
return data.position != len(data)
#
# Get all tags.
#
# @param type
# Output type.
# @param list
# List of tags by ID.
# @param tagsByName
# List of tags by name.
#
@classmethod
def __getTags(cls, type_, list_, tagsByName):
if type_ == TranslatorOutputType.SIMPLE_XML:
TranslatorSimpleTags.getGeneralTags(list_)
TranslatorSimpleTags.getSnTags(list_)
TranslatorSimpleTags.getLnTags(list_)
TranslatorSimpleTags.getGloTags(list_)
TranslatorSimpleTags.getDedTags(list_)
TranslatorSimpleTags.getTranslatorTags(list_)
TranslatorSimpleTags.getDataTypeTags(list_)
else:
TranslatorStandardTags.getGeneralTags(list_)
TranslatorStandardTags.getSnTags(list_)
TranslatorStandardTags.getLnTags(list_)
TranslatorStandardTags.getGloTags(list_)
TranslatorStandardTags.getDedTags(list_)
TranslatorStandardTags.getTranslatorTags(list_)
TranslatorStandardTags.getDataTypeTags(list_)
# Simple is not case sensitive.
lowercase = type_ == TranslatorOutputType.SIMPLE_XML
for it in list_:
str_ = list_[it]
if lowercase:
str_ = str_.lower()
if str_ not in tagsByName:
tagsByName[str_] = it
def getPdu(self, value):
return self.getPdu(GXByteBuffer(value))
#
# Identify used DLMS framing type.
#
# @param value
# Input data.
# Interface type.
#
@classmethod
def getDlmsFraming(cls, value):
pos = value.position
while pos != len(value):
if value.getUInt8(pos) == 0x7E:
return InterfaceType.HDLC
if value.available() > 1 and value.getUInt16(pos) == 1:
return InterfaceType.WRAPPER
if GXDLMS.isWirelessMBusData(value):
return InterfaceType.WIRELESS_MBUS
pos += 1
raise ValueError("Invalid DLMS framing.")
def getPdu_0(self, value):
framing = self.getDlmsFraming(value)
data = GXReplyData()
data.xml = GXDLMSTranslatorStructure(
self.outputType,
self.omitXmlNameSpace,
self.hex,
self.showStringAsHex,
self.comments,
self.tags,
)
settings = GXDLMSSettings(True, None)
settings.interfaceType = framing
GXDLMS.getData(settings, value, data, None)
return data.data
def getCiphering(self, settings, force):
if force or self.security != Security.NONE:
c = GXCiphering(self.systemTitle)
c.security = self.security
c.systemTitle = self.systemTitle
c.blockCipherKey = self.blockCipherKey
c.authenticationKey = self.authenticationKey
c.invocationCounter = self.invocationCounter
c.dedicatedKey = self.dedicatedKey
settings.sourceSystemTitle = self.serverSystemTitle
settings.cipher = c
else:
settings.cipher = None
#
# Clear {@link messageToXml} internal settings.
#
def clear(self):
self.multipleFrames = False
self.pduFrames.clear()
@classmethod
def checkFrame(cls, frame_, xml):
if frame_ == 0x93:
xml.appendComment("SNRM frame.")
elif frame_ == 0x73:
xml.appendComment("UA frame.")
elif (frame_ & HdlcFrameType.S_FRAME) == HdlcFrameType.S_FRAME:
# If S -frame.
xml.appendComment("S frame.")
elif (frame_ & 1) == HdlcFrameType.U_FRAME:
# Handle U-frame.
xml.appendComment("U frame.")
else:
# I-frame.
if frame_ == 0x10:
xml.appendComment("AARQ frame.")
elif frame_ == 0x30:
xml.appendComment("AARE frame.")
else:
xml.appendComment("I frame.")
#
# Get logical and physical address from the server address.
#
@classmethod
def __getLogicalAndPhysicalAddress(cls, value):
if value > 0x3FFF:
logical = int(value >> 14)
physical = int(value & 0x3FFF)
else:
logical = int(value >> 7)
physical = int(value & 0x7F)
return (logical, physical)
@classmethod
def __updateAddress(cls, settings, msg):
reply = True
if msg.command in (
Command.READ_REQUEST,
Command.WRITE_REQUEST,
Command.GET_REQUEST,
Command.SET_REQUEST,
Command.METHOD_REQUEST,
Command.SNRM,
Command.AARQ,
Command.DISCONNECT_REQUEST,
Command.RELEASE_REQUEST,
Command.ACCESS_REQUEST,
Command.GLO_GET_REQUEST,
Command.GLO_SET_REQUEST,
Command.GLO_METHOD_REQUEST,
Command.GLO_INITIATE_REQUEST,
Command.GLO_READ_REQUEST,
Command.GLO_WRITE_REQUEST,
Command.DED_INITIATE_REQUEST,
Command.DED_READ_REQUEST,
Command.DED_WRITE_REQUEST,
Command.DED_GET_REQUEST,
Command.DED_SET_REQUEST,
Command.DED_METHOD_REQUEST,
Command.GATEWAY_REQUEST,
Command.DISCOVER_REQUEST,
Command.REGISTER_REQUEST,
Command.PING_REQUEST,
):
reply = False
if reply:
msg.targetAddress = settings.clientAddress
msg.sourceAddress = settings.serverAddress
else:
msg.sourceAddress = settings.clientAddress
msg.targetAddress = settings.serverAddress
#
#
#
# pylint:disable=broad-except
def messageToXml(self, msg):
"""
Convert message to XML.
msg : Translator message data.
Returns Converted xml.
"""
# pylint: disable=too-many-nested-blocks
if not isinstance(msg, (GXDLMSTranslatorMessage)):
if not isinstance(msg, GXByteBuffer):
data = GXByteBuffer(msg)
else:
data = msg
msg = GXDLMSTranslatorMessage()
msg.message = data
if not msg:
raise ValueError("msg")
msg.exception = None
xml = GXDLMSTranslatorStructure(
self.outputType,
self.omitXmlNameSpace,
self.hex,
self.showStringAsHex,
self.comments,
self.tags,
)
data = GXReplyData()
settings = GXDLMSSettings(True, None)
self.getCiphering(settings, True)
data.xml = xml
try:
offset = msg.message.position
# If HDLC framing.
if (
msg.interfaceType
in (None, InterfaceType.HDLC, InterfaceType.HDLC_WITH_MODE_E)
and msg.message.getUInt8(msg.message.position) == 0x7E
):
msg.interfaceType = settings.interfaceType = InterfaceType.HDLC
if GXDLMS.getData(settings, msg.message, data, None):
msg.moreData = data.moreData
msg.sourceAddress = data.sourceAddress
msg.targetAddress = data.targetAddress
if not self.pduOnly:
xml.appendLine(
'<HDLC len="'
+ xml.integerToHex(data.packetLength - offset, 0)
+ '" >'
)
(
logical,
physical,
) = GXDLMSTranslator.__getLogicalAndPhysicalAddress(
settings.serverAddress
)
if logical != 0:
xml.appendComment(
"Logical address:"
+ str(logical)
+ ", Physical address:"
+ str(physical)
)
xml.appendLine(
'<TargetAddress Value="'
+ xml.integerToHex(settings.serverAddress, 0)
+ '" />'
)
xml.appendLine(
'<SourceAddress Value="'
+ xml.integerToHex(settings.clientAddress, 0)
+ '" />'
)
# Check frame.
if self.comments:
self.checkFrame(data.frameId, xml)
xml.appendLine(
'<FrameType Value="'
+ xml.integerToHex(data.frameId, 2, True)
+ '" />'
)
if not data.data:
if (data.frameId & 1) != 0 and data.command == Command.NONE:
if not self.completePdu:
xml.appendLine('<Command Value="NextFrame" />')
self.multipleFrames = True
else:
xml.appendStartTag(data.command)
xml.appendEndTag(data.command)
else:
if self.multipleFrames or data.isMoreData():
if self.completePdu:
self.pduFrames.set(data.data)
if data.moreData == RequestTypes.NONE:
xml.appendLine(
self.__pduToXml(self.pduFrames, True, True)
)
self.pduFrames.clear()
else:
xml.appendLine(
'<NextFrame Value="'
+ data.data.toHex(
False,
data.data.position,
data.data.size - data.data.position,
)
+ '" />'
)
if data.moreData != RequestTypes.DATABLOCK:
self.multipleFrames = False
else:
if not self.pduOnly:
xml.appendLine("<PDU>")
if self.pduFrames:
self.pduFrames.set(data.data.data)
xml.appendLine(
self.__pduToXml(self.pduFrames, True, True)
)
self.pduFrames.clear()
else:
if data.command in (Command.SNRM, Command.UA):
xml.appendStartTag(data.command)
self._pduToXml2(xml, data.data, True, True, True)
xml.appendEndTag(data.command)
xml.setXmlLength(xml.getXmlLength() + 2)
else:
xml.appendLine(self.__pduToXml(data.data, True, True))
# Remove \r\n.
xml.trim()
if not self.pduOnly:
xml.appendLine("</PDU>")
if not self.pduOnly:
xml.appendLine("</HDLC>")
self.__updateAddress(settings, msg)
msg.xml = str(xml)
return msg.xml
# If wrapper.
if (
msg.interfaceType in (None, InterfaceType.WRAPPER)
and (msg.message.available() > 1)
and msg.message.getUInt16(msg.message.position) == 1
):
msg.interfaceType = settings.interfaceType = InterfaceType.WRAPPER
GXDLMS.getData(settings, msg.message, data, None)
msg.moreData = data.moreData
msg.sourceAddress = data.sourceAddress
msg.targetAddress = data.targetAddress
pdu = self.__pduToXml(
data.data, self.omitXmlDeclaration, self.omitXmlNameSpace
)
if not self.pduOnly:
xml.appendLine(
'<WRAPPER len="'
+ xml.integerToHex(data.packetLength - offset, 0)
+ '" >'
)
xml.appendLine(
'<TargetAddress Value="'
+ xml.integerToHex(settings.clientAddress, 0)
+ '" />'
)
xml.appendLine(
'<SourceAddress Value="'
+ xml.integerToHex(settings.serverAddress, 0)
+ '" />'
)
if not self.pduOnly:
xml.appendLine("<PDU>")
xml.appendLine(pdu)
# Remove \r\n.
xml.trim()
if not self.pduOnly:
xml.appendLine("</PDU>")
if not self.pduOnly:
xml.appendLine("</WRAPPER>")
self.__updateAddress(settings, msg)
msg.xml = str(xml)
return msg.xml
# If PLC.
if (
msg.interfaceType in (None, InterfaceType.PLC)
and msg.message.getUInt8(msg.message.position) == 2
):
msg.interfaceType = settings.interfaceType = InterfaceType.PLC
GXDLMS.getData(settings, msg.message, data, None)
msg.moreData = data.moreData
msg.sourceAddress = data.sourceAddress
msg.targetAddress = data.targetAddress
if not self.pduOnly:
xml.appendLine(
'<Plc len="'
+ xml.integerToHex(data.packetLength - offset, 0)
+ '" >'
)
if self.comments:
if data.targetAddress == PlcSourceAddress.INITIATOR:
xml.appendComment("Initiator")
elif data.targetAddress == PlcSourceAddress.NEW:
xml.appendComment("New")
xml.appendLine(
'<SourceAddress Value="'
+ xml.integerToHex(data.targetAddress, 0)
+ '" />'
)
if (
self.comments
and data.sourceAddress == PlcDestinationAddress.ALL_PHYSICAL
):
xml.appendComment("AllPhysical")
xml.appendLine(
'<DestinationAddress Value="'
+ xml.integerToHex(data.sourceAddress, 0)
+ '" />'
)
if data.data.size == 0:
xml.appendLine(
'<Command Value="' + Command.toString(data.command) + '" />'
)
else:
if not self.pduOnly:
xml.appendLine("<PDU>")
xml.appendLine(
self.__pduToXml(
data.data,
self.omitXmlDeclaration,
self.omitXmlNameSpace,
msg,
)
)
# Remove \r\n.
xml.trim()
if not self.pduOnly:
xml.appendLine("</PDU>")
if not self.pduOnly:
xml.appendLine("</Plc>")
self.__updateAddress(settings, msg)
msg.xml = str(xml)
return msg.xml
# If Wired M-Bus.
if msg.interfaceType in (
None,
InterfaceType.WIRED_MBUS,
) and GXDLMS.isWiredMBusData(msg.message):
msg.interfaceType = settings.interfaceType = InterfaceType.WIRED_MBUS
len_ = xml.getXmlLength()
GXDLMS.getData(settings, msg.message, data, None)
msg.moreData = data.moreData
msg.sourceAddress = data.sourceAddress
msg.targetAddress = data.targetAddress
tmp = str(xml)[0:len_]
xml.setXmlLength(len_)
if not self.pduOnly:
xml.appendLine(
'<WiredMBus len="'
+ xml.integerToHex(data.packetLength - offset, 0)
+ '" >'
)
xml.appendLine(
'<TargetAddress Value="'
+ xml.integerToHex(settings.serverAddress, 0)
+ '" />'
)
xml.appendLine(
'<SourceAddress Value="'
+ xml.integerToHex(settings.clientAddress, 0)
+ '" />'
)
xml.append(tmp)
if data.data.size == 0:
xml.appendLine(
'<Command Value="' + Command.toString(data.command) + '" />'
)
else:
if self.multipleFrames or (data.moreData & RequestTypes.FRAME) != 0:
if self.completePdu:
self.pduFrames.set(data.data)
if data.moreData == RequestTypes.NONE:
xml.appendLine(
self.__pduToXml(self.pduFrames, True, True)
)
self.pduFrames.clear()
else:
xml.appendLine(
'<NextFrame Value="'
+ data.data.toHex(
False, data.data.position, data.data.available()
)
+ '" />'
)
if data.moreData & RequestTypes.FRAME != 0:
self.multipleFrames = True
if data.moreData == RequestTypes.DATABLOCK:
self.multipleFrames = False
else:
if not self.pduOnly:
xml.appendLine("<PDU>")
if self.pduFrames.size != 0:
self.pduFrames.set(data.data)
data.data.clear()
data.data.set(self.pduFrames)
xml.appendLine(
self.__pduToXml(
data.data,
self.omitXmlDeclaration,
self.omitXmlNameSpace,
)
)
# Remove \r\n.
xml.trim()
if not self.pduOnly:
xml.appendLine("</PDU>")
if not self.pduOnly:
xml.appendLine("</WiredMBus>")
self.__updateAddress(settings, msg)
msg.xml = str(xml)
return msg.xml
# If Wireless M-Bus.
if msg.interfaceType in (
None,
InterfaceType.WIRELESS_MBUS,
) and GXDLMS.isWirelessMBusData(msg.message):
msg.interfaceType = settings.interfaceType = InterfaceType.WIRELESS_MBUS
len_ = xml.getXmlLength()
GXDLMS.getData(settings, msg.message, data, None)
msg.moreData = data.moreData
msg.sourceAddress = data.sourceAddress
msg.targetAddress = data.targetAddress
tmp = str(xml)[0:len_]
xml.setXmlLength(len_)
if not self.pduOnly:
xml.appendLine(
'<WirelessMBus len="'
+ xml.integerToHex(data.packetLength - offset, 0)
+ '" >'
)
xml.appendLine(
'<TargetAddress Value="'
+ xml.integerToHex(settings.serverAddress, 0)
+ '" />'
)
xml.appendLine(
'<SourceAddress Value="'
+ xml.integerToHex(settings.clientAddress, 0)
+ '" />'
)
xml.append(tmp)
if data.data.size == 0:
xml.appendLine(
'<Command Value="' + Command.toString(data.command) + '" />'
)
else:
if not self.pduOnly:
xml.appendLine("<PDU>")
xml.appendLine(
self.__pduToXml(
data.data,
self.omitXmlDeclaration,
self.omitXmlNameSpace,
msg,
)
)
# Remove \r\n.
xml.trim()
if not self.pduOnly:
xml.appendLine("</PDU>")
if not self.pduOnly:
xml.appendLine("</WirelessMBus>")
self.__updateAddress(settings, msg)
msg.xml = str(xml)
return msg.xml
except Exception as ex:
print(ex)
raise ValueError("Invalid DLMS framing.")
#
# Convert PDU in hex string to XML.
#
# @param pdu
# Converted hex string or GXByteBuffer.
# Converted XML.
#
def pduToXml(self, pdu):
if not isinstance(pdu, GXByteBuffer):
pdu = GXByteBuffer(pdu)
return self.__pduToXml(pdu, self.omitXmlDeclaration, self.omitXmlNameSpace)
@classmethod
def getUa(cls, data, xml):
data.getUInt8()
# Skip FromatID
data.getUInt8()
# Skip Group ID.
data.getUInt8()
# Skip Group length.
val = None
while data.position < len(data):
id_ = data.getUInt8()
len_ = data.getUInt8()
if len_ == 1:
val = data.getUInt8()
elif len_ == 2:
val = data.getUInt16()
elif len_ == 4:
val = data.getUInt32()
else:
raise GXDLMSException("Invalid Exception.")
if id_ == _HDLCInfo.MAX_INFO_TX:
xml.appendLine('<MaxInfoTX Value="' + str(val) + '" />')
elif id_ == _HDLCInfo.MAX_INFO_RX:
xml.appendLine('<MaxInfoRX Value="' + str(val) + '" />')
elif id_ == _HDLCInfo.WINDOW_SIZE_TX:
xml.appendLine('<WindowSizeTX Value="' + str(val) + '" />')
elif id_ == _HDLCInfo.WINDOW_SIZE_RX:
xml.appendLine('<WindowSizeRX Value="' + str(val) + '" />')
else:
raise GXDLMSException("Invalid UA response.")
#
# Convert bytes to XML.
#
# @param value
# Bytes to convert.
# Converted XML.
#
def __pduToXml(self, value, omitDeclaration, omitNameSpace):
xml = GXDLMSTranslatorStructure(
self.outputType,
self.omitXmlNameSpace,
self.hex,
self.showStringAsHex,
self.comments,
self.tags,
)
return self._pduToXml2(xml, value, omitDeclaration, omitNameSpace, True)
@classmethod
def isCiphered(cls, cmd):
return cmd in (
Command.GLO_READ_REQUEST,
Command.GLO_WRITE_REQUEST,
Command.GLO_GET_REQUEST,
Command.GLO_SET_REQUEST,
Command.GLO_READ_RESPONSE,
Command.GLO_WRITE_RESPONSE,
Command.GLO_GET_RESPONSE,
Command.GLO_SET_RESPONSE,
Command.GLO_METHOD_REQUEST,
Command.GLO_METHOD_RESPONSE,
Command.DED_GET_REQUEST,
Command.DED_SET_REQUEST,
Command.DED_READ_RESPONSE,
Command.DED_GET_RESPONSE,
Command.DED_SET_RESPONSE,
Command.DED_METHOD_REQUEST,
Command.DED_METHOD_RESPONSE,
Command.GENERAL_GLO_CIPHERING,
Command.GENERAL_DED_CIPHERING,
Command.AARQ,
Command.AARE,
Command.GLO_CONFIRMED_SERVICE_ERROR,
Command.DED_CONFIRMED_SERVICE_ERROR,
Command.GENERAL_CIPHERING,
Command.RELEASE_REQUEST,
)
#
# Convert bytes to XML.
#
# @param value
# Bytes to convert.
# Converted XML.
#
def _pduToXml2(
self, xml, value, omitDeclaration, omitNameSpace, allowUnknownCommand=True
):
# pylint: disable=bad-option-value,too-many-arguments,too-many-locals,
# too-many-nested-blocks,redefined-variable-type
if not value:
raise ValueError("value")
settings = GXDLMSSettings(True, None)
settings.standard = self.standard
cmd = value.getUInt8()
self.getCiphering(settings, self.isCiphered(cmd))
data = GXReplyData()
str_ = None
if cmd == Command.AARQ:
value.position = 0
_GXAPDU.parsePDU(settings, settings.cipher, value, xml)
elif cmd == Command.INITIATE_REQUEST: