Bye Bye Moore

猫マンション建築の野望を胸に零細事業主として資本主義の荒波に漕ぎ出したアラサー男の技術メモ

Arduino on ESP32 でMQTTの実験をしてみる その3:ESP32からPublishする

shuzo-kino.hateblo.jp
のシリーズです。
いよいよ、今回から

実際のところ

動作環境

スクリプト

arduino向けMQTTクライアント"pubsubclient"のesp2866向けサンプルをベースにします。
pubsubclient/mqtt_esp8266.ino at master · knolleary/pubsubclient · GitHub
ESP32になってから"WiFi.h"を直に使えるようになったので注意して下さい。

#include <WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASS";
const char* mqtt_server = "YOUR_ACCOUNT/IP";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("msg/comment", "Coming Packets");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("msg/comment", msg);
  }
}

動作ログ

Arduino側のシリアルにはこんな感じでログが出ます

Connecting to YOURSSID
.....
WiFi connected
IP address: 
YOUR_ACCOUNT/IP
Attempting MQTT connection...connected
Publish message: hello world #1
Publish message: hello world #2
Publish message: hello world #3
Publish message: hello world #4
...

mosquittoの方には、こんな感じで接続情報がきます

1507644406: New connection from YOUR_ACCOUNT/IP on port 1883.
1507644406: New client connected from YOUR_ACCOUNT/IP as ESP32Client-1f85 (c1, k15).

subscriberはこんな塩梅

$ mosquitto_sub -h YOUR_ACCOUNT/IP -t msg/comment -q 1
hello world #1
hello world #2
...