-
-
Notifications
You must be signed in to change notification settings - Fork 113
/
client.py
2248 lines (1996 loc) · 113 KB
/
client.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
#
# Cpppo -- Communication Protocol Python Parser and Originator
#
# Copyright (c) 2013, Hard Consulting Corporation.
#
# Cpppo is free 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, either version 3 of the License, or (at your option) any later
# version. See the LICENSE file at the top of the source tree.
#
# Cpppo 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.
#
from __future__ import absolute_import, print_function, division
try:
from future_builtins import zip, map # Use Python 3 "lazy" zip, map
except ImportError:
pass
__author__ = "Perry Kundert"
__email__ = "perry@hardconsulting.com"
__copyright__ = "Copyright (c) 2013 Hard Consulting Corporation"
__license__ = "Dual License: GPLv3 (or later) and Commercial (see LICENSE)"
__all__ = ['parse_int', 'parse_path', 'parse_path_elements', 'parse_path_component',
'format_path', 'format_context', 'parse_context', 'CIP_TYPES', 'parse_operations',
'client', 'await_response', 'connector', 'recycle', 'main', 'ENIPStatusError' ]
"""enip.client -- EtherNet/IP client API and module entry point
A high-thruput pipelining API for accessing EtherNet/IP CIP Controller data via Tags or
Class/Instance/Attribute numbers.
Module entry point process tags specified on the command-line and/or from stdin (if '-'
specified). Optionally prints results (if --print specified).
"""
import argparse
import array
import collections
import contextlib
import csv
import itertools
import json
import logging
import random
import select
import socket
import sys
import traceback
import warnings
from ... import misc
from ...dotdict import dotdict
from ...automata import ( log_cfg, type_str_base, chainable, peekable )
from .. import network
from . import defaults, parser, device
# used to be defined here; retain for backward-compatibility...
def parse_int( *args, **kwds ):
return device.parse_int( *args, **kwds )
def parse_path( *args, **kwds ):
return device.parse_path( *args, **kwds )
def parse_path_elements( *args, **kwds ):
return device.parse_path_elements( *args, **kwds )
def parse_path_component( *args, **kwds ):
return device.parse_path_component( *args, **kwds )
log = logging.getLogger( "enip.cli" )
class ENIPStatusError( Exception ):
def __init__(self, status=None):
self.status = status
super( ENIPStatusError, self ).__init__("Response EtherNet/IP status: %d" % ( status ))
def format_path( segments, count=None ):
"""Format some simple path segment lists in a human-readable form. Raises an Exception if
unrecognized (only [{'symbolic': <tag>}, ...] or [{'class': ...}, {'instance': ...},
{'attribute': ...}, ...] paths are handled, optionally followed by an {'element': ...}.
If an 'element' segment is provided, we'll append a [#] element index; if count is also provided
we'll append a [#-#] element range.
"""
if isinstance( segments, type_str_base ):
path = segments
else:
symbolic = ''
numeric = []
element = None
for seg in segments:
if 'symbolic' in seg:
symbolic += ( '.' if symbolic else '' ) + seg['symbolic']
elif 'class' in seg and len( numeric ) == 0:
numeric.append( "0x%04X" % seg['class'] )
elif 'instance' in seg and len( numeric ) == 1:
numeric.append( "%d" % seg['instance'] )
elif 'attribute' in seg and len( numeric ) == 2:
numeric.append( "%d" % seg['attribute'] )
elif 'element' in seg:
element = seg['element']
else:
numeric.append( json.dumps( seg, separators=(',',':')))
assert bool( symbolic ) ^ bool( numeric ), \
"Unformattable path segment: %r" % seg
path = symbolic if symbolic else ('@' + '/'.join( numeric ))
if element is not None:
if count is not None:
path += "[%d-%d]" % ( element, element + count - 1 )
else:
path += "[%d]" % ( element )
log.detail( "Formatted %32s from: %s", path, segments )
return path
def format_context( sender_context ):
"""Produce a sender_context bytearray of exactly length 8, NUL-padding on the right."""
assert isinstance( sender_context, (bytes,bytearray,array.array) ), \
"Expected sender_context of bytes/bytearray/array, not %r" % sender_context
return bytearray( sender_context[:8] ).ljust( 8, b'\0' )
def parse_context( sender_context ):
"""Restore a bytes string from a bytearray sender_context, stripping any NUL padding on the
right."""
assert isinstance( sender_context, (bytes,bytearray,array.array) ), \
"Expected sender_context of bytes/bytearray/array, not %r" % sender_context
return bytes( bytearray( sender_context ).rstrip( b'\0' ))
#
# client.CIP_TYPES
#
# The supported CIP data types, and their CIP 'tag_type' values, byte sizes and validators. We
# are generous with the "signed" types (eg. SINT, INT, DINT, LINT), and we actually allow the full
# unsigned range, plus the negative range. There is little risk to doing this, as all provided
# values will fit legitimately into the data type without loss. It does however, make acceptance of
# automatically generated data easier, as we don't need to really know if the data is signed or
# unsigned; just that it fits into the target data type.
#
def int_validate( x, lo, hi ):
res = int( x )
assert lo <= res <= hi, "Invalid %d; not in range (%d,%d)" % ( res, lo, hi)
return res
def bool_validate( b ):
try:
res = int( b ) != 0
return res
except ValueError:
pass
lowered = b.lower()
if lowered == "true":
return True
if lowered == "false":
return False
raise ValueError("Invalid %s; could not be interpreted as boolean" % b)
CIP_TYPES = {
'STRING': (parser.STRING.tag_type, 0, str ),
'SSTRING': (parser.SSTRING.tag_type, 0, str ),
'BOOL': (parser.BOOL.tag_type, parser.BOOL.struct_calcsize, bool_validate ),
'REAL': (parser.REAL.tag_type, parser.REAL.struct_calcsize, float ),
'LREAL': (parser.LREAL.tag_type, parser.LREAL.struct_calcsize, float ),
'LINT': (parser.LINT.tag_type, parser.LINT.struct_calcsize, lambda x: int_validate( x, -2**63, 2**64-1 )), # extra range
'ULINT': (parser.ULINT.tag_type, parser.ULINT.struct_calcsize, lambda x: int_validate( x, 0, 2**64-1 )),
'DINT': (parser.DINT.tag_type, parser.DINT.struct_calcsize, lambda x: int_validate( x, -2**31, 2**32-1 )), # extra range
'UDINT': (parser.UDINT.tag_type, parser.UDINT.struct_calcsize, lambda x: int_validate( x, 0, 2**32-1 )),
'INT': (parser.INT.tag_type, parser.INT.struct_calcsize, lambda x: int_validate( x, -2**15, 2**16-1 )), # extra range
'UINT': (parser.UINT.tag_type, parser.UINT.struct_calcsize, lambda x: int_validate( x, 0, 2**16-1 )),
'SINT': (parser.SINT.tag_type, parser.SINT.struct_calcsize, lambda x: int_validate( x, -2**7, 2**8-1 )), # extra range
'USINT': (parser.USINT.tag_type, parser.USINT.struct_calcsize, lambda x: int_validate( x, 0, 2**8-1 )),
}
def parse_operations( tags, fragment=False, int_type=None, **kwds ):
"""Given a sequence of (string) tags, deduce the set of I/O desired operations, yielding each one.
If a dict is seen, it is passed through. Any additional keyword parameters are added to each
operation (eg. route_path = [{'link':0,'port':0}])
Parse each EtherNet/IP Tag Read or Write; only write operations will have 'data'; default
'method' is considered 'read':
TAG read 1 value (no element index)
TAG[0] read 1 value from element index 0
TAG[1-5] read 5 values from element indices 1 to 5
TAG[1-5]+4 read 5 values from element indices 1 to 5, beginning at byte offset 4
TAG[4-7]=1,2,3,4 write 4 values from indices 4 to 7
@0x1FF/01/0x1A[99] read the 100th element of class 511/0x1ff, instance 1, attribute 26
To support access to scalar attributes (no element index allowed in path), we cannot default to
supply an element index of 0; default is no element in path, and a data value count of 1. If a
byte offset is specified, the request is forced to use Read/Write Tag Fragmented.
Default CIP int_type for int data (data with no '.' in it, by default) is CIP 'INT'.
"""
if int_type is None:
int_type = 'INT'
for tag in tags:
# Pass-thru (already parsed) operation?
if isinstance( tag, dict ):
tag.update( kwds )
yield tag
continue
# Compute tag (stripping val and off), discarding whitespace around tag and val/off.
val = ''
opr = {}
if '=' in tag:
# A write; strip off the values into 'val'
tag,val = [s.strip() for s in tag.split( '=', 1 )]
opr['method'] = 'write'
if '+' in tag:
# A byte offset (valid for Fragmented)
tag,off = [s.strip() for s in tag.split( '+', 1 )]
if off:
opr['offset'] = int( off )
# If a count of elements is defined, save it; Otherwise, deduce it from values (write_tag),
# or leave it unset and use the method default (usually 1) if necessary (read_tag/frag)
seg,elm,cnt = device.parse_path_elements( tag )
opr['path'] = seg
if cnt is not None:
opr['elements'] = cnt
if val:
# Default between REAL/INT, by simply checking for '.' in the provided value(s)
if '.' in val:
opr['tag_type'],size,cast = CIP_TYPES['REAL']
else:
opr['tag_type'],size,cast = CIP_TYPES[int_type.strip().upper()]
# Allow an optional (TYPE)value,value,...
if val.strip().startswith( '(' ) and ')' in val:
typ,val = val.split( ')', 1 ) # Get leading: ['(TYPE', '), ...]
_,typ = typ.split( '(', 1 )
opr['tag_type'],size,cast = CIP_TYPES[typ.strip().upper()]
# The provided val is a comma-separated, whitespace-padded single-line list containing
# integers, reals and quoted strings. Perfect for using csv.reader to parse... Not
# quite perfect: doesn't handle trailing whitespace after quoted strings quite right,
# but much better than we can do by hand.
try:
val_list, = csv.reader(
[ val ], quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True )
except Exception as exc:
log.normal( "Invalid sequence of CSV values: %s; %s", val, exc )
raise
opr['data'] = list( map( cast, val_list ))
if 'offset' not in opr and not fragment:
# Non-fragment write. The exact correct number of data elements must be
# provided. If not specified, deduce it.
if 'elements' not in opr:
opr['elements'] = len( opr['data'] )
assert len( opr['data'] ) == opr['elements'], \
"Number of data values (%d: %r) doesn't match element count (%d): %s=%s" % (
len( opr['data'] ), opr['data'], opr['elements'], tag, val )
else:
# Known element size; allow Fragmented write, to an identified range of indices optionally w/offset into a
# buffer of known type, hence we can check length. If the byte offset + data
# provided doesn't match the number of elements, then a subsequent Write Tag
# Fragmented command will be required to write the balance. We can't deduce the
# final total number of elements from the data provided, b/c it may be partial.
assert size and 'elements' in opr, \
"Fragmented write must specify exact size and destination element range"
byte = opr.get( 'offset' ) or 0
assert byte % size == 0, \
"Invalid byte offset %d for elements of size %d bytes" % ( byte, size )
beg = byte // size
end = beg + len( opr['data'] )
assert end <= opr['elements'], \
"Number of elements (%d) provided and byte offset %d / %d-byte elements exceeds element count %d: %r" % (
len( opr['data'] ), byte, size, opr['elements'], opr )
if beg != 0 or end != opr['elements']:
log.detail( "Partial Write Tag Fragmented; elements %d-%d of %d", beg, end-1, opr['elements'] )
if kwds:
log.detail("Tag: %r yields Operation: %r.update(%r)", tag, opr, kwds )
opr.update( kwds )
else:
log.detail("Tag: %r yields Operation: %r", tag, opr )
yield opr
def enip_replies( response, multiple=False ):
"""Return valid EtherNet/IP response(s), or Falsey (None if nothing, {} if EOF). Raises Exception
if invalid response, EnipStatusError if valid but unsuccessful.
Find the replie(s) in the response; could be single or multiple; should match requests!
Unfortuantely, it is *impossible* to determine this without *knowing* if the issued request was
a Multiple Service Packet; at a higher level (where we collect responses for each issued
request), we can determine if the service code matches.
Returns a list of replies on success.
"""
if response is None: # None response indicates timeout
return None # "Response Not Received w/in timeout
elif not response: # empty response indicates clean EOF
return response # "Session terminated" # =~= raise StopIteration( "Session terminated" )
elif 'enip.status' not in response:
raise AssertionError( "Failed to receive EtherNet/IP response: %s", parser.enip_format( response ))
elif response.enip.status != 0:
raise ENIPStatusError( status=response.enip.status )
replies = None
item_1 = response.get( 'enip.CIP.send_data.CPF.item[1]' )
if item_1:
# Could be either Send RR Data or Send Unit Data
data = item_1.get( 'unconnected_send' ) or item_1.get( 'connection_data' )
if data:
# Could be a Multiple Service Packet or a single Service request. Multiple
# Service Packet is eg. a list of read/write_tag/frag; Single request is eg. a
# read/write_tag/frag, converted to a list.
request = data.get( 'request' )
if 'multiple.request' in request:
replies = request.multiple.request
else:
replies = [ request ]
assert replies, \
"Response Unrecognized: %s" % ( parser.enip_format( response ))
return replies
class client( object ):
"""Establish a connection (within timeout), and Transmit request(s), and yield replies as
available. The request will fail (raise exception) if it cannot be sent within the specified
timeout (None, if no timeout desired). After a session is registered, transactions may be
pipelined (requests sent before responses to previous requests are received.)
Issue requests immediately (avoid delays due to Nagle's Algorithm) to effectively maximize
thruput on high-latency links. Also enable keep-alive on the socket, to be able to (eventually)
detect half-open sockets (depends on the kernel's TCP/IP keepalive timer settings.)
Provide an alternative enip.device.Message_Router Object class instead of the (default) Logix,
to parse alternative sub-dialects of EtherNet/IP.
The first client created also sets the global "device.dialect"; all connections must use the
same dialect. The default is Logix.
"""
route_path_default = defaults.route_path_default
send_path_default = defaults.send_path_default
priority_time_tick = defaults.priority_time_tick
timeout_ticks = defaults.timeout_ticks
def __init__( self, host, port=None, timeout=None, dialect=None, profiler=None,
udp=False, broadcast=False, source_address=None, configuration=None ):
"""Connect to the EtherNet/IP client, waiting up to 'timeout' for a connection. Avoid using
the host OS platform default if 'host' is empty; this will be different on Mac OS-X, Linux,
Windows, ... So, for an empty host, we'll default to 'localhost'; this should be IPv4/IPv6
compatible (vs. '127.0.0.1', for example). Likewise, if both the supplied port and
defaults.address ends up 0, the OS-supplied default port is not used; use 44818.
If 'udp' specified and a 'broadcast' is intended, then we won't connect the UDP socket
(allowing multiple peers, and we'll set OS_BROADCAST.
It is not recommended to use 'broadcast' when high reliability is required. Since all
responses are parsed one after another by the same EtherNet/IP CIP response parser, an
invalid CIP response will cause the parser to fail. Instead, issue a broadcast "List
Services/Identity/Interfaces" request, and then manually collect the peer replies and
addresses using recvfrom. Then, issue individual requests to each identified peer.
If source_address "<address>[:<port>]" is specified, we'll attempt to bind to that
interface, and send using the specified source address (and optionally port number).
If host of None is provided, we'll load the default from 'Address' in the named
'configuration' section.
"""
# Bind to nothing by default (use default i'face as source address). Otherwise, use the
# specified interface (or the system default, specified by ''), and the specified port (or
# an ephemeral port, specified by 0).
self.ifce = None
if source_address:
ifce = source_address.split( ':', 1 )
self.ifce = ( str( ifce[0] ), int( ifce[1] if len( ifce ) > 1 else 0 ))
# If no 'host' supplied; get from 'Address' in configuration. Default is
if host is None:
addr_str = device.Object.config_override( host, 'Address', default='', section=configuration ).strip()
host,port_cnf = misc.parse_ip_port( addr_str, default=('localhost',defaults.address[1]) )
if port is None:
port = port_cnf # only override if nonexistent/None
if port is None:
port = defaults.address[1]
self.addr = str( host ),int( port ) # host may be ip_address; str-ingify...
self.addr_connected = not ( udp and broadcast )
self.conn = None
self.udp = udp
self.dialect = dialect # May be (temporarily) changed
# If provided, we'll disable/enable a profiler around the I/O code, to avoid corrupting the
# profile data with arbitrary I/O related delays
self.profiler = profiler
log.detail( "Connect: %s/IP to %r%s%s", "UPD" if udp else "TCP", self.addr,
" via %r" % ( self.ifce, ) if self.ifce else "",
" broadcast" if not self.addr_connected else "" )
if self.udp:
try:
self.conn = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
if self.ifce:
self.conn.bind( self.ifce )
if not broadcast:
self.conn.connect( self.addr )
except Exception as exc:
log.normal( "Couldn't %s to EtherNet/IP UDP server at %s:%s%s: %s",
"broadcast" if broadcast else "connect",
self.addr[0], self.addr[1],
( " via interface %s:%d" % ( self.ifce[0], self.ifce[1] )) if self.ifce else "",
exc )
raise
if broadcast:
try:
self.conn.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1 )
except Exception as exc:
log.warning( "Couldn't set SO_BROADCAST on socket to EtherNet/IP server at %s:%s: %s",
self.addr[0], self.addr[1], exc )
else:
try:
# If interface specified, use it. Maintain pre-2.7 socket.create_connection
# compatibility by avoiding the argument unless specified...
if self.ifce:
self.conn = socket.create_connection( self.addr, timeout=timeout,
source_address=self.ifce )
else:
self.conn = socket.create_connection( self.addr, timeout=timeout )
except Exception as exc:
log.normal( "Couldn't connect to EtherNet/IP TCP server at %s:%s%s: %s",
self.addr[0], self.addr[1],
( " via interface %s:%d" % ( self.ifce[0], self.ifce[1] )) if self.ifce else "",
exc )
raise
try:
self.conn.setsockopt( socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 )
except Exception as exc:
log.warning( "Couldn't set TCP_NODELAY on socket to EtherNet/IP server at %s:%s: %s",
self.addr[0], self.addr[1], exc )
try:
self.conn.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
except Exception as exc:
log.warning( "Couldn't set SO_KEEPALIVE on socket to EtherNet/IP server at %s:%s: %s",
self.addr[0], self.addr[1], exc )
self.session = None # Not set w/in client class; set manually, or in derived class
self.source = chainable()
self.data = None
# Parsers
self.engine = None # EtherNet/IP frame parsing in progress
self.frame = parser.enip_machine( terminal=True )
self.cip = parser.CIP( terminal=True ) # Parses a CIP request in an EtherNet/IP frame
# Ensure the requested dialect matches the globally selected dialect; Default to Logix. An
# EtherNet/IP CIP "server" receives requests containing a .path identifying the target
# Object (and its parser). The client doesn't have this when parsing responses; only when
# producing requests. Since the responses are parsed asynchronously and then matched up with
# the corresponding request alter (for pipelining), we need to remember a default
# parser. Normally, this will be a Message Router derived class (eg. logix.Logix). However,
# for some requests (eg. Forward Open), the target is the Connection Manager; we'll
# (temporarily) change the client.dialect while parsing these requests.
if device.dialect is None:
from . import logix # Avoid recursive module load
device.dialect = logix.Logix if dialect is None else dialect
if dialect is not None:
assert device.dialect is dialect, \
"Inconsistent EtherNet/IP dialect requested: %r (vs. default: %r)" % ( dialect, device.dialect )
def __str__( self ):
return "%s:%s[%r]" % ( self.addr[0], self.addr[1], self.session )
def __repr__( self ):
return "<%s %s>" % ( self.__class__.__name__, self )
def shutdown( self ):
"""A client-initiated clean shutdown of the EtherNet/IP session requires the client to close the
outgoing half of its TCP/IP connection, while harvesting the remaining responses incoming.
The peer will receive EOF, and cleanly close the connection. After the final response is
harvested, we will then receive EOF, and close the connection. All TCP/IP buffers will be
clear, and the connection will then close in a completely clean fashion.
"""
if not self.udp:
try:
self.conn.shutdown( socket.SHUT_WR )
except:
pass
def close( self ):
"""The lifespan of an EtherNet/IP CIP client connection is defined by client.__init__() and client.close()"""
if getattr( self, 'conn', None ) is not None:
self.conn.close()
self.conn = None
def __del__( self ):
"""Avoid invoking superclass .close, if we've already completed closing"""
if getattr( self, 'conn', None ) is not None:
self.close()
def __enter__( self ):
self.frame.__enter__()
return self
def __exit__( self, typ, val, tbk ):
"""We are leaving exclusive access to this client w/o having raised an Exception; we
better be "between" frames! If we have a partially parsed EtherNet/IP frame in
progress, then this client is no longer usable; raise an Exception."""
self.frame.__exit__( typ, val, tbk )
if typ is None:
assert self.engine is None, \
"Partial response parsed; client session is no longer valid: %s" % ( self.engine )
def __iter__( self ):
return self
def __next__( self ):
"""Return the next available response, or None if no complete response is available w/o
blocking. Raises StopIteration (cease iterating) on EOF between frames. Any other
Exception indicates a client failure, and should result in the client instance being
discarded.
If no input is presently available, harvest any input immediately available; terminate on
EOF.
The response may not actually contain a payload, eg. if the EtherNet/IP header contains a
non-zero status.
TODO: Defer parsing of CPF items in response payload to caller; only the caller knows the
corresponding request, and hence the correct CIP Object that knows how to parse the
request's reply! For example, a "Forward Open" is known to the Connection_Manager @6/1,
while most I/O requests (eg. "Get Attribute Single", "Read Tag Fragmented") are known to the
device-specific dialect of Message Router (eg. Logix). The request has the .path component
that identifies this Object...
"""
# Ensure that the caller has gained exclusive access to this client instance using:
#
# with <instance>:
#
# So long as the caller retains exclusive access, they may continue to attempt to parse
# a response. They may *only* safely release exclusive access between fully parsed
# EtherNet/IP frames (checked in __exit__, above)
self.frame.safe()
# Harvest any input immediately available, if we're empty. We may be coming back
# here after already having issued a non-transition event from the existing EtherNet/IP
# framer engine -- we can't re-enter the engine w/o getting some more input.
addr = self.addr # TCP/IP; may continue parsing data rx last time thru
if self.source.peek() is None:
if self.profiler:
self.profiler.disable()
try:
rcvd,addr = self.recvfrom( timeout=0 )
log.info(
"EtherNet/IP<--%16s:%-5s rcvd %5d: %r",
addr[0] if addr else None, addr[1] if addr else None,
len( rcvd ) if rcvd is not None else 0, rcvd )
if rcvd is not None:
# Some input (or EOF); source is empty; chain the input and drop back into
# the framer engine. It will detect a no-progress condition on EOF. If we
# don't have an engine, we can signal completion right here.
if len( rcvd ):
self.source.chain( rcvd ) # More input received
else:
logging.info( "EOF w/ %s input available, engine %s",
"empty" if self.source.peek() is None else " some",
"off" if self.engine is None else "running" )
if self.engine is None:
raise StopIteration # EOF between EtherNet/IP frames; Done.
else:
# Don't create parsing engine 'til we have some I/O to process. This avoids the
# degenerate situation where empty I/O (EOF) always matches the empty command (used
# to indicate the end of an EtherNet/IP session).
if self.engine is None:
return None
finally:
if self.profiler:
self.profiler.enable()
# Initiate or continue parsing input using the machine's engine; discard the engine at
# termination or on error (Exception). Any exception (including cpppo.NonTerminal) will be
# propagated. Identifies the responding peer address, by returning it via 'result.peer'.
result = None
try:
if self.engine is None:
self.data = dotdict( peer=addr )
self.engine = self.frame.run( source=self.source, data=self.data )
for mch,sta in self.engine:
if sta is None and self.source.peek() is None:
# Non-transition, and no input available; go get some -- all blocking is done
# externally (in the caller), to allow full operation on I/O latency. On a
# non-transition from a sub-machine, just loop if input is still available.
return None
# Engine has terminated w/ a recognized EtherNet/IP frame.
except Exception as exc:
log.normal( "EtherNet/IP<x>%16s:%-5d err.: %s",
self.addr[0], self.addr[1], str( exc ))
self.engine = None
raise
if self.frame.terminal:
log.info( "EtherNet/IP %16s:%-5d done: %s -> %10.10s; next byte %3d: %-10.10r: %r",
self.addr[0], self.addr[1], self.frame.name_centered(), self.frame.current,
self.source.sent, self.source.peek(), self.data )
# Got an EtherNet/IP frame. Return it (after parsing its payload.)
self.engine = None
result = self.data
# Parse the EtherNet/IP encapsulated CIP frame, if any. If the EtherNet/IP header .size was
# zero, it's status probably indicates why.
if result is not None and 'enip.input' in result:
with self.cip as machine:
with contextlib.closing( machine.run(
path='enip', source=peekable( result.enip.input ), data=result )) as engine:
for m,s in engine:
pass
assert machine.terminal, "No CIP payload in the EtherNet/IP frame: %r" % ( result )
# Parse the device (eg. Logix) request responses in the EtherNet/IP CIP payload's CPF items
if result is not None and 'enip.CIP.send_data' in result:
request = None
for item in result.enip.CIP.send_data.CPF.item:
if 'unconnected_send.request' in item:
request = item.unconnected_send.request
elif 'connection_data.request' in item:
request = item.connection_data.request
else:
continue
assert request and 'input' in request, \
"Response did not contain a recognized CIP send_data CPF item"
# A Connected/Unconnected Send that contained an encapsulated request (ie. not just a Get
# Attribute All). Use the globally-defined cpppo.server.enip.client's dialect's
# (eg. logix.Logix) parser to parse the contents of the CIP payload's CPF items.
dialect = self.dialect or device.dialect # May be (temporarily) changed
with dialect.parser as machine:
with contextlib.closing( machine.run( # for pypy, where gc may delay destruction of generators
source=peekable( request.input ),
data=request )) as engine:
for m,s in engine:
pass
assert machine.terminal, "No %r request in the EtherNet/IP CIP CPF frame: %r" % (
dialect, result )
if log.isEnabledFor( logging.DETAIL ):
log.detail( "Client CIP Rcvd: %s", parser.enip_format(
result if log.isEnabledFor( logging.INFO ) else result.enip.CIP ))
return result
next = __next__ # Python 2/3 compatibility
def recvfrom( self, timeout=None ):
"""Receive data (if any) and source address, if available within timeout."""
addr = self.addr
if self.addr_connected:
rcvd = network.recv( self.conn, timeout=timeout )
else:
rcvd,addr = network.recvfrom( self.conn, timeout=timeout )
return rcvd,addr
def send( self, request, timeout=None ):
"""Send encoded request data."""
assert self.writable( timeout=timeout ), \
"Failed to send to %r within %7.3fs: %r" % (
self.addr, misc.inf if timeout is None else timeout, request )
sent = bytes( request )
if self.addr_connected:
self.conn.sendall( sent ) # ensure full buffer is sent
else:
self.conn.sendto( sent, self.addr )
log.info(
"EtherNet/IP-->%16s:%-5d send %5d: %r",
self.addr[0], self.addr[1], len( request ), sent )
def writable( self, timeout=None ):
if self.profiler:
self.profiler.disable()
try:
r, w, e = select.select( [], [self.conn.fileno()], [], timeout )
finally:
if self.profiler:
self.profiler.enable()
return len( w ) > 0
def readable( self, timeout=None ):
if self.profiler:
self.profiler.disable()
try:
r, w, e = select.select( [self.conn.fileno()], [], [], timeout )
finally:
if self.profiler:
self.profiler.enable()
return len( r ) > 0
# Basic CIP Requests; sent immediately
def register( self, timeout=None, sender_context=b'' ):
cip = dotdict()
cip.register = {}
cip.register.options = 0
cip.register.protocol_version = 1
return self.cip_send( cip=cip, sender_context=sender_context, timeout=timeout )
def list_interfaces( self, timeout=None, sender_context=b'' ):
cip = dotdict()
cip.list_interfaces = {}
return self.cip_send( cip=cip, sender_context=sender_context, timeout=timeout )
def list_services( self, timeout=None, sender_context=b'' ):
cip = dotdict()
cip.list_services = {}
return self.cip_send( cip=cip, sender_context=sender_context, timeout=timeout )
def list_identity( self, timeout=None, sender_context=b'' ):
cip = dotdict()
cip.list_identity = {}
return self.cip_send( cip=cip, sender_context=sender_context, timeout=timeout )
def legacy( self, command, cip=None, timeout=None, sender_context=b'' ):
"""Transmit a Legacy EtherNet/IP CIP request, using the specified command code (eg. 0x0001).
If CIP is None, then no CIP payload will be generated.
"""
return self.cip_send( cip=cip )
# CIP Send...Data Requests; may be deferred (eg. for Multiple Service Packet)
def forward_open( self, path, connection_path,
priority_time_tick, timeout_ticks,
O_T, T_O, O_serial, O_vendor, connection_serial,
transport_class_triggers, connection_timeout_multiplier,
timeout=None, send=True,
route_path=False, send_path='', sender_context=b'',
**kwds ):
"""Forward Open uses a CPF encapsulation, but with no route_path or send_path. Must be used
with a self.dialect == Connection_Manager to properly produce request and parse response.
"""
req = dotdict()
req.path = { 'segment': [
dotdict( d )
for d in device.parse_path( path )
]}
req.forward_open = {}
fo = req.forward_open
fo.priority_time_tick = priority_time_tick
fo.timeout_ticks = timeout_ticks
fo.O_T = defaults.Connection( **( O_T or {} )).decoding
fo.T_O = defaults.Connection( **( T_O or {} )).decoding
fo.connection_serial = connection_serial
fo.O_vendor = O_vendor
fo.O_serial = O_serial
fo.transport_class_triggers = transport_class_triggers
fo.connection_timeout_multiplier = connection_timeout_multiplier
fo.connection_path = { 'segment': [
dotdict( d ) for d in device.parse_connection_path( connection_path )
]}
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def forward_close( self, path, connection_path,
priority_time_tick, timeout_ticks,
O_serial, O_vendor, connection_serial,
timeout=None, send=True,
route_path=False, send_path='', sender_context=b'' ):
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.forward_close = {}
fc = req.forward_close
fc.priority_time_tick = priority_time_tick
fc.timeout_ticks = timeout_ticks
fc.connection_serial = connection_serial
fc.O_vendor = O_vendor
fc.O_serial = O_serial
fc.connection_path = { 'segment': [
dotdict( d ) for d in device.parse_connection_path( connection_path )
]}
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def service_code( self, code, path, data=None, elements=None, tag_type=None,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, # for response data_size estimation
sender_context=b'', **kwds ):
"""Generic CIP Service Code, with path to target CIP Object, and supplied data payload (converted
to USINTs, if necessary). Minimally, we require the service, and an indication that it is a
bare Service Code request w/ no data:
data.service = 0x??
data.service_code = True
if a data payload is required, supply 'data' (and optionally a tag_type), and this will produce:
data.service = 0x??
data.service_code.data = [0, 1, 2, 3]
"""
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.service = code
if data is None:
req.service_code = True # indicate a payload-free Service Code request
else:
# If a tag_type has been specified, then we need to convert the data to SINT/USINT.
if elements is None:
elements = len( data )
else:
assert elements == len( data ), \
"Inconsistent elements: %d doesn't match data length: %d" % ( elements, len( data ))
if tag_type not in (None,parser.SINT.tag_type,parser.USINT.tag_type):
usints = [ v for v in bytearray(
parser.typed_data.produce( data={'tag_type': tag_type, 'data': data } )) ]
log.detail( "Converted %s[%d] to USINT[%d]",
parser.typed_data.TYPES_SUPPORTED[tag_type], elements, len( usints ))
data,elements = usints,len( usints )
req.service_code = {}
req.service_code.data = data
# We always render the transmitted data payload for Service Code
req.input = bytearray()
if data is not None:
req.data = data
req.input += bytearray( parser.typed_data.produce( req, tag_type=parser.USINT.tag_type ))
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def get_attributes_all( self, path,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, elements=None, tag_type=None, # for response data_size estimation
sender_context=b'', **kwds ):
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.get_attributes_all = True
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def get_attribute_single( self, path,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, elements=None, tag_type=None, # for response data_size estimation
sender_context=b'', **kwds ):
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.get_attribute_single= True
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def set_attribute_single( self, path, data, elements=1, tag_type=None,
route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'', **kwds ):
"""Convert the supplied tag_type data into USINTs if necessary, and perform the Set Attribute
Single. If no/None tag_type supplied, the data is assumed to be SINT/USINT.
"""
# If a tag_type has been specified, then we need to convert the data to SINT/USINT.
if elements is None:
elements = len( data )
else:
assert elements == len( data ), \
"Inconsistent elements: %d doesn't match data length: %d" % ( elements, len( data ))
if tag_type not in (None,parser.SINT.tag_type,parser.USINT.tag_type):
usints = [ v for v in bytearray(
parser.typed_data.produce( data={'tag_type': tag_type, 'data': data } )) ]
log.detail( "Converted %s[%d] to USINT[%d]",
parser.typed_data.TYPES_SUPPORTED[tag_type], elements, len( usints ))
data,elements = usints,len( usints )
req = dotdict()
req.path = { 'segment': [
dotdict( d ) for d in device.parse_path( path )
]}
req.set_attribute_single= {
'data': data,
'elements': elements,
}
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def read( self, path, elements=1, offset=0,
route_path=None, send_path=None, timeout=None, send=True,
data_size=None, tag_type=None, # for response data_size estimation
sender_context=b'', **kwds ):
"""Issue a Read Tag Fragmented request for the specified path. If no specific number of
elements is specified, get it from the path (if it is unparsed, eg Tag[0-9] or
@0x04/5/connection=100)
The Read Tag [Fragmented] response carries a data type; this may be a simple CIP type
(eg. DINT == 0x00c4), or it may indicate a C*Logix STRUCT == 0x02a0 + a UINT structure_tag).
We cannot parse these complex STRUCT types until we get the complete return value, since an
individual Read Tag [Fragmented] may return partial data -- and probably not fill STRUCT
records. So, we do not bother to transmit tag_type data describing the STRUCT, as it cannot
be used 'til the full response has been collected, possibly over several Read Tag
[Fragmented] calls. Thus, all STRUCT responses are returned as raw USINT data.
"""
req = dotdict()
seg,elm,cnt = device.parse_path_elements( path )
if cnt is not None:
elements = cnt
req.path = { 'segment': [ dotdict( s ) for s in seg ]}
if offset is None:
req.read_tag = {
'elements': elements
}
else:
req.read_frag = {
'elements': elements,
'offset': offset,
}
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def write( self, path, data, elements=1, offset=0, tag_type=None,
route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'', **kwds ):
req = dotdict()
seg,elm,cnt = device.parse_path_elements( path )
if cnt is not None:
elements = cnt
req.path = { 'segment': [ dotdict( s ) for s in seg ]}
if tag_type is None:
tag_type = parser.INT.tag_type
if offset is None:
req.write_tag = {
'elements': elements,
'data': data,
'type': tag_type,
}
else:
req.write_frag = {
'elements': elements,
'offset': offset,
'data': data,
'type': tag_type,
}
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
def multiple( self, request, path=None, route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'', **kwds ):
assert isinstance( request, list ), \
"A Multiple Service Packet requires a request list"
req = dotdict()
if path:
req.path = { 'segment': [
dotdict( s ) for s in device.parse_path( path )
]}
req.multiple = {
'request': request,
}
if send:
self.req_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context, **kwds )
return req
#
# ..._send -- transmit a request using the appropriate encapsulation
#
# Depending on the class of CIP connection, various encapsulations are appropriate. These
# should be as close to transparent to the higher-level APIs as possible; for consistency, we'll
# accept all of the required arguments, ignoring any that are irrelevant (in case they are
# provided in general-purpose higher-level code).
#