forked from daniel-leicht/pylogix2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheip.py
2059 lines (1800 loc) · 72.7 KB
/
eip.py
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
'''
Originally created by Burt Peterson
Updated and maintained by Dustin Roeder ([email protected])
Copyright 2019 Dustin Roeder
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
import socket
import sys
import time
from datetime import datetime, timedelta
from .lgxDevice import LGXDevice, GetDevice, GetVendor
from random import randrange
from struct import pack, unpack_from
class RouteAddressToSelfError(IOError):
pass
class CIPConnectionError(IOError):
pass
class PLC:
def __init__(self):
'''
Initialize our parameters
'''
self.IPAddress = ""
self.ProcessorSlot = 0
self.Micro800 = False
self.Port = 44818
self.VendorID = 0x1337
self.Context = 0x00
self.ContextPointer = 0
self.Socket = socket.socket()
self.SocketConnected = False
self.OTNetworkConnectionID=None
self.SessionHandle = 0x0000
self.SessionRegistered = False
self.SerialNumber = 0
self.OriginatorSerialNumber = 42
self.SequenceCounter = 1
self.ConnectionSize = 508
self.Offset = 0
self.KnownTags = {}
self.TagList = []
self.ProgramNames = []
self.StructIdentifier = 0x0fCE
self.CIPTypes = {160:(88 ,"STRUCT", 'B'),
193:(1, "BOOL", '?'),
194:(1, "SINT", 'b'),
195:(2, "INT", 'h'),
196:(4, "DINT", 'i'),
197:(8, "LINT", 'q'),
198:(1, "USINT", 'B'),
199:(2, "UINT", 'H'),
200:(4, "UDINT", 'I'),
201:(8, "LWORD", 'Q'),
202:(4, "REAL", 'f'),
203:(8, "LREAL", 'd'),
211:(4, "DWORD", 'I'),
218:(0, "STRING", 'B')}
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
'''
Clean up on exit
'''
return self._closeConnection()
def Read(self, tag, count=1, datatype=None):
'''
We have two options for reading depending on
the arguments, read a single tag, or read an array
'''
if isinstance(tag, (list, tuple)):
if len(tag) == 1:
return [ self._readTag(tag[0], count, datatype) ]
if datatype:
raise TypeError('Datatype should be set to None when reading lists')
return self._multiRead(tag)
else:
return self._readTag(tag, count, datatype)
def Write(self, tag, value, datatype=None):
'''
We have two options for writing depending on
the arguments, write a single tag, or write an array
'''
return self._writeTag(tag, value, datatype)
def MultiRead(self, tags):
'''
Read multiple tags in one request
'''
return self._multiRead(tags)
def GetPLCTime(self, raw=False):
'''
Get the PLC's clock time, return as human readable (default) or raw if raw=True
'''
return self._getPLCTime(raw)
def SetPLCTime(self):
'''
Sets the PLC's clock time
'''
return self._setPLCTime()
def GetTagList(self, allTags = True):
'''
Retrieves the tag list from the PLC
Optional parameter allTags set to True
If is set to False, it will return only controller
otherwise controller tags and program tags.
'''
tag_list = self._getTagList(allTags)
updated_list = self._getUDT(tag_list.value)
return Response(None, updated_list, tag_list.status)
def GetProgramTagList(self, programName):
'''
Retrieves a program tag list from the PLC
programName = "Program:ExampleProgram"
'''
if not self.ProgramNames:
tags = self._getTagList(False)
# Get a single program tags if progragName exists
if programName in self.ProgramNames:
program_tags = self._getProgramTagList(programName)
program_tags = self._getUDT(program_tags[1])
return Response(None, program_tags, tags[2])
else:
return Response(None, None, 'Program not found, please check name!')
def GetProgramsList(self):
'''
Retrieves a program names list from the PLC
Sanity check: checks if programNames is empty
and runs _getTagList
'''
if not self.ProgramNames:
tag_list = self._getTagList(True)
return Response(None, self.ProgramNames, tag_list[2])
def Discover(self):
'''
Query all the EIP devices on the network
'''
return self._discover()
def GetModuleProperties(self, slot=None, custom_routing_path=None, basic=False):
'''
Get the properties of module in specified slot
If CIP routing path is known it can be specified in custom_routing_path as a list of tuples: (port, slot)
By default GetModuleProperties used "GetAttributeAll" to retrive the identity, some modules
(such as DeviceNet modules) will only answer to "GetAttributeSingle", use basic=True to query the basic
attibutes using "GetAttributeSingle".
'''
if basic:
IDENTITY_ATTRIBUTES = {
"VendorID": (0x01, "word"),
"DeviceID": (0x02, "word"),
"ProductCode": (0x03, "word"),
"Revision": (0x04, "revision"),
"Status": (0x05, "word"),
"SerialNumber": (0x06, "dword"),
"ProductName": (0x07, "string"),
"State": (0x08, "word"),
}
module_object = LGXDevice()
value_list = list()
for attribute_name, attribute_info in IDENTITY_ATTRIBUTES.items():
attr_value = self._getModuleProperty(attribute_info, slot=slot, custom_routing_path=custom_routing_path)
if (attribute_name == "VendorID") and (attr_value == None):
return Response(None, LGXDevice(), 1)
value_list.append(attr_value)
setattr(module_object, attribute_name, attr_value)
return Response(None, module_object, 0)
else:
return self._getModuleProperties(slot=slot, custom_routing_path=custom_routing_path)
def Close(self):
'''
Close the connection to the PLC
'''
return self._closeConnection()
def _readTag(self, tag, elements, dt):
'''
processes the read request
'''
self.Offset = 0
if not self._connect(): return None
t,b,i = _parseTagName(tag, 0)
resp = self._initial_read(t, b, dt)
if resp[2] != 0 and resp[2] != 6:
return Response(tag, None, resp[2])
datatype = self.KnownTags[b][0]
bitCount = self.CIPTypes[datatype][0] * 8
if datatype == 211:
# bool array
tagData = self._buildTagIOI(tag, isBoolArray=True)
words = _getWordCount(i, elements, bitCount)
readRequest = self._addReadIOI(tagData, words)
elif BitofWord(t):
# bits of word
split_tag = tag.split('.')
bitPos = split_tag[len(split_tag)-1]
bitPos = int(bitPos)
tagData = self._buildTagIOI(tag, isBoolArray=False)
words = _getWordCount(bitPos, elements, bitCount)
readRequest = self._addReadIOI(tagData, words)
else:
# everything else
tagData = self._buildTagIOI(tag, isBoolArray=False)
readRequest = self._addReadIOI(tagData, elements)
eipHeader = self._buildEIPHeader(readRequest)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
return_value = self._parseReply(tag, elements, retData)
return Response(tag, return_value, status)
else:
return Response(tag, None, status)
def _writeTag(self, tag, value, dt):
'''
Processes the write request
'''
self.Offset = 0
writeData = []
if not self._connect(): return None
t,b,i = _parseTagName(tag, 0)
resp = self._initial_read(t, b, dt)
if resp[2] != 0 and resp[2] != 6:
return Response(tag, None, status)
dataType = self.KnownTags[b][0]
# check if values passed were a list
if isinstance(value, list):
elements = len(value)
else:
elements = 1
value = [value]
for v in value:
if dataType == 202 or dataType == 203:
writeData.append(float(v))
elif dataType == 160 or dataType == 218:
writeData.append(self._makeString(v))
else:
writeData.append(int(v))
# write a bit of a word, boolean array or everything else
if BitofWord(tag):
tagData = self._buildTagIOI(tag, isBoolArray=False)
writeRequest = self._addWriteBitIOI(tag, tagData, writeData, dataType)
elif dataType == 211:
tagData = self._buildTagIOI(tag, isBoolArray=True)
writeRequest = self._addWriteBitIOI(tag, tagData, writeData, dataType)
else:
tagData = self._buildTagIOI(tag, isBoolArray=False)
writeRequest = self._addWriteIOI(tagData, writeData, dataType)
eipHeader = self._buildEIPHeader(writeRequest)
status, retData = self._getBytes(eipHeader)
return Response(tag, value, status)
def _multiRead(self, tags):
'''
Processes the multiple read request
'''
serviceSegments = []
segments = b""
tagCount = len(tags)
self.Offset = 0
if not self._connect(): return None
for tag in tags:
if isinstance(tag, (list, tuple)):
tag_name, base, ind = _parseTagName(tag[0], 0)
self._initial_read(tag_name, base, tag[1])
else:
tag_name, base, ind = _parseTagName(tag, 0)
self._initial_read(tag_name, base, None)
if base in self.KnownTags.keys():
dataType = self.KnownTags[base][0]
else:
dataType = None
if dataType == 211:
tagIOI = self._buildTagIOI(tag_name, isBoolArray=True)
else:
tagIOI = self._buildTagIOI(tag_name, isBoolArray=False)
readIOI = self._addReadIOI(tagIOI, 1)
serviceSegments.append(readIOI)
header = self._buildMultiServiceHeader()
segmentCount = pack('<H', tagCount)
temp = len(header)
if tagCount > 2:
temp += (tagCount-2)*2
offsets = pack('<H', temp)
# assemble all the segments
for i in range(tagCount):
segments += serviceSegments[i]
for i in range(tagCount-1):
temp += len(serviceSegments[i])
offsets += pack('<H', temp)
readRequest = header+segmentCount+offsets+segments
eipHeader = self._buildEIPHeader(readRequest)
status, retData = self._getBytes(eipHeader)
return self._multiParser(tags, retData)
def _getPLCTime(self, raw=False):
'''
Requests the PLC clock time
'''
if not self._connect(): return None
AttributeService = 0x03
AttributeSize = 0x02
AttributeClassType = 0x20
AttributeClass = 0x8B
AttributeInstanceType = 0x24
AttributeInstance = 0x01
AttributeCount = 0x01
TimeAttribute = 0x0B
AttributePacket = pack('<BBBBBBH1H',
AttributeService,
AttributeSize,
AttributeClassType,
AttributeClass,
AttributeInstanceType,
AttributeInstance,
AttributeCount,
TimeAttribute)
eipHeader = self._buildEIPHeader(AttributePacket)
status, retData = self._getBytes(eipHeader)
if status == 0:
# get the time from the packet
plcTime = unpack_from('<Q', retData, 56)[0]
if raw:
value = plcTime
humanTime = datetime(1970, 1, 1) + timedelta(microseconds=plcTime)
value = humanTime
else:
value = None
return Response(None, value, status)
def _setPLCTime(self):
'''
Requests the PLC clock time
'''
if not self._connect(): return None
AttributeService = 0x04
AttributeSize = 0x02
AttributeClassType = 0x20
AttributeClass = 0x8B
AttributeInstanceType = 0x24
AttributeInstance = 0x01
AttributeCount = 0x01
Attribute = 0x06
Time = int(time.time() * 1000000)
AttributePacket = pack('<BBBBBBHHQ',
AttributeService,
AttributeSize,
AttributeClassType,
AttributeClass,
AttributeInstanceType,
AttributeInstance,
AttributeCount,
Attribute,
Time)
eipHeader = self._buildEIPHeader(AttributePacket)
status, retData = self._getBytes(eipHeader)
return Response(None, Time, status)
def _getTagList(self, allTags):
'''
Requests the controller tag list and returns a list of LgxTag type
'''
if not self._connect(): return None
self.Offset = 0
tags = []
request = self._buildTagListRequest(programName=None)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, programName=None)
else:
return Response(None, None, status)
while status == 6:
self.Offset += 1
request = self._buildTagListRequest(programName=None)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, programName=None)
else:
return Response(None, None, status)
if allTags:
for program_name in self.ProgramNames:
self.Offset = 0
request = self._buildTagListRequest(program_name)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, program_name)
else:
return Response(None, None, status)
while status == 6:
self.Offset += 1
request = self._buildTagListRequest(program_name)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, program_name)
else:
return Response(None, None, status)
return Response(None, tags, status)
def _getProgramTagList(self, programName):
'''
Requests tag list for a specific program and returns a list of LgxTag type
'''
if not self._connect(): return None
self.Offset = 0
tags = []
request = self._buildTagListRequest(programName)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, programName)
else:
return Response(None, None, status)
while status == 6:
self.Offset += 1
request = self._buildTagListRequest(programName)
eipHeader = self._buildEIPHeader(request)
status, retData = self._getBytes(eipHeader)
if status == 0 or status == 6:
tags += self._extractTagPacket(retData, programName)
else:
return Response(None, None, status)
return Response(None, tags, status)
def _getUDT(self, tag_list):
# get only tags that are a struct
struct_tags = [x for x in tag_list if x.Struct == 1]
# reduce our struct tag list to only unique instances
seen = set()
unique = [obj for obj in struct_tags if obj.DataTypeValue not in seen and not seen.add(obj.DataTypeValue)]
template = {}
for u in unique:
temp = self._getTemplateAttribute(u.DataTypeValue)
val = unpack_from('<I', temp[46:], 10)[0]
words = (val * 4) - 23
member_count = int(unpack_from('<H', temp[46:], 24)[0])
template[u.DataTypeValue] = [words, '', member_count]
for key,value in template.items():
t = self._getTemplate(key, value[0])
size = value[2] * 8
p = t[50:]
member_bytes = p[size:]
split_char = pack('<b', 0x00)
members = member_bytes.split(split_char)
split_char = pack('<b', 0x3b)
name = members[0].split(split_char)[0]
template[key][1] = str(name.decode('utf-8'))
for tag in tag_list:
if tag.DataTypeValue in template:
tag.DataType = template[tag.DataTypeValue][1]
elif tag.SymbolType in self.CIPTypes:
tag.DataType = self.CIPTypes[tag.SymbolType][1]
return tag_list
def _getTemplateAttribute(self, instance):
'''
Get the attributes of a UDT
'''
if not self._connect(): return None
readRequest = self._buildTemplateAttributes(instance)
eipHeader = self._buildEIPHeader(readRequest)
status, retData = self._getBytes(eipHeader)
return retData
def _getTemplate(self, instance, dataLen):
'''
Get the members of a UDT so we can get it
'''
if not self._connect(): return None
readRequest = self._readTemplateService(instance, dataLen)
eipHeader = self._buildEIPHeader(readRequest)
status, retData = self._getBytes(eipHeader)
return retData
def _buildTemplateAttributes(self, instance):
TemplateService = 0x03
TemplateLength = 0x03
TemplateClassType = 0x20
TemplateClass = 0x6c
TemplateInstanceType = 0x25
TemplateInstance = instance
AttribCount = 0x04
Attrib4 = 0x04
Attrib3 = 0x03
Attrib2 = 0x02
Attrib1 = 0x01
return pack('<BBBBHHHHHHH',
TemplateService,
TemplateLength,
TemplateClassType,
TemplateClass,
TemplateInstanceType,
TemplateInstance,
AttribCount,
Attrib4,
Attrib3,
Attrib2,
Attrib1)
def _readTemplateService(self, instance, dataLen):
TemplateService = 0x4c
TemplateLength = 0x03
TemplateClassType = 0x20
TemplateClass = 0x6c
TemplateInstanceType = 0x25
TemplateInstance = instance
TemplateOffset = 0x00
DataLength = dataLen
return pack('<BBBBHHIH',
TemplateService,
TemplateLength,
TemplateClassType,
TemplateClass,
TemplateInstanceType,
TemplateInstance,
TemplateOffset,
DataLength)
def _discover(self):
devices = []
request = self._buildListIdentity()
# get available ip addresses
addresses = socket.getaddrinfo(socket.gethostname(), None)
# we're going to send a request for all available ipv4
# addresses and build a list of all the devices that reply
for ip in addresses:
if ip[0] == 2: # IP v4
# create a socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0.5)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind((ip[4][0], 0))
s.sendto(request, ('255.255.255.255', 44818))
try:
while(1):
ret = s.recv(4096)
context = unpack_from('<Q', ret, 14)[0]
if context == 0x006d6f4d6948:
device = _parseIdentityResponse(ret)
if device.IPAddress:
devices.append(device)
except:
pass
# added this because looping through addresses above doesn't work on
# linux so this is a "just in case". If we don't get results with the
# above code, try one more time without binding to an address
if len(devices) == 0:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(0.5)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(request, ('255.255.255.255', 44818))
try:
while(1):
ret = s.recv(4096)
context = unpack_from('<Q', ret, 14)[0]
if context == 0x006d6f4d6948:
device = _parseIdentityResponse(ret)
if device.IPAddress:
devices.append(device)
except:
pass
return Response(None, devices, 0)
def _getModuleProperties(self, slot, custom_routing_path=None):
'''
Request the properties of a module in a particular
slot or module that is located in specific routing path. Returns Response object.
'''
if not self._connect(): return None
if (slot == None) and (custom_routing_path == None):
raise ValueError("Either slot number or a routing path should be specified")
AttributeService = 0x01
AttributeSize = 0x02
AttributeClassType = 0x20
AttributeClass = 0x01
AttributeInstanceType = 0x24
AttributeInstance = 0x01
PathRouteSize = 0x01
Reserved = 0x00
Backplane = 0x01
LinkAddress = slot
AttributePacket = pack('<6B',
AttributeService,
AttributeSize,
AttributeClassType,
AttributeClass,
AttributeInstanceType,
AttributeInstance)
if custom_routing_path == None:
AttributePacket += pack('<4B',
PathRouteSize,
Reserved,
Backplane,
LinkAddress)
else:
"""
Use custom routing -> it should be a list with tuples containing pairs of port number & slot address.
"""
custom_route_path_size = len(custom_routing_path)
route_path = pack('<2B',
custom_route_path_size,
Reserved)
for routing_pair in custom_routing_path:
assert len(routing_pair) == 2, "Routing path should be list of 2-tuples."
port_segment = 0b00001111 & routing_pair[0]
link_address = routing_pair[1]
route_path += pack("<2B",
port_segment,
link_address)
AttributePacket += route_path
frame = self._buildCIPUnconnectedSend() + AttributePacket
eipHeader = self._buildEIPSendRRDataHeader(len(frame)) + frame
pad = pack('<I', 0x00)
self.Socket.send(eipHeader)
retData = pad + self.recv_data()
status = retData[46]
if status == 0:
return Response(None, _parseIdentityResponse(retData), status)
else:
if status == 1:
if retData[47] == 0x01: # Extended status bit
extended_status = unpack_from("<H",retData, 48)[0]
if extended_status == 0x0318: # Link address to self!
raise RouteAddressToSelfError
return Response(None, LGXDevice(), status)
def _getModuleProperty(self, attribute_info, slot, custom_routing_path=None):
'''
Request the properties of a module in a particular
slot or module that is located in specific routing path. Returns Response object.
'''
if not self._connect(): return None
if (slot == None) and (custom_routing_path == None):
raise ValueError("Either slot number or a routing path should be specified")
attribute_id, attribute_type = attribute_info
Service = 0x0e # Get attribute Single
RequestPathSize = 0x05 # length in words
# Class is Identity
AttributeClassType = 0x0021
AttributeClass = 0x0001
# Class Instance = 1
AttributeInstanceType = 0x0025
AttributeInstance = 0x0001
# Single Attribute:
AttributeType = 0x30
Attribute = attribute_id
PathRouteSize = 0x01
Reserved = 0x00
Backplane = 0x01
LinkAddress = slot
AttributePacket = pack('<2B4H2B',
Service,
RequestPathSize,
AttributeClassType,
AttributeClass,
AttributeInstanceType,
AttributeInstance,
AttributeType,
Attribute)
if custom_routing_path == None:
AttributePacket += pack('<4B',
PathRouteSize,
Reserved,
Backplane,
LinkAddress)
else:
"""
Use custom routing -> it should be a list with tuples containing pairs of port number & slot address.
"""
custom_route_path_size = len(custom_routing_path)
route_path = pack('<2B',
custom_route_path_size,
Reserved)
for routing_pair in custom_routing_path:
assert len(routing_pair) == 2, "Routing path should be list of 2-tuples."
port_segment = 0b00001111 & routing_pair[0]
link_address = routing_pair[1]
route_path += pack("<2B",
port_segment,
link_address)
AttributePacket += route_path
frame = self._buildCIPUnconnectedSend(ServiceSize=12) + AttributePacket
eipHeader = self._buildEIPSendRRDataHeader(len(frame)) + frame
pad = pack('<I', 0x00)
self.Socket.send(eipHeader)
retData = pad + self.recv_data()
status = unpack_from('<B', retData, 46)[0]
if status == 0:
if attribute_type == "word":
return unpack_from("<H", retData[-2:])[0]
elif attribute_type == "dword":
int_value = unpack_from("<I", retData[-4:])[0]
return hex(int_value)[2:].upper().rjust(8, "0")
elif attribute_type == "revision":
return "%s.%s" % (retData[-2], retData[-1])
elif attribute_type == "string":
value = retData[48:]
str_size = value[0]
return unpack_from("%ss" % str_size, value[1:])[0].decode("utf-8")
else:
raise TypeError("Unknown attribute type %s" % attribute_type)
else:
return None
def _connect(self):
'''
Open a connection to the PLC
'''
if self.SocketConnected:
return True
# Make sure the connection size is correct
if not 500 <= self.ConnectionSize <= 4000:
raise ValueError("ConnectionSize must be an integer between 500 and 4000")
try:
self.Socket = socket.socket()
self.Socket.settimeout(5.0)
self.Socket.connect((self.IPAddress, self.Port))
except(socket.error):
self.SocketConnected = False
self.SequenceCounter = 1
self.Socket.close()
raise
self.Socket.send(self._buildRegisterSession())
retData = self.recv_data()
if retData:
self.SessionHandle = unpack_from('<I', retData, 4)[0]
else:
self.SocketConnected = False
raise CIPConnectionError("Failed to register session")
self.Socket.send(self._buildForwardOpenPacket())
retData = self.recv_data()
sts = unpack_from('<b', retData, 42)[0]
if not sts:
self.OTNetworkConnectionID = unpack_from('<I', retData, 44)[0]
self.SocketConnected = True
else:
self.SocketConnected = False
raise CIPConnectionError("Forward Open Failed")
return True
def _closeConnection(self):
'''
Close the connection to the PLC (forward close, unregister session)
'''
self.SocketConnected = False
close_packet = self._buildForwardClosePacket()
unreg_packet = self._buildUnregisterSession()
try:
self.Socket.send(close_packet)
self.Socket.send(unreg_packet)
self.Socket.close()
except:
self.Socket.close()
finally:
pass
def _getBytes(self, data):
'''
Sends data and gets the return data
'''
try:
self.Socket.send(data)
retData = self.recv_data()
if retData:
status = unpack_from('<B', retData, 48)[0]
return status, retData
else:
return 1, None
except (socket.gaierror):
self.SocketConnected = False
return 1, None
except (IOError):
self.SocketConnected = False
return 7, None
def _buildRegisterSession(self):
'''
Register our CIP connection
'''
EIPCommand = 0x0065
EIPLength = 0x0004
EIPSessionHandle = self.SessionHandle
EIPStatus = 0x0000
EIPContext = self.Context
EIPOptions = 0x0000
EIPProtocolVersion = 0x01
EIPOptionFlag = 0x00
return pack('<HHIIQIHH',
EIPCommand,
EIPLength,
EIPSessionHandle,
EIPStatus,
EIPContext,
EIPOptions,
EIPProtocolVersion,
EIPOptionFlag)
def _buildUnregisterSession(self):
EIPCommand = 0x66
EIPLength = 0x0
EIPSessionHandle = self.SessionHandle
EIPStatus = 0x0000
EIPContext = self.Context
EIPOptions = 0x0000
return pack('<HHIIQI',
EIPCommand,
EIPLength,
EIPSessionHandle,
EIPStatus,
EIPContext,
EIPOptions)
def _buildForwardOpenPacket(self):
'''
Assemble the forward open packet
'''
forwardOpen = self._buildCIPForwardOpen()
rrDataHeader = self._buildEIPSendRRDataHeader(len(forwardOpen))
return rrDataHeader+forwardOpen
def _buildForwardClosePacket(self):
'''
Assemble the forward close packet
'''
forwardClose = self._buildForwardClose()
rrDataHeader = self._buildEIPSendRRDataHeader(len(forwardClose))
return rrDataHeader + forwardClose
def _buildCIPForwardOpen(self):
'''
Forward Open happens after a connection is made,
this will sequp the CIP connection parameters
'''
CIPPathSize = 0x02
CIPClassType = 0x20
CIPClass = 0x06
CIPInstanceType = 0x24
CIPInstance = 0x01
CIPPriority = 0x0A
CIPTimeoutTicks = 0x0e
CIPOTConnectionID = 0x20000002
CIPTOConnectionID = 0x20000001
self.SerialNumber = randrange(65000)
CIPConnectionSerialNumber = self.SerialNumber
CIPVendorID = self.VendorID
CIPOriginatorSerialNumber = self.OriginatorSerialNumber
CIPMultiplier = 0x03
CIPOTRPI = 0x00201234
CIPConnectionParameters = 0x4200
CIPTORPI = 0x00204001
CIPTransportTrigger = 0xA3
# decide whether to use the standard ForwardOpen
# or the large format
if self.ConnectionSize <= 511:
CIPService = 0x54
CIPConnectionParameters += self.ConnectionSize
pack_format = '<BBBBBBBBIIHHIIIHIHB'
else:
CIPService = 0x5B
CIPConnectionParameters = CIPConnectionParameters << 16
CIPConnectionParameters += self.ConnectionSize
pack_format = '<BBBBBBBBIIHHIIIIIIB'
CIPOTNetworkConnectionParameters = CIPConnectionParameters
CIPTONetworkConnectionParameters = CIPConnectionParameters
ForwardOpen = pack(pack_format,
CIPService,
CIPPathSize,
CIPClassType,
CIPClass,
CIPInstanceType,