通信协议 Python 解析器和发起器 -- EtherNet/IP CIP
#+OPTIONS: ^:nil # Disable sub/superscripting with bare _; _{...} still works
Comm. Protocol Python Parser and Originator
Cpppo (pronounced 'c'+3*'p'+'o' in Python) is used to implement binary communications protocol parsers. The protocol's communication elements are described in terms of state machines which change state in response to input events, collecting the data and producing output data artifacts.
** Installing
Cpppo depends on several Python packages:
| Package | For? | Description | |--------------------+----------------+----------------------------------------------------------| | greenery>=2.0,2014.7 | history | The Python time-zone library | | tzlocal>=1.1.1 | history | Access to system's local timezone (on Mac, Windows) | | pymodbus>=1.2.0 | remote | Modbus/TCP support for polling Schneider compatible PLCs | | pytest | all tests | A Python unit-test framework | | web.py>=0.37 | web API (
To print a summary of PLC I/O to stdout:
: -p|--print
: --no-print (the default)
To specify and check for a specific =route_path= in incoming Unconnected Send requests, provide
one in "/" or JSON format; the default is to ignore the specified =route_path=
(accepting any =route_path=). If specified, it must be a list containing one dict, specifying a
=port= and =link= value. The =port= is either an 8- or 16-bit number (eg. port 1 typically
indicates the local backplane). The =link= is typically in the range 0-15 (eg. a "slot"
number), or is an IP address (eg. "1.2.3.4"). To specify that no =route_path= is accepted
(ie. only an empty =route_path= is allowed, ie. a Simple request), use 0 or false:
: --route-path '[{"port": 1, "link": 0]' # backplane, slot 0
: --route-path 1/0 # ''
: --route-path '[{"port": 2, "link": "192.168.1.2"}]' # { port 2, link 192.168.1.2 }
: --route-path 2/192.168.1.2 # ''
: --route-path 1/0/2/192.168.1.2 # { backplane, slot 0 }, { port 2, link 192.168.1.2 }
: --route-path false # No route_path accepted
Note that incoming "Simple" requests to a full-featured "Routing" simulator configured with a
route path *will be accepted*; the specified target CIP Object(s) must exist in the target
simulator.
Alternatively, to easily specify acceptance of no routing Unconnected Send
encapsulation (eg. to simulate simple non-routing CIP devices such as
Rockwell MicroLogix or A-B PowerFlex):
: -S|--simple
You may specify as many tags as you like on the command line; at least one
is required:
: =[] # eg. SCADA=INT[1000]
You may specifiy a CIP Class, Instance and Attribute number for the Tag to be
associated with:
: Motor_Velocity@0x93/3/10=REAL
The available types are SINT (8-bit), INT (16-bit), DINT (32-bit) integer,
and REAL (32-bit float). BOOL (8-bit, bit #0), SSTRING and STRING are also
supported.*** EtherNet/IP Controller Object Configuration
To replace the default values contained by default in the standard CIP
Objects (eg. the CIP Identity, TCP/IP Objects), place a =cpppo.cfg= file in
=/etc= or (on Windows) =%APPDATA%=, or a =.cpppo.cfg= in your home
directory, or a =cpppo.cfg= file in the current working directory where your
application is run.
For example, to change the simulated EtherNet/IP CIP Identity Object
'Product Name' (the SSTRING at Class 0x01, Instance 1, Attribute 7), and the
CIP TCP/IP Object Interface Configuration and Host Name, create a
=cpppo.cfg= file containing:
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
[Identity]
# Generally, strings are not quoted
Product Name = 1756-L61/B LOGIX5561
[TCPIP]
# However, some complex structures require JSON configuration:
Interface Configuration = {
"ip_address": "192.168.0.201",
"network_mask": "255.255.255.0",
"dns_primary": "8.8.8.8",
"dns_secondary": "8.8.4.4",
"domain_name": "example.com"
}
Host Name = controller
#+END_EXAMPLE
#+LATEX: }
See [[https://github.com/pjkundert/cpppo/blob/master/cpppo.cfg]] for details on
the file format ([[https://docs.python.org/3/library/configparser.html]]).
Place this file in one of the above-mentioned locations, and run:
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
$ python -m cpppo.server.enip -v
01-20 07:01:29.125 ... NORMAL main Loaded config files: ['cpppo.cfg']
...
#+END_EXAMPLE
#+LATEX: }
Use the new EtherNet/IP CIP =cpppo.server.enip.poll= API to poll the
Identity and TCPIP Objects and see the results:
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
$ python3 -m cpppo.server.enip.poll -v TCPIP Identity
01-20 07:04:46.253 ... NORMAL run Polling begins \
via: 1756-L61/C LOGIX5561 via localhost:44818[850764823]
TCPIP: [2, 48, 0, [{'class': 246}, {'instance': 1}], '192.168.0.201', \
'255.255.255.0', '0.0.0.0', '8.8.8.8', '8.8.4.4', 'example.com', 'controller']
Identity: [1, 15, 54, 2836, 12640, 7079450, '1756-L61/C LOGIX5561', 255]
#+END_EXAMPLE
#+LATEX: }*** Routing via =route_path= to other CIP Devices
A very basic facility for routing incoming CIP requests with complex =route_path= values is
available in the Cpppo EtherNet/IP CIP Communications Simulator. By default, the Simulator
responds to incoming requests with *any* route_path (basically, it ignores the value).
If you specify =--route-path=1/0= on the command-line, it will only respond to requests with
exactly the =route_path= equal to '{"port": 1, "link": 0}' (backplane, slot 0). Every other
CIP reqeuest with some other =route_path= value will be responded to with an error status.
If you wish to configure the allowable =route_path= in the =cpppo.cfg= file, use "Route Path =
...". Furthermore, if you want to route any other valid CIP request by the first element in
its =route_path=, specify a JSON mapping in the configuration file's "Route = { ...",
specifying each =route_path= by / (link ranges are handled), and the : it
should be routed to:
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
[UCMM]
Route Path = 1/0
Route = {
"1/1-15": "localhost:44819"
}
#+END_EXAMPLE
#+LATEX: }
This example (see =cpppo/cpppo-router.cfg= and =cpppo/cpppo.cfg= for more details) accepts and
handles CIP requests to =route_path= port 1, link 0 (backplane slot 0), and routes requests to
all other backplane slots to the EtherNet/IP CIP simulator on localhost port 44819. Any valid
=route_path= is allowed; for example, "2/1.2.3.4" would route requests with a =route_path=
segment specifying port 2, link "1.2.3.4".
When the request is forwarded, the first =route_path= segment is removed, and the remaining
segments (if any) are forwarded. If no more =route_path= segments are left, then the request
is forwarded as a "Simple" CIP request (with no =route_path= or =send_path= configured, as for
a simple non-routing CIP device such as a MicroLogix or A-B Powerflex, etc.)*** EtherNet/IP Controller I/O Customization
If you require access to the read and write I/O events streaming from
client(s) to and from the EtherNet/IP CIP Attributes hosted in your
simulated controller, you can easily make a custom cpppo.server.enip.device
Attribute implementation which will receive all PLC Read/Write Tag
[Fragmented] request data.
We provide two examples; one which records a history of all read/write
events to each Tag, and one which connects each Tag to the current
temperature of the city with the same name as the Tag.**** Record Tag History
For example purposes, we have implemented the cpppo.server.enip.historize
module which simulates an EtherNet/IP CIP device, intercepts all I/O (and
exceptions) and writes it to the file specified in the *first* command-line
argument to the module. It uses =cpppo.history.timestamp=, and requires
that the Python =pytz= module be installed (via =pip install pytz=), which
also requires that a system timezone be set.
This example *captures the first command line argument* as a file name; all
subsequent arguments are the same as described for the EtherNet/IP
Controller Communications Simulator, above:
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
$ python -m cpppo.server.enip.historize some_file.hst Tag_Name=INT[1000] &
$ tail -f some_file.txt
# 2014-07-15 22:03:35.945: Started recording Tag: Tag_Name
2014-07-15 22:03:44.186 ["Tag_Name", [0, 3]] {"write": [0, 1, 2, 3]}
...
#+END_EXAMPLE
#+LATEX: }
(in another terminal)
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE
$ python -m cpppo.server.enip.client Tag_Name[0-3]=[0,1,2,3]
#+END_EXAMPLE
#+LATEX: }
You can examine the code in =cpppo/server/enip/historize.py= to see how to
easily implement your own customization of the EtherNet/IP CIP Controller
simulator.
If you invoke the 'main' method provided by cpppo.server.enip.main directly,
all command-line args will be parsed, and the EtherNet/IP service will not
return control until termination. Alternatively, you may start the service
in a separate threading.Thread and provide it with a list of configuration
options. Note that each individual EtherNet/IP Client session is serviced
by a separate Thread, and thus all method invocations arriving at your
customized Attribute object need to process data in a Thread-safe fashion.**** City Temperature Tag
In this example, we intercept read requests to the Tag, and look up the
current temperature of the city named with the Tag's name. This example is
simple enough to include here (see =cpppo/server/enip/weather.py=):
#+LATEX: {\scriptsize
#+BEGIN_EXAMPLE python
import sys, logging, json
try: # Python2
from urllib2 import urlopen
from urllib import urlencode
except ImportError: # Python3
from urllib.request import urlopen
from urllib.parse import urlencode
from cpppo.server.enip import device, REAL
from cpppo.server.enip.main import main as enip_main
class Attribute_weather( device.Attribute ):
OPT = {
"appid": "078b5bd46e99c890482fc1252e9208d5",
"units": "metric",
"mode": "json",
}
URI = "http://api.openweathermap.org/data/2.5/weather"
def url( self, **kwds ):
"""Produce a url by joining the class' URI and OPTs with any keyword parameters"""
return self.URI + "?" + urlencode( dict( self.OPT, **kwds ))
def __getitem__( self, key ):
"""Obtain the temperature of the city's matching our Attribute's name, convert
it to an appropriate type; return a value appropriate to the request."""
try:
# eg. "http://api.openweathermap.org/...?...&q=City Name"
data = urlopen( self.url( q=self.name )).read()
if type( data ) is not str: # Python3 urlopen.read returns bytes
data = data.decode( 'utf-8' )
weather = json.loads( data )
assert weather.get( 'cod' ) == 200 and 'main' in weather, \
weather.ge暂无开放 Issues,或尚未同步最近议题。