Uploaded All Related Files For RFID Attendance Project

This commit is contained in:
ghassan committed 2020-01-28 09:57:11 +03:00
1 parent f58baa8998
commit d4c7181cbe
21 files changed
+876

No files matched your search

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,128 @@
// Included Libraries ------------------------------------
// File System & ESP8266
#include <FS.h> //this needs to be first, or it all crashes and burns...
#define strtFS SPIFFS.begin()
#define wipeFS SPIFFS.format()
// Button
#include <Button.h> // Button Library
//#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <WiFi.h>
// Needed For Library
#include <DNSServer.h>
//#include <ESP8266WebServer.h>
#include <WebServer.h>
#include <WiFiManager.h> //https://github.com/zhouhan0126/WIFIMANAGER-ESP32
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
// User Data To Be Displayed
String u_id = "";
String u_name = "";
String u_package = "";
String u_starttime = "";
String u_timing = "";
String u_remain = "";
String u_valid = "";
String u_sysmsg = "";
/* THIS SECTION IS FOR BASIC I/O */
//Button button(D3);
Button button(3);
/* WIFI MANAGER FUNCTION FLAG */
bool shouldSaveConfig = false;
String WiFi_SSID = "";
String WiFi_PASS = "";
/* DEVICE INFO */
const String devName = "TAKEONE WIFID ";// + String(ESP.getChipId());
String devID = ""; // Changable Via Web Interface
String devPASS = ""; // Changable Via Web Interface
const String devMac = String(WiFi.macAddress());
const String server = "http://192.168.1.3/index.php?card=";
// Included Libraries ------------------------------------
#include <rBase64.h>
// Included Libraries ------------------------------------
//#include <ESP8266HTTPClient.h>
#include <HTTPClient.h>
// Included Libraries ------------------------------------
#include <SPI.h>
#include <MFRC522.h>
//#define SS_PIN D8
//#define RST_PIN D0
#define SS_PIN 5
#define RST_PIN 4
MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class
// Included Libraries ------------------------------------
#include <TimeTrigger.h>
// Recuring Time Events
TimeTrigger blink(3000);
TimeTrigger testWiFi(1000);
// Included Libraries ------------------------------------
// Including I2C Library
#include <Wire.h>
// Define I2C Pins
//#define SDA_PIN D2
//#define SCL_PIN D1
#define SDA_PIN 21
#define SCL_PIN 22
// Included Libraries ------------------------------------
// Download From https://github.com/lucasmaziero/LiquidCrystal_I2C
#include <LiquidCrystal_I2C.h>
//#define I2C_LCD 0x3F
#define I2C_LCD 0x27
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(I2C_LCD, 16, 2);
// Included Libraries ------------------------------------
#include <RtcDS3231.h>
#include <EepromAt24C32.h>
#define countof(a) (sizeof(a) / sizeof(a[0]))
RtcDS3231<TwoWire> Rtc(Wire);
EepromAt24c32<TwoWire> RtcEeprom(Wire);
const char data[] = "What time is it in Greenwich?";
const uint16_t stringAddr = 64; // stored on page boundary
//========================================================
void setup()
{
// Calling Setup Routine
_setup();
}
//========================================================
void loop()
{
// Calling Loop Routine
_loop();
// Listen To Commands
command_reader();
}
// =======================================================
@@ -0,0 +1,117 @@
//====================================================================
// HTTP REQUESTS FROM WEB
//====================================================================
// HTTP Request To Send Data To Server Via WiFi
//--------------------------------------------------------------------
String prepare_HTTPData(String url, String data)
{
// Just For Display
Serial.println();
Serial.println("Sending To AWS Server ------------------------");
Serial.println();
// Card Code
String card = data;
// fOR TESTING PURPOSES
//url = "http://rfid.takeone.tech/index.php";
// PLANNER AWS LINK
//url += "?json=";
// COMBINNING INTO JSON DATA MESSAGE
data = post_json(data);
// Conversion Result
String ENCODED = base64(data);
// Serial Print Message
Serial.println(" -> CARD : " + card);
// Printing Data
Serial.println(" -> JSON DATA : " + data);
// New URL
url += ENCODED;
// Shows Us How It Would Look
Serial.println(" -> SERVER Request : " + url);
// Returnning The Value
return url;
}
//--------------------------------------------------------------------
// Send Http Request
//--------------------------------------------------------------------
String read_payload(String Request)
{
// HTTP Request
HTTPClient http;
// Empty PayLoad
String payload = "";
// HTTP Status Code
int httpCode = 0;
// Transmit Trials Count
int count = 0;
do {
// Counts
if(count < 3) {
count++;
Serial.println(" -> Trial #" + String(count));
//ESP.wdtFeed(); // Clearing Watch Dog Timer
} else {
break;
}
// configure traged server and url
http.begin(Request); //HTTP
Serial.print(" -> [HTTP] begin GET...\n");
// start connection and send HTTP header
httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf(" -> [HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
payload = http.getString();
Serial.println(" -> [HTTP] Response " + payload);
break;
}
} else {
Serial.printf(" -X [HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
payload = "";
}
} while(httpCode != HTTP_CODE_OK);
// Ending The Http Request
http.end();
// Returnning Payload
return payload;
}
//--------------------------------------------------------------------
// BASE64 Data Encoding
//--------------------------------------------------------------------
String base64(String data)
{
// Conversion Object
rBase64generic<4000> mybase64;
// Encoding The Data
if (mybase64.encode(data) == RBASE64_STATUS_OK) {
return mybase64.result();
} else {
return "";
}
}
@@ -0,0 +1,66 @@
//====================================================================
// JSON DATA REQUESTS
//====================================================================
// BUILDING JSON DATA FROM 3 ELEMTS : devID, devPASS, TADNUMBER
//--------------------------------------------------------------------
String post_json(String idCARD)
{
// Building The Buffer
DynamicJsonDocument data(2000);
// Inserting Data
data["request"] = "attendance";
data["divID"] = devID; // This is Predefined In The Seetings
data["divPASS"] = devPASS; // This Is Predefined In the Settings
data["divMAC"] = devMac; // This is from ESP8266 MacAddress Function
data["divDate"] = __DATE__; // This is from RTC Module
data["divTime"] = __TIME__; // This is from RTC Module
data["userRFID"] = idCARD; // This is from RFID Card Scanned By User
// Creating Output Memory
String output;
// Inserting Data To Output Variable
serializeJson(data, output);
// Clearing Data Memory
data.clear();
// Returnning Generated String
return output;
}
//--------------------------------------------------------------------
// BUILDING JSON DATA FROM 3 ELEMTS : devID, devPASS, TADNUMBER
//--------------------------------------------------------------------
bool person_read(String json)
{
// Building The Buffer
DynamicJsonDocument data(3000); // building JSON Buffer
// Reading Data From JSON
DeserializationError error = deserializeJson(data, json);
// Make Sure Was Converted Correctly
if(error) {
Serial.println("Error Parsing JSON");
return false;
}
// Reading Data
u_id = data["response"].as<String>();
u_name = data["name"].as<String>();
u_package = data["package"].as<String>();
u_starttime = data["starttime"].as<String>();
u_timing = data["timing"].as<String>();
u_remain = data["remain"].as<String>();
u_valid = data["valid"].as<String>();
u_sysmsg = data["sysmsg"].as<String>();
// Clearing Buffer
data.clear();
// Successfull
return true;
}
@@ -0,0 +1,100 @@
//====================================================================
// LCD Library Functions
//====================================================================
// LCD Initialize
//--------------------------------------------------------------------
void lcd_begin()
{
// Begin Wire
Wire.begin(SDA_PIN, SCL_PIN);
// Begin LCD
lcd.begin(SDA_PIN, SCL_PIN);
}
//--------------------------------------------------------------------
// LCD Clear
//--------------------------------------------------------------------
void lcd_clear()
{
lcd.clear();
lcd.home();
}
//--------------------------------------------------------------------
// LCD Testing Back Light
//--------------------------------------------------------------------
bool lcd_islight()
{
return lcd.getBacklight();
}
//--------------------------------------------------------------------
// LCD Light On
//--------------------------------------------------------------------
void lcd_light_on()
{
lcd.backlight();
}
//--------------------------------------------------------------------
// LCD Light Off
//--------------------------------------------------------------------
void lcd_light_off()
{
lcd.noBacklight();
}
//--------------------------------------------------------------------
// LCD Light Toggle
//--------------------------------------------------------------------
void lcd_light_toggle()
{
if(lcd_islight())
{
lcd_light_off();
}
else
{
lcd_light_on();
}
}
//--------------------------------------------------------------------
// LCD Line 1
//--------------------------------------------------------------------
void lcd_line1(String line1)
{
lcd.setCursor(0, 0);
lcd.print(line1);
}
//--------------------------------------------------------------------
// LCD Line 2
//--------------------------------------------------------------------
void lcd_line2(String line2)
{
lcd.setCursor(0, 1);
lcd.print(line2);
}
//--------------------------------------------------------------------
String lcd_center(String text)
{
int space = (16 - text.length())/2;
String txt_space = "";
for(int i=0; i<space; i++) {
txt_space += " ";
}
return txt_space + text;
}
@@ -0,0 +1,53 @@
/* ===================================================================================
* MAIN LOOP
* =================================================================================*/
void _loop()
{
// Reading The RFID
String card = rfid_read();
// Checking Card Content
if(card != "")
{
// Reset The Timer
blink.Reset();
// Turn On The LED
lcd_light_on();
// Display
lcd_line1("CARD: " + card);
// Send to Server
String payload = read_payload(prepare_HTTPData(server, card));
// Reading The Payload
person_read(payload);
// Wait For LED To Turn OFF
while(!blink.Trigger())
{
// Clearing Watch Dog Timer
//ESP.wdtFeed();
}
// Turn Off The Light
lcd_light_off();
// Clearing Display
lcd_clear();
// Clearing The Blink Counter
testWiFi.Reset();
}
// Clearing Watch Dog Timer
//ESP.wdtFeed();
// This Indicates That WiFi Is Alive
if(testWiFi.Trigger() && checkWiFi() == true)
{
digitalWrite(D4, !digitalRead(D4));
}
}
@@ -0,0 +1,45 @@
/* ===================================================================================
* RFID Reader Read
* =================================================================================*/
void rfid_begin()
{
SPI.begin(); // Init SPI bus
rfid.PCD_Init(); // Init MFRC522
}
//====================================================================================
String rfid_read()
{
String card = "";
// Look for new cards
if ( ! rfid.PICC_IsNewCardPresent())
return "";
// Verify if the NUID has been readed
if ( ! rfid.PICC_ReadCardSerial())
return "";
// Store NUID into nuidPICC array
for (byte i = 0; i < 4; i++)
{
card += String(rfid.uid.uidByte[i], HEX);
}
// REMOVE UNWANTED SPACES
card.trim();
// CHANGE TO CAPITAL LETTERS
card.toUpperCase();
// Halt PICC
rfid.PICC_HaltA();
// Stop encryption on PCD
rfid.PCD_StopCrypto1();
// Return Card Data
return card;
}
@@ -0,0 +1,10 @@
void rtc_begin()
{
// Starting RTC
Rtc.Begin();
// TurnOn RTC EEPROM
RtcEeprom.Begin();
// Read Date Time
RtcDateTime compiled = RtcDateTime(__DATE__, __TIME__);
}
@@ -0,0 +1,43 @@
//====================================================================
// SERIAL COMMANDS
//====================================================================
// LISTENS TO ALL COMMANDS
//--------------------------------------------------------------------
void command_reader()
{
if(Serial.available())
{
// SERIAL STRING READER
String msg = Serial.readStringUntil('\n');
msg.trim();
// RESTART THE DEVICE
command_restart(msg);
// RECONFIG THE WIFI MANAGER
command_reconfig(msg);
}
}
//--------------------------------------------------------------------
// RESTART THE DEVICE
//--------------------------------------------------------------------
void command_restart(String input) {
if(input == "restart" || input == "RESTART") {
ESP.restart();
}
}
//--------------------------------------------------------------------
// RECONFIG THE DEVICE
//--------------------------------------------------------------------
void command_reconfig(String input) {
if(input == "config" || input == "CONFIG") {
reconfig();
}
}
//--------------------------------------------------------------------
@@ -0,0 +1,32 @@
/* ===================================================================================
* VOID SETUP
* =================================================================================*/
void _setup()
{
// Serial Monitor
Serial.begin(115200);
delay(10);
// TurnOn RTC Module
//SPIFFS.format();
// Begin LCD
lcd_begin();
// Turn Off LCD Light
lcd_light_off();
// Wipe
lcd_clear();
// WiFi Connection
setupWiFi();
// RFID Begin
rfid_begin();
// Blue LED
pinMode(D4, OUTPUT);
digitalWrite(D4, !LOW);
}
@@ -0,0 +1,239 @@
/* ===================================================================================
* THIS SECTION IS FOR METHODES AND FUNCTIONS
* =================================================================================*/
void setupWiFi()
{
// Turn On LCD
lcd_light_on();
// Printing Device Mac Address
Serial.println();
Serial.println("-----------------------------------------------------------");
Serial.println(" TAKEONE WIFI MANAGER STARTING ");
Serial.println("-----------------------------------------------------------");
//Serial.println("TAKEONE: MAC Address:");
//Serial.println("TAKEONE: " + devMac);
// Starting File System
Serial.println("TAKEONE: Mounting File System");
read_config();
// The extra parameters to be configured (can be either global or just in the setup)
WiFiManagerParameter custom_devID("devID", "Club UserID", devID.c_str(), 100);
WiFiManagerParameter custom_devPASS("devPASS", "Club Password", devPASS.c_str(), 100);
//WiFiManager Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//add all your parameters here
//wifiManager.addParameter(&custom_server);
wifiManager.addParameter(&custom_devID);
wifiManager.addParameter(&custom_devPASS);
// Display Booting Up Message
lcd_clear();
lcd_line1("TAKEONE WiFi");
lcd_line2("RFID < READY >");
delay(2500);
// Reset Settings
if(button.pressed())
{
reconfig();
}
// Display On OLED
lcd_clear();
lcd_line1("CONNECTING TO");
lcd_line2("WiFi ROUTER");
delay(2500);
// Trying To Connect To Network Or Reconfig
if (!wifiManager.autoConnect(devName.c_str())) {
lcd_clear();
lcd_line1("CONNECTION TO");
lcd_line2("ROUTER FAILD!");
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
lcd_clear();
lcd_line1("< REBOOTING >");
delay(3000);
ESP.restart();
}
// Copying The SSID & Password Of Successfully Connected Network
WiFi_SSID = wifiManager.getSSID();
WiFi_PASS = wifiManager.getPassword();
lcd_clear();
lcd_line1("CONNECTION");
lcd_line2("< SUCCESSFUL >");
delay(2500);
lcd_clear();
lcd_line1("IP ADDRESS");
lcd_line2(WiFi.localIP().toString());
delay(2500);
//read updated parameters
devID = custom_devID.getValue();
devPASS = custom_devPASS.getValue();
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument json(4000);
// Assignning Parameters To JSON
json["devID"] = devID;
json["devPASS"] = devPASS;
// Opening The File For Reading
File configFile = SPIFFS.open("/config.json", "w");
// Checking If File Opened
if (!configFile) {
Serial.println("failed to open config file for writing");
}
// Print JSON Content On Monitor
String memory = "";
serializeJson(json, memory);
// Print To Serial Monitor
Serial.println(memory);
// Write To File
configFile.print(memory);
// Closing Config File
configFile.close();
// Clearing The Buffer Memory
json.clear();
//end save
}
// Display Data
Serial.println("TAKEONE: divID : " + devID);
Serial.println("TAKEONE: divPASS : " + devPASS);
Serial.println("TAKEONE: divMAC : " + devMac);
// End Of WiFi Manager
Serial.println("-----------------------------------------------------------");
// Clearing LCD
lcd_clear();
// Turnning Off LCD Light
lcd_light_off();
}
/* ===================================================================================
* THIS SECTION IS FOR METHODES AND FUNCTIONS
* =================================================================================*/
void saveConfigCallback ()
{
Serial.println("Should Save Config File");
shouldSaveConfig = true;
}
/* ===================================================================================
* THIS SECTION IS FOR METHODES AND FUNCTIONS
* =================================================================================*/
void reconfig()
{
lcd_clear();
lcd_light_on();
lcd_line1("Reset WiFi");
lcd_line2("Settings");
// Make Sure That Spiffs Started
if(!strtFS) {
delay(1000);
wipeFS;
}
WiFiManager wifiManager;
delay(1500);
wifiManager.resetSettings();
lcd_clear();
lcd_line1("Formating SPIFFS");
delay(1500);
// LCD Display
lcd_clear();
lcd_line1(lcd_center("< REBOOTING >"));
delay(1500);
lcd_light_off();
ESP.restart();
}
/* ===================================================================================
* THIS SECTION IS FOR METHODES AND FUNCTIONS
* =================================================================================*/
bool checkWiFi()
{
if(WiFi.status() == WL_CONNECTED)
{
return true;
}
else
{
return false;
}
}
/* ===================================================================================
* Reading Config File
* =================================================================================*/
void read_config()
{
// After Suceessfull Do The Following
if(strtFS)
{
Serial.println(" -> Mounted File System");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println(" -> Reading Config File");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
//Serial.println(" -> Opened Config File");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
// Display The Read Data
String mydata = String(buf.get());
mydata.trim();
//Serial.println(" -> My Stored Data : " + mydata);
// JSON Document
DynamicJsonDocument json(2000);
DeserializationError error = deserializeJson(json, mydata);
if (!error) {
devID = json["devID"].as<String>();
devPASS = json["devPASS"].as<String>();
} else {
Serial.println(" -> failed to load json config");
}
// Clearing JSON Memory
json.clear();
}
}
} else {
Serial.println(" -> failed to mount FS");
}
}
@@ -0,0 +1,43 @@
/* ===================================================================================
* WIRE SCANNER
* =================================================================================*/
void wire_scanner()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
}
Binary file not shown.