forked from pjkundert/cpppo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
1609 lines (1422 loc) · 78.4 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
from __future__ import print_function
from __future__ import division
try:
from future_builtins import zip
except ImportError:
pass # already available in Python3
__author__ = "Perry Kundert"
__email__ = "[email protected]"
__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', 'format_path',
'format_context', 'parse_context', 'CIP_TYPES', 'parse_operations',
'client', 'await', 'connector', 'recycle', 'main']
"""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 select
import socket
import sys
import traceback
import cpppo
from .. import network, enip
from . import logix, device, parser
from .device import parse_int, parse_path, parse_path_elements # used to be defined here...
log = logging.getLogger( "enip.cli" )
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, cpppo.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) ), \
"Expected sender_context of bytes/bytearray, 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), 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 = {
'SSTRING': (enip.SSTRING.tag_type, 0, str ),
'BOOL': (enip.BOOL.tag_type, enip.BOOL.struct_calcsize, bool_validate ),
'REAL': (enip.REAL.tag_type, enip.REAL.struct_calcsize, float ),
'DINT': (enip.DINT.tag_type, enip.DINT.struct_calcsize, lambda x: int_validate( x, -2**31, 2**32-1 )), # extra range
'UDINT': (enip.UDINT.tag_type, enip.UDINT.struct_calcsize, lambda x: int_validate( x, 0, 2**32-1 )),
'INT': (enip.INT.tag_type, enip.INT.struct_calcsize, lambda x: int_validate( x, -2**15, 2**16-1 )), # extra range
'UINT': (enip.UINT.tag_type, enip.UINT.struct_calcsize, lambda x: int_validate( x, 0, 2**16-1 )),
'SINT': (enip.SINT.tag_type, enip.SINT.struct_calcsize, lambda x: int_validate( x, -2**7, 2**8-1 )), # extra range
'USINT': (enip.USINT.tag_type, enip.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 tags, deduce the set of I/O desired operations, yielding each one. 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:
# Compute tag (stripping val and off)
val = ''
opr = {}
if '=' in tag:
# A write; strip off the values into 'val'
tag,val = tag.split( '=', 1 )
opr['method'] = 'write'
if '+' in tag:
# A byte offset (valid for Fragmented)
tag,off = 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 = 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
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.
"""
route_path_default = enip.route_path_default
send_path_default = enip.send_path_default
def __init__( self, host, port=None, timeout=None, dialect=logix.Logix, profiler=None,
udp=False, broadcast=False ):
"""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
enip.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.
"""
addr = ( host if host is not None else enip.address[0],
port if port is not None else enip.address[1] )
self.addr = ( addr[0] or 'localhost', addr[1] or 44818 )
self.addr_connected = not ( udp and broadcast )
self.conn = None
self.udp = udp
log.detail( "Connect: %s/IP to %r", "UPD" if udp else "TCP", self.addr )
if self.udp:
try:
self.conn = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
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",
"broadcast" if broadcast else "connect", self.addr[0], self.addr[1], 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:
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",
self.addr[0], self.addr[1], 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 = cpppo.chainable()
self.data = None
# Parsers
self.engine = None # EtherNet/IP frame parsing in progress
self.frame = enip.enip_machine( terminal=True )
self.cip = enip.CIP( terminal=True ) # Parses a CIP request in an EtherNet/IP frame
# Ensure the requested dialect matches the globally selected dialect
if device.dialect is None:
device.dialect = dialect
assert device.dialect is dialect, \
"Inconsistent EtherNet/IP dialect requested: %r (vs. default: %r)" % ( dialect, device.dialect )
# 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
def __str__( self ):
return "%s:%s[%r]" % ( self.addr[0], self.addr[1], self.session )
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 self.conn is not None:
self.conn.close()
def __del__( self ):
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.
"""
# 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:
if self.engine is None:
raise StopIteration # EOF between EtherNet/IP frames; Done.
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" )
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 = cpppo.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:
for mch,sta in machine.run(
path='enip', source=cpppo.peekable( result.enip.input ), data=result ):
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:
for item in result.enip.CIP.send_data.CPF.item:
if 'unconnected_send.request' in item:
# An 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.
with device.dialect.parser as machine:
with contextlib.closing( machine.run( # for pypy, where gc may delay destruction of generators
source=cpppo.peekable( item.unconnected_send.request.input ),
data=item.unconnected_send.request )) as engine:
for mch,sta in engine:
pass
assert machine.terminal, "No %r request in the EtherNet/IP CIP CPF frame: %r" % (
device.dialect, result )
log.info( "Returning result: %r", result )
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, cpppo.inf if timeout is None else timeout, request )
sent = bytes( request )
if self.addr_connected:
self.conn.send( 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 = cpppo.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 = cpppo.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 = cpppo.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 = cpppo.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 SendRRData Requests; may be deferred (eg. for Multiple Service Packet)
def get_attributes_all( self, path,
route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'',
data_size=None, elements=None, tag_type=None ):
req = cpppo.dotdict()
req.path = { 'segment': [ cpppo.dotdict( d ) for d in parse_path( path ) ]}
req.get_attributes_all = True
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def get_attribute_single( self, path,
route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'',
data_size=None, elements=None, tag_type=None ):
req = cpppo.dotdict()
req.path = { 'segment': [ cpppo.dotdict( d ) for d in parse_path( path ) ]}
req.get_attribute_single= True
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
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'' ):
"""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:
elemements = 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,enip.SINT.tag_type,enip.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 = cpppo.dotdict()
req.path = { 'segment': [ cpppo.dotdict( d ) for d in parse_path( path ) ]}
req.set_attribute_single= {
'data': data,
'elements': elements,
}
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def read( self, path, elements=1, offset=0,
route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'',
data_size=None, tag_type=None ):
"""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)"""
req = cpppo.dotdict()
seg,elm,cnt = parse_path_elements( path )
if cnt is not None:
elements = cnt
req.path = { 'segment': [ cpppo.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.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
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'' ):
req = cpppo.dotdict()
seg,elm,cnt = parse_path_elements( path )
if cnt is not None:
elements = cnt
req.path = { 'segment': [ cpppo.dotdict( s ) for s in seg ]}
if tag_type is None:
tag_type = enip.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.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def multiple( self, request, path=None, route_path=None, send_path=None, timeout=None, send=True,
sender_context=b'' ):
assert isinstance( request, list ), \
"A Multiple Service Packet requires a request list"
req = cpppo.dotdict()
if path:
req.path = { 'segment': [ cpppo.dotdict( s ) for s in parse_path( path )]}
req.multiple = {
'request': request,
}
if send:
self.unconnected_send(
request=req, route_path=route_path, send_path=send_path, timeout=timeout,
sender_context=sender_context )
return req
def unconnected_send( self, request, route_path=None, send_path=None, timeout=None,
sender_context=b'' ):
"""The default route_path is the CPU in chassis (link 0), port 1, and the default send_path is
to its Connection Manager (Class 6, Instance 1). These defaults can be configured on a
class or per-instance basis by changing the {route,send}_path_default attributes in either
the client class or instance.
"""
assert isinstance( request, dict )
# Default route_path to the CPU in chassis (link 0), port 1. If provided route_path is
# 0/False, then disable (no route_path provided to Unconnected Send)
if route_path is None:
route_path = self.route_path_default
if route_path:
assert isinstance( route_path, list )
if send_path is None: # could be a string path to parse or a list
# Default to the Connection Manager
send_path = self.send_path_default
cip = cpppo.dotdict()
cip.send_data = {}
sd = cip.send_data
sd.interface = 0
sd.timeout = 0
sd.CPF = {}
sd.CPF.item = [ cpppo.dotdict(), cpppo.dotdict() ]
sd.CPF.item[0].type_id = 0
sd.CPF.item[1].type_id = 178
sd.CPF.item[1].unconnected_send = {}
# If a non-empty send_path or route_path is desired, we'll need to use a Logix-style service
# 0x52 Unconnected Send within the SendRRData to carry these details. Only Originating
# Devices and devices that route between links need to implement this. Otherwise, just go
# straight to the command payload.
us = sd.CPF.item[1].unconnected_send
if send_path or route_path:
us.service = 82
us.status = 0
us.priority = 5
us.timeout_ticks = 157
us.path = { 'segment': [ cpppo.dotdict( s ) for s in parse_path( send_path ) ]}
if route_path: # May be None/0/False or empty
us.route_path = { 'segment': [ cpppo.dotdict( s ) for s in route_path ]} # must be {link/port}
us.request = request
us.request.input = bytearray( device.dialect.produce( us.request )) # eg. logix.Logix
return self.cip_send( cip=cip, sender_context=sender_context, timeout=timeout )
def cip_send( self, cip, command=None, timeout=None, sender_context=b'' ):
"""Encapsulates the CIP request and transmits it, returning the full encapsulation structure
used to carry the request. The response must be harvested later; a sender_context should be
supplied that may be used to associate the response to the originating request.
If the CIP contents can be used to deduce the correct EtherNet/IP CIP framing command
(eg. contains a recognized payload, such as ...CIP.list_identity or ...CIP.send_data), then
command may remain None. However, if sending "legacy" CIP requests (eg. 0x0001) with no CIP
payload, then command may be used to specify the data.enip.command for EtherNet/IP framing.
"""
data = cpppo.dotdict()
data.enip = {}
if command:
data.enip.command = command
data.enip.session_handle= self.session or 0 # May be None, if not yet registered
data.enip.options = 0
data.enip.status = 0
data.enip.sender_context= {}
data.enip.sender_context.input = format_context( sender_context )
data.enip.CIP = cip # Must have content encoded already produced
if log.isEnabledFor( logging.DETAIL ):
log.detail( "Client CIP Send: %s", enip.enip_format( data ))
data.enip.input = bytearray( enip.CIP.produce( data.enip )) # May deduce enip.command...
data.input = bytearray( enip.enip_encode( data.enip )) # for EtherNet/IP framing
log.info( "EtherNet/IP: %3d + CIP: %3d == %3d bytes total",
len( data.input ) - len( data.enip.input ),
len( data.enip.input ), len( data.input ))
if self.profiler:
self.profiler.disable()
try:
self.send( data.input, timeout=timeout )
finally:
if self.profiler:
self.profiler.enable()
return data
def await( cli, timeout=None ):
"""Await a response on an iterable client() instance (for timeout seconds, or forever if None).
Returns (response,elapsed). A 'timeout' may be supplied, of:
0 --> Immediate timeout (response must be ready)
None --> No timeout (wait forever for response)
float/int --> The specified number of seconds
Assumes that the supplied iterable (a client instance) yields None on failure to parse a frame
with presently available input. This is where we implement timeouts; wait up to 'timeout' for
the client to become readable; if not, return the None. Otherwise, loop back and continue
trying to gain a response.
An empty response {} indicates clean termination of a session (EOF received, with no input or
existing partial response in process of parsing in the cli iterator.)
"""
response = cpppo.dotdict()
begun = cpppo.timer()
for response in cli: # if StopIteration raised immediately, defaults to {} signalling completion
if response is None:
elapsed = cpppo.timer() - begun
if not timeout or elapsed <= timeout:
# 0 (immediate) or None (infinite), or unsatisfied timeout; input pending?
if cli.readable( timeout=timeout if not timeout else timeout - elapsed ):
continue # Client I/O pending w/in timeout; see if response complete
# No input available w'in timeout. A partially parsed response may remain
# in 'cli', which may be continued 'til the cli is release
break
elapsed = cpppo.timer() - begun
return response,elapsed
class connector( client ):
"""Register a connection to an EtherNet/IP controller, storing the returned session_handle in
self.session, ready for processing further requests.
Raises an Exception if no valid connection can be established within the supplied timeout.
NOTE:
Generally doesn't make sense to "Register" using a UDP/IP connection to an EtherNet/IP CIP
device, as it is not considered a valid request, so we don't issue it (self.session remains
None). We'll allow creation of a connector, as the client code may simply be using it to
perform otherwise valid requests (eg. List Identity, ...). However, we do not check for
validity of requests issued over the connection.
"""
def __init__( self, host, port=None, timeout=None, **kwds ): # possibly supply dialect, ...
"""Establish a TCP/IP connection and perform a successful CIP Register within 'timeout'. Allow the
full timeout for the TCP/IP connection to succeed. CIP Register is not valid for UDP/IP
type connections.
"""
begun = cpppo.timer()
try:
super( connector, self ).__init__( host=host, port=port, timeout=timeout, **kwds )
if self.udp:
return
with self:
# The register( timeout=... ) applies to the socket send only
elapsed_req = cpppo.timer() - begun
self.register( timeout=None if timeout is None else max( 0, timeout - elapsed_req ))
# Await the CIP response for remainder of timeout
elapsed_req = cpppo.timer() - begun
data,elapsed_rpy= await( self, timeout=None if timeout is None else max( 0, timeout - elapsed_req ))
assert data is not None, "Failed to receive any response"
assert 'enip.status' in data, "Failed to receive EtherNet/IP response"
assert data.enip.status == 0, "EtherNet/IP response indicates failure: %s" % data.enip.status
assert 'enip.CIP.register' in data, "Failed to receive Register response"
self.session = data.enip.session_handle
except Exception as exc:
log.normal( "Connect: Failure in %7.3fs/%7.3fs: %s", cpppo.timer() - begun,
cpppo.inf if timeout is None else timeout, exc )
raise
else:
log.normal( "Connect: Success in %7.3fs/%7.3fs", cpppo.timer() - begun,
cpppo.inf if timeout is None else timeout )
def issue( self, operations, index=0, fragment=False, multiple=0, timeout=None ):
"""Issue a sequence of I/O operations, returning the corresponding sequence of:
(<index>,<context>,<descr>,<op>,<request>). If a non-zero 'multiple' is provided, bundle
requests 'til we exceed the specified multiple service packet request size limit.
Each op is instrumented with a sender_context based on the provided 'index', indicating the
actual EtherNet/IP CIP request it is part of. This can be used to detect how many actual
I/O requests are on the wire if some are merged into Multiple Service Packet requests and
some are single requests.
Requests are variable in size due to the path (may have long symbolic names). Read replies
and Write requests are variable in size due to data type and length. Unfortunately, Reads
don't specify the data type; this is decided by the type of the target Attribute. So, any
guesses on size of reply are estimates at best. We'll assume 4-byte data for read replies,
and 10-byte Tag names.
Reads requests are ~22 bytes and replies ~4 bytes + data in response, Writes ~24 bytes +
data in request and ~4 bytes in response.
EtherNet/IP framing is ~24 bytes, CIP ~6, CPF + Unconnected Send ~24, Multiple Service
Packet ~14. So, a Multiple Service Packet request or reply has a wire-level overhead of
24+6+24+14 == 68 bytes; about 14 bytes more than a normal single CIP request/reply.
We must estimate the size of both the request and the reply, and attempt to ensure neither
exceeds the target 'multiple' request and/or response size. If data_size or elements and
tag_type (undefined/None defaults to assume 4-byte types) is provided (strictly not
necessary for read/get_attribute* calls), these will be used to calculate/estimate the
response size. Default assumption for Read Tag is 4-byte elements, for Get Attribute Single
is an average SSTRING, and for Get Attributes All is the maximum Multiple Service Packet
size (so it isn't merged, by default)
"""
sender_context = str( index ).encode( 'iso-8859-1' )
reqsiz = reqmin = 68
rpysiz = rpymin = 68
requests = [] # If we're collecting for a Multiple Service Packet
requests_paths = {} # Also, must collect all op route/send_paths
for op in operations:
# Chunk up requests if using Multiple Service Request, otherwise send immediately. Also
# handle Get Attribute(s) Single/All, but don't include ...All in Multiple Service Packet.
op['sender_context']= sender_context
descr = "Multi. " if multiple else "Single "
begun = cpppo.timer()
method = op.pop( 'method', 'write' if 'data' in op else 'read' )
if method == 'write':
descr += "Write "
if 'offset' not in op:
op['offset']= 0 if fragment else None # Force Write Tag Fragmented
req = self.write( timeout=timeout, send=not multiple, **op )
reqest = 24 + parser.typed_data.datasize(
tag_type=op.get( 'tag_type' ) or enip.INT.tag_type, size=len( op['data'] ))
rpyest = 4
elif method == 'read':
descr += "Read "
if 'offset' not in op:
op['offset']= 0 if fragment else None # Force Read Tag Fragmented
req = self.read( timeout=timeout, send=not multiple, **op )
reqest = 22
rpyest = 4
if op.get( 'data_size' ):
rpyest += op.get( 'data_size' )
else:
rpyest += parser.typed_data.datasize(
tag_type=op.get( 'tag_type' ) or enip.DINT.tag_type, size=op.get( 'elements', 1 ))
elif method == 'set_attribute_single':
descr += "S_A_S "
req = self.set_attribute_single( timeout=timeout, send=not multiple, **op )
reqest = 8 + parser.typed_data.datasize(
tag_type=op.get( 'tag_type' ) or enip.USINT.tag_type, size=len( op['data'] ))
rpyest = 4
elif method == 'get_attribute_single':
descr += "G_A_S "
req = self.get_attribute_single( timeout=timeout, send=not multiple, **op )
reqest = 8
rpyest = 0
if op.get( 'data_size' ):
rpyest += op.get( 'data_size' )
elif op.get( 'tag_type' ): # a non-0/None tag_type defined; use it (assumes 1 element Attribute)
rpyest += parser.typed_data.datasize(
tag_type=op.get( 'tag_type' ) or enip.DINT.tag_type, size=op.get( 'elements', 1 ))
else:
rpyest = multiple # Completely unknown; prevent merging...
elif method == 'get_attributes_all':
descr += "G_A_A "
req = self.get_attributes_all( timeout=timeout, send=not multiple, **op )
reqest = 8
rpyest = 0
if op.get( 'data_size' ):
rpyest += op.get( 'data_size' )
elif op.get( 'tag_type' ) and op.get( 'elements' ):
rpyest += parser.typed_data.datasize(
tag_type=op.get( 'tag_type' ) or enip.DINT.tag_type, size=op.get( 'elements', 1 ))
else:
rpyest = multiple # Completely unknown; prevent merging...
else:
log.detail( "Unrecognized operation method %s: %r", method, op )
elapsed = cpppo.timer() - begun
descr += ' ' if 'offset' not in op else 'Frag' if op['offset'] is not None else 'Tag '
descr += ' ' + format_path( op['path'], count=op.get( 'elements' ))
if multiple:
if (( not requests or max( reqsiz + reqest, rpysiz + rpyest ) < multiple )
and requests_paths.setdefault( 'route_path', op.get( 'route_path' )) == op.get( 'route_path' )
and requests_paths.setdefault( 'send_path', op.get( 'send_path' )) == op.get( 'send_path' )):
# Multiple Service Packet new or req/rpy est. size OK, and route/send_path same; keep collecting
reqsiz += reqest