Main Content

Communicate Securely with ThingSpeak MQTT Broker

Since R2024a

This example shows how to establish a secure connection and communicate with the ThingSpeak MQTT broker in MATLAB®.

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.

Set Up Broker and Get Root Certificate

To establish a connection with ThingSpeak, see Create a ThingSpeak MQTT Device (ThingSpeak). After creating the ThingSpeak MQTT device, you can get its Client ID, Username and Password from it. Assign the ClientID and Username values in MATLAB. Store the password in your MATLAB vault using the setSecret function on a MATLAB desktop environment.

clientID = "Your Client ID";
userName = "Your Username";
setSecret("MQTTpassword") 

Use the dialog box to set and add your password to your MATLAB vault. Toggle the eye icon in the text box to hide or show the characters in your password.

Secret Prompt to enter password

Download the root certificate from thingspeak.com as described in How to Download Root Certificate for Use With Industrial Communication Toolbox MQTT Functions. Get the path of the downloaded root certificate. The location and file name extension depends on the browser you use. For example, using Edge you might set rootCert like this:

rootCert = "C:\Downloads\DigiCert Global Root CA.crt";

The certificate saved from Firefox® might have the file extension .pem.

Create MQTT Client and Connect to Broker with SSL

Prepare the broker address and port number you want to connect. In this case, set up a secure connection to ThingSpeak via SSL with an appropriate port number.

brokerAddress = "ssl://mqtt3.thingspeak.com";
port = 8883;

Create an MQTT client using the mqttclient function. Provide the MQTT broker password stored in your vault using the getSecret function on a MATLAB desktop environment.

mqClient = mqttclient(brokerAddress, Port = port, ClientID = clientID,...
           Username = userName, Password = getSecret("MQTTpassword"), CARootCertificate = rootCert);

Note that the Connected property indicates the connection to the broker has been established.

mqClient.Connected
ans = logical
   1

Subscribe to Topic

With the connected MQTT client, use the subscribe function to subscribe to the topic of interest. The displayed table shows the subscribed topic. For details about the topics to subscribe to in ThingSpeak, see Subscribe to a Channel Field Feed (ThingSpeak).

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

    "channels/2579691/subscribe/fields/field2"           0               ""   

Write to Topic

To verify that the subscription is successful, make sure a message written to the subscribed topic is received by the MQTT client.

Use the write function to write messages to the topic of interest. For details about the topics to write to in ThingSpeak, see Publish to a Channel Field Feed (ThingSpeak).

topicToWrite = "channels/2579691/publish/fields/field2";
msg = "70";
write(mqClient, topicToWrite, msg)
pause(1) % Adding a pause to compensate for the communication latency

Peek at MQTT Client

Use the peek function to view the most recently received message for all subscribed topics in the MQTT client. The displayed timetable indicates the MQTT client has successfully received the message from the broker.

peek(mqClient)
ans=1×2 timetable
            Time                              Topic                       Data
    ____________________    __________________________________________    ____

    19-Jun-2024 09:43:00    "channels/2579691/subscribe/fields/field2"    "70"

Close MQTT Client

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

clear mqClient