2023年8月2日 星期三

RFID 實驗2-1 Node-RED , MQTT , ESP32 LED , SQLite , Line Notify

 RFID 實驗2-1 Node-RED , MQTT , ESP32 LED , SQLite , Line Notify








[{"id":"f7dae001c3314160","type":"comment","z":"bfec384c4faa9831","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":210,"y":40,"wires":[]},{"id":"dbc2bfd8348eec63","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":1,"width":2,"height":1,"passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"on","payloadType":"str","topic":"","topicType":"str","x":80,"y":80,"wires":[["cde8627353ccec65","0172f5806f2ca578","812263efbd257749"]]},{"id":"cde8627353ccec65","type":"mqtt out","z":"bfec384c4faa9831","name":"Control LED","topic":"alex9ufo/esp32/led","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"70940176.2b2d3","x":330,"y":80,"wires":[]},{"id":"e24b7e110800a06c","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":2,"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":80,"y":120,"wires":[["cde8627353ccec65","0172f5806f2ca578","812263efbd257749"]]},{"id":"d970e8fdf4530916","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":5,"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":80,"y":160,"wires":[["cde8627353ccec65","812263efbd257749","0172f5806f2ca578"]]},{"id":"812263efbd257749","type":"ui_text","z":"bfec384c4faa9831","group":"bcc5d75a99cd926e","order":7,"width":8,"height":1,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":390,"y":160,"wires":[]},{"id":"951bd841abaf9ec2","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":4,"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":80,"y":200,"wires":[["cde8627353ccec65","812263efbd257749","0172f5806f2ca578"]]},{"id":"42cce06e0e1c8c30","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":3,"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":90,"y":240,"wires":[["cde8627353ccec65","812263efbd257749","0172f5806f2ca578"]]},{"id":"0172f5806f2ca578","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","voice":"zh-TW","always":true,"x":320,"y":220,"wires":[]},{"id":"54711505154b656f","type":"comment","z":"bfec384c4faa9831","name":"Node-Red  subscribe HiveMQ Broker  , ESP32發行","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":200,"y":280,"wires":[]},{"id":"80030d0c3958e845","type":"comment","z":"bfec384c4faa9831","name":"Line Notify Message ","info":"","x":570,"y":280,"wires":[]},{"id":"a073d5b3a5535cf6","type":"function","z":"bfec384c4faa9831","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":430,"y":320,"wires":[["8349d1f3d7a98121"]]},{"id":"e5420d3f682a2646","type":"mqtt in","z":"bfec384c4faa9831","name":"LED status ","topic":"alex9ufo/esp32/led_status","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":80,"y":360,"wires":[["7cb9d91737b872eb"]]},{"id":"7cb9d91737b872eb","type":"function","z":"bfec384c4faa9831","name":"function 63","func":"msg.payload=\" ---ESP32回來資料---\" +msg.payload;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":250,"y":360,"wires":[["b6d4e95834b3e0b2","1b7d27c545c0f092","a073d5b3a5535cf6"]]},{"id":"8349d1f3d7a98121","type":"http request","z":"bfec384c4faa9831","name":"","method":"POST","ret":"txt","paytoqs":false,"url":"https://notify-api.line.me/api/notify","tls":"","persist":false,"proxy":"","authType":"","x":600,"y":320,"wires":[["c552b46647524559"]]},{"id":"c552b46647524559","type":"debug","z":"bfec384c4faa9831","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":750,"y":320,"wires":[]},{"id":"74c7723fda8e695c","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","voice":"en-US","always":"","x":560,"y":360,"wires":[]},{"id":"1b7d27c545c0f092","type":"delay","z":"bfec384c4faa9831","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":420,"y":360,"wires":[["74c7723fda8e695c"]]},{"id":"b6d4e95834b3e0b2","type":"ui_text","z":"bfec384c4faa9831","group":"bcc5d75a99cd926e","order":9,"width":8,"height":1,"name":"","label":"Node-RED 訂閱MQTT的資料","format":"{{msg.payload}}","layout":"row-left","className":"","x":480,"y":400,"wires":[]},{"id":"984acdd346d0bfb5","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":14,"width":3,"height":1,"passthru":false,"label":"建立資料庫","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"建立資料庫","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":440,"wires":[["3c17346ebaadcc29","cebc47e42b341ffe"]]},{"id":"3c17346ebaadcc29","type":"function","z":"bfec384c4faa9831","name":"CREATE DATABASE","func":"\n\n//CREATE TABLE \"LEDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"Status\"  TEXT,\n//  \"Ldate\" DATE, \n//  \"Ltime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);\nmsg.topic = \"CREATE TABLE LEDtable(id INTEGER PRIMARY KEY AUTOINCREMENT, Status TEXT, Ldate DATE, Ltime TIME)\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":480,"wires":[["090c3511cbd3d21a","a734f3d3f88d868e"]]},{"id":"cebc47e42b341ffe","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":260,"y":440,"wires":[]},{"id":"a734f3d3f88d868e","type":"function","z":"bfec384c4faa9831","name":"function 64","func":"var ms1=msg.payload[0];\nvar ms2=msg.payload[1];\nvar ms3=msg.payload[2];\n\nmsg.payload=\"新增一筆:\"+ms1+\", 日期: \"+ms2+\", 時間:\"+ms3;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":530,"y":440,"wires":[["31d42b1c09c073ca"]]},{"id":"31d42b1c09c073ca","type":"function","z":"bfec384c4faa9831","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":690,"y":440,"wires":[["834c0e3dc5b602bd"]]},{"id":"834c0e3dc5b602bd","type":"http request","z":"bfec384c4faa9831","name":"","method":"POST","ret":"txt","paytoqs":false,"url":"https://notify-api.line.me/api/notify","tls":"","persist":false,"proxy":"","authType":"","x":840,"y":440,"wires":[["cea6743652f08715"]]},{"id":"cea6743652f08715","type":"debug","z":"bfec384c4faa9831","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":970,"y":440,"wires":[]},{"id":"cfe32a2328c0d4a6","type":"comment","z":"bfec384c4faa9831","name":"Line Notify Message ","info":"","x":750,"y":400,"wires":[]},{"id":"cbfa761aac341775","type":"function","z":"bfec384c4faa9831","name":"檢視資料","func":"\n//CREATE TABLE \"RFIDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"Status\"  TEXT,\n//  \"Ldate\" DATE, \n//  \"Ltime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);\n\n//SELECT * FROM RFIDtable ORDER BY  id DESC LIMIT 50;\n\nmsg.topic = \"SELECT * FROM LEDtable ORDER BY id DESC LIMIT 50\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":540,"y":540,"wires":[["4602c172fa6b66ea"]]},{"id":"090c3511cbd3d21a","type":"sqlite","z":"bfec384c4faa9831","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_LED_database","x":530,"y":480,"wires":[["cbfa761aac341775","79fcb800cd598e68"]]},{"id":"4602c172fa6b66ea","type":"sqlite","z":"bfec384c4faa9831","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_LED_database","x":710,"y":540,"wires":[["9e060230c9354091"]]},{"id":"9e060230c9354091","type":"ui_table","z":"bfec384c4faa9831","group":"bcc5d75a99cd926e","name":"","order":16,"width":11,"height":8,"columns":[],"outputs":0,"cts":false,"x":870,"y":540,"wires":[]},{"id":"33b812997a1eaaf9","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":15,"width":5,"height":1,"passthru":false,"label":"檢視資料庫資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"檢視資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":540,"wires":[["99846cf16ee4af96","cbfa761aac341775"]]},{"id":"99846cf16ee4af96","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":280,"y":520,"wires":[]},{"id":"2e0974f4d7c58555","type":"function","z":"bfec384c4faa9831","name":"function ","func":"var temp= msg.payload;\nmsg.payload= \"新增一筆資料\" + temp;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":280,"y":640,"wires":[["8305de5e9264b0bc"]]},{"id":"c69e8880a8799c71","type":"ui_text","z":"bfec384c4faa9831","group":"bcc5d75a99cd926e","order":8,"width":3,"height":2,"name":"","label":"LED Status","format":"<font face='arial'><font size=4><font color={{fcolor}}>{{msg.payload}}","layout":"row-left","className":"","x":690,"y":640,"wires":[]},{"id":"a99150555b9286ba","type":"function","z":"bfec384c4faa9831","name":"INSERT","func":"var 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();     //秒\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}\nvar var_date = yyyy+'/'+MM+'/'+dd;\nvar var_time = h+':'+m+':'+s;\n\nvar myLED = msg.payload;\n\n\nmsg.topic = \"INSERT INTO LEDtable ( Status , Ldate, Ltime ) VALUES ($myLED,  $var_date ,  $var_time ) \" ;\nmsg.payload = [myLED, var_date , var_time ]\nreturn msg;\n\n//CREATE TABLE \"LEDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"Status\"  TEXT,\n//  \"Ldate\" DATE, \n//  \"Ltime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":280,"y":600,"wires":[["090c3511cbd3d21a","2f37f0399feb180d"]]},{"id":"79fcb800cd598e68","type":"debug","z":"bfec384c4faa9831","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":730,"y":480,"wires":[]},{"id":"2f37f0399feb180d","type":"debug","z":"bfec384c4faa9831","name":"debug ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":430,"y":600,"wires":[]},{"id":"cf8fb7ae79a7894c","type":"mqtt in","z":"bfec384c4faa9831","name":"LED status ","topic":"alex9ufo/esp32/led_status","qos":"2","datatype":"utf8","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":80,"y":600,"wires":[["a99150555b9286ba","2e0974f4d7c58555"]]},{"id":"8305de5e9264b0bc","type":"change","z":"bfec384c4faa9831","name":"","rules":[{"t":"set","p":"fcolor","pt":"msg","to":"red","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":440,"y":640,"wires":[["c69e8880a8799c71"]]},{"id":"c6125fb76a7fc1af","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":10,"width":3,"height":1,"passthru":false,"label":"刪除一筆資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除一筆資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":680,"wires":[["616db8f2855471e2","0d2bdf1382ec6de6"]]},{"id":"616db8f2855471e2","type":"function","z":"bfec384c4faa9831","name":"確認 刪除","func":"var del_id = flow.get(\"idtemp\");\n\nmsg.topic = \"DELETE FROM LEDtable WHERE id= ($del_id) \" ;\nmsg.payload = [del_id]\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":720,"wires":[["d9106170c3221428"]]},{"id":"d9106170c3221428","type":"sqlite","z":"bfec384c4faa9831","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"DELETE FROM dhtreadings WHERE id =  VALUES ($theid)","name":"My_LED_database","x":510,"y":720,"wires":[["cbfa761aac341775"]]},{"id":"db47617b0c9644d4","type":"debug","z":"bfec384c4faa9831","name":"debug 158","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":470,"y":800,"wires":[]},{"id":"47898d2d6a579a1d","type":"function","z":"bfec384c4faa9831","name":"SELECT ALL","func":"var del_idtemp=msg.payload;\nflow.set(\"idtemp\", del_idtemp);\n\nmsg.topic = \"SELECT * FROM LEDtable \";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":290,"y":800,"wires":[["4226de1a2c6402ec","db47617b0c9644d4"]]},{"id":"41b0a12dd8b06e59","type":"ui_numeric","z":"bfec384c4faa9831","name":"","label":"刪除的database_id","tooltip":"","group":"bcc5d75a99cd926e","order":11,"width":5,"height":1,"wrap":false,"passthru":true,"topic":"topic","topicType":"msg","format":"{{value}}","min":"1","max":"100","step":1,"className":"","x":110,"y":800,"wires":[["47898d2d6a579a1d","a7e7d69290dc1425"]]},{"id":"aefb902f83df4c6b","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":13,"width":3,"height":1,"passthru":false,"label":"刪除所有資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除所有資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":840,"wires":[["f8c86f7fd5094c39","a7e7d69290dc1425"]]},{"id":"025ac1787ba3952e","type":"ui_button","z":"bfec384c4faa9831","name":"","group":"bcc5d75a99cd926e","order":12,"width":3,"height":1,"passthru":false,"label":"刪除資料庫","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除資料庫","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":880,"wires":[["a665f6f582a9f77c","a7e7d69290dc1425"]]},{"id":"a665f6f582a9f77c","type":"function","z":"bfec384c4faa9831","name":"刪除資料庫","func":"//DROP TABLE LEDtable\nmsg.topic = \"DROP TABLE LEDtable\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":290,"y":880,"wires":[["4226de1a2c6402ec"]]},{"id":"f8c86f7fd5094c39","type":"function","z":"bfec384c4faa9831","name":"刪除所有資料","func":"//DELETE from LEDtable\nmsg.topic = \"DELETE from LEDtable\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":840,"wires":[["4226de1a2c6402ec"]]},{"id":"a7e7d69290dc1425","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"9eb91d4467c6eec5","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":300,"y":760,"wires":[]},{"id":"4226de1a2c6402ec","type":"sqlite","z":"bfec384c4faa9831","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_LED_database","x":510,"y":840,"wires":[["635fd1b5abfa8a5a"]]},{"id":"635fd1b5abfa8a5a","type":"debug","z":"bfec384c4faa9831","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":690,"y":840,"wires":[]},{"id":"0d2bdf1382ec6de6","type":"ui_audio","z":"bfec384c4faa9831","name":"","group":"9eb91d4467c6eec5","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":300,"y":680,"wires":[]},{"id":"bcc5d75a99cd926e","type":"ui_group","name":"LED CONTROL","tab":"e01b6f.a9d07c9","order":2,"disp":true,"width":11,"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":"dd7f8134e015a1cb","type":"sqlitedb","db":"C:\\Users\\User\\.node-red\\my_2023LED.db","mode":"RWC"},{"id":"9eb91d4467c6eec5","type":"ui_group","name":"Default","tab":"23af251c8a87881d","order":1,"disp":true,"width":"14","collapse":false,"className":""},{"id":"e01b6f.a9d07c9","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false},{"id":"23af251c8a87881d","type":"ui_tab","name":"Home_RFID","icon":"dashboard","disabled":false,"hidden":false}]

#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <MFRC522.h>
// GPIO 2 D1
#define LED 2
/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
 *             MFRC522      ESP32     Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD             Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin       Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          GPIO27    9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      GPIO5     10            53        D10        10               10
 * SPI MOSI    MOSI         GPIO23    11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         GPIO19    12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          GPIO18    13 / ICSP-3   52        D13        ICSP-3           15
 *
[1] (1, 2) Configurable, typically defined as RST_PIN in sketch/program.
[2] (1, 2) Configurable, typically defined as SS_PIN in sketch/program.
[3] The SDA pin might be labeled SS on some/older MFRC522 boards
=============================================================================
*/

#define SS_PIN  5  // ESP32 pin GIOP5
#define RST_PIN 27 // ESP32 pin GIOP27


// WiFi
const char *ssid = "alex9ufo"; // Enter your Wi-Fi name
const char *password = "alex9981";  // Enter Wi-Fi password

// MQTT Broker
const char *mqtt_broker = "broker.mqtt-dashboard.com";
const char *topic1 = "alex9ufo/esp32/led";
const char *topic2 = "alex9ufo/esp32/RFID";
const char *topic = "alex9ufo/esp32/Starting";
const char *topic3 = "alex9ufo/esp32/led_status";



const char *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

bool ledState = false;
bool atwork = false;

WiFiClient espClient;
PubSubClient client(espClient);
MFRC522 rfid(SS_PIN, RST_PIN); // Create MFRC522 instance

long lastMsg = 0;
long lastMsg1= 0;

char msg[50];
String json = "";
bool Flash = false;  //true
bool Timer = false;  //true
bool Send = false;  //true
int Count= 0;

char jsonChar1[100];  //client.publish("alex9ufo/Esp32/RFID"
//===========================================================
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 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("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}    
//===========================================================
void setup() {
    // Set software serial baud to 115200;
    Serial.begin(115200);
    delay(1000); // Delay for stability
    //======================================================
    // Connecting to a WiFi network
    setup_wifi();
    // Setting LED pin as output
    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);  // Turn off the LED initially
    //======================================================
    SPI.begin();           // Init SPI bus
    rfid.PCD_Init();    // Init MFRC522

    Serial.println(F("Ready!"));
    Serial.println(F("======================================================"));
    Serial.println("Tap an RFID/NFC tag on the RFID-RC522 reader");


    // Connecting to an MQTT broker
    client.setServer(mqtt_broker, 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);
    client.publish(topic,"ESP32 at work");
}
//===========================================================
void callback(char *topic, byte *payload, unsigned int length) {
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message: ");
    String message;
    for (int i = 0; i < length; i++) {
        message += (char) payload[i];  // Convert *byte to string
    }
    Serial.print(message);
    if (message == "on" && !ledState) {
        digitalWrite(LED, HIGH);  // Turn on the LED
        ledState = true;  //ledState = ture HIGH
        Flash = false;
        Timer = false;
        json ="ON";
        Send = true ;
    }
    if (message == "off" && ledState) {
        digitalWrite(LED, LOW); // Turn off the LED
        ledState = false; //ledState = false LOW
        Flash = false;
        Timer = false;
        json ="OFF";
        Send = true ;

    }
    if (message == "flash" ) {
        digitalWrite(LED, LOW); // Turn off the LED
        Flash = true;
        Timer = false;
        json ="FLASH";
        Send = true ;        

    }
    if (message == "timer" ) {
        digitalWrite(LED, LOW); // Turn off the LED
        Flash = false;
        Timer = true;
        json ="TIMER";
        Send = true ;
        Count= 11;
    }

    if (message == "toggle" ) {
        digitalWrite(LED, !digitalRead(LED));   // Turn the LED toggle
        if (digitalRead(LED))
            ledState = true;
        else
            ledState = false;
       
        Flash = false;
        Timer = false;
        json ="TOGGLE";
        Send = true ;        
    }

    Serial.println();
    Serial.println("-----------------------");
}
//===========================================================
void loop() {
    client.loop();
    delay(100); // Delay for a short period in each loop iteration
    if (Flash){
        digitalWrite(LED, !digitalRead(LED));
        delay(500);
        if (digitalRead(LED))
            ledState = true;
        else
            ledState = false;
    } //(Flash)
       
    if (Timer) {
        digitalWrite(LED, HIGH);
        delay(500);
        if (digitalRead(LED))
            ledState = true;
        else
            ledState = false;

        Count=Count-1;
        if (Count == 0 ){
            Timer=false;
            digitalWrite(LED, LOW);
            ledState = false;
        }
    } //(Timer)
   
    if (client.connected()) {        
        if (Send) {
          // Convert JSON string to character array
          json.toCharArray(jsonChar1, json.length()+1);
          Serial.print("Publish message: ");
          Serial.println(json);
          // Publish JSON character array to MQTT topic
          client.publish(topic3,jsonChar1);
        }
        Send = false;    
    }

    long now = millis();
    long now1 = millis();
    if (now1 - lastMsg1 > 80000) {
        lastMsg1 = now1;
        if (atwork) {
            client.publish(topic,"ESP32 at work");
            atwork=false;
        } else {
            client.publish(topic,"             ");
            atwork=true;
        }
     }
     
    if (now - lastMsg > 5000) {
      Serial.println("Reading RFIF card");
      lastMsg = now;
      if (rfid.PICC_IsNewCardPresent()) { // new tag is available
        if (rfid.PICC_ReadCardSerial()) { // NUID has been readed
          MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
          Serial.print("RFID/NFC Tag Type: ");
          Serial.println(rfid.PICC_GetTypeName(piccType));

          // print UID in Serial Monitor in the hex format
          Serial.print("UID:");
          for (int i = 0; i < rfid.uid.size; i++) {
            Serial.print(rfid.uid.uidByte[i] < 0x10 ? " 0" : " ");
            Serial.print(rfid.uid.uidByte[i], HEX);
          }
          Serial.println();

          String json = printHex(rfid.uid.uidByte, rfid.uid.size);
          // Convert JSON string to character array
          json.toCharArray(jsonChar1, json.length()+1);
   
          if  (client.connected()) {
            Serial.print("Publish message: ");
            Serial.println(json);
            // Publish JSON character array to MQTT topic
            client.publish(topic2,jsonChar1);
          }    
          rfid.PICC_HaltA(); // halt PICC
          rfid.PCD_StopCrypto1(); // stop encryption on PCD
         
         
        }
      }
       
  }

}
//===========================================================


沒有留言:

張貼留言

Messaging API作為替代方案

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