2019年8月9日 星期五

NodeMCU + RFID + MQTT + Node-RED (三)

NodeMCU + RFID + MQTT + Node-RED (三)

利用RFID rc522 reader讀取 mifare卡號,送至MQTT上。
用Node-RED 訂閱取得MQTT上刷卡卡號,並且顯示於Node-RED UI介面上。 可以使用 Node-RED UI上的 on LED ,off LED ,flash LED 控制 NodeMCU上的 LED on,off ,flash。










ESP8266程式
======================================================
/*
Many thanks to nikxha from the ESP8266 or WEMOSD1 forum
*/

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <SPI.h>
#include "MFRC522.h"

/* Wiring RFID RC522 module
=============================================================================
GND     = GND   3.3V    = 3.3V
The following table shows the typical pin layout used:
Signal              MFRC522     WeMos D1 mini     NodeMcu       Generic
RST/Reset     RST                  D3 [1]                     D3 [1]           GPIO-0 [1]
SPI SS            SDA [3]           D8 [2]                     D8 [2]           GPIO-15 [2]
SPI MOSI      MOSI               D7                           D7                 GPIO-13
SPI MISO      MISO               D6                           D6                 GPIO-12
SPI SCK         SCK                D5                            D5                GPIO-14
[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 RST_PIN  D3     // RST-PIN für RC522 - RFID - SPI - D3
#define SS_PIN   D8     // SDA-PIN für RC522 - RFID - SPI - D8

// Update these with values suitable for your network.
//const char *ssid = "PTS-2F";
//const char *pass = "PTS6662594";
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             "alex9981"                   //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

#define BUILTIN_LED        2                             // Arduino standard is GPIO13 but lolin nodeMCU is 2
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

struct RFIDTag {    // 定義結構
   byte uid[4];
   char *name;
};
//==================================
//先執行RFID_2程式確認卡號再來設定
// 初始化結構資料
// 將卡號變成代號Arduino....Raspberry Pi.....Espruino
//==================================
struct RFIDTag tags[] = {  // 初始化結構資料
   {{0x70,0x21,0xED,0x10}, "Alex9ufo"},
   {{0x44,0x51,0xBB,0x96}, "RaspberryPi"},
   {{0x15,0x8,0xA,0x53}, "Espruino"}
};

byte totalTags = sizeof(tags) / sizeof(RFIDTag);

//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;
  //String message;
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  Serial.println(message);
  String message1;
  for (int i = 0; i < length; i++) {
    message1 = message1 + (char)payload[i];  //Conver *byte to String
  }
  //Serial.print(message);
  if(message1 == "#on")
  {
      digitalWrite(BUILTIN_LED,LOW);
      Flash = false;
  }   //LED on 
  if(message1 == "#off")
  {
    digitalWrite(BUILTIN_LED,HIGH);
    Flash = false;
  } //LED off
  if(message1== "#flash") {
     Flash = true;
     digitalWrite(BUILTIN_LED, HIGH);
   } // if(message== "#flashLED")

 }
//======================================================
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())
  { // 如果出現新卡片就讀取卡片資料
      byte *id = mfrc522.uid.uidByte;   // 取得卡片的UID
      byte idSize = mfrc522.uid.size;   // 取得UID的長度
      bool foundTag = false;            // 是否找到紀錄中的標籤,預設為「否」。
      byte i=0;
      for (i=0; i<totalTags; i++) {
        if (memcmp(tags[i].uid, id, idSize) == 0) {
          Serial.print(F("Card UID:"));
          Serial.println(tags[i].name);  // 顯示標籤的名稱
          foundTag = true;  // 設定成「找到標籤了!」
          break;            // 退出for迴圈
        }
      }

      if (!foundTag) {    // 若掃描到紀錄之外的標籤,則顯示"Wrong card!"。
        Serial.println("Wrong card!");
      }

    mfrc522.PICC_HaltA();  // 讓卡片進入停止模式   

    //Serial.println(tags[i].name);
    IDNo_buf="";
    IDNo_buf=tags[i].name;
    // Convert data to JSON string
    String json =
    "{\"data\":{"
    "\"RFID_No\": \"" + IDNo_buf + "\"}"
    "}";
    // 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 (mfrc522.PICC_IsNewCardPresent()

}   //Loop
//======================================================

Node-red 程式 (用筆記簿存檔 不可以用wordpad)

[{"id":"36b9ac19.468a04","type":"mqtt in","z":"a47b5494.3eb618","name":"MQTT","topic":"alex9ufo/outTopic/RFID/json","qos":"2","broker":"40bf4d5e.0395f4","x":70,"y":80,"wires":[["f44190ce.e2ea1","bd8e1ae2.0b89e8"]]},{"id":"cbe61db9.a111f","type":"mqtt out","z":"a47b5494.3eb618","name":"","topic":"alex9ufo/inTopic","qos":"1","retain":"false","broker":"40bf4d5e.0395f4","x":460,"y":240,"wires":[]},{"id":"fdce570a.70c9a8","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"ON_LED","color":"white","bgcolor":"","icon":"fa-circle","payload":"#on","payloadType":"str","topic":"","x":80,"y":220,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"7789eb7e.2785d4","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"off_LED","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#off","payloadType":"str","topic":"","x":80,"y":280,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"b4dc5dae.5e7a5","type":"ui_text","z":"a47b5494.3eb618","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"name":"","label":"MQTT_send_Message","format":"{{msg.payload}}","layout":"row-center","x":540,"y":40,"wires":[]},{"id":"be2f332d.8a81c","type":"debug","z":"a47b5494.3eb618","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":370,"y":320,"wires":[]},{"id":"b13346c4.b6fb38","type":"ui_button","z":"a47b5494.3eb618","name":"","group":"e4b1387a.934b88","order":0,"width":0,"height":0,"passthru":false,"label":"flash_LED","color":"black","bgcolor":"","icon":"fa-circle-o","payload":"#flash","payloadType":"str","topic":"","x":90,"y":340,"wires":[["cbe61db9.a111f","be2f332d.8a81c"]]},{"id":"f44190ce.e2ea1","type":"function","z":"a47b5494.3eb618","name":"json+時分秒","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 = 'Time:(' + h + ':' + m + ':' + s + ')'+ msg.payload ;\nreturn msg;\n","outputs":1,"noerr":0,"x":230,"y":40,"wires":[["b4dc5dae.5e7a5"]]},{"id":"500454d2.a4bd3c","type":"debug","z":"a47b5494.3eb618","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":510,"y":160,"wires":[]},{"id":"bd8e1ae2.0b89e8","type":"switch","z":"a47b5494.3eb618","name":"","property":"payload","propertyType":"msg","rules":[{"t":"cont","v":"Alex9ufo","vt":"str"},{"t":"cont","v":"RaspberryPi","vt":"str"}],"checkall":"true","repair":false,"outputs":2,"x":190,"y":120,"wires":[["4acc1c61.ced694"],["c63a55f1.654808"]]},{"id":"973eb503.798ba8","type":"debug","z":"a47b5494.3eb618","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","x":510,"y":100,"wires":[]},{"id":"4acc1c61.ced694","type":"function","z":"a47b5494.3eb618","name":"#on","func":"msg.payload =\"#on\";\nreturn msg;\n","outputs":1,"noerr":0,"x":310,"y":100,"wires":[["973eb503.798ba8","cbe61db9.a111f"]]},{"id":"c63a55f1.654808","type":"function","z":"a47b5494.3eb618","name":"#off","func":"msg.payload =\"#off\";\nreturn msg;\n","outputs":1,"noerr":0,"x":310,"y":160,"wires":[["500454d2.a4bd3c","cbe61db9.a111f"]]},{"id":"40bf4d5e.0395f4","type":"mqtt-broker","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":15,"cleansession":true,"birthQos":"0","willQos":"0"},{"id":"e4b1387a.934b88","type":"ui_group","z":"","name":"Control led ESP8266 (ESP32)","tab":"8b6381a9.6f9d6","order":1,"disp":true,"width":"15","collapse":false},{"id":"8b6381a9.6f9d6","type":"ui_tab","name":"Tab 1","icon":"dashboard","order":1}]

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...