2023年6月14日 星期三

實驗2-1 LED control (MQTT + Node-Red + Sqlite + Li ne Notify)

 實驗2-1 LED control (MQTT + Node-Red + Sqlite + Li ne Notify)





[{"id":"57da059ec95e597e","type":"mqtt in","z":"5f992d028747508b","name":"","topic":"alex9ufo/led/led_status","qos":"1","datatype":"auto","broker":"841df58d.ee5e98","inputs":0,"x":140,"y":80,"wires":[["b2eba4ee3ad04a9b","1f1bf165106c3364","800138e2fa6b5a95"]]},{"id":"cf7929e1dc1f49f6","type":"ui_text","z":"5f992d028747508b","group":"46aabdb0f7bc62c1","order":0,"width":0,"height":0,"name":"","label":"ESP32發行到MQTT的資料","format":"{{msg.payload}}","layout":"col-center","className":"","x":440,"y":120,"wires":[]},{"id":"9966a56e4c194e95","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":0,"width":"3","height":"1","passthru":false,"label":"LED 開","tooltip":"","color":"white","bgcolor":"","className":"","icon":"fa-circle","payload":"ON","payloadType":"str","topic":"","topicType":"str","x":120,"y":400,"wires":[["953a7c0c5f0b9bb3","059c2cebf07ca67c","49e1085191a13188"]]},{"id":"8944c3c632b4881d","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":0,"width":"3","height":"1","passthru":false,"label":"LED 關","tooltip":"","color":"black","bgcolor":"","className":"","icon":"fa-circle-o","payload":"OFF","payloadType":"str","topic":"","topicType":"str","x":120,"y":440,"wires":[["953a7c0c5f0b9bb3","059c2cebf07ca67c","49e1085191a13188"]]},{"id":"953a7c0c5f0b9bb3","type":"mqtt out","z":"5f992d028747508b","name":"Control LED","topic":"alex9ufo/inTopic/led/led_event","qos":"1","retain":"true","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"841df58d.ee5e98","x":390,"y":500,"wires":[]},{"id":"b2eba4ee3ad04a9b","type":"function","z":"5f992d028747508b","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":170,"y":260,"wires":[["ce9a650f65d05095"]]},{"id":"ce9a650f65d05095","type":"function","z":"5f992d028747508b","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":350,"y":260,"wires":[["fd5234723ea48f84"]]},{"id":"fd5234723ea48f84","type":"http request","z":"5f992d028747508b","name":"","method":"POST","ret":"txt","paytoqs":false,"url":"https://notify-api.line.me/api/notify","tls":"","persist":false,"proxy":"","authType":"","x":520,"y":260,"wires":[["ba8df1f296e206e3"]]},{"id":"ba8df1f296e206e3","type":"debug","z":"5f992d028747508b","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":670,"y":260,"wires":[]},{"id":"1f1bf165106c3364","type":"debug","z":"5f992d028747508b","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":390,"y":80,"wires":[]},{"id":"d2dcb00d2dfa1eb4","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":0,"width":"3","height":"1","passthru":false,"label":"LED 開關反向","tooltip":"","color":"blue","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TOGGLE","payloadType":"str","topic":"","topicType":"str","x":140,"y":480,"wires":[["953a7c0c5f0b9bb3","059c2cebf07ca67c","49e1085191a13188"]]},{"id":"800138e2fa6b5a95","type":"function","z":"5f992d028747508b","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":250,"y":180,"wires":[["cf7929e1dc1f49f6","83a40f62df09f249","6b8c3a1c3cec0397"]]},{"id":"ad0eea0d1ef039a1","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":0,"width":"3","height":"1","passthru":false,"label":"LED 開5秒鐘","tooltip":"","color":"purple","bgcolor":"","className":"","icon":"fa-circle-o","payload":"TIMER","payloadType":"str","topic":"","topicType":"str","x":130,"y":560,"wires":[["953a7c0c5f0b9bb3","059c2cebf07ca67c","49e1085191a13188"]]},{"id":"f23457d961919b2b","type":"debug","z":"5f992d028747508b","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":690,"y":220,"wires":[]},{"id":"543e002f781ad1de","type":"comment","z":"5f992d028747508b","name":"Node-Red publish 到 HiveMQ Broker  , ESP32訂閱","info":"將 alex9ufo/inTopic 到(publish)HiveMQ Broker \n給 Arduino 訂閱(Subscribe)","x":250,"y":600,"wires":[]},{"id":"432d059452c3d17a","type":"comment","z":"5f992d028747508b","name":"ESP32向 HiveMQ Broker發行 Node-Red 訂閱subscribe","info":"將  Arduino 發行到(publish)HiveMQ Broker alex9ufo/led/led_status \n給 Node-red 或 MQTTB-Box 訂閱(Subscribe)","x":240,"y":40,"wires":[]},{"id":"9635ae8f45d96599","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":0,"width":"3","height":"1","passthru":false,"label":"LED 閃爍","tooltip":"","color":"yellow","bgcolor":"","className":"","icon":"fa-circle-o","payload":"FLASH","payloadType":"str","topic":"","topicType":"str","x":120,"y":520,"wires":[["953a7c0c5f0b9bb3","059c2cebf07ca67c","49e1085191a13188"]]},{"id":"059c2cebf07ca67c","type":"ui_audio","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","voice":"zh-TW","always":true,"x":380,"y":560,"wires":[]},{"id":"49e1085191a13188","type":"ui_text","z":"5f992d028747508b","group":"46aabdb0f7bc62c1","order":0,"width":0,"height":0,"name":"","label":"Node-RED發行到MQTT的資料","format":"{{msg.payload}}","layout":"row-center","className":"","x":430,"y":440,"wires":[]},{"id":"789671ac55f5b9f5","type":"inject","z":"5f992d028747508b","name":"CREATE","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":140,"y":340,"wires":[["4885df399c5b715b"]]},{"id":"e11b3ada51352da1","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":11,"width":"4","height":"1","passthru":false,"label":"建立資料庫(LED只能執行一次)","tooltip":"","color":"","bgcolor":" purple","className":"","icon":"","payload":"","payloadType":"str","topic":"","topicType":"str","x":170,"y":300,"wires":[["4885df399c5b715b"]]},{"id":"4885df399c5b715b","type":"sqlite","z":"5f992d028747508b","mydb":"af927aba.0dc108","sqlquery":"fixed","sql":"CREATE TABLE LEDS (id INTEGER, timeled TEXT,ledstatus TEXT, PRIMARY KEY(id AUTOINCREMENT))","name":"CREATE led.db","x":400,"y":340,"wires":[["2b9972183f540956"]]},{"id":"2b9972183f540956","type":"debug","z":"5f992d028747508b","name":"debug  ","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":550,"y":340,"wires":[]},{"id":"caab6a99213a0d02","type":"ui_button","z":"5f992d028747508b","name":"","group":"46aabdb0f7bc62c1","order":10,"width":"3","height":"1","passthru":false,"label":"View Data (LED)","tooltip":"","color":"","bgcolor":"","className":"","icon":"","payload":"檢視LED資料庫","payloadType":"str","topic":"SELECT * FROM LEDS ORDER BY  id  DESC LIMIT 100;","topicType":"str","x":470,"y":160,"wires":[["852ed9b9ce5989cd","83a40f62df09f249"]]},{"id":"83a40f62df09f249","type":"ui_text_input","z":"5f992d028747508b","name":"","label":"","tooltip":"","group":"46aabdb0f7bc62c1","order":9,"width":0,"height":0,"passthru":true,"mode":"text","delay":"0","topic":"","sendOnBlur":true,"className":"","topicType":"str","x":660,"y":180,"wires":[["dd7cf3a4df736de4"]]},{"id":"dd7cf3a4df736de4","type":"ui_audio","z":"5f992d028747508b","name":"播放聲音","group":"46aabdb0f7bc62c1","voice":"Google 國語(臺灣)","always":true,"x":800,"y":180,"wires":[]},{"id":"852ed9b9ce5989cd","type":"sqlite","z":"5f992d028747508b","mydb":"af927aba.0dc108","sqlquery":"msg.topic","sql":"","name":"LED","x":650,"y":140,"wires":[["3f1f8e28d531b7cc"]]},{"id":"3f1f8e28d531b7cc","type":"ui_template","z":"5f992d028747508b","group":"46aabdb0f7bc62c1","name":"","order":0,"width":"12","height":"4","format":"<table style=\"width:100%\">\n  <tr>\n    <th>Index</th> \n    <th>Time</th> \n    <th>STATUS</th>\n  </tr>\n  <tr ng-repeat=\"x in msg.payload | limitTo:20\">\n    <td>{{$index}}</td>\n    <td>{{msg.payload[$index].timeled}}</td>\n    <td>{{msg.payload[$index].ledstatus}}</td> \n  </tr>\n</table>","storeOutMessages":true,"fwdInMessages":true,"resendOnRefresh":false,"templateScope":"local","className":"","x":800,"y":140,"wires":[[]]},{"id":"6b8c3a1c3cec0397","type":"function","z":"5f992d028747508b","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.params = { $thetime:hms, $thevalue:msg.payload }\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":380,"y":220,"wires":[["96acafbee0f35c78"]]},{"id":"96acafbee0f35c78","type":"sqlite","z":"5f992d028747508b","mydb":"af927aba.0dc108","sqlquery":"prepared","sql":"insert into LEDS(timeled ,ledstatus) values ($thetime , $thevalue)\n","name":"LED","x":510,"y":220,"wires":[["f23457d961919b2b"]]},{"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":"46aabdb0f7bc62c1","type":"ui_group","name":"LED讀取","tab":"2bf82b8e33f9dd7c","order":1,"disp":true,"width":"15","collapse":false},{"id":"af927aba.0dc108","type":"sqlitedb","db":"C:\\Users\\User\\.node-red\\rfid_led.db","mode":"RWC"},{"id":"2bf82b8e33f9dd7c","type":"ui_tab","name":"LED","icon":"dashboard","order":1,"disabled":false,"hidden":false}]



#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include "MFRC522.h"
//=========================================
#include <WiFiManager.h>         // https://github.com/tzapu/WiFiManager
//=========================================
//#include <AutoConnect.h>
//#include <WebServer.h>
//WebServer server;
//AutoConnect  Portal(server);
/* 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
#define BUILTIN_LED 2
// Update these with values suitable for 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;
String IDNo_buf="";    //client.publish("alex9ufo/outTopic/RFID/json"
char jsonChar1[100];

String json = "";     //client.publish("alex9ufo/led/led_status",
char jsonChar2[100];

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 rootPage() {
//  char content[] = "Hello, world";
//  server.send(200, "text/plain", content);
//}  
//=======================================================
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", jsonChar1, MQTTpubQos); // true means retain
  // Once connected, publish an announcement...
  client.publish("alex9ufo/led/led_status", jsonChar2, MQTTpubQos); // true means retain
  // ... and resubscribe
  client.subscribe("alex9ufo/inTopic/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 == "OFF")
   
   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 == "ON")
   
   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 == "TOGGLE")
   
   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] == 'FLASH')
   
    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] == 'TIMER')
   
}
//======================================================
void setup() {
  Serial.begin(115200);
  //===================================================  
  // WiFiManager
  // Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;
 
  // Uncomment and run it once, if you want to erase all the stored information
  //wifiManager.resetSettings();
 
  // set custom ip for portal
  //wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

  // fetches ssid and pass from eeprom and tries to connect
  // if it does not connect it starts an access point with the specified name
  // here  "AutoConnectAP"
  // and goes into a blocking loop awaiting configuration
  //=================================================
  Serial.println("Configuring your Mobile WiFi to esp32ap...");
  Serial.println("Configuring another WiFi SSID,PWD...");
  //===================================================  
  wifiManager.autoConnect("AutoConnectAP");
  // or use this for auto generated name ESP + ChipID
  //wifiManager.autoConnect();
 
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");

  Serial.println("Configuring ESP32...");
  pinMode(BUILTIN_LED, OUTPUT);
  Serial.println(F("Booting...."));
  SPI.begin();           // Init SPI bus
  mfrc522.PCD_Init();    // Init MFRC522

  //server.on("/", rootPage);
  //if (Portal.begin()) {
  //  Serial.println("HTTP server:" + WiFi.localIP().toString());
  //}
  //  else {
  //  Serial.println("Connection failed");
  //  while(true) {yield();}
  //}


  //===================================================
  Serial.println(F("Ready!"));
  Serial.println(F("Control Build LED ON,OFF,FLASH,TOGGLE,TIMER...."));
  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 (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(jsonChar2, 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",jsonChar2);
         }
     Send = false;    
   }
 
  if (WiFi.status() == WL_CONNECTED) {
    //========Auto Connect===============================

  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 > 3000)) {  //不同卡片 或是 等3秒
         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 json1 =
         "{\"data\":{"
         "\"RFID_No\": \"" + IDNo + "\"}"
         "}";
         // Convert JSON string to character array
         json1.toCharArray(jsonChar1, json1.length()+1);
   
         if  (client.connected()) {
              Serial.print("Publish message: ");
              Serial.println(json1);
              // Publish JSON character array to MQTT topic
             client.publish("alex9ufo/outTopic/RFID/json",jsonChar1);
         }
      } // if ((IDNo != IDNo_buf) || (now - lastMsg > 5000))
   }  // if (mfrc522.PICC_IsNewCardPresent()
  } //========Auto Connect===============================
  //Portal.handleClient();
}   //Loop
//=========================================================

沒有留言:

張貼留言

WOKWI DHT22 & LED , Node-Red + SQLite database

 WOKWI DHT22 & LED , Node-Red + SQLite database Node-Red程式 [{"id":"6f0240353e534bbd","type":"comment&...