1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Arduinoを使用したESP8266のMQTTブローカーへの接続

Posted at

Arduinoを使用したESP8266のMQTTブローカーへの接続

MQTT は、IoTメッセージを交換し、データを配信するための軽量で柔軟なプロトコルです。IoT開発者のために、柔軟性とハードウェア/ネットワークリソースのバランスを実現することに専念しています。

ESP8266 は、高度に統合されたWi-Fi SoCソリューションを提供します。その低消費電力、コンパクトな設計、および高い安定性は、ユーザーの要件を満たすことができます。ESP8266には、独立して動作するか、または他のホストMCUのスレーブとして動作する完全かつ自己完結型のWi-Fiネットワーク機能があります。

このプロジェクトでは、Arduino IDEを使用してESP8266をプログラミングし、EMQX Cloudが運営・維持する無料の公開MQTTブローカーにESP8266を接続する方法を実装します。EMQX Cloudは、EMQが提供するセキュリティ付きMQTT IoTクラウドサービスプラットフォームです。一元化された運用保守代行と、ユニークな隔離環境を持つMQTT 5.0接続サービスを提供します。

必要なIoTコンポーネント

  • ESP8266
  • Arduino IDE
  • MQTTX: クロスプラットフォームMQTT 5.0クライアントツール
  • 無料の公開MQTTブローカー
    • ブローカー: broker.emqx.io
    • TCPポート: 1883
    • Websocketポート: 8083

ESP8266のPub/Sub

project.png

ソースコード

  1. まず、ライブラリESP8266WiFiPubSubClientをインポートします。ESP8266WiFiライブラリはESP8266をWi-Fiネットワークに接続し、PubSubClientライブラリはESP8266がMQTTブローカーにメッセージを公開し、トピックを購読することを可能にします。

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
  2. Wi-Fiの名前とパスワード、MQTTブローカーの接続アドレスとポートを設定します。

    // WiFi
    const char *ssid = "mousse"; // WiFi名を入力
    const char *password = "qweqweqwe";  // WiFiパスワードを入力
    
    // MQTTブローカー
    const char *mqtt_broker = "broker.emqx.io";
    const char *topic = "esp8266/test";
    const char *mqtt_username = "emqx";
    const char *mqtt_password = "public";
    const int mqtt_port = 1883;
    
  3. プログラムの結果を出力し、Wi-Fiネットワークに接続するためのシリアル接続を開きます。

    // ソフトウェアシリアルのボーレートを115200に設定;
    Serial.begin(115200);
    // Wi-Fiネットワークに接続
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Wi-Fiに接続中..");
    }
    
  4. MQTTブローカーを設定し、コールバック関数を書き、同時にシリアルモニターに接続情報を表示します。

    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
        String client_id = "esp8266-client-";
        client_id += String(WiFi.macAddress());
        Serial.printf("クライアント%sが公開mqttブローカーに接続\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        } else {
            Serial.print("接続失敗、ステート ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    
    void callback(char *topic, byte *payload, unsigned int length) {
        Serial.print("トピックでメッセージが到着: ");
        Serial.println(topic);
        Serial.print("メッセージ:");
        for (int i = 0; i < length; i++) {
            Serial.print((char) payload[i]);
        }
        Serial.println();
        Serial.println("-----------------------");
    }
    
  5. MQTTブローカーに正常に接続した後、ESP8266はメッセージを公開し、MQTTブローカーを購読します。

    // 公開と購読
    client.publish(topic, "hello emqx");
    client.subscribe(topic);
    
  6. シリアルポートにトピック名を表示し、受信したメッセージの各バイトを出力します。

    void callback(char *topic, byte *payload, unsigned int length) {
        Serial.print("トピックでメッセージが到着: ");
        Serial.println(topic);
        Serial.print("メッセージ:");
        for (int i = 0; i < length; i++) {
            Serial.print((char) payload[i]);
        }
        Serial.println();
        Serial.println("-----------------------");
    }
    
  7. 完全なコード

    #include <ESP8266WiFi.h>
    #include <PubSubClient.h>
    
    // WiFi
    const char *ssid = "mousse"; // WiFi名を入力
    const char *password = "qweqweqwe";  // WiFiパスワードを入力
    
    // MQTTブローカー
    const char *mqtt_broker = "broker.emqx.io";
    const char *topic = "esp8266/test";
    const char *mqtt_username = "emqx";
    const char *mqtt_password = "public";
    const int mqtt_port = 1883;
    
    WiFiClient espClient;
    PubSubClient client(espClient);
    
    void setup() {
      // ソフトウェアシリアルのボーレートを115200に設定;
      Serial.begin(115200);
      // Wi-Fiネットワークに接続
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED) {
          delay(500);
          Serial.println("Wi-Fiに接続中..");
      }
      Serial.println("Wi-Fiネットワークに接続しました");
      // mqttブローカーに接続
      client.setServer(mqtt_broker, mqtt_port);
      client.setCallback(callback);
      while (!client.connected()) {
          String client_id = "esp8266-client-";
          client_id += String(WiFi.macAddress());
          Serial.printf("クライアント%sが公開mqttブローカーに接続\n", client_id.c_str());
          if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
              Serial.println("公開emqx mqttブローカーに接続しました");
          } else {
              Serial.print("接続失敗、ステート ");
              Serial.print(client.state());
              delay(2000);
          }
      }
      // 公開と購読
      client.publish(topic, "hello emqx");
      client.subscribe(topic);
    }
    
    void callback(char *topic, byte *payload, unsigned int length) {
      Serial.print("トピックでメッセージが到着: ");
      Serial.println(topic);
      Serial.print("メッセージ:");
      for (int i = 0; i < length; i++) {
          Serial.print((char) payload[i]);
      }
      Serial.println();
      Serial.println("-----------------------");
    }
    
    void loop() {
      client.loop();
    }
    

実行とテスト

  1. Arduino IDEを使用してESP8266に完全なコードをアップロードし、シリアルモニターを開いてください。

    esp_con.png

  2. MQTTXクライアントとMQTTブローカーとの接続を確立し、ESP8266にメッセージを送信します。

    mqttx_pub.png

  3. シリアルモニターでESP8266が受信したメッセージを確認します。

    esp_msg.png

まとめ

これまでに、EMQX Cloudが提供する無料の公開MQTTブローカーにESP8266を接続することに成功しました。このプロジェクトでは、ESP8266をMQTTブローカーに接続しましたが、ESP8266はさまざまなIoTセンサーに接続し、センサーデータをMQTTブローカーに報告することも可能です。

次に、EMQが提供するMQTTプロトコルに関する簡単なガイドシリーズの記事で、MQTTプロトコルの特徴について学び、MQTTのより高度なアプリケーションを探求し、MQTTアプリケーションおよびサービス開発を始めることができます。

リソース

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?