Package: pycomm3
Introductionpycomm3started as a Python 3 fork ofpycomm, which is a Python 2 library for
communicating with Allen-Bradley PLCs using Ethernet/IP.  The initial Python 3 port was done
in thisforkand was used as the base forpycomm3.  Since then, the library has been
almost entirely rewritten and the API is no longer compatible withpycomm.  Without the
hard work done by the originalpycommdevelopers,pycomm3would not exist.  This
library seeks to expand upon their great work.Driverspycomm3includes 3 drivers:CIPDriverThis driver is the base driver for the library, it handles common CIP services used
by the other drivers.  Things like opening/closing a connection, register/unregister sessions,
forward open/close services, device discovery, and generic messaging.  It can be used to connect to
any Ethernet/IP device, like: drives, switches, meters, and other non-PLC devices.LogixDriverThis driver supports services specific to ControlLogix, CompactLogix, and Micro800 PLCs.
Services like reading/writing tags, uploading the tag list, and getting/setting the PLC time.SLCDriverThis driver supports basic reading/writing data files in a SLC500 or MicroLogix PLCs.  It is
a port of theSlcDriverfrompycommwith minimal changes to make the API similar to the
other drivers. Currently this driver is considered legacy and it’s development will be on
a limited basis.DisclaimerPLCs can be used to control heavy or dangerous equipment, this library is provided “as is” and makes no guarantees on
its reliability in a production environment.  This library makes no promises in the completeness or correctness of the
protocol implementations and should not be solely relied upon for critical systems.  The development for this library
is aimed at providing quick and convenient access for reading/writing data inside Allen-Bradley PLCs.SetupThe package can be installed fromPyPIusingpip:pip install pycomm3orpython-mpip install pycomm3.Optionally, you may configure logging using the Python standardlogginglibrary.  A convenience method is provided
to help configure basic logging, see theLogging Sectionin the docs for more information.Python and OS Supportpycomm3is a Python 3-only library and is supported on Python versions from 3.6.1 up to 3.10.
There should be no OS-specific requirements and should be able to run on any OS that Python is supported on.
Development and testing is done primarily on Windows 10.  If you encounter an OS-related problem, please open an issue
in theGitHub repositoryand it will be investigated.Attention!Python 3.6.0 is not supported due toNamedTuplenot supportingdefault values and methodsuntil 3.6.1DocumentationThis README covers a basic overview of the library, full documentation can be found onRead the Docsor by visitinghttps://pycomm3.dev.ContributionsIf you’d like to contribute or are having an issue, please read theContributingguidelines.Highlighted Featuresgeneric_messagefor extra functionality not directly implementedworking similar to the MSG instruction in Logix, arguments similar to the MESSAGE propertiesSee the examples section for things like getting/setting drive parameters, IP configuration, or uploading an EDS fileused internally to implement some of the other methods (get/set_plc_time, forward open/close, etc)simplified data typesallows use of standard Python types by abstracting CIP implementation details away from the userstrings use normal Pythonstrobjects, does not require handling of theLENandDATAattributes separatelycustom string types are also identified automatically and not limited to just the builtin oneBOOL arrays use normal Pythonboolobjects, does not require complicated bit shifting of the DWORD valuepowerful type system to allow types to represent any CIP object and handle encoding/decoding the objectLogixDriversimple API, only 1readmethod and 1writemethod for tags.does not require using different methods for different data typesrequires the tag name only, no other information required from the userautomatically manages request/response size to pack as many requests into a single packetautomatically handles fragmented requests for large tags that can’t fit in a single packetboth support full structure reading/writing (UDTs, AOIs, etc)forreadtheTag.valuewill be adictof{attribute: value}forwritethe value should be a dict of{attribute: value}, nesting as neededdoes not do partial writes, the value must match the complete structurenot recommended for builtin type (TIMER, CONTROL, COUNTER, etc)both require no attributes to have an External Access of Noneuploads the tag list and data type definitions from the PLCno requirement for user to determine tags available (like from an L5X export)definitions are required forread/writemethodsautomatically enables/disables different features based on the target PLCExtended Forward Open (EN2T or newer and v20+)Symbol Instance Addressing (Logix v21+)detection of Micro800 and disables unsupported features (CIP Path, Ex. Forward Open, Instance Addressing, etc)LogixDriver OverviewCreating a driver is simple, only apathargument is required.  Thepathcan be the IP address, IP and slot,
or a full CIP route, refer to the documentation for more details.  The example below shows how to create a simple
driver and print some of the information collected about the device.from pycomm3 import LogixDriver

with LogixDriver('10.20.30.100/1') as plc:
    print(plc)
    # OUTPUT:
    # Program Name: PLCA, Device: 1756-L83E/B, Revision: 28.13

    print(plc.info)
    # OUTPUT:
    # {'vendor': 'Rockwell Automation/Allen-Bradley', 'product_type': 'Programmable Logic Controller',
    #  'product_code': 166, 'version_major': 28, 'version_minor': 13, 'revision': '28.13', 'serial': 'FFFFFFFF',
    #  'device_type': '1756-L83E/B', 'keyswitch': 'REMOTE RUN', 'name': 'PLCA'}Reading/Writing TagsReading or writing tags is as simple as calling thereadandwritemethods. Both methods accept any number of tags,
and will automatically pack multiple tags into aMultiple Service Packet Service (0x0A)while making sure to stay below the connection size.
If there is a tag value that cannot fit within the request/reply packet, it will automatically handle that tag independently
using theRead Tag Fragmented (0x52)orWrite Tag Fragmented (0x53)requests.Both methods will returnTagobjects to reflect the success or failure of the operation.class Tag(NamedTuple):
    tag: str  # the name of the tag, does not include ``{<# elements>}`` from request
    value: Any  # value read or written, may be ``None`` if an error occurred
    type: Optional[str] = None  # data type of tag, including ``[<# elements>]`` from request
    error: Optional[str] = None  # ``None`` if successful, else the CIP error or exception thrownTagobjects are considered successful (truthy) if thevalueis notNoneand theerrorisNone.Examples:with LogixDriver('10.20.30.100') as plc:
    plc.read('tag1', 'tag2', 'tag3')  # read multiple tags
    plc.read('array{10}') # read 10 elements starting at 0 from an array
    plc.read('array[5]{20}) # read 20 elements starting at elements 5 from an array
    plc.read('string_tag')  # read a string tag and get a string
    plc.read('a_udt_tag') # the response .value will be a dict like: {'attr1`: 1, 'attr2': 'a string', ...}

    # writes require a sequence of tuples of [(tag name, value), ... ]
    plc.write('tag1', 0)  # single writes do not need to be passed as a tuple
    plc.write(('tag1', 0), ('tag2', 1), ('tag3', 2))  # write multiple tags
    plc.write(('array{5}', [1, 2, 3, 4, 5]))  # write 5 elements to an array starting at the 0 element
    plc.write('array[10]{5}', [1, 2, 3, 4, 5])  # write 5 elements to an array starting at element 10
    plc.write('string_tag', 'Hello World!')  # write to a string tag with a string
    plc.write('string_array[2]{5}', 'Write an array of strings'.split())  # write an array of 5 strings starting at element 2
    plc.write('a_udt_tag', {'attr1': 1, 'attr2': 'a string', ...})  # can also use a dict to write a struct

    # Check the results
    results = plc.read('tag1', 'tag2', 'tag3')
    if all(results):
        print('They all worked!')
    else:
        for result in results:
            if not result:
                print(f'Reading tag {result.tag} failed with error: {result.error}')NoteTag names for bothreadandwriteare case-sensitive and are required to be the same as they are named in
the controller.  This may change in the future.Unit Testingpytestis used for unit testing. Thetestsdirectory contains an L5X export of the testing program
that contains all tags necessary for testing.  The only requirement for testing (besides a running PLC with the testing
program) is the environment variablePLCPATHfor the PLC defined.User TestsThese tests are for users to run.  There are a few tests that are specific to a demo
plc, those are excluded. To run them you have the following options:withtox:modify thePLCPATHvariable intox.inithen run this command:tox-euseror withpytest:set PLCPATH=192.168.1.100
pytest --ignore tests/online/test_demo_plc.py(or the equivalent in your shell)NoteTest coverage is not complete, pull requests are welcome to help improve coverage.Licensepycomm3is distributed under the MIT License