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。


===================程式修正===================
flash flag
bool Flash = false;  //true

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




/*
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
//======================================================

沒有留言:

張貼留言

2024_09 作業3 以Node-Red 為主

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