2020年12月17日 星期四

ESP32 MQTT , Node-Red LED 控制

 ESP32 MQTT , Node-Red LED 控制






Arduino程式

#include <WiFi.h>

#include <PubSubClient.h>

#include <SPI.h>

#define BUILTIN_LED 26

// Update these with values suitable for your network.

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

//const char *pass = "PTS6662594";

//const char *ssid = "alex9ufo";

//const char *pass = "alex9981";


//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 json = "";


bool Flash = false;  //true

bool Timer = false;  //true

bool Send = 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_status", 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;

     json ="OFF";

     Send = true ;

    } 

   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; 

     json ="ON";

     Send = true ;

   }

   if (s == "TOGGLE") {

     digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));   // Turn the LED toggle 

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

     Serial.println("Received TOGGLE , Send Toggle(H->L , L->H) TO BuildIn_LED");

     Flash = false; 

     Timer = false; 

     json ="TOGGLE";

     Send = true ;     

   }

   

    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;

     json ="FLASH";

     Send = true ;  

     

   } //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;

     json ="TIMER";

     Send = true ; 

     

   } //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...."));

  Serial.println(F("Control Build LED ON,OFF,FLASH,TOGGLE,TIMER...."));

 }

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

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

    }

      

  }

  if (Send) {

     // Convert JSON string to character array

     json.toCharArray(jsonChar, json.length()+1);

     if  (client.connected()) {

              Serial.print("Publish message: ");

              Serial.println(json);

              // Publish JSON character array to MQTT topic

             client.publish("alex9ufo/led/led_status",jsonChar);

         } 

     Send = false;    

   }


}   //Loop

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

Node-Red程式

[{"id":"c683b38b.29c07","type":"mqtt in","z":"780055b2.c3306c","name":"","topic":"alex9ufo/led/led_status","qos":"1","datatype":"auto","broker":"841df58d.ee5e98","x":140,"y":100,"wires":[["da92767.4793288","4de7fad6.a30a64","cd44885a.0ab348"]]},{"id":"da92767.4793288","type":"ui_text","z":"780055b2.c3306c","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"name":"","label":"MQTT Suscribe Data :   ","format":"{{msg.payload}}","layout":"row-left","x":400,"y":100,"wires":[]},{"id":"49813706.0e0bb8","type":"ui_button","z":"780055b2.c3306c","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"On led","tooltip":"","color":"white","bgcolor":"","icon":"fa-circle","payload":"Light-emitting diode on","payloadType":"str","topic":"","x":110,"y":300,"wires":[["71c1c14c.dd9a7","1e895ef0.0fdf81"]]},{"id":"8138558a.9f9778","type":"ui_button","z":"780055b2.c3306c","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"Off led","tooltip":"","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"Light-emitting diode off","payloadType":"str","topic":"","x":110,"y":360,"wires":[["71c1c14c.dd9a7","26ec090f.33d196"]]},{"id":"56de513d.77d14","type":"mqtt out","z":"780055b2.c3306c","name":"","topic":"alex9ufo/led/led_event","qos":"1","retain":"false","broker":"841df58d.ee5e98","x":520,"y":340,"wires":[]},{"id":"71c1c14c.dd9a7","type":"ui_audio","z":"780055b2.c3306c","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":"","x":280,"y":420,"wires":[]},{"id":"4de7fad6.a30a64","type":"function","z":"780055b2.c3306c","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":370,"y":160,"wires":[["f2702b9c.b9abd8","f0f03cd0.85978"]]},{"id":"f2702b9c.b9abd8","type":"function","z":"780055b2.c3306c","name":"Set Line API ","func":"msg.headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer A4w1wPN1h2WqB7dlfeQyyIAwtggn1kfZSI5LkkCdia1gB'};\nmsg.payload = {\"message\":msg.payload};\nreturn msg;\n\n//oR7KdXvK1eobRr2sRRgsl4PMq23DjDlhfUs96SyUBZu","outputs":1,"noerr":0,"x":550,"y":160,"wires":[["75d380.c445ac8"]]},{"id":"75d380.c445ac8","type":"http request","z":"780055b2.c3306c","name":"","method":"POST","ret":"txt","paytoqs":false,"url":"https://notify-api.line.me/api/notify","tls":"","persist":false,"proxy":"","authType":"","x":700,"y":160,"wires":[["e1dad027.dcc8b"]]},{"id":"e1dad027.dcc8b","type":"debug","z":"780055b2.c3306c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":750,"y":220,"wires":[]},{"id":"cd44885a.0ab348","type":"debug","z":"780055b2.c3306c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":370,"y":60,"wires":[]},{"id":"1e895ef0.0fdf81","type":"function","z":"780055b2.c3306c","name":"","func":"msg.payload='ON';\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":270,"y":300,"wires":[["56de513d.77d14"]]},{"id":"26ec090f.33d196","type":"function","z":"780055b2.c3306c","name":"","func":"msg.payload='OFF';\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":270,"y":360,"wires":[["56de513d.77d14"]]},{"id":"f0f03cd0.85978","type":"ui_text","z":"780055b2.c3306c","group":"6c9116b.b62d4e8","order":34,"width":0,"height":0,"name":"","label":"LINE  Message :   ","format":"{{msg.payload}}","layout":"row-left","x":560,"y":240,"wires":[]},{"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":"6c9116b.b62d4e8","type":"ui_group","name":"LED","tab":"53b8c8f9.cfbe48","order":1,"disp":true,"width":"6","collapse":false},{"id":"53b8c8f9.cfbe48","type":"ui_tab","name":"Home","icon":"dashboard","order":2,"disabled":false,"hidden":false}]


沒有留言:

張貼留言

Messaging API作為替代方案

  LINE超好用功能要沒了!LINE Notify明年3月底終止服務,有什麼替代方案? LINE Notify將於2025年3月31日結束服務,官方建議改用Messaging API作為替代方案。 //CHANNEL_ACCESS_TOKEN = 'Messaging ...