mDNS名を追いかけてMQTTで何かを投げつけるボタン


RaspberryPiをシャットダウンorリセットするのに最適

Raspberry Piが再起動してIPアドレス変わった場合、ちゃんとIPアドレスを追いかけるようにした。

・追加したノードノード(うろ覚え)
node-red-contrib-rpi-shutdown
node-red-contrib-aedes

・いい感じにnode-REDを作っておく

トピック名はtopic

参考資料

https://qiita.com/hanapage/items/c2df143dbde33e03e674
https://qiita.com/poruruba/items/5d9434aec4895f8a6f7a

ソース


m5atom-MQTTswith
m5atom-MQTTswith.ino
#include <M5Atom.h>
#include <WiFi.h>
#include <PubSubClient.h>
#include <ESPmDNS.h>

WiFiClient wifi;
const char* wifi_ssid = "Wi-Fi";
const char* wifi_password = "pass";

PubSubClient client(wifi);

//.local不要
const char* mqtt_server = "your Raspberry Pi mDNS name";

const uint16_t mqtt_port = 1883; 
#define MQTT_CLIENT_NAME  "M5Atom"

#define BTN_PUSH_MARGIN 100
#define MQTT_BUFFER_SIZE 512

bool pressed = false; 

void wifi_connect(void){
  Serial.print("WiFi Connenting");

  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println("");
  Serial.print("Connected : ");
  Serial.println(WiFi.localIP());

}

void sendMessage(void){
  // MQTT Publish
  client.publish("topic","1");
  delay(BTN_PUSH_MARGIN);
  client.publish("topic","0");
}

void setup() {
  M5.begin(true, false, true);

  Serial.begin(115200);
  wifi_connect();
  if(!MDNS.begin("m5atom")){
    Serial.println("Error MDNS");
    while(1){
      delay(1000);
    }
  }
  client.setBufferSize(MQTT_BUFFER_SIZE);
}


void loop() {
  client.loop();
  while(!client.connected() ){
    if (MDNS.queryHost(mqtt_server)==IPAddress('0.0.0.0')){
      delay(1000);
    }
    IPAddress mqtt_server_ip = MDNS.queryHost(mqtt_server);
    Serial.println(mqtt_server_ip);
    client.setServer(mqtt_server_ip, mqtt_port);
    Serial.println("Mqtt Reconnecting");
    if( client.connect(MQTT_CLIENT_NAME) ){
      Serial.println("Mqtt Connected");
      break;
    }
    delay(1000);
  }

  M5.update();

    if (M5.Btn.isPressed() && !pressed ){
      pressed = true;
      // 送信
      sendMessage();
      Serial.println("Mqtt Send");
      delay(BTN_PUSH_MARGIN);
    }else if( M5.Btn.isReleased() && pressed ){
      pressed = false;

      delay(BTN_PUSH_MARGIN);
    }
}