MQTT Subscriptions Example▲
MQTT Subscriptions shows how to create an application that communicates with an MQTT broker. A new dialog opens for each subscription, where you can see the messages on the subscribed topics.
Creating a Client▲
We use the QMqttClient class to create an MQTT client and to set the broker host name and port to use for the connection:
m_client =
new
QMqttClient(this
);
m_client-&
gt;setHostname(ui-&
gt;lineEditHost-&
gt;text());
m_client-&
gt;setPort(ui-&
gt;spinBoxPort-&
gt;value());
Subscribing to Topics▲
When users subscribe to topics in the client, a new subscription object is created:
void
MainWindow::
on_buttonSubscribe_clicked()
{
auto
subscription =
m_client-&
gt;subscribe(ui-&
gt;lineEditTopic-&
gt;text(), ui-&
gt;spinQoS-&
gt;text().toUInt());
if
(!
subscription) {
QMessageBox::
critical(this
, QLatin1String("Error"
), QLatin1String("Could not subscribe. Is there a valid connection?"
));
return
;
}
auto
subWindow =
new
SubscriptionWindow(subscription);
subWindow-&
gt;setWindowTitle(subscription-&
gt;topic().filter());
subWindow-&
gt;show();
}
We use the QMqttSubscription class to store the topic, state, and QoS level of a subscription:
SubscriptionWindow::
SubscriptionWindow(QMqttSubscription *
sub, QWidget *
parent) :
QWidget(parent),
ui(new
Ui::
SubscriptionWindow),
m_sub(sub)
{
ui-&
gt;setupUi(this
);
ui-&
gt;labelSub-&
gt;setText(m_sub-&
gt;topic().filter());
ui-&
gt;labelQoS-&
gt;setText(QString::
number(m_sub-&
gt;qos()));
updateStatus(m_sub-&
gt;state());
connect(m_sub, &
amp;QMqttSubscription::
messageReceived, this
, &
amp;SubscriptionWindow::
updateMessage);
connect(m_sub, &
amp;QMqttSubscription::
stateChanged, this
, &
amp;SubscriptionWindow::
updateStatus);
connect(m_sub, &
amp;QMqttSubscription::
qosChanged, [this
](quint8 qos) {
ui-&
gt;labelQoS-&
gt;setText(QString::
number(qos));
}
);
connect(ui-&
gt;pushButton, &
amp;QAbstractButton::
clicked, m_sub, &
amp;QMqttSubscription::
unsubscribe);
}
The QoS level can be set separately for a message and for a subscription. The QoS level set for a subscription determines the minimum QoS level. If a message is sent with a higher QoS level, the broker increases the QoS of that message to the higher level. For example, if client A subscribed to topic with QoS 1, and client B publishes a message on the topic, with QoS 0, the broker will automatically increase the QoS of the message to 1. If client B publishes a message on the topic with the QoS 2, the broker will send it with QoS 2.
Receiving Messages▲
When the client receives a message, the QMqttMessage class is used to store the actual message payload:
void
SubscriptionWindow::
updateMessage(const
QMqttMessage &
amp;msg)
{
ui-&
gt;listWidget-&
gt;addItem(msg.payload());
}