How to Read Data from Siemens, Allen-Bradley and Modbus PLCs Without Changing Their Logic
DEV Community

How to Read Data from Siemens, Allen-Bradley and Modbus PLCs Without Changing Their Logic

A practical PLC-to-cloud pattern - pick the right read route per controller, keep the gateway read-only, buffer through outages, and prove the numbers against the line's own counters.

Most factories already have the data they keep asking for. The filler's PLC knows when it stopped, which fault tripped it and how many bottles it made. So do the labeller, the packer and the CIP skid.

The problem is that every machine came from a different supplier, at a different time, with its own controller and its own HMI. Nobody can see the whole line at once.

The usual proposal is to standardise the controllers. That turns a monitoring question into a controls project, with a shutdown, a re-commissioning and a budget that rarely gets approved.

There is a cheaper way, and it is the one we use most often as an IoT company in South Africa working with food and beverage plants. Monitoring and control are separate problems, so you can read a machine without changing what runs it.

This post covers the read side: which route to use for which PLC, what the gateway loop looks like, and how to check the numbers before anyone relies on them.

The pattern in one paragraph

An edge gateway sits on the plant network next to the controllers. It reads an agreed list of tags over each PLC's own protocol, adds names and scaling, writes every reading to a local buffer, and then sends the buffer outward to the platform over an encrypted connection.

The PLC program is never touched. The gateway never writes to it, and nothing outside the plant connects in.

Pick the read route per controller

Be precise about the route. "We support Siemens" tells you very little.

Controller Read route Port Things to check first
Siemens S7-1500 / S7-1200 Built-in OPC UA server 4840/tcp The server must be enabled and licensed on the CPU, and the variables must be exposed to OPC UA
Siemens S7-1500 / S7-1200 S7 communication (ISO-on-TCP) 102/tcp Needs PUT/GET enabled and non-optimised DBs. That is a controls change, so get it signed off
Allen-Bradley Logix EtherNet/IP (CIP) tag reads 44818/tcp Read tags by name. Agree the connection count with your controls engineer
Schneider Electric Modbus TCP, or Modbus RTU on serial 502/tcp You need the register map. Check word order on 32-bit values
Mitsubishi Electric MC protocol (SLMP), or Modbus where configured varies The Ethernet port has to be configured for MC protocol access
Delta and older serial PLCs Modbus RTU over RS-485 serial You need the register map, baud rate and parity

Two Siemens details catch people out most often.

PUT/GET. Classic S7 reads (for example with python-snap7) on an S7-1200 or S7-1500 only work if Permit access with PUT/GET communication from remote partner is ticked in the CPU's protection settings, and the data blocks you read have Optimized block access turned off. Both are changes to the PLC project. If a monitoring vendor makes them without asking, that is a red flag.

OPC UA exposure. On the OPC UA route, every DB variable has Accessible from HMI/OPC UA and Writable from HMI/OPC UA attributes in TIA Portal. Expose what the gateway needs and clear Writable on those variables. The read-only guarantee then lives in the PLC configuration, not in a vendor's promise.

If you are trying to decide between OPC UA, Modbus and MQTT, I wrote a longer comparison here: which industrial protocol for which PLC.

What the gateway loop actually does

Production gateways are usually purpose-built devices, not Python scripts. The loop underneath is still simple enough to sketch, and the sketch shows the two behaviours that matter: it only reads, and it never drops data when the link goes down.

# Minimal sketch of the edge pattern: read-only OPC UA poll -> local buffer -> MQTT over TLS.
# Illustrative only: no retries/backoff, the flush blocks the loop, and the buffer is never pruned.
import asyncio, json, sqlite3, time
import paho.mqtt.client as mqtt
from asyncua import Client

OPCUA_URL = "opc.tcp://192.168.10.20:4840" # PLC on the OT network
TOPIC = "plant/line2/filler"
POLL_S = 5
TAGS = { # name -> NodeId (S7-1500 style)
    "running": 'ns=3;s="Filler_DB"."Running"',
    "count": 'ns=3;s="Filler_DB"."BottleCount"',
    "faultCode": 'ns=3;s="Filler_DB"."FaultCode"',
}

db = sqlite3.connect("buffer.db")
db.execute("CREATE TABLE IF NOT EXISTS q (id INTEGER PRIMARY KEY, payload TEXT)")

mq = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="line2-edge")
mq.tls_set(ca_certs="ca.pem", certfile="edge.crt", keyfile="edge.key")
mq.connect_async("broker.example.com", 8883) # outbound only
mq.loop_start()

def flush():
    """Send buffered readings oldest-first; stop at the first failure."""
    if not mq.is_connected():
        return
    rows = db.execute("SELECT id, payload FROM q ORDER BY id LIMIT 500").fetchall()
    for row_id, payload in rows:
        info = mq.publish(TOPIC, payload, qos=1)
        try:
            info.wait_for_publish(timeout=5)
        except (RuntimeError, ValueError):
            return
        if not info.is_published():
            return
        db.execute("DELETE FROM q WHERE id = ?", (row_id,))
    db.commit()

async def main():
    async with Client(OPCUA_URL) as plc: # read-only user + security mode in real use
        nodes = {name: plc.get_node(nid) for name, nid in TAGS.items()}
        while True:
            values = await plc.read_values(list(nodes.values()))
            reading = {"ts": time.time(), **dict(zip(nodes, values))}
            db.execute("INSERT INTO q (payload) VALUES (?)", (json.dumps(reading),))
            db.commit()
            flush()
            await asyncio.sleep(POLL_S)

asyncio.run(main())

A few points the sketch makes concrete:

  • The timestamp is taken at the edge, when the value is read. It is not the time the cloud receives it. That is what makes backfill after an outage honest.
  • Every reading goes into the buffer first, so the buffer is the only path to the cloud. A dropped link only makes the queue longer.
  • QoS 1 plus delete-after-ack gives at-least-once delivery. The platform has to de-duplicate on (device, ts).
  • There is no write call anywhere. On a real gateway the PLC-side account should not be able to write either, so the guarantee doesn't rest on the code being correct.

For Allen-Bradley you would swap the OPC UA read for something like pycomm3's LogixDriver.read(), and for Modbus pymodbus's read_holding_registers(). The buffer and publish side stays the same.

Outages are the normal case

On many sites, especially in South Africa with scheduled power cuts, a link drop is not an edge case. A dashboard that shows nothing while the link is down is misleading, because the gap looks like downtime.

Three requirements follow:

  • Size the buffer for the longest realistic outage, not the average one. Readings per second × bytes per reading × outage seconds, then double it.
  • Fail over between links, such as wired, Wi-Fi and 4G, without anyone touching the gateway.
  • Record the outage as its own event. Then a power cut shows up as a power cut, not as a machine fault in the shift report.

Respect the PLC's scan budget

A read-only connection can still hurt a controller if it polls too hard. Before going live, agree three numbers with the plant's controls engineer:

  • Poll interval per tag group. Counters and states every 1-5 s are plenty for OEE. Energy totals every 60 s are fine.
  • Number of concurrent connections to the CPU. Older CPUs have small connection limits that HMIs and SCADA already use.
  • Tag count per request. Batch reads, such as read_values or multi-register Modbus reads, are kinder to the CPU than one request per tag.

Prove it before anyone trusts it

The acceptance test is boring on purpose. Run the gateway alongside the line for several real shifts and compare:

  • the dashboard's count with the machine's own counter at shift end,
  • stop events and fault codes with the HMI alarm log,
  • run rate with the machine's rated speed.

When the numbers agree, people stop arguing about the data and start arguing about the causes. That is the point of the exercise.

What to show first

Don't stream every tag the controller holds. Start with the question the plant already argues about:

  • running / stopped / faulted per machine, with the stop reason from the PLC's own fault codes,
  • counts, run rate and rejects per shift and per product,
  • CIP and changeover durations read from the controller, not written up by hand,
  • water, power and compressed air per line, next to production,
  • an alert on a long stop, sent to the person who can act on it.

I work at addanode, a South African IoT company. We connect the PLCs and instruments plants already own to our industrial IoT platform. The full route-by-brand detail is on our PLC to cloud monitoring page.

The code above is a teaching sketch, not our gateway firmware. Questions about a specific controller are welcome in the comments.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.