IMD SolutionComputing LibraryShop main store

How-to

Set up the MQTT Client SL library on a CODESYS controller

Edge computing and IIoT Published Updated 7 min read

Short answer

MQTT Client SL is part of the CODESYS IIoT Libraries SL package. Verify the exact controller runtime and its license, pin the library version, batch JSON per asset, and set the controller clock before opening a TLS session.

On this page
  1. What the package gives you and what it licenses
  2. Install the package and reach a clean compile
  3. Design the publish path before writing logic
  4. Worked example: batching 40 values at 1 s into one payload per second
  5. When the connection never comes up: work the hops
  6. When to move the client off the controller
  7. Questions asked

MQTT Client SL is part of the CODESYS IIoT Libraries SL package. Check the package requirements against the controller firmware, device description and CODESYS Control runtime before installing it. Confirm the controller can run it continuously with the license you have. Then pin the library version, keep client calls cyclic, batch the published values and set the controller clock before TLS.

What the package gives you and what it licenses #

The CODESYS IIoT Libraries SL package is the delivery vehicle. Alongside the MQTT client it bundles the web client, the mail service and the Azure IoT Hub client libraries, and it installs into the IDE like any other library. MQTT Client SL is the piece you are after: it publishes messages from IEC 61131 code to any MQTT broker and subscribes by topic, so one client carries telemetry out and commands in. The alternative, hand-rolling MQTT over raw TCP sockets, puts packet framing, keepalive scheduling and reconnect logic into your maintenance scope and buys nothing the library lacks.

The CODESYS IIoT Libraries SL data sheet for item 2311000000 lists CODESYS Development System and Control V3.5.18.0 for the documented release, plus the networking and TLS libraries under system requirements. Check the release notes for the package version you install and use the CODESYS Device Reader project to confirm the target supports the required components.

A package download lets you install and compile the example. An unlicensed runtime can run the demo for 30 minutes. Continuous operation requires a valid entitlement on the target. For a WAGO controller, check the exact order number, installed firmware and runtime documentation, then confirm the active license on the physical device. CODESYS documents license activation in a controller-bound software container or on a supported CODESYS Key.

With the direct MQTT client, you control the topic tree and payload format. Size the design against payload limits, task cycle time and broker throughput. Compare those limits with the specific vendor cloud connection if you are replacing one.

If you have not yet settled whether the controller should publish directly or hand off to a gateway box, settle that first: PLC MQTT direct publishing versus an IoT gateway works through that trade. The rest of this article assumes the controller publishes.

Install the package and reach a clean compile #

  1. Check your controller and runtime against the versioned system requirements, then download the CODESYS IIoT Libraries SL package from the CODESYS Store.
  2. In the IDE, install it through Tools > Package Manager, then restart CODESYS so the library repository re-indexes.
  3. Open the example project the package ships (Example: Using the MQTT Client SL Library) and compile it against your controller's device description before writing your own code. A clean compile proves the package installed and the target resolves the library.
  4. In your project, add MQTT Client SL in the Library Manager and pin the exact version, so placeholder resolution on a different engineering PC cannot shift interfaces under you.
  5. Enter the broker parameters: DNS host name, TCP port (1883 plain, 8883 with TLS), a unique client ID, keepalive, the clean-session flag, and the Last Will topic and payload.
  6. For TLS, load the broker's CA certificate into the controller certificate store and reference it from the client's TLS settings. Configure NTP and confirm the controller time first.
  7. Download to the physical controller, go online and verify the license on that runtime. If the client reports a licensing fault, confirm the connected target, the package version and the active license container. Run the commissioning test past the demo window before relying on continuous operation.

Design the publish path before writing logic #

Structure topics by asset and split telemetry from status: plant1/line3/pfc01/telemetry for values, plant1/line3/pfc01/status for session state, with the Last Will on the status topic. A subscriber can then tell 'no new data' from 'controller gone' without watching the value stream.

Batch related values into one JSON payload per publish instead of one topic per tag; the worked example below puts numbers on it. Build the JSON deliberately: IEC 61131 string handling that leaves a stray prefix or an unescaped quote in the buffer is enough for a strict broker to reject the payload, and fixing extra characters in a PLC MQTT JSON payload shows where those bytes come from.

Run the client instance from a task that never blocks. If that task also does file I/O or long string work, the cyclic calls stretch, the keepalive request misses its window, and the broker drops the session on keepalive expiry, which then looks exactly like a network fault. Keep blocking work in a different task.

The client always initiates the TCP connection, so the plant firewall needs one outbound rule to the broker host on the standard TLS port 8883 and no inbound rule at all. Reserve plain 1883 for the bench.

Worked example: batching 40 values at 1 s into one payload per second #

Inputs: 40 process values on one controller, each worth reporting once per second, which is a typical case for this topic (put your own count and cadence in), and one telemetry topic, plant1/line3/pfc01/telemetry, per the scheme above.

Rule: messages per day equal payloads per second times seconds per day. Batching puts every value into one payload per cycle, so the value count leaves the message arithmetic entirely.

Arithmetic:

  • Seconds per day: 24 x 60 x 60 = 86,400 s.
  • One topic per value: 40 x 86,400 = 3,456,000 messages per day, which is 40 messages every second.
  • One batched payload per cycle: 1 x 86,400 = 86,400 messages per day, which is 1 message per second.
  • Ratio: 3,456,000 / 86,400 = 40. Over a 30-day month, 103,680,000 messages versus 2,592,000.

Result: the same information for one fortieth of the messages. Broker work, the controller's MQTT stack and any per-message metering all scale with message count, not value count.

Decision: this controller publishes one JSON payload per second on plant1/line3/pfc01/telemetry. Reserve single-value topics for values a subscriber must read alone, such as a once-per-shift counter or a state flag, never for bulk telemetry on a shared cadence.

When the connection never comes up: work the hops #

The path runs task, controller Ethernet interface, plant network, edge firewall, broker socket. Work up it and stop at the first failing hop; every layer above reports the same timeout whatever the real cause.

Hop Check Failure signature
Link Link LED and port counters on the uplink No traffic anywhere; counters flat
IP and route Address, mask and default gateway on the interface that reaches the broker With two Ethernet interfaces, only one holds the default route; packets exit the wrong port
DNS Broker host name resolves from the controller's configured DNS server Connect attempt times out silently instead of returning a name error
Firewall Outbound TCP 8883 (TLS) or 1883 (plain) permitted end to end TCP SYN sent, no SYN/ACK returned
TCP openssl s_client -connect broker:8883 from a laptop on the controller subnet Connection refused means the wrong port; a timeout means a filtered path
TLS CA certificate in the controller store, controller clock inside certificate validity, host string matching the certificate name Handshake aborts immediately after ClientHello
MQTT session CONNACK returned, credentials accepted, client ID unique Connect and disconnect flapping at a fixed interval
Application mosquitto_sub -h broker -t 'plant1/line3/pfc01/#' -v from any subscriber Session up, no output: the publish trigger logic never fires

Three of these failures account for most aborted setups on this class of controller.

The controller clock reads valid certificates as not-yet-valid #

A controller that boots with an unset clock sits before the broker certificate's valid-from date, so the client rejects a perfectly good certificate and the handshake dies right after ClientHello. Configure NTP, confirm the time in the controller settings, reconnect. When peer verification still fails after that, fix a CODESYS MQTT TLS peer verification handshake failure walks the certificate chain.

Two controllers, one client ID #

Projects cloned from one another ship the same client ID, and the broker's rule is last one in: the older session is evicted every time the newer client connects. Both controllers then flap at a fixed interval, which reads as an unstable network. Derive the client ID from the serial number or station name so it cannot repeat.

An IP address where the certificate carries a name #

The client checks the host string against the certificate's subject and SAN entries. Entering the broker by IP address while the certificate carries only a DNS name fails validation before any credential is sent. Configure the client with the DNS name and let DNS carry the address.

When to move the client off the controller #

A separate gateway can own the broker session when the controller cannot support or license the library, or when its machine tasks cannot call the client cyclically without blocking. A fanless mini PC can collect values from the controller over a supported local protocol and publish them to the broker.

Questions asked

Is the MQTT Client SL license free, or does it stop after a trial?

The package is available to download for evaluation. CODESYS documents a 30-minute demo without a license. For continuous use, verify the entitlement on the exact controller and runtime, then activate a compatible device license if required. Confirm the runtime license online on the deployed controller.

Why did the connection work on the bench and fail in the cabinet?

Because the bench had no edge in the middle. In the cabinet the session crosses NAT, a proxy or the plant firewall, and any of them can swallow the outbound 8883 session or break DNS resolution for the broker name. Reproduce from a laptop on the controller subnet with openssl s_client -connect broker:8883, and the hop that differs shows itself.

Can I prove the client works before my own broker exists?

Yes. Community example projects for CODESYS MQTT publish to the public test broker test.mosquitto.org, with and without TLS, so no broker of your own is needed to see a first message land. Treat that broker as public: prove the plumbing with dummy values, then point the client at your own broker before real plant data flows.

Does the client only publish, or can it subscribe too?

Both. The library sends messages to a broker and subscribes by topic, so the same controller can consume setpoints or commands while it publishes telemetry. Give subscriptions their own topic branch, away from the telemetry tree, so inbound commands and outbound data stay separable when you audit the flow.

Where should the Last Will message be published?

On the asset status topic, not the telemetry topic, and marked retained so a subscriber that arrives late still sees the offline state. Anyone watching plant1/line3/pfc01/status can then tell no new data from controller gone without monitoring the telemetry stream itself.

Corrections

  • : Clarified the CODESYS demo limit and how to verify the required runtime license on the exact controller.

Keep reading

  • Troubleshooting

    Fix Node-RED Docker x509 Certificate Expired on an Edge PC

    The error x509: certificate has expired or is not yet valid means Docker reached the registry over TLS but the controller clock falls outside the certificate's validity dates. Set the correct date and an NTP server, confirm the controller shows the right UTC time, and re-run the same docker run command — the pull verifies on the next connection. Change nothing else first.

    Edge computing and IIoT

  • Comparison

    MQTT on a CoDeSys 2.3 PLC: gateway vs controller client

    No MQTT client library is identified for the WAGO 750-830 running CoDeSys 2.3, so the controller cannot be the MQTT client; keep it on control and publish from an external gateway or edge PC that reads it over an interface the installation already supports. Migrate the controller only when MQTT must run inside it. The comparison below gives the decision for each path.

    Edge computing and IIoT

  • How-to

    Bridge a cellular tracker's TCP stream into MQTT for AWS IoT Core

    Build a small ingest service on your edge PC: it terminates the tracker's raw TCP session, decodes each stored record, and republishes one MQTT message per fix over TLS on port 8883. Acknowledge a packet only after every publish is confirmed, or a coverage-gap batch is silently lost.

    Edge computing and IIoT