2023年7月13日 星期四

實驗 RFID + Node-Red +SQLite 建立資料庫 新增 刪除一筆 刪除全部資料 刪除資料庫

 實驗 RFID + Node-Red +SQLite 建立資料庫 新增 刪除一筆 刪除全部資料 刪除資料庫









[{"id":"fc2bc05aaeb53a69","type":"ui_button","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","order":21,"width":"3","height":"1","passthru":false,"label":"建立資料庫","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"建立資料庫","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":60,"wires":[["829a7127d56826ac","14eacaf6ab54d79d"]]},{"id":"4438df7c6a76e928","type":"ui_button","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","order":45,"width":"3","height":"1","passthru":false,"label":"檢視資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"檢視資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":260,"wires":[["494b685c1733dc8f","9e276d6d151de3a9"]]},{"id":"36c87a2c69aedce2","type":"ui_button","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","order":47,"width":"3","height":"1","passthru":false,"label":"刪除所有資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除所有資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":400,"wires":[["f6ae9a1ac227ccf2","9e276d6d151de3a9"]]},{"id":"8252e64dda450261","type":"sqlite","z":"7aebcf1d53039222","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_RFID_database","x":540,"y":60,"wires":[["168b6d52dfb43542"]]},{"id":"829a7127d56826ac","type":"function","z":"7aebcf1d53039222","name":"CREATE DATABASE","func":"\n\n//CREATE TABLE \"RFIDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"uidname\"  TEXT,\n//  \"currentdate\" DATE, \n//  \"currenttime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);\nmsg.topic = \"CREATE TABLE RFIDtable(id INTEGER PRIMARY KEY AUTOINCREMENT, uidname TEXT, currentdate DATE, currenttime TIME)\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":280,"y":60,"wires":[["8252e64dda450261"]]},{"id":"168b6d52dfb43542","type":"debug","z":"7aebcf1d53039222","name":"debug 97","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":740,"y":60,"wires":[]},{"id":"c0527e21b1adaf97","type":"function","z":"7aebcf1d53039222","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();     //秒\n\nvar var_date = yyyy+'/'+MM+'/'+dd;\nvar var_time = h+':'+m+':'+s;\n\nvar myRFID = msg.payload;\n\n\nmsg.topic = \"INSERT INTO RFIDtable ( uidname , currentdate, currenttime ) VALUES ($myRFID,  $var_date ,  $var_time ) \" ;\nmsg.payload = [myRFID, var_date , var_time ]\nreturn msg;\n\n//CREATE TABLE \"RFIDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"uidname\"  TEXT,\n//  \"currentdate\" DATE, \n//  \"currenttime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":100,"wires":[["4717378946fa2f42","8252e64dda450261"]]},{"id":"f6ae9a1ac227ccf2","type":"function","z":"7aebcf1d53039222","name":"刪除所有資料","func":"//DELETE from RFIDtable\nmsg.topic = \"DELETE from RFIDtable\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":320,"y":400,"wires":[["b8a824f5153c6fd8"]]},{"id":"b8a824f5153c6fd8","type":"sqlite","z":"7aebcf1d53039222","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_RFID_database","x":560,"y":380,"wires":[["9339112b5f11b666"]]},{"id":"22d6aa6b9b59b1ef","type":"ui_button","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","order":47,"width":"3","height":"1","passthru":false,"label":"刪除資料庫","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除資料庫","payloadType":"str","topic":"topic","topicType":"msg","x":90,"y":440,"wires":[["a19483da5e58cbf4","9e276d6d151de3a9"]]},{"id":"a19483da5e58cbf4","type":"function","z":"7aebcf1d53039222","name":"刪除資料庫","func":"//DROP TABLE RFIDtable\nmsg.topic = \"DROP TABLE RFIDtable\";\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":310,"y":440,"wires":[["b8a824f5153c6fd8"]]},{"id":"47110d4be5ce7045","type":"ui_template","z":"7aebcf1d53039222","group":"fe68da70e8d7a3c8","name":"","order":0,"width":"12","height":"10","format":"<table style=\"width:100%\">\n  <tr>\n    <th>idex</th> \n    <th>database_id</th>\n    <th>UID </th>\n    <th>Date</th>\n    <th>Times</th>\n  </tr>\n  \n  <tr ng-repeat=\"x in msg.payload | limitTo:50\">\n    <td>{{$index}}</td>\n    <td>{{msg.payload[$index].id}}</td>\n    <td>{{msg.payload[$index].uidname}}</td>\n    <td>{{msg.payload[$index].currentdate}}</td>\n    <td>{{msg.payload[$index].currenttime}}</td>\n  </tr>\n</table>","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":true,"templateScope":"local","className":"","x":760,"y":220,"wires":[[]]},{"id":"9339112b5f11b666","type":"debug","z":"7aebcf1d53039222","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":770,"y":380,"wires":[]},{"id":"494b685c1733dc8f","type":"function","z":"7aebcf1d53039222","name":"檢視資料","func":"\n//CREATE TABLE \"RFIDtable\" (\n//\t\"id\"\tINT NOT NULL,\n//  \"uidname\"  TEXT,\n//  \"currentdate\" DATE, \n//  \"currenttime\" TIME\n//\tPRIMARY KEY(\"id\")\n//);\n\n//SELECT * FROM RFIDtable ORDER BY  id DESC LIMIT 50;\n\nmsg.topic = \"SELECT * FROM RFIDtable ORDER BY  id DESC LIMIT 50\";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":220,"wires":[["313ed708cbe77e86"]]},{"id":"313ed708cbe77e86","type":"sqlite","z":"7aebcf1d53039222","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"","name":"My_RFID_database","x":540,"y":220,"wires":[["47110d4be5ce7045","1a261bc18a1f5965"]]},{"id":"95fbcdf86ed8fbcb","type":"function","z":"7aebcf1d53039222","name":"SELECT ALL","func":"var del_idtemp=msg.payload;\nflow.set(\"idtemp\", del_idtemp);\n\nmsg.topic = \"SELECT * FROM RFIDtable \";\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":310,"y":360,"wires":[["b8a824f5153c6fd8","f9cbb712b6ee61a0"]]},{"id":"a1677f0f8fd20351","type":"function","z":"7aebcf1d53039222","name":"確認 刪除","func":"var del_id = flow.get(\"idtemp\");\n\n\nmsg.topic = \"DELETE FROM RFIDtable WHERE id= ($del_id) \" ;\nmsg.payload = [del_id]\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":300,"wires":[["a696ffa0a72fbd77"]]},{"id":"6395bc41a36b7b4f","type":"ui_numeric","z":"7aebcf1d53039222","name":"","label":"刪除的database_id","tooltip":"","group":"fe68da70e8d7a3c8","order":30,"width":"4","height":"1","wrap":false,"passthru":true,"topic":"topic","topicType":"msg","format":"{{value}}","min":"1","max":"100","step":1,"className":"","x":110,"y":360,"wires":[["95fbcdf86ed8fbcb","9e276d6d151de3a9"]]},{"id":"a696ffa0a72fbd77","type":"sqlite","z":"7aebcf1d53039222","mydb":"dd7f8134e015a1cb","sqlquery":"msg.topic","sql":"DELETE FROM dhtreadings WHERE id =  VALUES ($theid)","name":"My_RFID_database","x":480,"y":300,"wires":[["1a261bc18a1f5965"]]},{"id":"1a261bc18a1f5965","type":"debug","z":"7aebcf1d53039222","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":730,"y":300,"wires":[]},{"id":"dd7e69860ea9730d","type":"ui_button","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","order":44,"width":"3","height":"1","passthru":false,"label":"刪除一筆資料","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"刪除一筆資料","payloadType":"str","topic":"topic","topicType":"msg","x":100,"y":300,"wires":[["a1677f0f8fd20351","9e276d6d151de3a9"]]},{"id":"f9cbb712b6ee61a0","type":"debug","z":"7aebcf1d53039222","name":"debug 98","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":480,"y":340,"wires":[]},{"id":"caa123a28d1ba978","type":"mqtt in","z":"7aebcf1d53039222","name":"新增 RFID","topic":"alex9ufo/esp32/RFID","qos":"2","datatype":"auto-detect","broker":"841df58d.ee5e98","nl":false,"rap":true,"rh":0,"inputs":0,"x":80,"y":140,"wires":[["c0527e21b1adaf97","2dddad4e20242887","b59d1f7d9c7476ae"]]},{"id":"4717378946fa2f42","type":"debug","z":"7aebcf1d53039222","name":"debug 100","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":510,"y":100,"wires":[]},{"id":"2dddad4e20242887","type":"ui_text_input","z":"7aebcf1d53039222","name":"","label":"新增一筆資料","tooltip":"","group":"fe68da70e8d7a3c8","order":7,"width":0,"height":0,"passthru":true,"mode":"text","delay":300,"topic":"topic","sendOnBlur":true,"className":"","topicType":"msg","x":320,"y":140,"wires":[[]]},{"id":"db8cbbfbf7372391","type":"ui_audio","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":440,"y":180,"wires":[]},{"id":"b59d1f7d9c7476ae","type":"function","z":"7aebcf1d53039222","name":"function ","func":"var temp= msg.payload;\nmsg.payload= \"新增一筆資料\" + temp;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":300,"y":180,"wires":[["db8cbbfbf7372391"]]},{"id":"9e276d6d151de3a9","type":"ui_audio","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":300,"y":260,"wires":[]},{"id":"14eacaf6ab54d79d","type":"ui_audio","z":"7aebcf1d53039222","name":"","group":"fe68da70e8d7a3c8","voice":"Microsoft Hanhan - Chinese (Traditional, Taiwan)","always":true,"x":260,"y":20,"wires":[]},{"id":"fe68da70e8d7a3c8","type":"ui_group","name":"2023 RFID","tab":"eeb8e179.a47a4","order":3,"disp":true,"width":"10","collapse":false,"className":""},{"id":"dd7f8134e015a1cb","type":"sqlitedb","db":"C:\\Users\\User\\.node-red\\my_2023rfid.db","mode":"RWC"},{"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":"RFID Database","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 *mqtt_username = "alex9ufo";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

bool ledState = false;

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

long lastMsg = 0;
char msg[50];
String json = "";    
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() {
    // Set software serial baud to 115200;
    Serial.begin(115200);
    delay(1000); // Delay for stability
    //======================================================
    // Connecting to a WiFi network
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.println("Connecting to WiFi...");
    }
    Serial.println("Connected to the WiFi network");

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

}
//===========================================================
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;
    }
    if (message == "off" && ledState) {
        digitalWrite(LED, LOW); // Turn off the LED
        ledState = false;
    }
    Serial.println();
    Serial.println("-----------------------");
}
//===========================================================
void loop() {
    client.loop();
    delay(100); // Delay for a short period in each loop iteration
    long now = millis();
    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

        }
      }
       
  }

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

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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