Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Arduino on ESP32 でMQTTの実験をしてみる その4:ESP32でsubmitする

shuzo-kino.hateblo.jp
では送信をやりました。
次は受信です。

実際のところ

動作環境

スクリプト

前回と同様、以下をベースにします。
pubsubclient/mqtt_esp8266.ino at master · knolleary/pubsubclient · GitHub
アスキーの"0"をおくると消灯、それ以外は点灯というロジックです。

#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 callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(LED_BUILTIN, LOW); 
    Serial.println("coming here");
  } else {
    digitalWrite(LED_BUILTIN, HIGH); 
  }

}

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");
      client.subscribe("msg/led");
    } 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(LED_BUILTIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

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

動作ログ

初期接続に成功すると、mosquittoの方には、こんな感じで接続情報がきます

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

この状態からpublisherで以下のような感じで送ると……

$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 0 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
...

Arduino側のシリアルにはこんな感じでログが出でて、
LEDの方もちゃんと突いたり消えたりしてくれます。

Connecting to YOURSSID
.....
WiFi connected
IP address: 
YOUR_ACCOUNT/IP
Attempting MQTT connection...connected
Message arrived [msg/led] 1
coming here
Message arrived [msg/led] 1
coming here
Message arrived [msg/led] 0
Message arrived [msg/led] 1
coming here
...