Topic: DMD0436

Help File Version: 2.9.4.37

MQTTSUB - IoT Subscribe to MQTT Topics


Note: this instruction can only be used with a BRX CPU or the Do-more Simulator !

 

The IoT Subscribe to MQTT Topics (MQTTSUB) instruction is used to subscribe to Topics in an MQTT Broker. An MQTTSUB instruction can contain up to 50 subscriptions for a Broker. After a client successfully subscribes to one or more Topics, as long as the instruction remains enabled, it will receive every published message matching the Topic of the subscription.

 

When the MQTTSUB instruction is disabled it will automatically attempt to unsubscribe from any Topics it is currently subscribed to.

 

The BRX CPU uses an MQTT Client Device to establish the connection to the broker. This connection can use either MQTT (unsecured, plain text) or MQTTS (secured, TLS / SSL encryption).

 

Note: using SSL / TLS encryption is a very CPU intensive operation because of the math involved. Because the CPU must keep the PLC's scan time in check, the SSL encoding is processed as a time-slicing event, meaning that only a portion of each scan time is used to work on the encryption; this prevents the scan time from exceeding the watchdog timer. Processing the encryption can take several seconds depending on the number of security certificates that must be processed and the amount of data being transferred.

 

The amount of time the CPU allots to processing TLS transactions on each scan is called the TLS Timeslice. This value can be changed on the CPU page of the System Configuration. Increasing this value can allow the TLS process to complete sooner, but at the cost of increasing the PLC's scan time. The Default TLS Timeslice value will be used by the TLS encryption engine each time the PLC powers up and goes into RUN mode. RUN-mode changes to this value can be made by changing the value in $TLSTimeslice (DST68).

Quality of Service

Quality of Service (QoS) is a major feature of MQTT in that it makes communication in unreliable networks much easier because the protocol handles retransmission and guarantees the delivery of the message regardless of the unreliability of the underlying transport. The QoS level is an agreement between sender and receiver of a message regarding the guarantee of delivering a message. The following QoS levels are supported: At most once (0), and At least once (1). The MQTTSUB instruction uses the QoS level specified in the MQTT Client Device.

 

Note: although RUN-mode edits are allowed on existing MQTTSUB instructions, doing so will likely cause a "Duplicate MQTTSUB topic ..." warning message as the PLC works through resubscribing the Topics in the message list. The re-subscribes work properly after the RUN-mode edit; this is just a warning caused by a temporary situation. You can clear this warning message on the System Status tab of the System Information utility.

 

 

MQTT Client Device selects which of the preconfigured MQTT Client devices this instruction will use to establish the connection to the broker. This connection can use either MQTT (unsecured, plain text) or MQTTS (secured, TLS / SSL encryption).

Click create device to open the Add Device dialog of the System Configuration where a new MQTT Client device can be created.

Note: each MQTT Client device can only provide a subscription space for 100 concurrent topics spread across a maximum of 10 active MQTTSUB instructions, for example 2 enabled instructions with 50 Topics each, or 10 enabled instructions with 10 Topics each. To subscribe to more than 100 Topics, create multiple MQTT Client devices to the same MQTT Broker.


The next section contains a list of up to 50 Topics that get subscribed to from the selected MQTT Broker.

 

Enabling the Optional Topic Prefix allows Topics to use repeated text. If there are multiple Topics that begin with the same text, you can put the repeated text in this Optional Topic Prefix and then select that optional text when the Topic is created and added to the list. This can be any string literal (text enclosed with double quotes) of any user-defined or system-defined String. Remember, Topics are case sensitive.

 

 

The buttons below the list are functions which manage the rows in the instruction: Edit opens the editor for the currently selected row, Insert adds an empty row before the currently selected row and opens the editor for this new row, Remove deletes the currently selected row from the table, and Move Up / Move Down shifts the currently selected row up one or down one row respectively in the table.

 

Clicking the Edit (on an existing Topic) or Insert button will open a sub-editor where the contents of the message are managed. The Topic group specifies the Topic to subscribe to:

 

If an Optional Topic Prefix was created on the main dialog, you can enable the Use Common Optional Topic Prefix to prepend the prefix text to the Topic text to construct the full name of the Topic.

 

The Topic itself is a simple UTF-8 string, consisting of one or more levels, which are separated by a forward slash (aka the topic level separator). Each topic must have at least 1 character to be valid and it can contain spaces. A leading forward slash is not recommended. A Topic is case-sensitive. MQTTSUB does not support Wildcards (+ or #) in Topics. The Topic can be entered as a String literal (text within double quotes) up to 128 characters, or a user-defined String or a system-defined String element.


The Payload is the memory location(s) in the PLC where the data from the subscribed Topic will be stored. MQTT protocol itself is data-agnostic, meaning the format of the data is irrelevant to the protocol; it totally depends on the how the data was initially published to the Broker. It’s completely up to the publisher if it wants to send bits, numbers, binary data, or text.

 

The payload data can consist of a Bit (which can be stored in either a Bit memory location or a numeric location), a numeric value (which can be stored in either an integer or floating point memory location), or text which can be stored in a String element. If needed, use the Convert String to Integer (STR2INT) or Convert String to Real (STR2REAL) instructions to convert the contents of the received Strings to numbers. Use the Get Bytes Out of a String (STRGETB) instruction to extract raw bytes of data into a byte buffer.

 

Note: the maximum length of the Topic (including the Optional Topic Prefix if selected) plus the Payload is 1024 characters.


When this instruction is first enabled the On Success and On Error indicators will be turned OFF. Then the instruction will process each subscribe entry in the list. The On Success will be turned ON if at least one of the Topics in the instruction was successfully subscribed to. If none of the Topics were successfully subscribed the On Error will be turned ON.

 

When this instruction is disabled, it will process each entry in the list of Topics and attempt to unsubscribe each of them. The On Success will be turned ON if at least one of the Topics in the instruction was successfully unsubscribed. If none of the Topics were successfully unsubscribed the On Error will be turned ON.

 

On Success : select any writable bit location.

On Error : select any writable bit location.

 


The Extended Error Information is a DWord location that contains a combination value. Using the :SD cast here provides a good method for easily separating the high / low values, for example: V100:SD would place the high word in V101 and the low Word in V100).

 

The high Word is the entry number of the first Topic that failed. There may have been multiple failures, but only the entry number of first one that failed will be listed in the Return Code. That error must be corrected before failures for any later entry numbers will be shown.

 

The low Word contains the error code itself from the table below:

 

Value in Low Word

 

Error

 

Description

 

0

 

No Error

 

 

57

 

Unexpected MQTT Response

 

The response from the MQTT Broker was not properly formed.

 

58

 

MQTT Broker Rejected

 

The MQTT Broker refused the Topic, could be a bad username or password, or a security violation on the Broker itself.

 

59

 

Out of Resources (MQTTSUB only)

 

There are more than 10 MQTTSUB instructions using the same MQTT Client device, or there are more than 100 Topics using the same MQTT Client device.

 

60

 

Invalid Topic

 

This typically means the Topics is empty.

 

61

 

Duplicate Topic

 

The Topic is already subscribed to in a different MQTTSUB instruction.

 

63

 

Server Not Found

 

The DNS lookup for the Broker specified in the MQTT Client failed.

 

64

 

No Connection

 

There is no network connection to the Broker, either it was never initially established, or was lost after it was established.

 

 


Additional Error Handling:

The last error code reported by the MQTT Broker will be in $LastProtoError (DST38).

 


Another tool that is useful tool for debugging problems with getting MQTTSUB to function properly from the PLC's perspective is Do-more Logger. Setting the system status bit $EnableMsgDump (ST36) ON will cause the MQTTSUB instruction to automatically echo the MQTT communication traffic between the Do-more CPU and the MQTT Broker to the Do-more Logger. Do-more Logger will capture and display this conversation which allows to programmer to see what changes need to be made to correct any errors.

 

So between the High Word (:W1) of the Extended Error Information value telling you which entry number failed, and the Low Word of the Extended Error Information value telling you why that entry failed, and the value in $LastProtoError (DST38) giving you the MQTT Broker's error value, and Do-more Logger displaying the communication traffic, you should be able to resolve any fault conditions.

 


Communication protocols (like MQTT) have the potential to generate a lot of error and status messages while they are operating which can increase the PLC scan time beyond acceptable limits. To help manage the amount of message handling in the CPU there is a system register named $SysMsgLevel (DST61) that controls the amount of messaging data that is generated by the various communication protocols:

0 = No Error or Messages reported.

1 = Only report Errors (default).

2 = Report Errors and Messages.


See Also

MQTT Broker Device (IoT)

 

MQTTPUB - IoT Publish MQTT Topics

 

MQTTSUB - IoT Subscribe to MQTT Topics

 


Related Topics

HTTPCMD - Process HTTP Command

 

JSONBUILD - Build JSON Record

 

JSONPARSE - Parse JSON Record

 

JSON Pretty Print

 

Do-more Logger

 


Example