MQTTサブスクリプション
MQTTブローカーと通信するアプリケーションの作成
MQTT サブスクリプションでは、MQTT ブローカーと通信するアプリケーションの作成方法を説明します。サブスクリプションごとに新しいダイアログが開き、サブスクライブされたトピック上のメッセージを確認できます。
クライアントの作成
QMqttClient クラスを使用して MQTT クライアントを作成し、接続に使用するブローカのホスト名とポートを設定します:
m_client = new QMqttClient(this); m_client->setHostname(ui->lineEditHost->text()); m_client->setPort(static_cast<quint16>(ui->spinBoxPort->value()));
トピックの購読
ユーザーがクライアントでトピックを購読すると、新しい購読オブジェクトが作成されます:
void MainWindow::on_buttonSubscribe_clicked() { auto subscription = m_client->subscribe(ui->lineEditTopic->text(), static_cast<quint8>(ui->spinQoS->text().toUInt())); if (!subscription) { QMessageBox::critical(this, u"Error"_s, u"Could not subscribe. Is there a valid connection?"_s); return; } auto subWindow = new SubscriptionWindow(subscription); subWindow->setWindowTitle(subscription->topic().filter()); subWindow->show(); }
QMqttSubscription クラスを使用して、サブスクリプションのトピック、ステート、QoS レベルを格納します:
SubscriptionWindow::SubscriptionWindow(QMqttSubscription *sub, QWidget *parent) : QWidget(parent), ui(new Ui::SubscriptionWindow), m_sub(sub) { ui->setupUi(this); ui->labelSub->setText(m_sub->topic().filter()); ui->labelQoS->setText(QString::number(m_sub->qos())); updateStatus(m_sub->state()); connect(m_sub, &QMqttSubscription::messageReceived, this, &SubscriptionWindow::updateMessage); connect(m_sub, &QMqttSubscription::stateChanged, this, &SubscriptionWindow::updateStatus); connect(m_sub, &QMqttSubscription::qosChanged, [this](quint8 qos) { ui->labelQoS->setText(QString::number(qos)); }); connect(ui->pushButton, &QAbstractButton::clicked, m_sub, &QMqttSubscription::unsubscribe); }
QoSレベルはメッセージとサブスクリプションで別々に設定できる。サブスクリプションに設定された QoS レベルは、最小 QoS レベルを決定する。メッセージがより高い QoS レベルで送られる場合、ブローカーはそのメッセージの QoS をより高いレベルに上げる。例えば、クライアントAがQoS 1でトピックを購読し、クライアントBがQoS 0でトピックにメッセージを公開した場合、ブローカーは自動的にメッセージのQoSを1に上げます。
メッセージの受信
クライアントがメッセージを受信すると、QMqttMessage クラスが実際のメッセージペイロードを格納するために使用されます:
void SubscriptionWindow::updateMessage(const QMqttMessage &msg) { ui->listWidget->addItem(msg.payload()); }
ファイル:
© 2025 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.