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.
On This Page (7)
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.
from __future__ import annotations
import asyncioimport loggingimport structimport timefrom dataclasses import dataclassfrom 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:
# Fragile legacy loop: drifts over time and leaks half-open socketswhile 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 backoffnext_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.
[Unit]Description=PK Automation PLC Telemetry PollerAfter=network-online.targetWants=network-online.target
[Service]Type=simpleUser=pkcollectorWorkingDirectory=/opt/pk-pollerExecStart=/opt/pk-poller/.venv/bin/python -m collector.main --config /etc/pk-poller/line04.tomlRestart=alwaysRestartSec=5MemoryMax=256MStandardOutput=journalStandardError=journal
[Install]WantedBy=multi-user.targetEnable the service and confirm clean journal telemetry and restart limits:
sudo systemctl daemon-reloadsudo systemctl enable --now pk-plc-poller.servicesudo systemctl status pk-plc-poller.service --no-pagerjournalctl -u pk-plc-poller.service -n 20 --output=short-isoCommissioning Checklist
Before signing off on a plant-floor edge collector, verify these five failure injections in sequence:
- Pull the patch cable for 90 seconds, plug it back in, and confirm telemetry resumes within
<= 30 swithout manual intervention. - Switch the PLC to
STOPand back toRUNand confirm no duplicate TCP sessions remain inss -tnp | grep :502. - Reboot the Linux edge box and verify
pk-plc-poller.servicestarts automatically once the NIC link comes up. - Verify PLC communication load in TIA Portal (
Online & Diagnostics -> Cycle Time) stays below 20%. - Confirm log rotation via
journaldSystemMaxUseso logs never fill the industrial PC’s SD card or eMMC storage.