-
Notifications
You must be signed in to change notification settings - Fork 182
/
eip.py
1967 lines (1725 loc) · 65.9 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 (dmroeder@gmail.com)
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.
'''
from datetime import datetime, timedelta
from .lgxDevice import *
import math
from random import randrange
import socket
from struct import *
import sys
import time
programNames = []
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 = 511
self.Offset = 0
self.KnownTags = {}
self.TagList = []
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 _closeConnection(self)
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):
if datatype:
raise TypeError('Datatype should be set to None when reading lists')
return _multiRead(self, tag)
else:
return _readTag(self, 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 _writeTag(self, tag, value, datatype)
def MultiRead(self, tags):
'''
Read multiple tags in one request
'''
return _multiRead(self, tags)
def GetPLCTime(self):
'''
Get the PLC's clock time
'''
return _getPLCTime(self)
def SetPLCTime(self):
'''
Sets the PLC's clock time
'''
return _setPLCTime(self)
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.
'''
if allTags:
_getTagList(self)
_getAllProgramsTags(self)
else:
_getTagList(self)
_getUDT(self)
return self.TagList
def GetProgramTagList(self, programName):
'''
Retrieves a program tag list from the PLC
programName = "Program:ExampleProgram"
'''
# Ensure programNames is not empty
if not programNames:
_getTagList(self)
# Get a single program tags if progragName exists
if programName in programNames:
program_tags = _getProgramTagList(self, programName)
_getUDT(self)
return self.TagList
if programName not in programNames:
print("Program not found, please check name!")
return None
def GetProgramsList(self):
'''
Retrieves a program names list from the PLC
Sanity check: checks if programNames is empty
and runs _getTagList
'''
if not programNames:
_getTagList(self)
return programNames
def Discover(self):
'''
Query all the EIP devices on the network
'''
return _discover()
def GetModuleProperties(self, slot):
'''
Get the properties of module in specified slot
'''
return _getModuleProperties(self, slot)
def Close(self):
'''
Close the connection to the PLC
'''
return _closeConnection(self)
class LgxTag:
def __init__(self):
self.TagName = ''
self.InstanceID = 0x00
self.SymbolType = 0x00
self.DataTypeValue = 0x00
self.DataType = ''
self.Array = 0x00
self.Struct = 0x00
self.Size = 0x00
def _readTag(self, tag, elements, dt):
'''
processes the read request
'''
self.Offset = 0
if not _connect(self): return None
t,b,i = TagNameParser(tag, 0)
InitialRead(self, t, b, dt)
datatype = self.KnownTags[b][0]
bitCount = self.CIPTypes[datatype][0] * 8
if datatype == 211:
# bool array
tagData = _buildTagIOI(self, tag, isBoolArray=True)
words = _getWordCount(i, elements, bitCount)
readRequest = _addReadIOI(self, tagData, words)
elif BitofWord(t):
# bits of word
split_tag = tag.split('.')
bitPos = split_tag[len(split_tag)-1]
bitPos = int(bitPos)
tagData = _buildTagIOI(self, tag, isBoolArray=False)
words = _getWordCount(bitPos, elements, bitCount)
readRequest = _addReadIOI(self, tagData, words)
else:
# everything else
tagData = _buildTagIOI(self, tag, isBoolArray=False)
readRequest = _addReadIOI(self, tagData, elements)
eipHeader = _buildEIPHeader(self, readRequest)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
return _parseReply(self, tag, elements, retData)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Read failed: {}'.format(err))
def _writeTag(self, tag, value, dt):
'''
Processes the write request
'''
self.Offset = 0
writeData = []
if not _connect(self): return None
t,b,i = TagNameParser(tag, 0)
InitialRead(self, t, b, dt)
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:
writeData.append(float(v))
elif dataType == 160 or dataType == 218:
writeData.append(MakeString(self, v))
else:
writeData.append(int(v))
# write a bit of a word, boolean array or everything else
if BitofWord(tag):
tagData = _buildTagIOI(self, tag, isBoolArray=False)
writeRequest = _addWriteBitIOI(self, tag, tagData, writeData, dataType)
elif dataType == 211:
tagData = _buildTagIOI(self, tag, isBoolArray=True)
writeRequest = _addWriteBitIOI(self, tag, tagData, writeData, dataType)
else:
tagData = _buildTagIOI(self, tag, isBoolArray=False)
writeRequest = _addWriteIOI(self, tagData, writeData, dataType)
eipHeader = _buildEIPHeader(self, writeRequest)
status, retData = _getBytes(self, eipHeader)
if status == 0:
return
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Write Failed: {}'.format(err))
def _multiRead(self, tags):
'''
Processes the multiple read request
'''
serviceSegments = []
segments = b""
tagCount = len(tags)
self.Offset = 0
if not _connect(self): return None
for tag in tags:
if isinstance(tag, (list, tuple)):
tag_name, base, ind = TagNameParser(tag[0], 0)
InitialRead(self, tag_name, base, tag[1])
else:
tag_name, base, ind = TagNameParser(tag, 0)
InitialRead(self, tag_name, base, None)
dataType = self.KnownTags[base][0]
if dataType == 211:
tagIOI = _buildTagIOI(self, tag_name, isBoolArray=True)
else:
tagIOI = _buildTagIOI(self, tag_name, isBoolArray=False)
readIOI = _addReadIOI(self, tagIOI, 1)
serviceSegments.append(readIOI)
header = _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 = _buildEIPHeader(self, readRequest)
status, retData = _getBytes(self, eipHeader)
if status == 0:
return MultiParser(self, tags, retData)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Multi-read failed: {}'.format(err))
def _getPLCTime(self):
'''
Requests the PLC clock time
'''
if not _connect(self): 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 = _buildEIPHeader(self, AttributePacket)
status, retData = _getBytes(self, eipHeader)
if status == 0:
# get the time from the packet
plcTime = unpack_from('<Q', retData, 56)[0]
humanTime = datetime(1970, 1, 1) + timedelta(microseconds=plcTime)
return humanTime
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get PLC time: {}'.format(err))
def _setPLCTime(self):
'''
Requests the PLC clock time
'''
if not _connect(self): 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 = _buildEIPHeader(self, AttributePacket)
status, retData = _getBytes(self, eipHeader)
if status == 0:
return
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to set PLC time: {}'.format(err))
def _getTagList(self):
'''
Requests the controller tag list and returns a list of LgxTag type
'''
if not _connect(self): return None
self.Offset = 0
del programNames[:]
del self.TagList[:]
request = _buildTagListRequest(self, programName=None)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName=None)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get tag list {}'.format(err))
while status == 6:
self.Offset += 1
request = _buildTagListRequest(self, programName=None)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName=None)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get tag list: {}'.format(err))
return
def _getAllProgramsTags(self):
'''
Requests all programs tag list and appends to taglist (LgxTag type)
'''
if not _connect(self): return None
self.Offset = 0
for programName in programNames:
self.Offset = 0
request = _buildTagListRequest(self, programName)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get program tag list: {}'.format(err))
while status == 6:
self.Offset += 1
request = _buildTagListRequest(self, programName)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get program tag list: {}'.format(err))
return
def _getProgramTagList(self, programName):
'''
Requests tag list for a specific program and returns a list of LgxTag type
'''
if not _connect(self): return None
self.Offset = 0
del self.TagList[:]
request = _buildTagListRequest(self, programName)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get program tag list: {}'.format(err))
while status == 6:
self.Offset += 1
request = _buildTagListRequest(self, programName)
eipHeader = _buildEIPHeader(self, request)
status, retData = _getBytes(self, eipHeader)
if status == 0 or status == 6:
extractTagPacket(self, retData, programName)
else:
if status in cipErrorCodes.keys():
err = cipErrorCodes[status]
else:
err = 'Unknown error {}'.format(status)
raise ValueError('Failed to get program tag list: {}'.format(err))
return
def _getUDT(self):
# get only tags that are a struct
struct_tags = [x for x in self.TagList 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:
y = _getTemplateAttribute(self, u.DataTypeValue)
val = unpack_from('<I', y[46:], 10)[0]
x = (val * 4) - 23
size = int(math.ceil(x / 4.0)) * 4
member_count = int(unpack_from('<H', y[46:], 24)[0])
template[u.DataTypeValue] = [size, '', member_count]
for key,value in template.items():
t = _getTemplate(self, key, value[0])
size = value[2] * 8
p = t[50:]
memberBytes = p[size:]
split_char = pack('<b', 0x00)
members = memberBytes.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 self.TagList:
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
def _getTemplateAttribute(self, instance):
'''
Get the attributes of a UDT
'''
if not _connect(self): return None
readRequest = _buildTemplateAttributes(instance)
eipHeader = _buildEIPHeader(self, readRequest)
status, retData = _getBytes(self, eipHeader)
return retData
def _getTemplate(self, instance, dataLen):
'''
Get the members of a UDT so we can get it
'''
if not _connect(self): return None
readRequest = _readTemplateService(instance, dataLen)
eipHeader = _buildEIPHeader(self, readRequest)
status, retData = _getBytes(self, eipHeader)
return retData
def _buildTemplateAttributes(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 _buildTemplateService(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 _readTemplateService(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():
devices = []
request = _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 devices
def _getModuleProperties(self, slot):
'''
Request the properties of a module in a particular
slot. Returns LgxDevice
'''
if not _connect(self): return None
AttributeService = 0x01
AttributeSize = 0x02
AttributeClassType = 0x20
AttributeClass = 0x01
AttributeInstanceType = 0x24
AttributeInstance = 0x01
PathRouteSize = 0x01
Reserved = 0x00
Backplane = 0x01
LinkAddress = slot
AttributePacket = pack('<10B',
AttributeService,
AttributeSize,
AttributeClassType,
AttributeClass,
AttributeInstanceType,
AttributeInstance,
PathRouteSize,
Reserved,
Backplane,
LinkAddress)
frame = _buildCIPUnconnectedSend() + AttributePacket
eipHeader = _buildEIPSendRRDataHeader(self, len(frame)) + frame
pad = pack('<I', 0x00)
self.Socket.send(eipHeader)
retData = pad + recv_data(self)
status = unpack_from('<B', retData, 46)[0]
if status == 0:
return _parseIdentityResponse(retData)
else:
return LGXDevice()
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(_buildRegisterSession(self))
retData = recv_data(self)
if retData:
self.SessionHandle = unpack_from('<I', retData, 4)[0]
else:
self.SocketConnected = False
raise Exception("Failed to register session")
self.Socket.send(_buildForwardOpenPacket(self))
retData = recv_data(self)
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 Exception("Forward Open Failed")
return True
def _closeConnection(self):
'''
Close the connection to the PLC (forward close, unregister session)
'''
self.SocketConnected = False
closePacket = _buildForwardClosePacket(self)
unregPacket = _buildUnregisterSession(self)
try:
self.Socket.send(closePacket)
retData = recv_data(self)
self.Socket.send(unregPacket)
retData = recv_data(self)
self.Socket.close()
except:
pass
def _getBytes(self, data):
'''
Sends data and gets the return data
'''
try:
self.Socket.send(data)
retData = recv_data(self)
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 #(H)Register Session Command (Vol 2 2-3.2)
EIPLength = 0x0004 #(H)Lenght of Payload (2-3.3)
EIPSessionHandle = self.SessionHandle #(I)Session Handle (2-3.4)
EIPStatus = 0x0000 #(I)Status always 0x00 (2-3.5)
EIPContext = self.Context #(Q) (2-3.6)
EIPOptions = 0x0000 #(I)Options always 0x00 (2-3.7)
#Begin Command Specific Data
EIPProtocolVersion = 0x01 #(H)Always 0x01 (2-4.7)
EIPOptionFlag = 0x00 #(H)Always 0x00 (2-4.7)
return pack('<HHIIQIHH',
EIPCommand,
EIPLength,
EIPSessionHandle,
EIPStatus,
EIPContext,
EIPOptions,
EIPProtocolVersion,
EIPOptionFlag)
def _buildUnregisterSession(self):
EIPCommand = 0x66 #(H)
EIPLength = 0x00 #(H)
EIPSessionHandle = self.SessionHandle #(I)
EIPStatus = 0x0000 #(I)
EIPContext = self.Context #(Q)
EIPOptions = 0x0000 #(I)
return pack('<HHIIQI',
EIPCommand,
EIPLength,
EIPSessionHandle,
EIPStatus,
EIPContext,
EIPOptions)
def _buildForwardOpenPacket(self):
'''
Assemble the forward open packet
'''
forwardOpen = _buildCIPForwardOpen(self)
rrDataHeader = _buildEIPSendRRDataHeader(self, len(forwardOpen))
return rrDataHeader+forwardOpen
def _buildForwardClosePacket(self):
'''
Assemble the forward close packet
'''
forwardClose = _buildForwardClose(self)
rrDataHeader = _buildEIPSendRRDataHeader(self, 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 = 0xC200
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,
CIPInstance,
CIPPriority,
CIPTimeoutTicks,
CIPOTConnectionID,
CIPTOConnectionID,
CIPConnectionSerialNumber,
CIPVendorID,
CIPOriginatorSerialNumber,
CIPMultiplier,
CIPOTRPI,
CIPOTNetworkConnectionParameters,
CIPTORPI,
CIPTONetworkConnectionParameters,
CIPTransportTrigger)
# add the connection path
if self.Micro800:
ConnectionPath = [0x20, 0x02, 0x24, 0x01]
else:
ConnectionPath = [0x01, self.ProcessorSlot, 0x20, 0x02, 0x24, 0x01]
ConnectionPathSize = int(len(ConnectionPath)/2)
pack_format = '<B' + str(len(ConnectionPath)) + 'B'
CIPConnectionPath = pack(pack_format, ConnectionPathSize, *ConnectionPath)
return ForwardOpen + CIPConnectionPath
def _buildForwardClose(self):
'''
Forward Close packet for closing the connection
'''
CIPService = 0x4E
CIPPathSize = 0x02
CIPClassType = 0x20
CIPClass = 0x06
CIPInstanceType = 0x24
CIPInstance = 0x01
CIPPriority = 0x0A
CIPTimeoutTicks = 0x0e
CIPConnectionSerialNumber = self.SerialNumber
CIPVendorID = self.VendorID
CIPOriginatorSerialNumber = self.OriginatorSerialNumber
ForwardClose = pack('<BBBBBBBBHHI',
CIPService,
CIPPathSize,
CIPClassType,
CIPClass,
CIPInstanceType,
CIPInstance,
CIPPriority,
CIPTimeoutTicks,
CIPConnectionSerialNumber,
CIPVendorID,
CIPOriginatorSerialNumber)