Machine data from OPC UA to Grafana

Getting controller values into a database and onto a dashboard, even when something along the way fails. Design, trade-offs and configuration.

  1. ControllerOPC UA server
  2. Python servicesubscription
  3. RabbitMQAMQP, buffer
  4. Telegrafwriter
  5. InfluxDBtime series
  6. Grafanadashboards
Each stage only knows the next one. If the database goes down, messages collect in the broker.

A machine data pipeline reads values from the controller over OPC UA, buffers them in a message broker and writes them to a time-series database that Grafana displays. In BLUECTRL, the platform of BLUELINE / Linetechnology GmbH for modular recycling plants, a Python service reads OPC UA, RabbitMQ carries the data over AMQP and Telegraf writes to InfluxDB. Splitting the chain into separate stages means an outage in one place costs no measurements as long as the buffer holds, and each component can be replaced on its own.

The data is already in the controller: states, counters, temperatures, faults. Service and product teams can only use it once it reaches a database reliably and with a correct timestamp. This article walks through the chain stage by stage and explains the reasoning. The BLUECTRL case study shows the overall system.

Reading OPC UA with Python instead of a Telegraf plugin

Telegraf ships its own OPC UA plugins, inputs.opcua and inputs.opcua_listener. For one plant with a fixed set of variables, they are often enough. A dedicated Python client starts to pay off when you have several machine types:

  • Data model: the service maps PLC variables to stable names with units. When someone renames a variable on the controller, you change one mapping and no dashboards.
  • Connection handling: reconnects, recreating subscriptions after a controller restart and dealing with status codes all stay under your control.
  • Decoupling: the service delivers to the broker and doesn’t need to know who reads the data later.

The price is code that someone has to test and maintain. If you are connecting a single machine, the plugin is the cheaper option.

OPC UA subscriptions rather than polling

A subscription is the better way to read. The server reports changes, so the client doesn’t have to ask for each variable in turn. With the Python library asyncua, the core looks like this, shortened:

from asyncua import Client

class Handler:
    def datachange_notification(self, node, value, data):
        ts = data.monitored_item.Value.SourceTimestamp
        publish(node, value, ts)  # to the broker

async with Client(url=ENDPOINT) as client:
    sub = await client.create_subscription(500, Handler())
    node = client.get_node("ns=2;s=Line1.Temperature")
    await sub.subscribe_data_change(node, queuesize=10)

Three settings determine load and accuracy: the sampling interval (how often the server checks the value), the publishing interval (how often it delivers changes) and the queue size per monitored item. With too small a queue, fast changes between two deliveries are lost. A deadband filters noise on analogue values.

Also keep the controller’s source timestamp, because the arrival time means little after a connection loss. And check the status code, so that a Bad value doesn’t end up in the database as a measurement.

The server side on the controller is set up by the PLC programmers, including security mode and application certificates. The pipeline starts at that interface.

RabbitMQ as the buffer between machine and database

The broker separates the pace of the machine from the pace of the database. If the database fails or is under maintenance, messages collect in the queue. That only holds with a durable queue, persistent messages and publisher confirms. Leave one out and a restart can lose data without anyone noticing.

Every buffer has a limit. x-max-length caps the queue and x-overflow defines what happens when it is full: drop the oldest messages or reject new ones. Dropping old telemetry is often acceptable. For counters and fault messages it may not be.

Where the broker runs is still a decision to make. A broker on the edge device that forwards to a central instance via Shovel rides out long network outages, at the cost of storage and flash wear on the device. With a central broker, the Python service has to buffer locally when the network is down. The answer depends on how long you expect devices to be offline and how much storage they have.

MQTT is the common alternative to AMQP, especially when controllers publish directly or bandwidth is tight. AMQP gives you more routing and several independent consumers. RabbitMQ speaks both via a plugin, so the choice doesn’t have to be final.

Telegraf writes to the time-series database

Telegraf picks up the messages and handles batching and retries. A few lines of configuration are enough:

[[inputs.amqp_consumer]]
  brokers = ["amqp://broker:5672/"]
  exchange = "machine-data"
  queue = "telemetry"
  binding_key = "#"
  max_undelivered_messages = 1000
  data_format = "influx"

The setting that matters is max_undelivered_messages. Telegraf only acknowledges a message once an output has written it. If the database is down, messages stay in the broker and Telegraf stops fetching more. Backpressure ends up where it belongs.

OPC UA to database: InfluxDB or TimescaleDB

In BLUECTRL, Telegraf writes to InfluxDB today, and a migration to TimescaleDB is planned. As a general rule, InfluxDB suits pure measurement series. Plant and module go into tags, measured values into fields. Using order or part numbers as tags drives up cardinality and slows the database down.

TimescaleDB sits on PostgreSQL and comes into its own when you want to query time series together with master data or orders, using ordinary SQL joins. Continuous aggregates take care of downsampling older data.

Because only Telegraf knows about the database, switching stays manageable. A second output (outputs.postgresql) writes in parallel for a while, then the dashboards move across. The earlier stages never notice.

Grafana: dashboards from the repository

Keep dashboards and data sources in the repository using provisioning. Every new plant then gets the same version, and changes can be traced. One variable per plant saves you from copying dashboards.

Watch the pipeline itself as well. The key value is queue length: if it grows, the write side is stuck, long before gaps show up on a dashboard. Grafana is a tool for your engineers here. An interface for end customers is usually a separate application on the same data.

Summary for management

Data still arrives when the network or the database is briefly gone, because there is a buffer in between. The components are widely used open-source tools that can be replaced individually, so you aren’t tied to a platform licence. And the effort sits at the start, in a data model that engineering and service should agree on before the second plant comes along.

Let’s talk about your devices

Which devices, how many, what is missing today: a short paragraph is enough for a first assessment.