python-snap7

3.0.0 · active · verified Thu Apr 16

python-snap7 is a pure Python S7 communication library for Siemens PLCs, implementing the full protocol stack (TPKT, COTP, S7) in Python. As of version 3.0.0, it no longer requires the underlying Snap7 C library. It provides an interface for connecting to and interacting with Siemens S7-300, S7-400, S7-1200, and S7-1500 PLCs. The library is actively maintained with a moderate release cadence, with major versions introducing significant architectural changes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Siemens PLC using `snap7.client.Client`, read 10 bytes from Data Block (DB) 10, and then disconnect. Ensure the PLC's IP address, rack, and slot are correctly configured. Remember to enable PUT/GET communication on your PLC for the library to function correctly.

import snap7
from snap7.snap7types import S7AreaDB
import os

# Configure PLC connection details
plc_ip = os.environ.get('PLC_IP', '192.168.0.100') # Placeholder IP
plc_rack = int(os.environ.get('PLC_RACK', '0'))
plc_slot = int(os.environ.get('PLC_SLOT', '1'))

client = snap7.client.Client()

try:
    client.connect(plc_ip, plc_rack, plc_slot)
    if client.get_connected():
        print(f"Successfully connected to PLC at {plc_ip}")

        # Example: Read 10 bytes from Data Block (DB) number 10, starting at byte 0
        db_number = 10
        start_byte = 0
        size = 10
        data_buffer = client.db_read(db_number, start_byte, size)
        print(f"Read from DB{db_number}, Start:{start_byte}, Size:{size}: {data_buffer}")

        # Example: Write 10 bytes to Data Block (DB) number 10, starting at byte 0
        # Make sure the PLC is configured to allow writes.
        # new_data = bytearray([0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A])
        # client.db_write(db_number, start_byte, new_data)
        # print(f"Wrote to DB{db_number}, Start:{start_byte}, Size:{size}: {new_data}")

    else:
        print("Failed to connect to PLC.")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if client.get_connected():
        client.disconnect()
        print("Disconnected from PLC.")

view raw JSON →