Main Content

Get Started with MQTT

This example shows how to connect and communicate with an 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.

Create MQTT Client and Connect to Broker with TCP

Create an MQTT client using the mqttclient function. This example creates a nonsecure MQTT client connection to a HiveMQ public broker using port 1883 and client ID as myClient.

mqClient = mqttclient("tcp://broker.hivemq.com",ClientID="myClient",Port=1883);

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.

topicToSub = "trubits/mqTop48";
subscribe(mqClient, topicToSub)
ans=1×3 table
          Topic          QualityOfService    Callback
    _________________    ________________    ________

    "trubits/mqTop48"           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.

topicToWrite = "trubits/mqTop48";
msg = "70";
write(mqClient, topicToWrite, msg)
pause(1)
msg = "100";
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 
    ____________________    _________________    _____

    20-Jun-2024 09:01:22    "trubits/mqTop48"    "100"

Read from Topic

Use the read function to read all available messages from the topic of interest.

topicToRead = "trubits/mqTop48";
read(mqClient, Topic= topicToRead)
ans=2×2 timetable
            Time                  Topic          Data 
    ____________________    _________________    _____

    20-Jun-2024 09:01:21    "trubits/mqTop48"    "70" 
    20-Jun-2024 09:01:22    "trubits/mqTop48"    "100"

Close MQTT Client

Close the connection to HiveMQ public broker by clearing the MQTT client variable from the workspace.

clear mqClient