IMD SolutionComputing LibraryShop main store

Troubleshooting

Why a CODESYS MQTT crash follows the code path not the flag

Edge computing and IIoT Published 7 min read

Short answer

When a CODESYS MQTT client crashes only after the program sets xEnable, and not when you force the same variable, the fault is in the code path around the call — most often an allocation sized for a PC runtime that an embedded controller cannot serve. Isolate the flag in its own task, add implicit check POUs, size every declaration for the target, and call the client block unconditionally each cycle.

On this page
  1. Why forcing the flag behaves differently
  2. Three failure classes produce this signature
  3. Six steps from crash to cause
  4. Size declarations for the controller, not the desktop
  5. Call the client block once per cycle, unconditionally
  6. Hand the connection to a background task
  7. The decision for each case
  8. Questions asked

If a CODESYS application takes the runtime down the moment the program sets xEnable := TRUE on the MQTT client block, but the same variable forced TRUE from the online view with Ctrl+F7 runs clean, the MQTT client is not your offender. A force writes one BOOL. The program assignment executes the entire scan path around it, and that is where the fault lives. In the reported case — a CC100 on firmware version 26, encrypted connection, no client certificates — the cause was a different library whose initialization reserved a size the desktop runtime absorbed and the embedded controller could not. Below: the isolation sequence, the declaration audit with the arithmetic shown, the correct call order for the client and its publish blocks, and the decision for every signature in this family.

Why forcing the flag behaves differently #

Forcing a variable changes exactly one value at one instant. The assignment xEnable := TRUE inside your program does more: everything in that code path executes with it. On first entry that includes structure and buffer initialization, array writes in the same branch, the loop over your publish and subscribe instances, and every other library that wakes up in that scan. If the fault were inside the client block, both routes would crash, because both end with the client enabled. Only the program route crashes, so the fault sits somewhere only that route travels. That asymmetry is the diagnosis; everything below just locates the stop.

Three failure classes produce this signature #

Before stepping through diagnostics, know what you are looking for. On a small embedded controller, three failure classes crash exactly this way:

Class Mechanism What it looks like
Oversized declaration or allocation An array, string buffer or library parameter sized for desktop RAM; the controller cannot reserve it Runs in simulation and on a desktop runtime, dies on the target, tied to a scan path rather than to a value
Starved client queue Publish and subscribe blocks enqueue work while the client block is not called every cycle to drain it Runs for seconds or minutes, memory use climbs, crash follows a busy publish period
Bounds or pointer violation An index or pointer leaves its range in application code An implicit check POU reports the violation before the runtime dies

The reported case landed in the first row. The second produces the same delayed crash with a different fix, and the third is what your check POUs exist to catch.

Six steps from crash to cause #

  1. Split the trigger from the path. Move the xEnable assignment into an otherwise empty POU that runs alone in a low-priority task. If the crash disappears, the client block is clean and the surrounding logic carries the fault — the same isolation move that untangles a blocking library in its own task, spelled out for a CAN driver in isolate a blocking CAN library in its own FreeRTOS task.
  2. Add the implicit check POUs. Put CheckBounds, CheckRangeSigned, CheckRangeUnsigned, CheckDivInt and the pointer checks into the application and rerun. They catch IEC-level violations only: an allocation that is simply too large for the target dies with no check firing. In the reported case the checks were already in place and the crash persisted, which is the expected result for the first row of the table, not evidence that the checks failed.
  3. Inventory every declaration added since the last build that ran on the target. Search the project for ARRAY[1..n] with a large n, STRING[n] with an oversized n, and library parameter lists that set payload buffer sizes, subscription counts or queue depths. Judge each against the controller's documented RAM, never against what the desktop runtime tolerated.
  4. Count the publish and subscribe instances and record how they are called. A FOR loop over publish blocks with the client block called only inside a conditional branch is the starved-queue pattern, and it crashes later than the scan that seeds it.
  5. Take TLS out of the equation once. Connect the client to a plain, unencrypted broker on your bench or an isolated segment. If the crash stops, the fault is in the certificate store, trusted-CA handling or the memory the TLS context reserves on the target — the verification side is covered in Fix CODESYS MQTT TLS peer verification handshake failure. Re-enable TLS before the controller returns to the plant network: an unencrypted MQTT link is a diagnostic state, not a configuration.
  6. Read the runtime log. Open the device log in the CODESYS device editor and export it after the next crash. Exception entries and out-of-memory messages name the failing component and the task that was executing when it died.

Size declarations for the controller, not the desktop #

The allocation class deserves its own arithmetic, because the desktop hides it completely. The numbers below are an example sized to show the method; your project's number is the sum of its own declarations.

Suppose a logging routine carried over from a PC project declares a message ring:

arMsg : ARRAY[1..2000] OF STRING[8191];  // illustrative declaration, not the reported one

Each element reserves 8191 characters plus one terminator byte, so 8192 bytes. The declaration asks for 2000 × 8192 = 16,384,000 bytes, which is 16,384,000 ÷ 1024 = 16,000 KiB, or 16,000 ÷ 1024 = 15.625 MiB. A desktop runtime with gigabytes of RAM resolves that request without comment. On an embedded controller the same request can swallow a large share of the runtime's memory pool, and the runtime dies in the scan where that POU initializes — which, in the reported case, was the same scan in which the program set the client's enable flag.

The same audit applies to the MQTT Client SL library's own parameters: payload buffer sizes, subscription counts and queue depth. Set each so that no larger variable is instantiated than your traffic needs, and re-check the total against the controller's documented memory.

Decision: any declaration or parameter set that a desktop runtime absorbs silently but the controller's documented RAM cannot serve is your fault. Resize it to the traffic the controller actually carries, and the crash on that scan disappears.

Call the client block once per cycle, unconditionally #

Publish and subscribe blocks only enqueue work; the client block's own call is what drains the queue. Gate the client behind a condition that can be false while publishers keep running, and the queue grows without end until memory is gone. The names in the listing are illustrative apart from xEnable and itfAsyncProperty, which the client block documents; use your own instance names.

VAR
    fbClient    : MQTTClient;         // client FB from MQTT Client SL
    fbAsyncProp : NBS.AsyncProperty;  // optional background-task binding
    xConnectReq : BOOL := FALSE;      // connection request, set by your program
    axRequest   : ARRAY[1..4] OF BOOL := [FALSE, FALSE, FALSE, FALSE];
    i           : INT := 0;
END_VAR

// every cycle, unconditionally, in the task that owns the connection
fbClient(xEnable := xConnectReq, itfAsyncProperty := fbAsyncProp);

// publishers may wait for an open connection; the client call above never does
FOR i := 1 TO 4 DO
    afbPublish[i](xExecute := axRequest[i]);   // enqueue only
END_FOR

// wrong: the client runs only while a batching flag holds
// IF xBatching THEN
//     fbClient(xEnable := TRUE);
// END_IF

Count what gating costs. In a 10 ms task with four publish blocks called every scan, one second with the client branch closed strands 4 × 100 = 400 enqueued operations, and a minute of it leaves 24,000 that nothing drains. The test that proves the fix: watch the runtime's memory figure stay flat through an hour at peak publish rate.

Once the runtime survives the full scan but messages still do not move, you have a connectivity fault rather than a crash — work through Fix a PLC MQTT client that never reaches your broker.

Decision: one client call per cycle, before the publish loop, outside every conditional branch. Gating publishers on connection state is fine; gating the client is not.

Hand the connection to a background task #

The client block's itfAsyncProperty input attaches connection handling to a background task, and the online help documents it thinly. The mechanism lives in the Net Base Services library: declare an instance of NBS.AsyncProperty, initialize it in the declaration with the task properties you want the connection handled under, and pass that instance to the input, as fbAsyncProp does in the listing above. TLS handshakes and socket work then run outside your cyclic task, which stops connect and reconnect stalls from stretching the scan.

It fixes neither of the two memory failures: an oversized allocation still dies and a starved queue still grows. Verify sizing and call order first; add the background task when the crash is gone and connection stalls are what remains.

Decision: bind itfAsyncProperty when connect or reconnect visibly stalls the cyclic task, not as a remedy for this crash.

The decision for each case #

  • Crash on the program-set enable, absent on a forced enable, checks clean: memory sizing on the executed path. Audit declarations and library parameters against the controller's documented RAM and resize.
  • Crash after minutes of running with memory climbing: starved queue. Call the client block unconditionally every cycle.
  • A check POU fires: fix the index, range or division it names; that class closes at the check.
  • Crash stops without TLS: the TLS context on the target. Work the certificates and verification, then restore encryption.
  • Crash also follows a forced enable: the fault is in the client's own configuration or the runtime itself. Export the device log and work from the component it names.

Questions asked

Does this crash mean the MQTT Client SL library itself is broken?

No. In the reported case the client block ran without a fault once the surrounding path was cleaned up; the crash came from a different library whose initialization reserved a size the controller could not serve. The signature itself argues the client is innocent: a fault inside the client block would also fire on a forced enable, because a force ends with the client running just as the program assignment does.

Do implicit check POUs make the runtime crash-proof?

They cover the bounds class only. When a check POU fires, it names the index, range or division to fix, and that failure class is closed. When no check fires and the crash persists, the violation sits below the IEC level: memory that cannot be reserved reports nothing to CheckBounds or CheckRangeSigned. That silence is itself diagnostic, not the absence of a fault.

Do the IIoT libraries need a separate license on the CC100?

In the case as reported, no. The IIoT library set on that controller is pre-paid by its maker, so no activation is due for it, and the device rejects installing further CODESYS licenses. The consequence: any library carrying its own activation cannot be added on that controller, so direct communication through such a library is out, and a gateway that bridges the other protocol into MQTT is the workable design.

How many publish and subscribe blocks can one client block serve?

Size them by queue depth and buffer size, not by block count. Set the library's payload buffers and queue depth for your worst publish burst, call the client block every cycle so nothing accumulates, and confirm free memory on the target after an hour at peak rate. Within those limits the instance count is your design choice; the crash comes from a starved queue or an oversized buffer, never from the number of blocks itself.

Why does the same project run on the PC runtime and crash on the controller?

A desktop runtime draws on gigabytes of RAM, so a declaration that over-reserves still resolves and nothing reports it. The controller reserves from a much smaller pool, so the same declaration consumes a large share of it or fails outright. Before the first download to the target, run the declaration audit from this article against the controller's documented memory figure; never treat a clean desktop run as a memory test.

Keep reading

  • How-to

    Set up the MQTT Client SL library on a CODESYS controller

    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.

    Edge computing and IIoT

  • Troubleshooting

    PLCnext MQTT client ENO false: readiness before broker checks

    A false ENO on the PLCnext MQTT client function block means the client instance is not ready for method calls; it is not a verdict on broker credentials or the network. Keep EN true across scans until ENO turns true, issue Connect once per attempt, then verify the same-subnet path and the TCP connection before blaming authentication.

    Edge computing and IIoT

  • Explainer

    MQTT client ID device versus application roles explained

    One MQTT client ID identifies exactly one connection, and a broker must disconnect an established client the moment another connects with its ID. A publishing edge device therefore connects with a device-form ID such as d:orgId:deviceType:deviceId, while a cloud subscriber connects as an application with a:orgId:appId. Give every node its own client ID; the specialized IoT input connects because it builds that identity for you.

    Edge computing and IIoT