「Qtの基礎 - MQTT」の版間の差分

ナビゲーションに移動 検索に移動
193行目: 193行目:
  <syntaxhighlight lang="cmake">
  <syntaxhighlight lang="cmake">
  # パッケージの検索
  # パッケージの検索
  find_package(Qt6 COMPONENTS Core Network Mqtt REQUIRED)
  find_package(QT NAMES Qt6 REQUIRED COMPONENTS Core Network Mqtt)
  find_package(PkgConfig REQUIRED)
  find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core Network Mqtt)
# # Pkg-configを使用してMQTTライブラリを検索
pkg_check_modules(MQTT REQUIRED IMPORTED_TARGET
    libmosquitto
    libmosquittopp
)
   
   
  # ライブラリのリンク
  # ライブラリのリンク
207行目: 201行目:
     Qt6::Network
     Qt6::Network
     Qt6::Mqtt
     Qt6::Mqtt
    PkgConfig::MQTT
  ) </syntaxhighlight>
  )
# インクルードするディレクトリの設定
target_include_directories(<プロジェクト名> PRIVATE
    # ...略
    ${MQTT_INCLUDE_DIRS}
)
</syntaxhighlight>
<br>
<br>
* Qtプロジェクトファイルを使用する場合
* Qtプロジェクトファイルを使用する場合
  <syntaxhighlight lang="make">
  <syntaxhighlight lang="make">
  QT += core network mqtt
  QT += core network mqtt
# Pkg-configを使用してMQTTライブラリを検索
CONFIG += link_pkgconfig
PKGCONFIG += libmosquitto libmosquittopp
  </syntaxhighlight>
  </syntaxhighlight>
<br>
<br>
434行目: 416行目:
     {
     {
       // 全ての購読を解除
       // 全ての購読を解除
       for (auto subscription : m_subscriptions) {
       for (auto it = m_subscriptions.constBegin(); it != m_subscriptions.constEnd(); it++) {
           subscription->unsubscribe();
           it.value()->unsubscribe();
           delete subscription;
           delete it.value();
       }
       }
   
   
447行目: 429行目:
   
   
     // MQTT接続を開始する
     // MQTT接続を開始する
     void connectToHost(const QString &host, quint16 port)
     void connectToHost(const QString &host, quint16 port, const QString &username = QString(), const QString &password = QString())
     {
     {
       m_host = host;
       m_host = host;
455行目: 437行目:
       m_client->setHostname(host);
       m_client->setHostname(host);
       m_client->setPort(port);
       m_client->setPort(port);
      // ユーザ名とパスワードが指定されている場合は設定
      if (!username.isEmpty()) {
          m_client->setUsername(username);
      }
      if (!password.isEmpty()) {
          m_client->setPassword(password);
      }
   
   
       // 非同期で接続を開始
       // 非同期で接続を開始
477行目: 468行目:
       auto subscription = m_client->subscribe(topic, 1);
       auto subscription = m_client->subscribe(topic, 1);
       if (!subscription) {
       if (!subscription) {
           qWarning() << "トピックの購読に失敗しました:" << topic;
           qWarning() << "トピックの購読に失敗しました : " << topic;
           return;
           return;
       }
       }
486行目: 477行目:
       // 購読リストに追加
       // 購読リストに追加
       m_subscriptions.insert(topic, subscription);
       m_subscriptions.insert(topic, subscription);
       qInfo() << "トピックを購読開始しました:" << topic;
       qInfo() << "トピックを購読開始しました : " << topic;
     }
     }
   
   
498行目: 489行目:
   
   
  signals:
  signals:
     // メッセージ受信時のシグナル
     void connected();
     void messageReceived(const QString &topic, const QByteArray &message);
     void messageReceived(const QString &topic, const QByteArray &message);
   
   
508行目: 499行目:
           case QMqttClient::Connected:
           case QMqttClient::Connected:
             qInfo() << "MQTTブローカーに接続しました";
             qInfo() << "MQTTブローカーに接続しました";
            emit connected();  // 接続成功時にシグナルを発行
             break;
             break;
           case QMqttClient::Disconnected:
           case QMqttClient::Disconnected:
             qInfo() << "MQTTブローカーから切断されました";
             qInfo() << "MQTTブローカーから切断されました";
            // 切断時に再接続を試みる
            QTimer::singleShot(5000, this, [this]() {
                qInfo() << "再接続を試みます...";
                this->connectToHost(m_host, m_port, m_client->username(), m_client->password());
            });
             break;
             break;
           case QMqttClient::Connecting:
           case QMqttClient::Connecting:
561行目: 560行目:
       // エラー発生時は再接続を試みる
       // エラー発生時は再接続を試みる
       if (m_client->state() != QMqttClient::Connected) {
       if (m_client->state() != QMqttClient::Connected) {
           QTimer::singleShot(5000, [this]() {
           QTimer::singleShot(5000, this, [this]() {
             qInfo() << "再接続を試みます...";
             qInfo() << "再接続を試みます...";
             this->connectToHost(m_host, m_port);
             this->connectToHost(m_host, m_port, m_client->username(), m_client->password());
           });
           });
       }
       }
571行目: 570行目:
     void handleMessage(const QByteArray &message, const QMqttTopicName &topic)
     void handleMessage(const QByteArray &message, const QMqttTopicName &topic)
     {
     {
       // メッセージを受信したことをログに記録
       // シグナルを発行してアプリケーションに通知
      qInfo() << "メッセージを受信しました - トピック: " << topic.name();
      qInfo() << "メッセージ: " << message;
      // シグナルを発行して、アプリケーションの他の部分に通知
       emit messageReceived(topic.name(), message);
       emit messageReceived(topic.name(), message);
     }
     }
591行目: 586行目:
   
   
     MqttSubscriber subscriber;
     MqttSubscriber subscriber;
    subscriber.connectToHost("localhost", 1883);
   
   
     // メッセージ受信時の処理
     // メッセージ受信時の処理
     QObject::connect(&subscriber, &MqttSubscriber::messageReceived, [](const QString &topic, const QByteArray &message) {
     QObject::connect(&subscriber, &Subscriber::messageReceived, [](const QString &topic, const QByteArray &message) {
       qDebug() << "受信 - トピック: " << topic;
       qDebug() << "受信 - トピック : " << topic;
       qDebug() << "メッセージ: "  << message;
       qDebug() << "メッセージ : "  << message;
    });
    // 接続成功時の処理を追加
    QObject::connect(&subscriber, &Subscriber::connected, [&subscriber]() {
      subscriber.subscribe("qt/topic");
     });
     });
   
   
     subscriber.subscribe("qt/topic");
     subscriber.connectToHost("localhost", 1883, "<MQTTユーザ名>", "<MQTTユーザのパスワード>");
   
   
     return a.exec();
     return a.exec();

案内メニュー