Main Content

mqttclient

Create MQTT client connected to broker

Since R2022a

Description

An icomm.mqtt.Client object represents an MQTT client in MATLAB® that connects to an external MQTT broker.

Creation

Description

mqttClient = mqttclient(brokerAddr) creates an MQTT client connected to the broker specified by brokerAddr. brokerAddr is a host name or IP address of the MQTT broker including the connection protocol. The function supports the MQTT, TCP, WS, SSL, and WSS protocols.

mqttClient = mqttclient(brokerAddr,Name=Value) specifies function options and properties of mqttClient using optional name-value arguments.

example

Input Arguments

expand all

Location of the MQTT broker as a URL, including protocol, specified as a string or character vector.

The function supports these protocols:

mqtt://
tcp://
ws://
ssl://
wss://

Example: mq=mqttclient("tcp://broker.hivemq.com")

Data Types: string | char

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: mqttClient = mqttclient("wss://mqtt3.thingspeak.com", Port=443, Username="MyUserID", ClientID="MyClientID", Password="MyPassword")

Name-value arguments can specify the properties Port, ClientID, Timeout, KeepAliveDuration, LastWillTopic, LastWillMessage, LastWillQOS, and LastWillRetain; and the following options:

User name for connection to the broker, specified as a string or character vector.

Data Types: char | string

User password for connection to the broker, specified as a string or character vector. Use the setSecret and getSecret functions on MATLAB desktop environment to securely store and retrieve the password from your MATLAB vault.

Data Types: char | string

Server root certificate for broker authentication during a secure connection, specified as a string or character vector.

Data Types: char | string

Certificate for client authentication during a secure connection, specified as a string or character vector.

Data Types: char | string

Private key file for client authentication, specified as a string or character vector. The function uses ClientKey along with ClientCertificate for authentication during secure connection.

Data Types: char | string

Password to decrypt the private ClientKey file, specified as a string or character vector.

Data Types: char | string

Note

Security Considerations: When using CARootCertificate, ClientCertificate or, ClientKey, do not store private keys or certificate files on an unencrypted file system. You can use these methods to store sensitive data:

  • Save the files in dedicated certificate stores of your operating system and set appropriate access rights using the options provided by the operating system.

  • Use TPM modules or external secured hardware, such as USB-based authentication tokens.

Properties

expand all

Client Configuration

This property is read-only.

Socket port number to use when connecting to the MQTT broker, specified as an integer.

Example: mq=mqttclient("tcp://broker.hivemq.com", Port=8883)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical

This property is read-only.

Identifier of the client for connection to broker, specified as a string or character vector.

Data Types: char | string

This property is read-only.

Maximum time allowed to complete the connection, specified as a numeric integer in seconds or as a duration.

Example: mq=mqttclient("tcp://broker.hivemq.com", Timeout=60)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | duration

This property is read-only.

Maximum idle time allowed between broker and client, specified as a numeric integer value in seconds or as a duration. If no traffic occurs in this time span, the client issues a keep-alive packet.

Example: mq=mqttclient("tcp://broker.hivemq.com", KeepAliveDuration=minutes(5))

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | duration

This property is read-only.

Location of the MQTT broker, specified as a string or character vector. BrokerAddress identifies the host name or IP address of the MQTT broker, including the connection protocol. The function supports the MQTT, TCP, WS, SSL, and WSS protocols.

Example: "tcp://broker.hivemq.com"

Data Types: char | string

This property is read-only.

Topics that the client is subscribed to, specified as a table.

Data Types: table

This property is read-only.

Status of the client connection to the broker, returned as logical 1 (connected) or 0 (not connected). Connection status of 0 can indicate an issue with the broker; check that you have the correct address, clear the object, and try creating it again.

Data Types: logical

Last Will and Testament

Since R2024b

MQTT topic containing the last will message, specified as a string or character vector.

Example: mq=mqttclient("tcp://172.19.135.122", LastWillTopic="MATLAB/LastWill")

Note

You must specify LastWillTopic to enable the Last Will and Testament feature for your client.

Data Types: char | string

Since R2024b

Last will message payload to deliver to the subscribed clients, specified as a string or character vector. The message is empty by default.

Example: mq=mqttclient("tcp://172.19.135.122", LastWillTopic="MATLAB/LastWill", LastWillMessage="Offline")

Data Types: char | string

Since R2024b

Service quality of last will message delivery, specified as one of these values:

  • 0 — Messages delivered at most once, not more (default).

  • 1 — Messages delivered at least once, not less.

  • 2 — Messages delivered exactly once, not more or less.

Example: mq=mqttclient("tcp://172.19.135.122", LastWillTopic="MATLAB/LastWill", LastWillQOS=1)

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

Since R2024b

Option to retain the last will message, specified as one these:

  • true: The broker stores the last will message, and the message is available to the new subscribers.

  • false: The broker does not store last will message, and the message is not available to the new subscribers.

Example: mq=mqttclient("tcp://172.19.135.122", LastWillTopic= "MATLAB/LastWill", LastWillRetain=false)

Data Types: logical

Object Functions

subscribeSubscribe to MQTT topic
unsubscribeUnsubscribe from MQTT topics
readRead available messages from MQTT topic
peekView most recent message from MQTT topic
flushClear received MQTT messages
writeWrite message to MQTT topic

Examples

collapse all

Create a nonsecure MQTT client connection to a HiveMQ public broker with default settings.

mqttClient = mqttclient("tcp://broker.hivemq.com")
mqttClient = 

  Client with properties:

        BrokerAddress: "tcp://broker.hivemq.com"
                 Port: 1883
             ClientID: ""
              Timeout: 5
    KeepAliveDuration: 60
        Subscriptions: [0×3 table]
            Connected: 1
  Show all properties

Create a nonsecure MQTT client connection to a HiveMQ public broker using port 1883 and specify the client ID as myClient.

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

  Client with properties:

        BrokerAddress: "tcp://broker.hivemq.com"
                 Port: 1883
             ClientID: "myClient"
              Timeout: 5
    KeepAliveDuration: 60
        Subscriptions: [0×3 table]
            Connected: 1
  Show all properties

Create an MQTT client with a secure connection over SSL using certificates for authentication. Connect the client to the Eclipse Mosquitto™ public broker at port 8884 and specify the broker root certificate, client certificate, and private key.

mqttClientSSL = mqttclient("ssl://mosquitto.org",Port=8884,...
        CARootCertificate="C:\mqtt\mosquitto.org.pem",...
        ClientCertificate="C:\mqtt\client.pem",...
        ClientKey="C:\mqtt\client.key");

Connecting with the MQTT interface on ThingSpeak requires ClientID, Username, and Password. Use the setSecret and getSecret functions on MATLAB desktop environment to securely store and retrieve the password from your MATLAB vault.

setSecret("MyPassword")

password prompt for MQTT

Create an MQTT client securely connected with websockets to ThingSpeak™.

mqttClient = mqttclient("wss://mqtt3.thingspeak.com",Port=443,...
             Username="MyUserID",ClientID="MyClientID",Password=getSecret("MyPassword"));

For releases prior to R2024a, specify password as a string.

Since R2024b

Configure a custom last will message for an MQTT client connected to a HiveMQ public broker. Configure the LastWillQOS and LastWillRetain properties to determine the service quality and the availability of last will message to new subscribers.

mqttClient = mqttclient("tcp://broker.hivemq.com",...
             LastWillTopic="MATLAB",LastWillMessage="Offline",...
             LastWillQOS=1,LastWillRetain=true)
mqttClient = 

  Client with properties:

        BrokerAddress: "tcp://broker.hivemq.com"
                 Port: 1883
             ClientID: ""
              Timeout: 5
    KeepAliveDuration: 60
        Subscriptions: [0×3 table]
            Connected: 1
        LastWillTopic: "MATLAB"
      LastWillMessage: "Offline"
          LastWillQOS: 1
       LastWillRetain: 1

Version History

Introduced in R2022a

expand all