2023年7月13日 星期四

實驗 ESP32 MQTT – Publish and Subscribe Control Build LED

 實驗 ESP32 MQTT – Publish and Subscribe  Control Build LED














[{"id":"fb18ee16bd390f17","type":"ui_button","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","order":0,"width":"2","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":220,"y":120,"wires":[["1215bf485e4e05ac","99f45318686f3b50","ece516667caf5287"]]},{"id":"d3c9013c82e7208d","type":"ui_button","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","order":0,"width":"2","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"off","payloadType":"str","topic":"","topicType":"str","x":220,"y":160,"wires":[["1215bf485e4e05ac","99f45318686f3b50","ece516667caf5287"]]},{"id":"1215bf485e4e05ac","type":"mqtt out","z":"292f11a42dcd8cc6","name":"Control LED","topic":"alex9ufo/ESP32/LEDOUTPUT","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":470,"y":120,"wires":[]},{"id":"afdfd6c80c401e46","type":"comment","z":"292f11a42dcd8cc6","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":350,"y":60,"wires":[]},{"id":"99f45318686f3b50","type":"ui_audio","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","voice":"zh-TW","always":true,"x":460,"y":260,"wires":[]},{"id":"ece516667caf5287","type":"ui_text","z":"292f11a42dcd8cc6","group":"85b1efd8d6d7c0dd","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":530,"y":200,"wires":[]},{"id":"f36454366bb73576","type":"ui_audio","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","voice":"en-US","always":"","x":760,"y":360,"wires":[]},{"id":"ee071aaa4be34a08","type":"mqtt in","z":"292f11a42dcd8cc6","name":"LED status ","topic":"alex9ufo/ESP32/LED_status","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":240,"y":420,"wires":[["06db1cd963fdc4c0","525b36ad0d551f68"]]},{"id":"06db1cd963fdc4c0","type":"debug","z":"292f11a42dcd8cc6","name":"debug 95","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":460,"y":440,"wires":[]},{"id":"0cc50378a4f78cf1","type":"comment","z":"292f11a42dcd8cc6","name":"Node-Red  subscribe HiveMQ Broker  , ESP32發行","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":340,"y":320,"wires":[]},{"id":"2c68e0bd754ec016","type":"ui_text","z":"292f11a42dcd8cc6","group":"85b1efd8d6d7c0dd","order":0,"width":0,"height":0,"name":"","label":"Node-RED 訂閱MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":660,"y":400,"wires":[]},{"id":"35f02379c87a6a78","type":"ui_button","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","order":0,"width":"2","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"flash","payloadType":"str","topic":"","topicType":"str","x":220,"y":200,"wires":[["1215bf485e4e05ac","ece516667caf5287","99f45318686f3b50"]]},{"id":"420821c68c32a9f5","type":"ui_button","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","order":0,"width":"2","height":"1","passthru":false,"label":"LED反向","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"toggle","payloadType":"str","topic":"","topicType":"str","x":220,"y":240,"wires":[["1215bf485e4e05ac","ece516667caf5287","99f45318686f3b50"]]},{"id":"222e01e31287760a","type":"ui_button","z":"292f11a42dcd8cc6","name":"","group":"85b1efd8d6d7c0dd","order":0,"width":"2","height":"1","passthru":false,"label":"LED 定時5秒","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"timer","payloadType":"str","topic":"","topicType":"str","x":230,"y":280,"wires":[["1215bf485e4e05ac","ece516667caf5287","99f45318686f3b50"]]},{"id":"525b36ad0d551f68","type":"function","z":"292f11a42dcd8cc6","name":"function 26","func":"msg.payload=\" ---ESP32回來資料---\" +msg.payload;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":450,"y":400,"wires":[["2c68e0bd754ec016","739d35b9914f0a4c"]]},{"id":"739d35b9914f0a4c","type":"delay","z":"292f11a42dcd8cc6","name":"","pauseType":"delay","timeout":"1","timeoutUnits":"seconds","rate":"1","nbRateUnits":"1","rateUnits":"second","randomFirst":"1","randomLast":"5","randomUnits":"seconds","drop":false,"allowrate":false,"outputs":1,"x":620,"y":360,"wires":[["f36454366bb73576"]]},{"id":"85b1efd8d6d7c0dd","type":"ui_group","name":"ESP32","tab":"eeb8e179.a47a4","order":2,"disp":true,"width":"10","collapse":false,"className":""},{"id":"70940176.2b2d3","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"841df58d.ee5e98","type":"mqtt-broker","name":"","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":false,"keepalive":"15","cleansession":true,"birthTopic":"","birthQos":"0","birthPayload":"","closeTopic":"","closePayload":"","willTopic":"","willQos":"0","willPayload":""},{"id":"eeb8e179.a47a4","type":"ui_tab","name":"LED Control","icon":"dashboard","disabled":false,"hidden":false}]


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

// Replace the next variables with your SSID/Password combination
//const char* ssid = "XXXXXXXXX";
//const char* password = "XXXXXXXXX";
const char* ssid = "alex9ufo"; // Enter your Wi-Fi name
const char* password = "alex9981";  // Enter Wi-Fi password


// Add your MQTT Broker IP address, example:
//const char* mqtt_server = "192.168.1.144";
const char* mqtt_server = "broker.mqtt-dashboard.com";
const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;


WiFiClient espClient;
PubSubClient client(espClient);
char msg[50];
const char *topic1 = "alex9ufo/ESP32/LEDOUTPUT";
const char *topic2 = "alex9ufo/ESP32/LED_status";

// LED Pin
#define BUILTIN_LED 2
String json = "";     //client.publish("alex9ufo/led/led_status",
char jsonChar2[20];
bool Flash = false;  //true
bool Timer = false;  //true
bool Send = false;  //true
int Count= 0;
//==========================================
void setup() {
  Serial.begin(115200);
  // default settings
  delay(500);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  while (!client.connected()) {
    String client_id = "esp32-client-";
    client_id += String(WiFi.macAddress());
    Serial.printf("The client %s connects to the public MQTT broker\n", client_id.c_str());
    if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
        Serial.println("Public HiveMQ MQTT broker (broker.mqtt-dashboard.com) connected");
    } else {
        Serial.print("Failed with state ");
        Serial.print(client.state());
        delay(2000);
    }
  }

  // Publish and subscribe
  client.subscribe(topic1);

  pinMode(BUILTIN_LED, OUTPUT);
}
//==========================================
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(".");
  }

  Serial.println("");
  Serial.println("ESP32 WiFi connected to ");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
//==========================================
void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
 
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT

  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off".
  // Changes the output state according to the message
  if (String(topic) == "alex9ufo/ESP32/LEDOUTPUT") {
    Serial.print("Changing output to ");
    if(messageTemp == "on"){
      Serial.println("on");
      digitalWrite(BUILTIN_LED, HIGH);
      Flash = false;
      Timer = false;
      json ="ON";
      Send = true ;
    }
    else if(messageTemp == "off"){
      Serial.println("off");
      digitalWrite(BUILTIN_LED, LOW);
      Flash = false;
      Timer = false;
      json ="OFF";
      Send = true ;
    }
    else if(messageTemp == "toggle"){
      digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));   // Turn the LED toggle
      bool val = digitalRead (BUILTIN_LED);
      Serial.println("toggle");
      Flash = false;
      Timer = false;
      Send = true ;  
      json ="TOGGLE now=off ";
      if (val) {
        json ="TOGGLE now=on ";
      }
 
    }
    else if(messageTemp == "flash"){
      digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
      Serial.println("flash");
      Flash = true;
      Timer = false;
      json ="FLASH";
      Send = true ;  
    }
    else if(messageTemp == "timer"){
      digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level
      Serial.println("timer");
      Flash = false;
      Timer = true;
      Count= 10;
      json ="TIMER";
      Send = true ;
    }
  }
}
//==========================================
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      // Subscribe
      client.subscribe(topic1);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//==========================================
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  //----------------------------------
  if (Flash)
  {
    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));
    delay(500);
  }
  if (Timer)
  {
    digitalWrite(BUILTIN_LED, HIGH);
    delay(500);
    Count=Count-1;
    if (Count == 0 ){
       Timer=false;
       digitalWrite(BUILTIN_LED, LOW);
    }
  }
  if (Send) {
    // Convert JSON string to character array

    json.toCharArray(jsonChar2, json.length()+1);
    if  (client.connected()) {
         Serial.print("Publish message: ");
         Serial.println(json);
         // Publish JSON character array to MQTT topic
         client.publish(topic2,jsonChar2);
    }
    Send = false;    
  }
  //----------------------------------

}

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...