Skip to Content
On this page

MQTT collection client

The MQTT Collection Client subscribes to broker topics and maps fields from valid JSON messages to gateway variables. RawString controls write publishing; it does not enable telemetry mapping from arbitrary non-JSON text.

Compatible devices and models

Device series / model examplesConnection requirements
Devices or platforms publishing messages over MQTTThe gateway connects to an MQTT broker. Match topics, QoS and payload mapping to the publisher.

Connect the broker and publisher

The MQTT collection client connects to a broker and maps JSON payload fields to gateway variables. Publishers may be equipment, another gateway, or an application. PLC rack, slot, and register numbers do not apply.

Obtain the broker host, listening port, MQTT version, credentials, and topic permissions. The gateway and publisher must use the same broker. The gateway account needs permission to subscribe to telemetry and, for control variables, publish to control topics. 127.0.0.1 refers to the computer running each program; use the broker’s reachable interface address across computers.

This example uses 127.0.0.1:18883 and telemetry/line1. The MQTT collection server can provide this listener.

  1. Create an MQTTX connection named Collect_MQTTX: mqtt://, host 127.0.0.1, port 18883, Client ID collect-mqttx, MQTT 3.1.1. Match credentials and SSL/TLS to the broker, then connect.

MQTTX broker address, port, client identity, and protocol version

Open the complete MQTTX connection window. Give MQTTX and the gateway different Client IDs; duplicate IDs can disconnect each other.

  1. Open Development Configuration → Collection Configuration → Add Device, and select MQTT Collection Client. This plugin owns its connection; do not create an ordinary TCP or serial channel. The device execution interval can remain 1000 ms. Telemetry updates when messages arrive, independently of that interval.

MQTT collection client identity and basic device properties

  1. In Plugin Properties, select Tcp, 127.0.0.1, port 18883, Client ID collect-gateway-client, MQTT 3.1.1, and QoS 0. Save and enable the device.

MQTT client TCP transport, port, Client ID, and MQTT version

Enter the broker host without a port in IP address:

MQTT client broker IP address

Plugin properties

Connection

SettingDescription
Connection typeDefault Tcp. Use WebSocket only for a broker endpoint providing MQTT over WebSocket. An HTTP management console is not an MQTT endpoint.
IP addressDefault localhost. Broker IP or host name without scheme, port, or path. Use a reachable address for a remote broker.
PortDefault 1883. Match the actual broker listener, including its TLS or WebSocket port. The example uses 18883.
WebSocket pathDefault /mqtt; used only for WebSocket. Empty uses /mqtt, and a missing leading slash is added. Match the broker and proxy path. SSL changes the scheme to wss://.
Client IDEmpty by default, producing a random identity that can change when the connection instance is rebuilt. Use a stable, unique ID for persistent sessions and ID-based authorization.
Clean sessionEnabled by default. Requests a clean session. When disabled, use a stable Client ID and check the broker’s session policy. This setting does not make telemetry retained.
MQTT versionDefault MQTT 3.1.1; options are 3.1, 3.1.1, and 5.0. Match the broker. Start with 3.1.1; if a 3.1 connection fails, use mutually supported 3.1.1 or 5.0.

TLS and authentication

SettingDescription
Enable SSLDisabled by default. Enable for a TLS or WSS broker listener and use its matching port.
SSL target hostEmpty by default. Host name expected in the broker certificate; configure the certificate name when connecting through an IP address.
Client certificateSelect a client certificate with its private key from Certificate Management when the broker requires mutual TLS.
CA certificateSelect the CA used to trust the broker certificate. Import the required private root or intermediate CA first. This is separate from the client identity.
Allow untrusted certificateEnabled by default. Disable when validating broker identity and configure the correct CA and target host. This cannot correct a wrong port, account, or topic permission.
SSL protocolDefault System Default negotiates TLS through the operating system when SSL is enabled. Explicit TLS 1.2/1.3 requires support at both ends and in the OS. Legacy Default is the SSL 3.0/TLS 1.0 combination.
Check certificate revocationDisabled by default. Requires access to the relevant certificate status service when enabled. Disabling this does not disable certificate-chain validation.
UsernameEmpty by default. MQTT account assigned by the broker, separate from Client ID. Grant the account the required topic permissions.
PasswordEmpty by default. Password for the MQTT account. Account and certificate authentication are separate checks.

Runtime and messages

SettingDescription
Keep-aliveDefault 60 seconds. Maintains the MQTT session and must fit broker policy; it is not the telemetry update interval.
Connection timeoutDefault 3000. This setting does not adjust the MQTT handshake timeout for this plugin; use device logs to diagnose actual connection failures.
QoSDefault 0, used for subscription requests and plugin publishes. 0: at most once; 1: at least once; 2: exactly once. Handle duplicates at the application level when using QoS 1.
Detailed logDisabled by default. Enable for connection, topic, and payload diagnosis; disable afterward to reduce logging.
Check and cleanup intervalDefault 60000, in seconds. A readable variable becomes offline after this time without a sample and recovers with a new valid message. Set the permitted missing-sample duration, for example 5 seconds. This does not clean disk caches.

Client keep-alive, QoS, logging, and missing-sample interval

QoS 2 subscription acknowledgements can currently be treated as failures, affecting the confirmed subscription list and RPC readiness. Use QoS 0 or 1 when subscription confirmation is required. Protocol delivery confirmation does not establish remote equipment execution.

Map a variable and compare messages

  1. Add MQTT_Client_Temperature to the device. Choose Int16, Read only, and array length 1 for this single integer. Array length is neither a topic count nor a JSON character count. Use a floating-point, Boolean, or string type for the corresponding payload; use Object for a complete object.

Client variable name, address, data type, and read permission

Variable device, enabled state, and array length 1

  1. Open Variable Address → Edit fields. Enable Subscribe topic and JSONPath, entering telemetry/line1 and $.data.value. Leave explicit null, condition, publish, and RPC fields unchecked. Click Confirm and fill, then save the variable.

Build the MQTT address from a topic and JSONPath

The address becomes SubscribeTopic=telemetry/line1;Path=$.data.value;. value is a JSON property, not a PLC byte offset; register word order does not apply. See Collection Configuration for common transforms, alarms, and permissions.

  1. In MQTTX, publish {"data":{"value":31}} to telemetry/line1, QoS 0, Retain disabled, then click the green arrow at the bottom right of the send area. Publish after saving the variable; an earlier non-retained message is not replayed to a new subscription.

MQTTX telemetry topic, QoS, Retain and JSON payload input

MQTTX published telemetry topic, QoS, and JSON payload

  1. Open Live Variables → Details and compare current value 31, raw value, and collection time. Change 31 to 32 in MQTTX and publish again; the value and collection time should update.

Client variable address, current value 31, and raw value

A broker connection can stay online while telemetry stops. The variable then follows the missing-sample interval. Invalid JSON, an unmatched path, or a false condition also prevents a valid new sample.

Write a variable and receive control messages in MQTTX

Collection flows from MQTTX publishing telemetry to a gateway variable. Writing flows from a gateway variable through the broker to a control-topic subscriber. The written value becomes the message body; the plugin does not wrap it in {"data":{"value":…}}. Write the required object directly, or build it with the variable’s write transform chain.

  1. Click New Subscription in MQTTX. Enter commands/line1/#, choose QoS 0, and confirm. # receives this level and its descendants; the gateway must publish to a concrete topic.

MQTTX subscription to commands/line1/# for gateway control messages

  1. Add MQTT_Client_Command under the client device: Int16, Write only, array length 1. Keep the read-only temperature variable separate.

Client command variable name, Int16 type, and write-only permission

Variable device, enabled state, and array length 1

  1. Open Edit fields. Under Control write, enable Publish topic = commands/line1/setpoint, Payload mode = Json, and the Retain property with its switch off. Leave telemetry fields, response topic, and timeout unchecked. Click Confirm and fill.

Client command topic, Json payload mode, and disabled Retain switch

The address is:

PublishTopic=commands/line1/setpoint;PayloadMode=Json;Retain=false
  1. Enable RPC write in the variable’s RPC Configuration, then save. This switch permits writes through the variable write entry. RPC → Response topic in the address editor instead enables waiting for an MQTT peer acknowledgement. Leave the response topic unset for ordinary publishing.

RPC write permission enabled and remote-control insurance disabled

  1. In Live Variables, click Write on MQTT_Client_Command, enter 42, check that the input is recognized as a number, and submit. Use the command variable’s write action, rather than the temperature variable or the initial-value field.

Writing the number 42 to MQTT_Client_Command

  1. In MQTTX, locate topic commands/line1/setpoint with body 42. Check both topic and body. This command does not directly change the value mapped from telemetry/line1; the equipment must publish new telemetry for the reading to reflect its resulting state.

MQTTX receiving client setpoint 42 and server-setpoint 43 on separate topics

Choose JSON values or raw strings

The Write dialog recognizes JSON numbers, Booleans, objects, and arrays; other text is treated as a string. Match the variable type and payload mode to the receiver:

Required bodyVariable type and modeWrite dialog input
JSON number 42Int16, Json42
JSON string "42"String, Json"42", including quotes
JSON Boolean trueBoolean, Jsontrue
JSON object {"setpoint":42}Object, Json{"setpoint":42}
Unquoted text RUNString, RawStringRUN
Unquoted text trueString, RawString"true", so the input is recognized as a string

RawString accepts only a string value and removes its enclosing JSON quotes when publishing. It does not automatically turn a number, Boolean, or object into text. Retain=true stores the last message for later subscribers. This command example uses false; choose retention according to the peer’s control semantics.

Wait for a peer acknowledgement

An ordinary publish returns after sending the message. To wait for the peer’s command result, use {RequestId} as the final level of both request and response topics and set a timeout:

PublishTopic=commands/line1/request/{RequestId};PayloadMode=Json;Retain=false;ResponseTopic=commands/line1/response/{RequestId};Timeout=5000

The peer subscribes to commands/line1/request/+. Each write generates a fresh ID. For example, a request on commands/line1/request/abc123 with body 42 requires a reply on commands/line1/response/abc123: {"success":true} or {"success":false,"message":"reason"}. The lowercase success property must contain a JSON Boolean; disable Retain on the reply. Timeout is 100–60000 milliseconds. For a manual MQTTX reply, start with a longer timeout and copy the current request’s final topic level into the response topic. Keep the placeholder in gateway configuration and use the actual ID in the response.

Address rule

Use PropertyName=Value; for each configured property. Property order is unrestricted and names are case-insensitive. Omit unused properties; the final semicolon is optional. Duplicate properties and mixed named/positional fields are rejected.

SubscribeTopic=vendor/device;Path=$.data.temperature;Condition=TelemetryCondition;
PropertyDescription
SubscribeTopicTelemetry subscription topic or filter. Configure together with Path.
PathJSONPath into a valid JSON payload. Separate candidate paths with ||.
ConditionOptional compiled DataTrans script name. The message is accepted only when the script returns true.
ConditionParametersOptional JSON object mapping script input names to parameter text. Every value is a string, for example {"Minimum":"12.5"}.
PublishTopicControl or RPC request topic. Omit for read-only variables.
PayloadModeJson preserves the JSON type; RawString sends unwrapped string text. Default: Json.
Retaintrue or false. Default: false; the Broker determines retention support.
ResponseTopicRPC response topic using the same final {RequestId} level as the request.
TimeoutRPC timeout in milliseconds, 100–60000. Configure together with ResponseTopic.

Examples:

UseAddress
Read a JSON valueSubscribeTopic=vendor/device;Path=$.data.temperature;
Condition with parametersSubscribeTopic=vendor/device;Path=$.data.temperature;Condition=TelemetryCondition;ConditionParameters={"Minimum":"12.5"};
Publish a raw writePublishTopic=factory/a/reboot;PayloadMode=RawString;Retain=false;
RPC request and responsePublishTopic=factory/a/command/{RequestId};PayloadMode=Json;Retain=false;ResponseTopic=factory/a/response/{RequestId};Timeout=5000;

Path=$.data.temperature;SubscribeTopic=vendor/device; is equivalent to the first example.

Configure condition parameters in the Web editor

  1. Open the variable form and click Edit fields beside Variable Address.
  2. Enter the subscribe topic and JSONPath, enable the condition field, and select a compiled DataTrans script.
  3. Fill in the inputs shown with their names, types, and descriptions. The order of inputs does not affect their binding.
  4. Click Confirm and fill, then save the variable. Applying a changed legacy address generates the named format; viewing or cancelling leaves the original text unchanged.

Parameter text is parsed as a JSON value when possible, otherwise as a string, and is converted to the declared input type. Use 12.5 for a number, true for a Boolean, and JSON for an object or array. Strings may be entered directly; use a quoted JSON string such as "true" to preserve a string resembling a Boolean, null, or number. Unknown inputs and invalid types prevent saving. Each variable stores its own parameter values.

Clearing an input removes its explicit override. Unspecified inputs keep their script defaults; Topic, MqttTopic, ClientId, and MqttClientId receive message context when not explicitly configured. The client plugin receives no publisher ClientId, so those inputs are empty.

Only the first = separates a property from its value; JSONPath filters containing == work unchanged. In named address values, encode ; as %3B and % as %25. Values are decoded once and + remains literal. The editor handles escaping automatically. For example, ConditionParameters={"Marker":"a%3Bb%25"} supplies the string a;b%.

Legacy eight-segment addresses

Existing positional addresses remain supported. Keep unused intermediate segments empty and omit trailing empty segments as needed. Use the named format or Web editor to add condition parameters.

{subscribeTopic};{jsonPath1||jsonPath2};{condition};{publishTopic};{Json|RawString};{retain};{rpcResponseTopic};{rpcTimeoutMs} vendor/device;$.data.temperature;TelemetryCondition ;;;factory/a/command/{RequestId};Json;false;factory/a/response/{RequestId};5000

Payload paths support $, dot paths such as items.0.value, filters [?()], wildcards [*] and .*, and recursive search $..name. With ||, the first existing candidate path is used. Exact case-sensitive property names are preferred; a unique case-insensitive match is used only when no exact name exists.

A present field with null does not guarantee fallback to the next path. Multiple JSONPath matches select the first result rather than creating multiple variables. Use Object to retain an object value and check scalar types against the actual payload.

The condition is a DataTrans script name. Its raw input contains the complete JSON payload; it may also declare Topic or MqttTopic to inspect the published topic. A wildcard subscription updates the same variable for every matching message, so use an exact topic or filter by Topic when values must be separated by device.

The subscribed message does not include the publisher’s client ID. ClientId and MqttClientId inputs are therefore empty for this plugin. Publish topics cannot contain + or #; {RequestId} must be the final topic level.

A subscribe topic and JSONPath must be provided together; publish options require a publish topic. RPC response topic and timeout are a pair, and the timeout must be 100–60000 ms. A read-only variable cannot contain publish fields, a write-only variable cannot contain telemetry fields, and every variable must configure at least one route.

Device debug

Open Development Configuration → Collection Configuration, select the MQTT device, open Protocol Debug at the top of the workspace.

Subscriptions and publishing

MQTT client confirmed subscription topic

Use Publish Message to send a small payload to an approved test topic. Subscription management and received-message inspection are available in the corresponding protocol workspace tabs.

Functions

FunctionPurpose
Publish messagePublish a topic, payload, QoS, and Retain flag through the current broker connection.
Subscription managementCreate, refresh, or remove subscriptions and inspect the received updates.
Refresh subscriptionsReload the subscriptions confirmed by the current MQTT session.

Messages and freshness

  1. Subscribe to an exact test topic.
  2. Publish a JSON payload containing one known field.
  3. Confirm that the JSONPath or condition script selects the expected value.
  4. Check that the variable value and collection time update.
  5. Test publishing or RPC only when the variable and device permissions allow it.

Keep the broker connected and stop new telemetry to test freshness. For a short test, set Check and cleanup interval to 5 seconds, wait for the point to become offline, then publish a new valid value and confirm recovery. Restore the production interval afterward. MQTT keepalive maintains a session; it does not establish that a point is receiving fresh data.

For control, enable the variable’s RPC write permission, inspect the exact Topic and raw payload with an independent subscriber, and verify field feedback. Json preserves the input JSON type; RawString accepts only a JSON string and publishes its unwrapped text. For RPC, an old retained response, a different RequestId, or a response arriving after timeout cannot complete the new request.

Enabling Retain stores the last message for later subscribers; it does not store history or confirm command execution. Publishing later with Retain false does not delete an older retained message. Use a fresh test topic or clear the old retained message through the Broker before verifying the disabled setting.

Troubleshooting

SymptomCheck
Cannot connectBroker address, port, Client ID, credentials, TLS settings, firewall, and broker ACL.
Message arrives but variable is unchangedExact topic, JSONPath, condition script, payload shape, and variable data type.
Wrong device value is updatedAvoid a shared wildcard topic or filter by Topic in the condition script.
Publish or RPC failsPublish topic, {RequestId} position, QoS, response topic, timeout, and permissions.
Certificate is rejectedClient certificate, CA, target host name, and trust settings.