2020年10月7日 星期三

eWELink + Node-RED + Arduino

 eWELink + Node-RED + Arduino 




https://www.ruten.com.tw/item/show?21903585336836




#include <WiFi.h>

#include <PubSubClient.h>

#include <SPI.h>

#include "MFRC522.h"


const int RST_PIN = 22; // Reset pin

const int SS_PIN = 21; // Slave select pin

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

//esp32     mfrc522

//21        SDA

//18        SCK

//23        MOSI

//21        MISO

//22        RST

//GND       GND

//3.3v      3.3V

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

#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


MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance


//Variables

long lastMsg = 0;

char jsonChar[100];

String IDNo_buf="";


bool Flash = false;  //true

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

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


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

String printHex(byte *buffer, byte bufferSize) {

      String id = "";

      for (byte i = 0; i < bufferSize; i++) {

        id += buffer[i] < 0x10 ? "0" : "";

        id += String(buffer[i], HEX);

      }

      return id;

    }

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

void mqttConnectedCb() {

  Serial.println("connected");

  

  // Once connected, publish an announcement...

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

  // ... and resubscribe

  client.subscribe("alex9ufo/inTopic", 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);

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

  if (message[0] == '0') {

     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 0 , Send LOW TO BuildIn_LED");

     Flash = false; 

    } 

   if (message[0] == '1') {

     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 1 , Send HIGH TO BuildIn_LED");

     Flash = false;  

   }

    if (message[0] == '2') {

     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 2 , Flashing BuildIn_LED ");

     Flash = 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...."));

  SPI.begin();           // Init SPI bus

  mfrc522.PCD_Init();    // Init MFRC522

  Serial.println(F("Ready!"));

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

  Serial.println(F("Scan for Card and print UID:"));

}

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

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

  long now = millis();

  if (Flash)

  {

    digitalWrite(BUILTIN_LED, !digitalRead(BUILTIN_LED));

    delay(500);

  }


  

  if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) { // 如果出現新卡片就讀取卡片資料

     delay(100);

     String IDNo = printHex(mfrc522.uid.uidByte, mfrc522.uid.size);

     // Show some details of the PICC (that is: the tag/card)

     if ((IDNo != IDNo_buf) || (now - lastMsg > 5000)) {  //不同卡片 或是 等5秒

         lastMsg = now; 

         Serial.print(F("Card UID:"));

         Serial.println(IDNo);

         //Serial.println(IDNo_buf);

    

         IDNo_buf="";

         IDNo_buf=IDNo;

         // Convert data to JSON string 

         String json =

         "{\"data\":{"

         "\"RFID_No\": \"" + IDNo + "\"}"

         "}";

         // 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/outTopic/RFID/json",jsonChar);

         } 

      } // if ((IDNo != IDNo_buf) || (now - lastMsg > 5000))

  }  // if (mfrc522.PICC_IsNewCardPresent()


}   //Loop

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






[{"id":"51754690.ffee38","type":"mqtt in","z":"c1eadc43.582be","name":"","topic":"alex9ufo/led/led_status","qos":"1","datatype":"auto","broker":"841df58d.ee5e98","x":140,"y":60,"wires":[["94302818.ae36a8","96f2f0d8.1fbfa","d1d1e654.843568","b99597a3.65f958","eb018e99.e78b"]]},{"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":420,"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":100,"y":340,"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":100,"y":380,"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":380,"y":420,"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":300,"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":340,"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":440,"y":340,"wires":[["847c3e7e.3b5fc"]]},{"id":"847c3e7e.3b5fc","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":590,"y":340,"wires":[]},{"id":"d1d1e654.843568","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":390,"y":40,"wires":[]},{"id":"e473ddb0.8d753","type":"ui_audio","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","voice":"zh-TW","always":true,"x":340,"y":180,"wires":[]},{"id":"fc1ee7eb.f3c0d8","type":"ui_button","z":"c1eadc43.582be","name":"","group":"6c9116b.b62d4e8","order":0,"width":0,"height":0,"passthru":false,"label":"LED Toggle","tooltip":"","color":"blue","bgcolor":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","x":110,"y":420,"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}\nelse if (msg.payload === \"TOGGLE\") {\n  st1=\"LED ON OFF 交換\";\n}\n\nmsg.payload=st1;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":170,"y":180,"wires":[["e473ddb0.8d753","faeddd08.b340c","5b2052d1.e5ce1c"]]},{"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":120,"y":500,"wires":[["e4961251.9311c"]]},{"id":"f465a5e1.e917d8","type":"mysql","z":"c1eadc43.582be","mydb":"73a92d28.0c3eb4","name":"LED STATUS","x":380,"y":280,"wires":[["272e1d81.bb3b82"]]},{"id":"faeddd08.b340c","type":"function","z":"c1eadc43.582be","name":"MySQL Function","func":"var status = msg.payload ;\nmsg.topic = \"INSERT INTO mysql_led_status (`LED_MQTT_Status`) VALUES  ( '\" + status + \"');\"\nnode.status({text:msg.topic});\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":190,"y":260,"wires":[["f465a5e1.e917d8"]]},{"id":"272e1d81.bb3b82","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":550,"y":280,"wires":[]},{"id":"5b2052d1.e5ce1c","type":"function","z":"c1eadc43.582be","name":"INSERT","func":"msg.topic = \"INSERT INTO LED (time_led, led_status) VALUES (?,?)\";\n//msg.topic = \"INSERT INTO LED (id, time_led, led_status) VALUES (?,?,?)\";\n\n\nvar Today = new Date();\nvar yyyy = Today.getFullYear(); //年\nvar MM = Today.getMonth()+1;    //月\nvar dd = Today.getDate();       //日\nvar h = Today.getHours();       //時\nvar m = Today.getMinutes();     //分\nvar s = Today.getSeconds();     //秒\n\nif(MM<10)\n{\n   MM = '0'+MM;\n}\n\nif(dd<10)\n{\n   dd = '0'+dd;\n}\n\nif(h<10)\n{\n   h = '0'+h;\n}\n\nif(m<10)\n{\n  m = '0' + m;\n}\n\nif(s<10)\n{\n  s = '0' + s;\n}\n\nvar hms= yyyy + '/'+ MM + '/'+ dd + ' ' + h + ':' + m + ':' + s ;\n//var id= Date.now() ;\n//msg.payload = [id ,hms, msg.payload];\nmsg.payload = [hms, msg.payload];\n\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":340,"y":220,"wires":[["258da7b9.8fe668"]]},{"id":"258da7b9.8fe668","type":"sqlite","z":"c1eadc43.582be","mydb":"19f59ce9.3edc23","sqlquery":"msg.topic","sql":"","name":"LED Status","x":490,"y":220,"wires":[["c7736a87.ce1068"]]},{"id":"c7736a87.ce1068","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":650,"y":220,"wires":[]},{"id":"33f95dca.ec7452","type":"comment","z":"c1eadc43.582be","name":"publish 到 HiveMQ Broker ","info":"將 alex9ufo/led/led_event 發行到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":370,"y":480,"wires":[]},{"id":"734fd11b.3e4b4","type":"comment","z":"c1eadc43.582be","name":"向 HiveMQ Broker 訂閱subscribe","info":"將  Arduino 發行到(publish)HiveMQ Broker alex9ufo/led/led_status \n給 Node-red 或 MQTTB-Box 訂閱(Subscribe)","x":170,"y":20,"wires":[]},{"id":"6e3e7724.f64dc8","type":"debug","z":"c1eadc43.582be","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":550,"y":120,"wires":[]},{"id":"eb018e99.e78b","type":"ewelink-power-state-write","z":"c1eadc43.582be","name":"eWeLink-1","deviceId":"1000dad49d","channel":1,"auth":"53e58455.b9d5dc","x":390,"y":120,"wires":[["6e3e7724.f64dc8"]]},{"id":"b0cb85e5.cf8c38","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":120,"y":460,"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":"73a92d28.0c3eb4","type":"MySQLdatabase","z":"","name":"mysql_mqtt_led","host":"127.0.0.1","port":"3306","db":"mysql_mqtt_led","tz":"GMT +8"},{"id":"19f59ce9.3edc23","type":"sqlitedb","z":"","db":"MQTT_LED.db","mode":"RWC"},{"id":"53e58455.b9d5dc","type":"ewelink-credentials","z":""},{"id":"eeb8e179.a47a4","type":"ui_tab","z":"","name":"MySQL","icon":"dashboard","disabled":false,"hidden":false}]

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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