QMqttClient Class

The QMqttClient class represents the central access communicating with an MQTT broker. More...

Header: #include <QMqttClient>
qmake: QT += mqtt
Inherits: QObject

Public Types

enum ClientError { NoError, InvalidProtocolVersion, IdRejected, ServerUnavailable, ..., UnknownError }
enum ClientState { Disconnected, Connecting, Connected }
enum ProtocolVersion { MQTT_3_1, MQTT_3_1_1 }
enum TransportType { IODevice, AbstractSocket, SecureSocket }

Properties

  • 1 property inherited from QObject

Public Functions

QMqttClient(QObject *parent = nullptr)
bool cleanSession() const
QString clientId() const
void connectToHost()
void connectToHostEncrypted(const QString &sslPeerName = QString())
void disconnectFromHost()
QMqttClient::ClientError error() const
QString hostname() const
quint16 keepAlive() const
QString password() const
quint16 port() const
QMqttClient::ProtocolVersion protocolVersion() const
qint32 publish(const QMqttTopicName &topic, const QByteArray &message = QByteArray(), quint8 qos = 0, bool retain = false)
bool requestPing()
void setTransport(QIODevice *device, QMqttClient::TransportType transport)
QMqttClient::ClientState state() const
QMqttSubscription *subscribe(const QMqttTopicFilter &topic, quint8 qos = 0)
QIODevice *transport() const
void unsubscribe(const QMqttTopicFilter &topic)
QString username() const
QByteArray willMessage() const
quint8 willQoS() const
bool willRetain() const
QString willTopic() const
  • 34 public functions inherited from QObject

Public Slots

void setCleanSession(bool cleanSession)
void setClientId(const QString &clientId)
void setError(QMqttClient::ClientError error)
void setHostname(const QString &hostname)
void setKeepAlive(quint16 keepAlive)
void setPassword(const QString &password)
void setPort(quint16 port)
void setProtocolVersion(QMqttClient::ProtocolVersion protocolVersion)
void setState(QMqttClient::ClientState state)
void setUsername(const QString &username)
void setWillMessage(const QByteArray &willMessage)
void setWillQoS(quint8 willQoS)
void setWillRetain(bool willRetain)
void setWillTopic(const QString &willTopic)
  • 1 public slot inherited from QObject

Signals

void brokerSessionRestored()
void cleanSessionChanged(bool cleanSession)
void clientIdChanged(QString clientId)
void connected()
void disconnected()
void errorChanged(QMqttClient::ClientError error)
void hostnameChanged(QString hostname)
void keepAliveChanged(quint16 keepAlive)
void messageReceived(const QByteArray &message, const QMqttTopicName &topic = QMqttTopicName())
void messageSent(qint32 id)
void passwordChanged(QString password)
void pingResponseReceived()
void portChanged(quint16 port)
void protocolVersionChanged(QMqttClient::ProtocolVersion protocolVersion)
void stateChanged(QMqttClient::ClientState state)
void usernameChanged(QString username)
void willMessageChanged(QByteArray willMessage)
void willQoSChanged(quint8 willQoS)
void willRetainChanged(bool willRetain)
void willTopicChanged(QString willTopic)

Additional Inherited Members

  • 1 public variable inherited from QObject
  • 10 static public members inherited from QObject
  • 9 protected functions inherited from QObject
  • 2 protected variables inherited from QObject

Detailed Description

The QMqttClient class represents the central access communicating with an MQTT broker.

An MQTT client is a program or device that uses MQTT to create a network connection to an MQTT server, also called a broker. The connection request must contain a unique client identifier. Optionally, it can contain a Will Topic, Will Message, user name, and password.

Once a connection is created, a client can send messages that other clients might be interested in receiving, subscribe to request notifications on topics, unsubscribe to remove a request for notifications, and disconnect from the broker.

Member Type Documentation

enum QMqttClient::ClientError

This enum type specifies the error state of a client.

ConstantValueDescription
QMqttClient::NoError0No error occurred.
QMqttClient::InvalidProtocolVersion1The broker does not accept a connection using the specified protocol version.
QMqttClient::IdRejected2The client ID is malformed. This might be related to its length.
QMqttClient::ServerUnavailable3The network connection has been established, but the service is unavailable on the broker side.
QMqttClient::BadUsernameOrPassword4The data in the username or password is malformed.
QMqttClient::NotAuthorized5The client is not authorized to connect.
QMqttClient::TransportInvalid256The underlying transport caused an error. For example, the connection might have been interrupted unexpectedly.
QMqttClient::ProtocolViolation257The client encountered a protocol violation, and therefore closed the connection.
QMqttClient::UnknownError258An unknown error occurred.

enum QMqttClient::ClientState

This enum type specifies the states a client can enter.

ConstantValueDescription
QMqttClient::Disconnected0The client is disconnected from the broker.
QMqttClient::Connecting1A connection request has been made, but the broker has not approved the connection yet.
QMqttClient::Connected2The client is connected to the broker.

enum QMqttClient::ProtocolVersion

This enum specifies the protocol version of the MQTT standard to use during communication with a broker.

ConstantValueDescription
QMqttClient::MQTT_3_13MQTT Standard 3.1
QMqttClient::MQTT_3_1_14MQTT Standard 3.1.1, publicly referred to as version 4

enum QMqttClient::TransportType

This enum type specifies the connection method to be used to instantiate a connection to a broker.

ConstantValueDescription
QMqttClient::IODevice0The transport uses a class based on a QIODevice.
QMqttClient::AbstractSocket1The transport uses a class based on a QAbstractSocket.
QMqttClient::SecureSocket2The transport uses a class based on a QSslSocket.

Property Documentation

cleanSession : bool

This property holds the state after connecting to a broker.

Access functions:

bool cleanSession() const
void setCleanSession(bool cleanSession)

Notifier signal:

void cleanSessionChanged(bool cleanSession)

clientId : QString

This property holds the client's identifier value.

Each client needs to have a unique ID to be able to connect to an MQTT broker. If no client ID is specified by the user, one will be generated automatically when a connection is established.

Access functions:

QString clientId() const
void setClientId(const QString &clientId)

Notifier signal:

void clientIdChanged(QString clientId)

error : ClientError

Specifies the current error of the client.

Access functions:

QMqttClient::ClientError error() const
void setError(QMqttClient::ClientError error)

Notifier signal:

void errorChanged(QMqttClient::ClientError error)

hostname : QString

This property holds the hostname of the MQTT broker to connect to.

If no transport is specified via setTransport(), the client will instantiate a socket connection to the specified hostname itself.

Access functions:

QString hostname() const
void setHostname(const QString &hostname)

Notifier signal:

void hostnameChanged(QString hostname)

keepAlive : quint16

This property holds the interval at which regular ping messages are sent to the broker.

Once a connection to a broker is established, the client needs to send frequent updates to propagate it can still be reached. The interval between those updates is specified by this property.

The interval is specified in milliseconds. However, most brokers are not capable of using such a high granularity and will fall back to an interval specified in seconds.

Access functions:

quint16 keepAlive() const
void setKeepAlive(quint16 keepAlive)

Notifier signal:

void keepAliveChanged(quint16 keepAlive)

password : QString

This property holds the password for connecting to a broker.

Access functions:

QString password() const
void setPassword(const QString &password)

Notifier signal:

void passwordChanged(QString password)

port : quint16

This property holds the port to connect to the MQTT broker.

If no transport is specified via setTransport(), the client will instantiate a socket connection to a host with this port number.

Access functions:

quint16 port() const
void setPort(quint16 port)

Notifier signal:

void portChanged(quint16 port)

protocolVersion : ProtocolVersion

This property holds the MQTT standard version to use for connections.

Specifies the version of the standard the client uses for connecting to a broker. Valid values are:

  • 3: MQTT standard version 3.1.
  • 4: MQTT standard version 3.1.1, often referred to MQTT 4.

Access functions:

QMqttClient::ProtocolVersion protocolVersion() const
void setProtocolVersion(QMqttClient::ProtocolVersion protocolVersion)

Notifier signal:

void protocolVersionChanged(QMqttClient::ProtocolVersion protocolVersion)

state : ClientState

This property holds the current state of the client.

Access functions:

QMqttClient::ClientState state() const
void setState(QMqttClient::ClientState state)

Notifier signal:

void stateChanged(QMqttClient::ClientState state)

username : QString

This property holds the user name for connecting to a broker.

Access functions:

QString username() const
void setUsername(const QString &username)

Notifier signal:

void usernameChanged(QString username)

willMessage : QByteArray

This property holds the payload of a Will Message.

Access functions:

QByteArray willMessage() const
void setWillMessage(const QByteArray &willMessage)

Notifier signal:

void willMessageChanged(QByteArray willMessage)

willQoS : quint8

This property holds the level of QoS for sending and storing the Will Message.

Access functions:

quint8 willQoS() const
void setWillQoS(quint8 willQoS)

Notifier signal:

void willQoSChanged(quint8 willQoS)

willRetain : bool

This property holds whether the Will Message should be retained on the broker for future subscribers to receive.

Access functions:

bool willRetain() const
void setWillRetain(bool willRetain)

Notifier signal:

void willRetainChanged(bool willRetain)

willTopic : QString

This property holds the Will Topic.

Access functions:

QString willTopic() const
void setWillTopic(const QString &willTopic)

Notifier signal:

void willTopicChanged(QString willTopic)

Member Function Documentation

QMqttClient::QMqttClient(QObject *parent = nullptr)

Creates a new MQTT client instance with the specified parent.

[signal] void QMqttClient::brokerSessionRestored()

This signal is emitted after a client has successfully connected to a broker with the cleanSession property set to false, and the broker has restored the session.

Sessions can be restored if a client has connected previously using the same clientId.

void QMqttClient::connectToHost()

Initiates a connection to the MQTT broker.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

void QMqttClient::connectToHostEncrypted(const QString &sslPeerName = QString())

Initiates an encrypted connection to the MQTT broker.

sslPeerName specifies the peer name to be passed to the socket.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

[signal] void QMqttClient::connected()

This signal is emitted when a connection has been established.

void QMqttClient::disconnectFromHost()

Disconnects from the MQTT broker.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

[signal] void QMqttClient::disconnected()

This signal is emitted when a connection has been closed. A connection may be closed when disconnectFromHost() is called or when the broker disconnects.

[signal] void QMqttClient::messageReceived(const QByteArray &message, const QMqttTopicName &topic = QMqttTopicName())

This signal is emitted when a new message has been received. The category of the message is specified by topic with the content being message.

[signal] void QMqttClient::messageSent(qint32 id)

Indicates that a message that was sent via the publish() function has been received by the broker. The id is the same as returned by publish() to help tracking the status of the message.

[signal] void QMqttClient::pingResponseReceived()

This signal is emitted after the broker responds to a requestPing() call or a keepAlive() ping message, and the connection is still valid.

qint32 QMqttClient::publish(const QMqttTopicName &topic, const QByteArray &message = QByteArray(), quint8 qos = 0, bool retain = false)

Publishes a message to the broker with the specified topic. qos specifies the level of security required for transferring the message.

If retain is set to true, the message will stay on the broker for other clients to connect and receive the message.

Returns an ID that is used internally to identify the message.

Note: This function can be invoked via the meta-object system and from QML. See Q_INVOKABLE.

bool QMqttClient::requestPing()

Sends a ping message to the broker and expects a reply. If the connection is active, the MQTT client will automatically send a ping message at keepAlive intervals.

To check whether the ping is successful, connect to the pingResponseReceived() signal.

Returns true if the ping request could be sent.

void QMqttClient::setTransport(QIODevice *device, QMqttClient::TransportType transport)

Sets the transport to device. A transport can be either a socket type or derived from QIODevice and is specified by transport.

Note: The transport can only be exchanged if the MQTT client is in the Disconnected state.

See also transport().

QMqttSubscription *QMqttClient::subscribe(const QMqttTopicFilter &topic, quint8 qos = 0)

Adds a new subscription to receive notifications on topic. The parameter qos specifies the level at which security messages are received. For more information about the available QoS levels, see Quality of Service.

This function returns a pointer to a QMqttSubscription. If the same topic is subscribed twice, the return value points to the same subscription instance. The MQTT client is the owner of the subscription.

QIODevice *QMqttClient::transport() const

Returns the transport used for communication with the broker.

See also setTransport().

void QMqttClient::unsubscribe(const QMqttTopicFilter &topic)

Unsubscribes from topic. No notifications will be sent to any of the subscriptions made by calling subscribe().

Note: If a client disconnects from a broker without unsubscribing, the broker will store all messages and publish them on the next reconnect.

© 2018 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.