Skip to main content
PK Automation
Deep Dives
Deep DiveSiemens S7-1500 / Modbus TCP

Building a Resilient Python Polling Service for Siemens S7 & Modbus TCP PLCs

An architecture guide to writing fault-tolerant Python telemetry collectors for factory-floor PLCs—covering socket timeouts, exponential backoff, cycle-time budgeting, and systemd supervision.

Most factory-floor data collection scripts start as a 30-line Python while True: loop running inside an interactive terminal on an engineering workstation. They work fine during commissioning—right up until a managed switch drops a spanning-tree topology change, a PLC enters STOP mode during a weekend changeover, or a half-open TCP socket silently hangs the entire polling thread for 15 minutes.

This guide walks through a production-hardened pattern for polling industrial PLCs from Linux using Python, asyncio, bounded timeouts, and systemd. The goal is predictable recovery without overwhelming the PLC communication processor.

Choosing the Right Protocol & Polling Budget

Before writing collector code, establish a strict communication budget with the controls engineer owning the cell. Every register block read consumes PLC communication load slice time—usually capped at 15–20% of the scan cycle.

Protocol Default Port Typical Poll Interval Failure Mode Under Load Best Fit
Modbus TCP 502/tcp 250 ms – 2 s Connection slot exhaustion (RST) Drives, power meters, remote I/O
Siemens S7comm 102/tcp 200 ms – 1 s PDU truncation / ISO-TSAP timeout Non-optimized DB reads on S7-300/1200/1500
OPC UA 4840/tcp 100 ms – 1 s (pub/sub) Subscription queue overflow Modern S7-1500 / Beckhoff / multi-vendor cells
EtherNet/IP (CIP) 44818/tcp 100 ms – 500 ms Unconnected message timeout (16#0204) ControlLogix / CompactLogix explicit tags

Contiguous Block Reads Beat Single-Tag Polling

Reading 40 individual holding registers across 40 separate requests multiplies Ethernet framing and PLC interrupt overhead by 40x. Always pack telemetry into a single contiguous Data Block (DB) or holding register range (40001–40064), perform one atomic read per cycle, and unpack the raw bytes in Python using struct.

Core Async Poller with Explicit Timeouts

Python’s default TCP socket behavior can block indefinitely when a fiber uplink drops without sending a FIN or RST packet. Every network call—connect, read, and close—must be wrapped in asyncio.wait_for() with a deterministic deadline shorter than your polling interval.

collector/plc_poller.py
from __future__ import annotations
import asyncio
import logging
import struct
import time
from dataclasses import dataclass
from pymodbus.client import AsyncModbusTcpClient
log = logging.getLogger("pk.poller")
@dataclass(slots=True)
class LineSnapshot:
timestamp_ns: int
cycle_count: int
spindle_rpm: float
motor_temp_c: float
fault_word: int
class ResilientPlcPoller:
def __init__(self, host: str, port: int = 502, unit_id: int = 1) -> None:
self.host = host
self.port = port
self.unit_id = unit_id
self.client = AsyncModbusTcpClient(
host=host,
port=port,
timeout=1.5,
retries=0, # Handle backoff explicitly; avoid hidden retry storms
)
self._backoff_s = 1.0
self._max_backoff_s = 30.0
async def poll_once(self) -> LineSnapshot:
if not self.client.connected:
await asyncio.wait_for(self.client.connect(), timeout=2.0)
# Single contiguous read: 8 holding registers (16 bytes) starting at HR 100
response = await asyncio.wait_for(
self.client.read_holding_registers(address=100, count=8, device_id=self.unit_id),
timeout=1.5,
)
if response.isError():
raise RuntimeError(f"Modbus exception response: {response}")
raw_bytes = b"".join(struct.pack(">H", reg) for reg in response.registers)
cycle_count, spindle_rpm, motor_temp_c, fault_word = struct.unpack(">IffHxx", raw_bytes)
self._backoff_s = 1.0 # Reset backoff only after a verified payload
return LineSnapshot(
timestamp_ns=time.time_ns(),
cycle_count=cycle_count,
spindle_rpm=round(spindle_rpm, 2),
motor_temp_c=round(motor_temp_c, 1),
fault_word=fault_word,
)
async def run(self, interval_s: float = 1.0) -> None:
while True:
started = time.monotonic()
try:
snapshot = await self.poll_once()
log.info("telemetry_ok", extra={"snapshot": snapshot})
sleep_for = max(0.05, interval_s - (time.monotonic() - started))
await asyncio.sleep(sleep_for)
except (TimeoutError, OSError, RuntimeError) as exc:
log.warning("poll_failed host=%s err=%s retry_in=%.1fs", self.host, exc, self._backoff_s)
self.client.close()
await asyncio.sleep(self._backoff_s)
self._backoff_s = min(self._backoff_s * 2.0, self._max_backoff_s)

Handling Byte Order & Word Swapping

Industrial hardware rarely agrees on 32-bit floating-point endianness. Siemens S7 DBs and standard Modbus big-endian (ABCD) match struct.unpack(">f", ...), whereas many Modicon, Schneider, and Rockwell Modbus gateways emit word-swapped floats (CDAB). Validate a known non-zero test constant—such as 123.45 (0x42F6E666)—during Factory Acceptance Testing (FAT) before trusting production metrics.

Hardening Socket Keepalives & Circuit Breakers

When tightening an existing collector that hangs during switch failovers, the critical fix is replacing naive time.sleep() loops with drift-compensated deadlines and forcing socket teardown on error:

collector/loop_upgrade.py
# Fragile legacy loop: drifts over time and leaks half-open sockets
while True:
data = client.read_holding_registers(100, 8)
save_to_csv(data)
time.sleep(1.0)
# Drift-compensated async loop with explicit teardown and bounded backoff
next_tick = time.monotonic()
while not stop_event.is_set():
next_tick += interval_s
await safe_poll_with_teardown(client)
delay = max(0.0, next_tick - time.monotonic())
await asyncio.sleep(delay)

Supervising the Service with systemd

Never run production collectors inside a tmux or screen session. Deploy a minimal systemd unit with automatic restarts, memory caps, and journal logging so the service survives power cycles unattended.

/etc/systemd/system/pk-plc-poller.service
[Unit]
Description=PK Automation PLC Telemetry Poller
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=pkcollector
WorkingDirectory=/opt/pk-poller
ExecStart=/opt/pk-poller/.venv/bin/python -m collector.main --config /etc/pk-poller/line04.toml
Restart=always
RestartSec=5
MemoryMax=256M
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

Enable the service and confirm clean journal telemetry and restart limits:

Enable and verify systemd unit
sudo systemctl daemon-reload
sudo systemctl enable --now pk-plc-poller.service
sudo systemctl status pk-plc-poller.service --no-pager
journalctl -u pk-plc-poller.service -n 20 --output=short-iso

Commissioning Checklist

Before signing off on a plant-floor edge collector, verify these five failure injections in sequence:

  1. Pull the patch cable for 90 seconds, plug it back in, and confirm telemetry resumes within <= 30 s without manual intervention.
  2. Switch the PLC to STOP and back to RUN and confirm no duplicate TCP sessions remain in ss -tnp | grep :502.
  3. Reboot the Linux edge box and verify pk-plc-poller.service starts automatically once the NIC link comes up.
  4. Verify PLC communication load in TIA Portal (Online & Diagnostics -> Cycle Time) stays below 20%.
  5. Confirm log rotation via journald SystemMaxUse so logs never fill the industrial PC’s SD card or eMMC storage.

Search full-text engineering posts

Try:

↑↓ navigate · ↵ open · esc closeStatic Index