Topic: DMD0435

Help File Version: 2.9.4.37

MQTTPUB - IoT Publish MQTT Topics


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

 

The IoT Publish MQTT Topics (MQTTPUB) instruction is used to publish messages from a BRX CPU to an MQTT Broker. Each published message must contain a Topic, which will be used by the Broker to forward the message to interested clients, and a Payload which contains the actual data to transmit. When a client publishes a message to a MQTT Broker, the Broker will determine which other clients have subscribed to that Topic and then send the appropriate message to those clients. The client who publishes the message is only concerned about delivering the message to the Broker. From there on it is the responsibility of the Broker to deliver the message to all subscribers. The publishing client doesn’t get any feedback that says subscribers have received the message.

 

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 MQTTPUB instruction uses the QoS level specified in the MQTT Client Device. And remember that in a MQTT system there are always two different parts of delivering a message: publishing client to Broker then Broker to subscribing client(s). The QoS level for publishing client to Broker is set when the client connects to the Broker. When the Broker transfers a message to a subscribing client it uses the QoS of the subscription made by the client.

 

 

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.


Enable selects how often the Topics in this instruction will be published. Choose one of the following:

 

  • Select the Once on Leading Edge option to have this instruction make exactly one attempt to publish each of the Topics in the instruction.

     

  • Select the Continuous on Power Flow at Interval option to have this instruction attempt to publish each of the Topics in the instruction when the instruction is first enabled, then as long as this instruction remains enabled, each time the specified time interval is reached, the list of Topics is reprocessed. Refer to the Publish Interval Setting below which determines if a Topic is published only if it has changed, or published every time the list is processed.

     

    The following options select how much time (in milliseconds) to wait between successive runs. A value of 0ms means the instruction will re-run immediately. Be aware of setting an interval value that is very low because many Brokers will protect themselves against overloading by rejecting or ignoring messages.

 

    • Constant means the interval time is a fixed value specified as Hours / Minutes / Seconds / Milliseconds. 

       

    • Variable means this can be any writable numeric location that contains a value between 0 and 2,147,483,647.

       


The next section contains a list of up to 50 Topics that get published to 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 publish:

 

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). A Topic is case-sensitive. Each Topic must have at least 1 character to be valid and it can contain spaces. A leading forward slash is not recommended. Published Topics cannot start with $. MQTTPUB 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 data to be published to the Broker. MQTT protocol itself is data-agnostic, meaning the format of the data is irrelevant to the protocol; it totally depends on the how the Payload will be used by the subscribing clients. It’s completely up to the publishing client if it wants to send numbers, binary data, or text.

 

The payload data can consist of a Bit (constant 0 or 1, or a bit memory location), a numeric value (integer or floating point constant, or integer or floating point memory location), or text which can be either a String literal (text within double quotes) up to 128 characters, or characters stored in a String element. Use the Print to String (STRPRINT) instruction with it's collection of String Functions to embed PLC data into ASCII text Payload. Use the Put Bytes into a String (STRPUTB) instruction to generate a Payload consisting of raw bytes of data.

 

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


The Retain flag determines if the message will be saved by the Broker even after sending it to all current subscribers. This effectively makes the message for the Topic a "last known good value". Normally if a publisher publishes a message to a Topic, and no one is currently subscribed to that Topic, the message is simply discarded by the Broker. However, the publisher can tell the Broker to keep the last message for that Topic by setting the Retain flag. New clients that subscribe to a Topic that is Retained will receive the "last known good value" for that Topic as soon as they subscribe. Without retained messages, any new subscribers would have to wait for the status to change before it received a message. Only one message is Retained per Topic. The next message published on that Topic replaces the last Retained message for that Topic.

To Delete a retained message send another Retained message with an empty Payload (a zero-byte String, for example "") to the same Topic where the previous Retained message is stored. The Broker deletes the Retained message meaning new subscribers will no longer get a "last known good value" message for that Topic.


Publish Interval Setting is only available if the Enable selection is set to Continuous on Power Flow at Interval. The selection determines whether or not the Topic will be published each time the MQTTPUB executes regardless of whether the Topic or the Payload changed since the last interval:

 

  • Publish at interval only if value changed since the last interval means each time the MQTTPUB instruction processes the entry list the Topic and Payload will be published only if either the Topic or the Payload have changed since the last time the list was processed.

  • Publish at every interval even if value has not changed means each time the MQTTPUB instruction processes the entry list the Topic and Payload will be published even if neither the Topic or Payload have changed since the last time the list was processed.

Depending on the Enable selection, this instruction will run to completion exactly one time, or run to completion multiple times as long as the instruction is enabled. The On Success and On Error parameters specify what action to perform when this instruction completes. You do not have to use the same type of selection for both On Success and On Error.

If the MQTT Client device is configured for QoS level 0 (at most once), each time the execution of this instruction completes it is deemed a Success if at least one of the Topics in the list was successfully published. If none of the Topics were successfully published the instruction is deemed to be in Error.

 

If the MQTT Client device is configured for QoS level 1 (at least once), you should only have one Topic in the MQTTPUB instruction's Topic list. This lets you use the On Success / On Error indications to confirm the message was sent to the Broker and you can then retry Publishing this topic as many times as required.

If the Set Bit selection is used for either On Success or On Error, the specified BIT location will be SET OFF when the instruction is first enabled and will remain OFF until the instruction completes. Once complete, the appropriate Success or Error bit location will be set ON. The specified Bit location is enabled with a SET (Latch) operation (not an OUT operation) meaning that it will remain ON even if this instruction's input logic goes OFF.

 

If the JMP to Stage selection is used for either On Success or On Error the target Stage must be in the same Program code-block as this instruction, you cannot specify a target Stage that exists in a different Program code-block. When the operation finishes, the target Stage will be enabled the same way as a standalone Jump to Stage (JMP) instruction would do it. The JMP to Stage option will only be selectable if this instruction is placed in a Program code-block.

 

On Success selects which of the following actions to perform if the operation is successful:

  • Set Bit : enable this selection then specify any writable bit location.
  • JMP to Stage : enable this selection then specify any Stage number from S0 to S127 in the current Program code-block.

 

On Error selects which of the following actions to perform if the operation is unsuccessful:

  • SET Bit : enable this selection then specify writable bit location.
  • JMP to Stage : enable this selection then specify any Stage number from S0 to S127 in the current Program code-block.

 


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 following table:

 

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 Topic 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.

 

 


Automatically create the SG box for any NEW stage number : if either the On Success or On Error selections are set to JMP to Stage, this option will be enabled which will automatically create any target stage that does not already exist.

  • Below this rung : the new target stage will be created on a new rung following this instruction.
  • At end of code-block : the new target stage will be created as the last rung of this Program.

 


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 MQTTPUB to function properly from the PLC's perspective is Do-more Logger. Setting the system status bit $EnableMsgDump (ST36) ON will cause the MQTTPUB 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