Main Content

Subscribe to an MQTT Topic with a Callback Function

This example shows how to use an MQTT client to subscribe to a topic with a callback function.

ThingSpeak™ is used as the broker in this example.

Message Queuing Telemetry Transport (MQTT) is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth.

ThingSpeak is an IoT analytics platform service that allows you to aggregate, visualize, and analyze live data streams in the cloud. You can send data to ThingSpeak from your devices, create instant visualization of live data, and send alerts.

Create an MQTT Client and Connect to the Broker

Set up a ThingSpeak broker and get Client ID, Username, and Password from it. Download the root certificate from thingspeak.com and use its local path. Assign those values in MATLAB®.

clientID = "Your Client ID";
userName = "Your Username";
password = "Your Password";
rootCert = "C:\Downloads\thingspeakcert.cer";

Establish a secure connection to ThingSpeak with an appropriate port number using the mqttclient function.

brokerAddress = "ssl://mqtt3.thingspeak.com";
port = 8883;
mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,...
           Username = userName, Password = password, CARootCertificate = rootCert);

Subscribe to a Topic with a Callback Function

To subscribe with a callback function, create a callback function named showmessage. The showmessage function prints the received data and corresponding topic when triggered.

Use the subscribe function to subscribe to the topic of interest. Use a Name-Value pair argument to assign the callback function at the same time. The displayed table shows the subscribed topic and the corresponding callback function.

topicToSub = "channels/1393455/subscribe/fields/field2";
subscribe(mqClient, topicToSub, Callback = "showmessage")
ans=1×3 table
                      Topic                       QualityOfService      Callback   
    __________________________________________    ________________    _____________

    "channels/1393455/subscribe/fields/field2"           0            "showmessage"

Write to the Subscribed Topic

To trigger the callback function, the MQTT client needs to receive messages for the subscribed topic. Use the write function to write messages to the subscribed topic.

topicToWrite = "channels/1393455/publish/fields/field2";
msg = "70";
write(mqClient, topicToWrite, msg)

Trigger Callback Function

Pause to allow the message to transfer from the MQTT client, to the MQTT broker, and back to the client.

pause(2)

When the MQTT client receives the message from the subscribed topic, the callback function showmessage is automatically triggered. The following context is printed in the MATLAB Command Window.

Topic: channels/1393455/subscribe/fields/field2, Message: 70

Close the MQTT Client

Close access to ThingSpeak by clearing the MQTT client variable from the workspace.

clear mqClient