pycomm3 Documentation

repository·master·Indexed 19 days ago

https://github.com/ottowayi/pycomm3

A Python library for communicating with Allen-Bradley Logix and SLC-series controllers. It provides the LogixDriver for interacting with PLC tags and data, the SLCDriver for SLC-series PLCs, and the CIPDriver base class for Common Industrial Protocol (CIP) communication. The library supports reading and writing single tags, arrays, strings, and User-Defined Types (UDTs), as well as generic messaging via LogixDriver.generic_message for low-level CIP operations, such as interacting with PowerFlex 525 drives and Ethernet modules.

Tokens
10.4K
Snippets
47
Records
54
Agent score
67%

What's inside pycomm3

  1. Install and use pycomm3 for Allen-Bradley PLC communication

    master

    pycomm3 is a Python Ethernet/IP library designed for communicating with Allen-Bradley PLCs. It provides drivers to interact with various PLC families via the Ethernet/IP protocol.

    To get started, you should refer to the following core sections of the documentation:

    • Getting Started: Initial setup and installation.
    • Usage: Detailed guides on how to perform specific communication tasks.
    • Examples: Practical code snippets for common use cases.
    • API Reference: Full technical documentation of the library's classes and methods.
    • CIP Reference: Information regarding the Common Industrial Protocol (CIP) implementation.
    pip install pycomm3
  2. Overview of pycomm3 drivers

    master

    The library provides three distinct drivers for communicating with different types of Ethernet/IP devices:

    • CIPDriver: The base driver. It handles common CIP services like opening/closing connections, device discovery, and generic messaging. Use this for non-PLC devices like drives, switches, or meters.
    • LogixDriver: Specifically designed for ControlLogix, CompactLogix, and Micro800 PLCs. It supports high-level services like reading/writing tags, uploading tag lists, and managing PLC time.
    • SLCDriver: A legacy driver for basic reading/writing of data files in SLC500 or MicroLogix PLCs.
  3. Configure CIP paths for Drivers

    master

    Every driver requires a path argument representing the CIP path to the destination device. pycomm3 supports several formats:

    1. IP Address Only (10.20.30.100): Used for devices without a backplane (drives, switches, Micro800) or for PLCs in slot 0. LogixDriver and SLCDriver will automatically append backplane/0 if no slot is specified.
    2. IP Address/Slot (10.20.30.100/1): Used for PLCs in a backplane not in slot 0. Supported by LogixDriver and SLCDriver only.
    3. CIP Routing Path (1.2.3.4/backplane/2/enet/6.7.8.9/backplane/0): A full route. Use backplane or bp for the backplane and enet for the ethernet port. Supports both / and \ delimiters.

    Custom Ports: To use a custom port, append it to the IP address with a colon: 10.20.30.100:4444. Delimiters: Path segments can be delimited by forward slashes, backslashes, or commas (e.g., 10.10.30.100,bp,0).

  4. Use CIP service and class codes for generic messaging

    master

    For generic messaging or low-level CIP (Common Industrial Protocol) operations, pycomm3 provides enum-like classes containing documented CIP service and class codes. These can be imported directly from the pycomm3 package to ensure type safety and avoid hardcoding magic numbers.

    Key classes available for import include:

    • EncapsulationCommands (from pycomm3.cip.services)
    • Services (from pycomm3.cip.services)
    • ClassCode (from pycomm3.cip.object_library)
    • CommonClassAttributes (from pycomm3.cip.object_library)
  5. Handle Tag response objects

    master

    Methods like .read(), .write(), or .generic_message() return a Tag object.

    To check if a request was successful, use the object's truthiness or check its attributes:

    • Success: The Tag object is truthy, tag.value is not None, and tag.error is None.
    • Failure: The Tag object is falsy, and tag.error contains the CIP error message or the exception raised during the request.
  6. Access Program-Scoped Tags

    master

    To access tags that are scoped to a specific program in the PLC, use the format Program:<program_name>.<tag_name}.

    Example: To access a tag named SomeTag inside the program MainProgram, use the string Program:MainProgram.SomeTag.

    # Example access
    plc.read('Program:MainProgram.SomeTag')
  7. Work with Array Tags and Indexing

    master

    Pycomm3 uses a specific syntax for array manipulation that mirrors Logix behavior:

    1. Indexing: Use square brackets []. Multiple dimensions are comma-separated (e.g., array[1,0]). If no index is provided, it defaults to index 0.
    2. Element Count: When reading or writing, you must specify the number of elements using curly braces {} at the end of the tag name (e.g., array[0]{5} reads 5 elements starting at index 0).

    Special Case: BOOL Arrays BOOL arrays are implemented as DWORD arrays in the PLC.

    • The element count in the request ('{#}') represents the number of BOOL elements.
    • Writing: To write multiple elements, you must write the entire underlying DWORD. This means the starting index and the number of elements must be multiples of 32 (e.g., bools[32]{64}).
    • Reading: There are no such restrictions for reading.
    # Accessing a 2D array element
    plc.read('array2[1,0]')
    
    # Reading 5 elements from an array
    plc.read('an_array{5}')
    
    # Reading 3 elements starting at index 20
    plc.read('an_array[20]{3}')
    
    # Writing to a BOOL array (must be multiples of 32)
    plc.write('bools[32]{64}', [True] * 64)
  8. Use LogixDriver.generic_message for custom CIP services

    master

    The LogixDriver.generic_message method functions similarly to the MSG instruction in Rockwell Logix controllers. It allows you to perform Common Industrial Protocol (CIP) messaging services that are not explicitly implemented as high-level methods in the library. This is useful for accessing specialized device parameters or performing low-level communication tasks like Forward Open or getting/setting PLC time.

    # Conceptual usage pattern
    # driver.generic_message(service_code, path, data)
  9. Handle String Tags transparently

    master

    In pycomm3, strings are treated as atomic types. Even though they are technically structures in the PLC (consisting of LEN and DATA attributes), the library automatically converts them to and from Python str objects.

    • Reading: plc.read('string_tag') returns a Python string.
    • Writing: plc.write(('tag', 'my string')) sends the string to the PLC. If the string is longer than the PLC tag capacity, it will be truncated.
    # Reading a string
    string_val = plc.read('string_tag').value
    
    # Writing a string
    plc.write(('short_string_tag', 'Test Write'))
  10. Access and use Structure Definitions

    master

    When complex data types (UDTs, AOIs, or built-in structures) are uploaded, their full definitions are stored. You can access these definitions via the LogixDriver.data_types property, which is a dictionary of {data_type_name: definition}.

    For a tag with a complex type, the data_type attribute in the tag's definition will contain the structure definition dictionary.

    Structure Definition Properties:

    • name: Name of the data type, UDT, AOI, or built-in structure.
    • attributes: A list of names for each attribute in the structure (excludes internal tags).
    • template: Internal dictionary used by LogixDriver to monitor request/response sizes and perform reads/writes.
    • internal_tags: A dictionary {attribute: {definition}} containing all attributes, including internal ones. Each attribute definition includes:
      • tag_type, data_type, data_type_name, string (if applicable).
      • offset: Byte offset of this tag's data in the response.
      • bit: Optional: For BOOL tags aliased to internal integer tags, indicates the bit index.
      • array: Optional: Length of the array (0 if not an array).
    • type_class: The pycomm3.cip.data_types.DataType representing this structure.
  11. Run user tests with pytest

    master

    To run the user-facing tests, you must set the PLCPATH environment variable to the IP address of your PLC. You should also ignore the demo PLC specific tests to avoid errors if you are not using the specific demo hardware.

    In a Windows command prompt, use:

    set PLCPATH=192.168.1.100
    pytest --ignore tests/online/test_demo_plc.py

    Ensure you use the equivalent command for your specific shell (e.g., export PLCPATH=192.168.1.100 in bash).

  12. Initialize LogixDriver and manage tag uploads

    master

    When you instantiate LogixDriver, it automatically uploads tag definitions from the PLC. These definitions are required for the read and write methods to work correctly, as they abstract the underlying Ethernet/IP protocol details.

    By default, LogixDriver uploads both controller-scoped and program-scoped tags. You can control this behavior using the following keyword arguments:

    • init_tags (bool, default True): If False, only controller-scoped tags are uploaded.
    • init_program_tags (bool, default True): If False, program-scoped tags are not uploaded.

    Note that uploading tags introduces a small upfront overhead depending on the PLC program size and network speed.

    # Default: uploads all controller and program tags
    plc1 = LogixDriver('10.20.30.100')
    
    # Only upload controller-scoped tags
    plc2 = LogixDriver('10.20.30.100', init_tags=False)
    
    # Explicitly upload program tags (default behavior)
    plc3 = LogixDriver('10.20.30.100', init_program_tags=True)