Connection
The connection module implements the ISO on TCP transport layer (TPKT/COTP) used for S7 communication.
ISO on TCP connection management (RFC 1006).
Implements TPKT (Transport Service on top of TCP) and COTP (Connection Oriented Transport Protocol) layers for S7 communication.
- class snap7.connection.ISOTCPConnection(host: str, port: int = 102, local_tsap: int = 256, remote_tsap: int | bytes = 258, tpdu_size: TPDUSize = TPDUSize.S_1024)[source]
ISO on TCP connection implementation.
Handles the transport layer for S7 communication including: - TCP socket management - TPKT framing (RFC 1006) - COTP connection setup and data transfer - PDU size negotiation
- __enter__() ISOTCPConnection[source]
Context manager entry.
- __exit__(exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None) None[source]
Context manager exit.
- __init__(host: str, port: int = 102, local_tsap: int = 256, remote_tsap: int | bytes = 258, tpdu_size: TPDUSize = TPDUSize.S_1024)[source]
Initialize ISO TCP connection.
- Parameters:
host – Target PLC IP address
port – TCP port (default 102 for S7)
local_tsap – Local Transport Service Access Point
remote_tsap – Remote Transport Service Access Point (int for 2-byte TSAP, bytes for variable-length TSAP like b”SIMATIC-ROOT-HMI”)
tpdu_size – TPDU size to request during COTP negotiation
- check_connection() bool[source]
Check if the TCP connection is still alive.
Uses a non-blocking socket peek to detect broken connections.
- connect(timeout: float = 5.0) None[source]
Establish ISO on TCP connection.
- Parameters:
timeout – Connection timeout in seconds
- data_available(timeout: float = 0.0) bool[source]
Check if data is available to read without blocking.
Uses
select()to poll the socket for readable data.- Parameters:
timeout – How long to wait in seconds (0.0 = immediate poll).
- Returns:
True if data is available on the socket.
- send_data(data: bytes) None[source]
Send data over ISO connection.
- Parameters:
data – S7 PDU data to send
- set_routing(subnet_id: int, dest_rack: int, dest_slot: int) None[source]
Configure S7 routing parameters for multi-subnet access.
When routing is enabled, the COTP Connection Request includes additional parameters that instruct the gateway PLC to forward the connection to a target PLC on another subnet.
Warning
This method is experimental and may change in future versions.
- Parameters:
subnet_id – Subnet ID of the target network (2 bytes)
dest_rack – Rack number of the destination PLC
dest_slot – Slot number of the destination PLC