2020年10月2日 星期五

Node-RED + MQTT + ESP32 LED Control

 Node-RED + MQTT + ESP32 LED Control


Node-RED UI介面 控制ESP32 Build in LED 

1.ON , 2. OFF , 3. FLASH , 4. Timer ON 5 SEC


1) ESP32 Arduino 程式

#include <WiFi.h>

#include <PubSubClient.h>

#include <SPI.h>

#define BUILTIN_LED 2

// Update these with values suitable for your network.

//const char *ssid = "PTS-2F";

//const char *pass = "PTS6662594";

//const char *ssid = "WBR-2200";

//const char *pass = "0226452362";

const char *ssid = "74170287";

const char *pass = "24063173";

//const char *ssid =  "yourSSID";     // change according to your Network - cannot be longer than 32 characters!

//const char *pass =  "yourPASSWORD"; // change according to your Network


#define MQTTid              ""                           //id of this mqtt client

#define MQTTip              "broker.mqtt-dashboard.com"  //ip address or hostname of the mqtt broker

#define MQTTport            1883                         //port of the mqtt broker

#define MQTTuser            "alex9ufo"                   //username of this mqtt client

#define MQTTpsw             "alex1234"                   //password of this mqtt client

//#define MQTTuser          "your_username"              //username of this mqtt client

//#define MQTTpsw           "your_password"              //password of this mqtt client

#define MQTTpubQos          2                            //qos of publish (see README)

#define MQTTsubQos          1                            //qos of subscribe


//Variables

long lastMsg = 0;

char jsonChar[100];

String IDNo_buf="";


bool Flash = false;  //true

bool Timer = false;  //true

int Count= 0;

//=============================================================================

boolean pendingDisconnect = false;

void mqttConnectedCb(); // on connect callback

void mqttDisconnectedCb(); // on disconnect callback

void mqttDataCb(char* topic, byte* payload, unsigned int length); // on new message callback


WiFiClient wclient;

PubSubClient client(MQTTip, MQTTport, mqttDataCb, wclient);

//=============================================================================

void mqttConnectedCb() {

  Serial.println("connected");

  

  // Once connected, publish an announcement...

  client.publish("alex9ufo/led/led_event/json", jsonChar, MQTTpubQos, true); // true means retain

  // ... and resubscribe

  client.subscribe("alex9ufo/led/led_event", MQTTsubQos);

}

//=============================================================================

void mqttDisconnectedCb() {

  Serial.println("disconnected");

}

//=============================================================================

void mqttDataCb(char* topic, byte* payload, unsigned int length) {


  /*

  you can convert payload to a C string appending a null terminator to it;

  this is possible when the message (including protocol overhead) doesn't

  exceeds the MQTT_MAX_PACKET_SIZE defined in the library header.

  you can consider safe to do so when the length of topic plus the length of

  message doesn't exceeds 115 characters

  */

  char* message = (char *) payload;

  message[length] = 0;


  Serial.print("Message arrived [");

  Serial.print(topic);

  Serial.print("] ");

  Serial.println(message);

  String s = message;

  s.trim();

  // Switch on the LED if an 1 was received as first character

  if (s == "OFF") {

     digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level

     // but actually the LED is on; this is because 

     Serial.println("Received OFF , Send LOW TO BuildIn_LED");

     Flash = false;

     Timer = false;

    } 

   if (s == "ON") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received ON , Send HIGH TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

   }

    if (s == "FLASH") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received FLASH , Flashing BuildIn_LED ");

     Flash = true;

     Timer = false;

   } //if (message[0] == '2')

   

    if (s == "TIMER") {

     digitalWrite(BUILTIN_LED, HIGH);   // Turn the LED off (Note that HIGH is the voltage level

     // but actually the LED is on; this is because

     Serial.println("Received TIMER ,  BuildIn_LED ON 5 SEC");

     Flash = false;

     Timer = true;

     Count= 10;

   } //if (message[0] == '2')

   

}

//======================================================

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, pass);


  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }


  Serial.println("");

  Serial.println("WiFi connected");

  Serial.println("IP address: ");

  Serial.println(WiFi.localIP());

  

}

//======================================================

void setup() {

  Serial.begin(115200);

  setup_wifi();

  pinMode(BUILTIN_LED, OUTPUT);

  Serial.println(F("Booting...."));

 }

//======================================================

void process_mqtt() {

  if (WiFi.status() == WL_CONNECTED) {

    if (client.connected()) {

      client.loop();

    } else {

    // client id, client username, client password, last will topic, last will qos, last will retain, last will message

      if (client.connect(MQTTid, MQTTuser, MQTTpsw, MQTTid "/status", 2, true, "0")) {

          pendingDisconnect = false;

          mqttConnectedCb();

      }

    }

  } else {

    if (client.connected())

      client.disconnect();

  }

  if (!client.connected() && !pendingDisconnect) {

    pendingDisconnect = true;

    mqttDisconnectedCb();

  }

}

//======================================================

void loop() {

  process_mqtt();

  

  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);

    }

      

  }



}   //Loop

//======================================================

下載程式點

http://www.mediafire.com/file/c3alg5x86lmdnx7/ESP32_MQTT_LED.ino/file



PubSubClient.h 程式庫下載點

http://www.mediafire.com/file/ndfqkgl45m0m31b/pubsubclient-master.rar/file

2) Node-RED 程式

http://127.0.0.1:1880



http://127.0.0.1:1880/ui

[{"id":"51754690.ffee38","type":"mqtt in","z":"c1eadc43.582be","name":"","topic":"alex9ufo/led/led_event","qos":"1","datatype":"auto","broker":"841df58d.ee5e98","x":140,"y":80,"wires":[["94302818.ae36a8","96f2f0d8.1fbfa","d1d1e654.843568","b99597a3.65f958"]]},{"id":"94302818.ae36a8","type":"ui_text","z":"c1eadc43.582be","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"name":"","label":"MQTT Suscribe Data","format":"{{msg.payload}}","layout":"col-center","x":400,"y":80,"wires":[]},{"id":"e7f38845.851508","type":"ui_button","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"LED ON","tooltip":"","color":"white","bgcolor":"","icon":"fa-circle","payload":"ON","payloadType":"str","topic":"","x":120,"y":240,"wires":[["e4961251.9311c"]]},{"id":"19bfc564.049e4b","type":"ui_button","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"LED OFF","tooltip":"","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"OFF","payloadType":"str","topic":"","x":120,"y":280,"wires":[["e4961251.9311c"]]},{"id":"e4961251.9311c","type":"mqtt out","z":"c1eadc43.582be","name":"","topic":"alex9ufo/led/led_event","qos":"1","retain":"false","broker":"841df58d.ee5e98","x":400,"y":280,"wires":[]},{"id":"96f2f0d8.1fbfa","type":"function","z":"c1eadc43.582be","name":"Format timestamp","func":"var date = new Date();\nvar h = date.getHours();\nvar m = date.getMinutes();\nvar s = date.getSeconds();\nif(h<10){\n    h = '0'+h;\n}\nif(m<10){\n    m = '0' + m;\n}\nif(s<10){\n    s = '0' + s;\n}\nmsg.payload = msg.payload + ' --> Time:(' + h + ':' + m + ':' + s + ')' ;\n\nreturn msg;","outputs":1,"noerr":0,"x":150,"y":160,"wires":[["c5252b6e.bebcc8"]]},{"id":"c5252b6e.bebcc8","type":"function","z":"c1eadc43.582be","name":"Set Line API ","func":"msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer A4wwPNh2WqB7dlfeQyyIAwtggn1kfZSI5LkkCdia1gB'};\nmsg.payload = {\"message\":msg.payload};\nreturn msg;\n\n//oR7KdXvK1eobRr2sRRgsl4PMq23DjDlhfUs96SyUBZu","outputs":1,"noerr":0,"x":290,"y":200,"wires":[["7f86a659.2321c8"]]},{"id":"7f86a659.2321c8","type":"http request","z":"c1eadc43.582be","name":"","method":"POST","ret":"txt","paytoqs":false,"url":"https://notify-api.line.me/api/notify","tls":"","persist":false,"proxy":"","authType":"","x":400,"y":160,"wires":[["847c3e7e.3b5fc"]]},{"id":"847c3e7e.3b5fc","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":530,"y":200,"wires":[]},{"id":"d1d1e654.843568","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":390,"y":20,"wires":[]},{"id":"e473ddb0.8d753","type":"ui_audio","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":520,"y":120,"wires":[]},{"id":"fc1ee7eb.f3c0d8","type":"ui_button","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"LED Flashing","tooltip":"","color":"blue","bgcolor":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","x":140,"y":320,"wires":[["e4961251.9311c"]]},{"id":"b99597a3.65f958","type":"function","z":"c1eadc43.582be","name":"","func":"var st1;\nif (msg.payload === \"ON\") {\n   st1=\"LED開\"; \n} \nelse if (msg.payload === \"OFF\") {\n  st1=\"LED關\";\n}\nelse if (msg.payload === \"FLASH\") {\n  st1=\"LED閃爍\";\n}\nelse if (msg.payload === \"TIMER\") {\n  st1=\"LED開五秒鐘\";\n}\n\nmsg.payload=st1;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":330,"y":120,"wires":[["e473ddb0.8d753"]]},{"id":"75bd5e9a.f45f5","type":"ui_button","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"LED ON 5 Sec","tooltip":"","color":"purple","bgcolor":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","x":140,"y":360,"wires":[["e4961251.9311c"]]},{"id":"841df58d.ee5e98","type":"mqtt-broker","z":"","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":"6c9116b.b62d4e8","type":"ui_group","z":"","name":"Storing IOT Data ","tab":"eeb8e179.a47a4","order":1,"disp":true,"width":"6","collapse":false},{"id":"eeb8e179.a47a4","type":"ui_tab","z":"","name":"MySQL","icon":"dashboard","disabled":false,"hidden":false}]

程式下載點

http://www.mediafire.com/file/b6haw3ovwy0apxs/flows_ESP32_LED.json/file


3) LINE 程式修改 發行權杖






msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer A4wwPNh2WqB7dlfeQyyIAwtggn1kfZSI5LkkCdia1gB'};

msg.payload = {"message":msg.payload};

return msg;

上面的紅字 需改成自己的發行權杖

請參考 https://alex9ufoexploer.blogspot.com/2020/10/line-notify.html


沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...