QMqttClient Class

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

头: #include <QMqttClient>
qmake: QT += mqtt
继承: QObject

公共类型

enum ClientError { NoError, InvalidProtocolVersion, IdRejected, ServerUnavailable, BadUsernameOrPassword, …, Mqtt5SpecificError }
enum ClientState { Disconnected, Connecting, Connected }
enum ProtocolVersion { MQTT_3_1, MQTT_3_1_1, MQTT_5_0 }
enum TransportType { IODevice, AbstractSocket, SecureSocket }

特性

公共函数

virtual ~QMqttClient () override
void authenticate (const QMqttAuthenticationProperties & prop )
bool autoKeepAlive () const
bool cleanSession () const
QString clientId () const
void connectToHost ()
void connectToHostEncrypted (const QSslConfiguration & conf )
QMqttConnectionProperties connectionProperties () const
void disconnectFromHost ()
QMqttClient::ClientError error () const
QString hostname () const
quint16 keepAlive () const
QMqttLastWillProperties lastWillProperties () 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)
qint32 publish (const QMqttTopicName & topic , const QMqttPublishProperties & properties , const QByteArray & message = QByteArray(), quint8 qos = 0, bool retain = false)
bool requestPing ()
QMqttServerConnectionProperties serverConnectionProperties () const
void setConnectionProperties (const QMqttConnectionProperties & prop )
void setLastWillProperties (const QMqttLastWillProperties & prop )
void setTransport (QIODevice * device , QMqttClient::TransportType transport )
QMqttClient::ClientState state () const
QMqttSubscription * subscribe (const QMqttTopicFilter & topic , quint8 qos = 0)
QMqttSubscription * subscribe (const QMqttTopicFilter & topic , const QMqttSubscriptionProperties & properties , quint8 qos = 0)
QIODevice * transport () const
void unsubscribe (const QMqttTopicFilter & topic )
void unsubscribe (const QMqttTopicFilter & topic , const QMqttUnsubscriptionProperties & properties )
QString username () const
QByteArray willMessage () const
quint8 willQoS () const
bool willRetain () const
QString willTopic () const

公共槽

void setAutoKeepAlive (bool autoKeepAlive )
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 )

信号

void authenticationFinished (const QMqttAuthenticationProperties & p )
void authenticationRequested (const QMqttAuthenticationProperties & p )
void autoKeepAliveChanged (bool autoKeepAlive )
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 messageStatusChanged (qint32 id , QMqtt::MessageStatus s , const QMqttMessageStatusProperties & properties )
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 )

详细描述

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.

成员类型文档编制

enum QMqttClient:: ClientError

This enum type specifies the error state of a client.

常量 描述
QMqttClient::NoError 0 没有出现错误。
QMqttClient::InvalidProtocolVersion 1 The broker does not accept a connection using the specified protocol version.
QMqttClient::IdRejected 2 The client ID is malformed. This might be related to its length.
QMqttClient::ServerUnavailable 3 The network connection has been established, but the service is unavailable on the broker side.
QMqttClient::BadUsernameOrPassword 4 The data in the username or password is malformed.
QMqttClient::NotAuthorized 5 The client is not authorized to connect.
QMqttClient::TransportInvalid 256 The underlying transport caused an error. For example, the connection might have been interrupted unexpectedly.
QMqttClient::ProtocolViolation 257 The client encountered a protocol violation, and therefore closed the connection.
QMqttClient::UnknownError 258 出现未知错误。
QMqttClient::Mqtt5SpecificError 259 The error is related to MQTT protocol level 5. A reason code might provide more details.

enum QMqttClient:: ClientState

This enum type specifies the states a client can enter.

常量 描述
QMqttClient::Disconnected 0 The client is disconnected from the broker.
QMqttClient::Connecting 1 A connection request has been made, but the broker has not approved the connection yet.
QMqttClient::Connected 2 The 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.

常量 描述
QMqttClient::MQTT_3_1 3 MQTT Standard 3.1
QMqttClient::MQTT_3_1_1 4 MQTT Standard 3.1.1, publicly referred to as version 4
QMqttClient::MQTT_5_0 5 MQTT Standard 5.0

enum QMqttClient:: TransportType

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

常量 描述
QMqttClient::IODevice 0 The transport uses a class based on a QIODevice .
QMqttClient::AbstractSocket 1 The transport uses a class based on a QAbstractSocket .
QMqttClient::SecureSocket 2 The transport uses a class based on a QSslSocket .

特性文档编制

[since 5.14] autoKeepAlive : bool

This property holds whether the client will automatically manage keep alive messages to the server.

若此特性为 true , then the client will automatically send a ping message to the server at the keepAlive interval.

Otherwise, a user will have to manually invoke requestPing within the specified interval of the connection. If no ping has been sent within the interval, the server will disconnect.

The default of this property is true .

该特性在 Qt 5.14 引入。

访问函数:

bool autoKeepAlive () const
void setAutoKeepAlive (bool autoKeepAlive )

通知程序信号:

void autoKeepAliveChanged (bool autoKeepAlive )

另请参阅 keepAlive (), requestPing (), serverConnectionProperties (),和 pingResponseReceived ().

cleanSession : bool

This property holds the state after connecting to a broker.

访问函数:

bool cleanSession () const
void setCleanSession (bool cleanSession )

通知程序信号:

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.

访问函数:

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

通知程序信号:

void clientIdChanged (QString clientId )

error : ClientError

Specifies the current error of the client.

访问函数:

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

通知程序信号:

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.

访问函数:

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

通知程序信号:

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 seconds.

If the broker does not respond within a grace period the connection will be closed.

访问函数:

quint16 keepAlive () const
void setKeepAlive (quint16 keepAlive )

通知程序信号:

void keepAliveChanged (quint16 keepAlive )

另请参阅 autoKeepAlive (), requestPing (),和 pingResponseReceived ().

password : QString

This property holds the password for connecting to a broker.

访问函数:

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

通知程序信号:

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.

访问函数:

quint16 port () const
void setPort (quint16 port )

通知程序信号:

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.

访问函数:

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

通知程序信号:

void protocolVersionChanged (QMqttClient::ProtocolVersion protocolVersion )

state : ClientState

This property holds the current state of the client.

访问函数:

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

通知程序信号:

void stateChanged (QMqttClient::ClientState state )

username : QString

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

访问函数:

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

通知程序信号:

void usernameChanged (QString username )

willMessage : QByteArray

This property holds the payload of a Will Message.

访问函数:

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

通知程序信号:

void willMessageChanged (QByteArray willMessage )

willQoS : quint8

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

访问函数:

quint8 willQoS () const
void setWillQoS (quint8 willQoS )

通知程序信号:

void willQoSChanged (quint8 willQoS )

willRetain : bool

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

访问函数:

bool willRetain () const
void setWillRetain (bool willRetain )

通知程序信号:

void willRetainChanged (bool willRetain )

willTopic : QString

This property holds the Will Topic.

访问函数:

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

通知程序信号:

void willTopicChanged (QString willTopic )

成员函数文档编制

[signal, since 5.12] void QMqttClient:: authenticationFinished (const QMqttAuthenticationProperties & p )

This signal is emitted after extended authentication has finished. p specifies available details on the authentication process.

After successful authentication QMqttClient::connected is emitted.

注意: Extended authentication is part of the MQTT 5.0 standard and can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 authenticationRequested () 和 authenticate ().

[signal, since 5.12] void QMqttClient:: authenticationRequested (const QMqttAuthenticationProperties & p )

This signal is emitted after a client invoked QMqttClient::connectToHost or QMqttClient::connectToHostEncrypted and before the connection is established. In extended authentication, a broker might request additional details which need to be provided by invoking QMqttClient::authenticate . p specifies properties provided by the broker.

注意: Extended authentication is part of the MQTT 5.0 standard and can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 authenticationFinished () 和 authenticate ().

[signal] void QMqttClient:: brokerSessionRestored ()

This signal is emitted after a client has successfully connected to a broker with the cleanSession 特性被设为 false , and the broker has restored the session.

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

[signal] void QMqttClient:: connected ()

This signal is emitted when a connection has been established.

[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, since 5.12] void QMqttClient:: messageStatusChanged ( qint32 id , QMqtt::MessageStatus s , const QMqttMessageStatusProperties & properties )

This signal is emitted when the status for the message identified by id 改变。 s specifies the new status of the message, and properties specify additional properties provided by the server.

该函数在 Qt 5.12 引入。

[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.

[override virtual] QMqttClient:: ~QMqttClient ()

Deletes a MQTT client. If the MQTT client was not already disconnected from the MQTT broker, it will be disconnected from automatically.

[since 5.12] void QMqttClient:: authenticate (const QMqttAuthenticationProperties & prop )

Sends an authentication request to the broker. prop specifies the required information to fulfill the authentication request.

This function should only be called after a QMqttClient::authenticationRequested 信号已发射。

注意: Extended authentication is part of the MQTT 5.0 standard and can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 authenticationRequested () 和 authenticationFinished ().

[invokable] void QMqttClient:: connectToHost ()

Initiates a connection to the MQTT broker.

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

[since 5.14] void QMqttClient:: connectToHostEncrypted (const QSslConfiguration & conf )

Initiates an encrypted connection to the MQTT broker.

conf specifies the SSL configuration to be used for the connection

该函数在 Qt 5.14 引入。

[since 5.12] QMqttConnectionProperties QMqttClient:: connectionProperties () const

Returns the connection properties the client requests to the broker.

注意: QMqttConnectionProperties can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 setConnectionProperties ().

[invokable] void QMqttClient:: disconnectFromHost ()

Disconnects from the MQTT broker.

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

[since 5.12] QMqttLastWillProperties QMqttClient:: lastWillProperties () const

Returns the last will properties.

注意: QMqttLastWillProperties can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 setLastWillProperties ().

[invokable] 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 QoS level required for transferring the message.

retain 被设为 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.

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

[invokable, since 5.12] qint32 QMqttClient:: publish (const QMqttTopicName & topic , const QMqttPublishProperties & properties , const QByteArray & message = QByteArray(), quint8 qos = 0, bool retain = false)

Publishes a message to the broker with the specified properties and topic . qos specifies the QoS level required for transferring the message.

retain 被设为 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.

注意: properties will only be passed to the broker when the client specifies MQTT_5_0 as ProtocolVersion .

注意: 此函数可以被援引,通过元对象系统和从 QML。见 Q_INVOKABLE .

该函数在 Qt 5.12 引入。

bool QMqttClient:: requestPing ()

Sends a ping message to the broker and expects a reply.

If the connection is active and autoKeepAlive is true , then calling this function will fail as the client is responsible for managing this process.

使用 requestPing() manually requires a call every time within the keepAlive interval as long as the connection is active.

To check whether the ping is successful, connect to the pingResponseReceived () 信号。

返回 true if the ping request could be sent.

另请参阅 pingResponseReceived (), autoKeepAlive (),和 keepAlive ().

[since 5.12] QMqttServerConnectionProperties QMqttClient:: serverConnectionProperties () const

返回 QMqttServerConnectionProperties the broker returned after a connection attempt.

This can be used to verify that client side connection properties set by QMqttClient::setConnectionProperties have been accepted by the broker. Also, in case of a failed connection attempt, it can be used for connection diagnostics.

注意: QMqttServerConnectionProperties can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 connectionProperties ().

[since 5.12] void QMqttClient:: setConnectionProperties (const QMqttConnectionProperties & prop )

Sets the connection properties to prop . QMqttConnectionProperties can be used to ask the server to use a specific feature set. After a connection request the server response can be obtained by calling QMqttClient::serverConnectionProperties .

注意: The connection properties can only be set if the MQTT client is in the Disconnected 状态。

注意: QMqttConnectionProperties can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 connectionProperties ().

[since 5.12] void QMqttClient:: setLastWillProperties (const QMqttLastWillProperties & prop )

Sets the last will properties to prop . QMqttLastWillProperties allows to set additional features for the last will message stored at the broker.

注意: The connection properties can only be set if the MQTT client is in the Disconnected 状态。

注意: QMqttLastWillProperties can only be used when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

另请参阅 lastWillProperties ().

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 .

注意: The transport can only be exchanged if the MQTT client is in the Disconnected 状态。

注意: Setting a custom transport for a client does not pass over responsibility on connection management. The transport has to be opened for QIODevice based transports or connected for socket type transports before calling QMqttClient::connectToHost ().

另请参阅 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 服务品质 .

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.

[since 5.12] QMqttSubscription *QMqttClient:: subscribe (const QMqttTopicFilter & topic , const QMqttSubscriptionProperties & properties , quint8 qos = 0)

Adds a new subscription to receive notifications on topic . The parameter properties specifies additional subscription properties to be validated by the broker. The parameter qos specifies the level at which security messages are received. For more information about the available QoS levels, see 服务品质 .

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.

注意: properties will only be passed to the broker when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。

QIODevice *QMqttClient:: transport () const

Returns the transport used for communication with the broker.

另请参阅 setTransport ().

void QMqttClient:: unsubscribe (const QMqttTopicFilter & topic )

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

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

[since 5.12] void QMqttClient:: unsubscribe (const QMqttTopicFilter & topic , const QMqttUnsubscriptionProperties & properties )

Unsubscribes from topic . No notifications will be sent to any of the subscriptions made by calling subscribe (). properties specifies additional user properties to be passed to the broker.

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

注意: properties will only be passed to the broker when the client specifies MQTT_5_0 as ProtocolVersion .

该函数在 Qt 5.12 引入。