DEV Community

Cover image for Your PLC Doesn't Care About Your Event Loop
MkKiefer
MkKiefer

Posted on AI-assisted

Your PLC Doesn't Care About Your Event Loop

Four lessons from putting asyncio on the factory floor


At some point, almost every automation team picks up Python.

It rarely starts as a big decision. Someone needs a quick script to log a few PLC variables to a CSV. Then the script needs a small web dashboard. Then it has to push data to a database, watch a second machine, and send an alert when a value drifts. A few months later the "quick script" is a service that the production line depends on.

If your controllers are Beckhoff TwinCAT systems, that service talks ADS, the Automation Device Specification. ADS is a compact binary protocol over TCP (port 48898), and it is pleasant to work with once you know it. The usual way to use it from Python, though, is synchronous: open a connection, read a value, sleep, repeat. To watch more than one thing, you add threads.

That works fine, until the service has to watch thirty machines, serve a UI, and write to a historian, all at once.

I spent a good part of the last year moving this kind of workload to asyncio. Here is what I learned, mostly the hard way.


Lesson 1: Round-trips are the real cost

A PLC answers a single read quickly. The time goes into the round-trip: framing the request, crossing the network, waiting for the runtime to pick it up, and coming back. Do that 500 times in a loop and you have a slow application, however fast each read is.

ADS has an answer that is easy to miss: sum commands. Instead of 500 separate requests, you send one request that holds 500 sub-requests, and you get one response back. On a typical network this turns seconds of polling into milliseconds.

There is a catch. Batching has a ceiling, and the PLC enforces it. Ask for too much in one request (for example, symbol metadata for hundreds of variables, each with a generous response buffer) and the router simply refuses with an error. The fix is dull but important: size your batches by the bytes you expect back, not only by the number of items.

Takeaway: Batch by default, and size each batch by its payload, not by its item count.


Lesson 2: async does not mean non-blocking

This one surprised me most.

The network side of an async ADS client is easy: await the socket and let the event loop do the rest. But once a large response arrives, you have to decode it: parse thousands of values, map them onto symbol types, and build Python objects. That is pure CPU work, and if it runs in one coroutine without a single await, it blocks the entire event loop.

On my desk this was invisible. On a real system, while a big bulk read was being decoded, every other connection in the process stopped. Heartbeats were late, other requests timed out, and the dashboard froze. Nothing crashed, and nothing was logged. The only symptom was latency.

The first fix is almost embarrassingly small: give control back to the loop between chunks of work.

results = []
for chunk in chunks:
    results.extend(decode(chunk))
    await asyncio.sleep(0)  # let everyone else breathe
Enter fullscreen mode Exit fullscreen mode

The cleaner long-term design splits the work. The event loop only frames and routes messages, and a pure, side-effect-free codec does the heavy decoding in a thread pool. The loop stays responsive however big the payload is.

Takeaway: In asyncio, CPU-bound work is a shared resource. Measure loop latency, not only request latency.


Lesson 3: Stop polling, but plan for backpressure

Polling is the habit everyone starts with. ADS offers something better: notifications. You register a variable once, and the PLC pushes new values to you, either cyclically or on change. Less traffic, lower latency, less work for everyone.

Push-based data raises a question that polling never had to answer: what happens when your consumer is slower than the PLC?

A notification on a fast-changing variable can produce more values than your callback can handle, especially if that callback writes to a database. Without a plan, memory grows until something gives.

The pattern that worked for me is a bounded queue per subscription with an explicit overflow policy:

  • Drop oldest. Keep the most recent values. A good default for monitoring.
  • Drop newest. Keep what arrived first and ignore new values until the consumer has caught up.
  • Latest only. Always deliver just the current value. Ideal for dashboards, where nobody wants to see stale history.

Three more details mattered in practice:

  1. Let the PLC bundle values. A larger max delay means fewer, bigger frames, which are much cheaper to process than a stream of tiny ones.
  2. Clean up after yourself. A crashed process can leave notification handles on the PLC that keep firing into the void. The runtime only allows around 1024 of them, so orphans are a real problem.
  3. Resubscribe after reconnects. Networks on the shop floor drop. Subscriptions should survive that without the application having to notice.

Takeaway: Push-based data needs a backpressure policy, and you should choose it on purpose.


Lesson 4: The transport is not always TCP

The classic picture is a client opening a TCP connection straight to the controller. More and more installations look different: PLCs behind firewalls, edge gateways, and messages routed through an MQTT broker. TwinCAT supports ADS over MQTT for exactly this case.

If your protocol code is tied to a TCP socket, supporting that means a rewrite. If the protocol layer only knows "send these bytes, give me those bytes," a new transport is just a small adapter.

Takeaway: Keep the protocol and the transport apart from day one. Your future network diagram will thank you.


Where these lessons ended up

All of this eventually turned into a small open-source library I have been building on the side: aioads, an asyncio-native ADS client for TwinCAT.

It is my attempt to bake the lessons above into the defaults:

  • Batched reads, so reading many variables costs one round-trip instead of hundreds
  • Symbol and data-type caching, so repeated reads skip the metadata lookup
  • Notifications with bounded queues, overflow policies, and automatic resubscription
  • Pluggable transports: plain TCP, or ADS over MQTT
  • Fully typed, Python 3.12+, and no runtime dependencies for the TCP client

This is roughly what it looks like:

import asyncio
from aioads import AdsClient, AmsAddress
from aioads.ams_service_port import AmsServicePort

async def main():
    client = AdsClient.create_tcp(
        src=AmsAddress(net_id="192.168.1.100.1.1", port=1234),
        dst=AmsAddress(net_id="192.168.1.200.1.1",
                       port=AmsServicePort.TC3_RUNTIME_1),
        ip="192.168.1.200",
    )
    await client.connect()
    try:
        values = await client.read_symbols_by_names(
            ["MAIN.Temperature", "MAIN.Pressure", "MAIN.FlowRate"]
        )
        print(values)
    finally:
        await client.disconnect()

asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

It is still young. Version 0.1.0 has just come out, and the notification API is marked as a preview. If you run TwinCAT systems and write Python, I would really like to hear how it behaves on your hardware, and especially where it falls short.


The bigger picture

Industrial software and modern Python have moved forward mostly side by side, without much contact. The tools on the plant floor are reliable but often synchronous and tied to one platform. The Python ecosystem has excellent async tooling but little knowledge of fieldbuses and PLC runtimes.

The gap is closing, and it is a fun place to work. Whether or not you use my library, the lessons hold: batch your round-trips, protect your event loop, give push-based data a backpressure policy, and keep your transport replaceable.

Your PLC doesn't care about your event loop. Your users will.

Top comments (0)