This commit is contained in:
TheJoKlLa 2022-10-07 01:58:26 +02:00
parent 90d77ec303
commit 3932b57660
12 changed files with 1891 additions and 155 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "src/FabReader_v2/lib/rfid-desfire"]
path = src/FabReader_v2/lib/rfid-desfire
url = https://github.com/JPG-Consulting/rfid-desfire.git

View File

@ -1,5 +1,13 @@
{ {
"files.associations": { "files.associations": {
"random": "cpp" "random": "cpp",
"cstddef": "cpp",
"array": "cpp",
"string_view": "cpp",
"initializer_list": "cpp",
"ranges": "cpp",
"utility": "cpp",
"string": "cpp",
"functional": "cpp"
} }
} }

@ -0,0 +1 @@
Subproject commit ee897bedb4c55ff488058b8f85df1650e64c8568

View File

@ -1,40 +1,51 @@
#include "NFC.h" #include "NFC.h"
#include <SPI.h> #include <SPI.h>
#include <PubSubClient.h> #include <PubSubClient.h>
#include <MFRC522.h> #include <DESFire.h>
#include "helpers.h"
NFC::NFC(int pin_ss, int pin_rst) NFC::NFC(int pin_ss, int pin_rst)
{ {
SPI.begin(); SPI.begin();
rfid = new MFRC522(pin_ss, pin_rst); rfid = new DESFire(pin_ss, pin_rst);
rfid->PCD_Init(); rfid->PCD_Init();
} }
bool NFC::hasNewCard() bool NFC::hasNewCard()
{ {
if(rfid->PICC_IsNewCardPresent() && rfid->PICC_ReadCardSerial()) if(rfid->PICC_IsNewCardPresent() && rfid->PICC_ReadCardSerial() && rfid->uid.sak == 0x20)
{ {
Serial.println("New Card detected");
return true; return true;
// byte atqaLen = sizeof(atqa);
// MFRC522::StatusCode status = rfid->PICC_RequestA(atqa, &atqaLen);
// Serial.printf("PICC_RequestA: 0x%02x\n", status);
// if(status == MFRC522::STATUS_OK && atqa[0] == 0x44)
// {
// return true;
// }
} }
return false; return false;
} }
MFRC522::Uid NFC::getUID()
{
return uid;
}
bool NFC::selectCard() bool NFC::selectCard()
{ {
// MFRC522::StatusCode status = rfid->PICC_Select(&(rfid->uid)); MFRC522::StatusCode status;
// Serial.printf("PICC_Select: 0x%02x\n", status); byte ats_buffer[16];
// if(status != MFRC522::STATUS_OK) byte ats_buffer_len = 16;
// {
// return false; status = rfid->PICC_RequestATS(ats_buffer, &ats_buffer_len);
// } if (status != MFRC522::STATUS_OK)
{
Serial.printf("PICC_RequestATS: 0x%02x\n", status);
return false;
}
status = rfid->PICC_ProtocolAndParameterSelection(0x00, 0x11, 0x00);
if (status != MFRC522::STATUS_OK)
{
Serial.printf("PICC_ProtocolAndParameterSelection: 0x%02x\n", status);
return false;
}
cardSelected = true; cardSelected = true;
uid = rfid->uid; uid = rfid->uid;
@ -44,19 +55,17 @@ bool NFC::selectCard()
bool NFC::deselectCard() bool NFC::deselectCard()
{ {
// MFRC522::StatusCode status = rfid->PICC_HaltA();
// Serial.printf("PICC_HaltA: 0x%02x\n", status);
// if(status != MFRC522::STATUS_OK)
// {
// return false;
// }
cardSelected = false; cardSelected = false;
Serial.println("Card Deselected"); Serial.println("Card Deselected");
return true; return true;
} }
bool NFC::hasCardSelected()
{
return cardSelected;
}
bool NFC::isCardLost() bool NFC::isCardLost()
{ {
uint8_t control = 0x00; uint8_t control = 0x00;
@ -76,15 +85,46 @@ bool NFC::isCardLost()
} }
control += 0x4; control += 0x4;
} }
return !(control == 13 || control == 14);
if(!(control == 13 || control == 14))
{
Serial.println("Card Lost");
return true;
}
else
{
return false;
}
} }
MFRC522::StatusCode NFC::Transceive(byte* command, byte command_len, byte* response, byte response_len) MFRC522::StatusCode NFC::Transceive(byte* command, byte command_len, byte* response, byte* response_len)
{ {
return rfid->PCD_TransceiveData(command, command_len, response, &response_len, NULL, 0, true); byte buffer[APDU_BUFFER_SIZE + 4];
} byte buffer_len = command_len + 4;
MFRC522::StatusCode status;
MFRC522::Uid NFC::getUID() buffer[0] = 0x0A;
{ buffer[1] = 0x00;
return uid; memcpy(&buffer[2], command, command_len);
status = rfid->PCD_CalculateCRC(buffer, buffer_len - 2, &buffer[buffer_len - 2]);
if (status != MFRC522::STATUS_OK)
{
Serial.printf("PCD_CalculateCRC: 0x%02x\n", status);
return status;
}
// Serial.println(buffer_len);
// char command_h[APDU_BUFFER_SIZE*2] = { 0 };
// bytes2chars(buffer, buffer_len, command_h, true);
// Serial.println(command_h);
status = rfid->PCD_TransceiveData(buffer, buffer_len, response, response_len);
if (status != MFRC522::STATUS_OK)
{
Serial.printf("PCD_TransceiveData: 0x%02x\n", status);
return status;
}
return status;
} }

View File

@ -2,26 +2,27 @@
#define NFC_H #define NFC_H
#include <PubSubClient.h> #include <PubSubClient.h>
#include <MFRC522.h> #include <DESFIre.h>
#define APDU_BUFFER_SIZE 256
class NFC class NFC
{ {
private: private:
MFRC522::Uid uid; MFRC522::Uid uid;
bool cardSelected; bool cardSelected = false;
byte atqa[2];
public: public:
MFRC522* rfid; DESFire* rfid;
NFC(int pin_ss, int pin_rst); NFC(int pin_ss, int pin_rst);
bool hasNewCard(); bool hasNewCard();
bool selectCard(); bool selectCard();
bool deselectCard(); bool deselectCard();
bool isCardLost(); bool isCardLost();
bool hasCardSelected();
MFRC522::Uid getUID(); MFRC522::Uid getUID();
MFRC522::StatusCode Transceive(byte* command, byte command_len, byte* response, byte response_len); MFRC522::StatusCode Transceive(byte* command, byte command_len, byte* response, byte* response_len);
}; };
#endif #endif

View File

@ -48,17 +48,26 @@ void OTAProxy::continueOTA(char* topic, byte* payload, unsigned int length)
{ {
Serial.println("Request OTA"); Serial.println("Request OTA");
byte response[APDU_BUFFER_SIZE] = {0}; byte response[APDU_BUFFER_SIZE] = {0};
byte response_len;
MFRC522::StatusCode status;
do
{
status = nfc->Transceive(payload, length, response, APDU_BUFFER_SIZE);
Serial.printf("PICC_Tranceive: 0x%02x\n", status);
delay(100);
}
while (status != MFRC522::STATUS_OK);
for(int i = 0; i < APDU_BUFFER_SIZE; i++) MFRC522::StatusCode status;
while (true)
{
if(nfc->isCardLost())
{
Serial.println("Card Lost");
return;
}
Serial.println("Run Transceive");
status = nfc->Transceive(payload, length, response, &response_len);
Serial.printf("PICC_Tranceive: 0x%02x\n", status);
if(status == MFRC522::STATUS_OK)
{
break;
}
}
for(int i = 0; i < response_len; i++)
{ {
char hexCar[2]; char hexCar[2];
@ -67,7 +76,7 @@ void OTAProxy::continueOTA(char* topic, byte* payload, unsigned int length)
} }
Serial.println(); Serial.println();
mqtt->publish(topic_responseOTA, response, APDU_BUFFER_SIZE); mqtt->publish(topic_responseOTA, response, response_len);
Serial.println("Response OTA"); Serial.println("Response OTA");
} }
else if(!strcmp(topic, topic_stopOTA)) else if(!strcmp(topic, topic_stopOTA))

View File

@ -4,7 +4,6 @@
#include <PubSubClient.h> #include <PubSubClient.h>
#include "NFC.h" #include "NFC.h"
#define MSG_BUFFER_SIZE 50 #define MSG_BUFFER_SIZE 50
#define APDU_BUFFER_SIZE 256
class OTAProxy class OTAProxy
{ {

View File

@ -0,0 +1,61 @@
#include "helpers.h"
void char2byte(char* str, byte* array)
{
for(int i=0; i <2 ; i++)
{
char c = *str;
if (c >= '0' && c <= '9')
{
*array *= 16;
*array += c - '0';
}
else if (c >= 'A' && c <= 'F')
{
*array *= 16;
*array += (c - 'A') + 10;
}
else if (c >= 'a' && c <= 'f')
{
*array *= 16;
*array += (c - 'a') + 10;
}
str++;
}
}
void chars2bytes(char* str, byte* array, bool msb)
{
int len = strlen(str);
for(int i = 0; i < len; i += 2)
{
if(msb)
{
char2byte(&str[i], &array[i/2]);
}
else
{
char2byte(&str[i], &array[len-2 - i/2]);
}
}
}
void byte2char(byte* array, char* str)
{
sprintf(str, "%02x", *array);
}
void bytes2chars(byte* array, byte array_len, char* str, bool msb)
{
for(int i = 0; i < array_len; i++)
{
if(msb)
{
byte2char(&array[i], &str[i*2]);
}
else
{
byte2char(&array[array_len-2 - i], &str[i*2]);
}
}
}

View File

@ -0,0 +1,11 @@
#ifndef HELPERS_H
#define HELPERS_H
#include <Arduino.h>
void char2byte(char* str, byte* array);
void chars2bytes(char* str, byte* array, bool msb);
void byte2char(byte* array, char* str);
void bytes2chars(byte* array, byte array_len, char* str, bool msb);
#endif

View File

@ -1,128 +1,145 @@
#include <Arduino.h> /*
#include <ArduinoLog.h> * --------------------------------------------------------------------------------------------------------------------
* Example sketch/program showing how to read data from a PICC to serial.
* --------------------------------------------------------------------------------------------------------------------
* This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
*
* Example sketch/program showing how to read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
* Reader on the Arduino SPI interface.
*
* When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
* then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
* you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
* will show the ID/UID, type and any data blocks it can read. Note: you may see "Timeout in communication" messages
* when removing the PICC from reading distance too early.
*
* If your reader supports it, this sketch/program will read all the PICCs presented (that is: multiple tag reading).
* So if you stack two or more PICCs on top of each other and present them to the reader, it will first output all
* details of the first and then the next PICC. Note that this may take some time as all data blocks are dumped, so
* keep the PICCs at reading distance until complete.
*
* @license Released into the public domain.
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/
#include "config.h"
#include "pins.h"
#include "nfc.h"
#include "otaproxy.h"
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <SPI.h> #include <SPI.h>
#include <MFRC522.h> #include <MFRC522.h>
#include <SSD1306Wire.h> #include <Desfire.h>
WiFiClient espClient; #define RST_PIN 9 // Configurable, see typical pin layout above
//Config_Data config; #define SS_PIN 10 // Configurable, see typical pin layout above
PubSubClient* mqtt; #include "Pins.h"
NFC* nfc;
OTAProxy* ota;
void setup_wifi() DESFire mfrc522(PIN_RFID_SPI_SS, PIN_RFID_RST); // Create MFRC522 instance
{
delay(10);
Serial.println("Connecting Wifi ...");
WiFi.mode(WIFI_STA); void setup() {
WiFi.begin(WLAN_SSID, WLAN_PASS); Serial.begin(115200); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
while (WiFi.status() != WL_CONNECTED) SPI.begin(); // Init SPI bus
{ mfrc522.PCD_Init(); // Init MFRC522
delay(500); mfrc522.PCD_DumpVersionToSerial(); // Show details of PCD - MFRC522 Card Reader details
} Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
randomSeed(micros());
Serial.println("WiFi connected");
} }
void reconnect() void loop() {
{ // Look for new cards
while (!mqtt->connected()) if ( ! mfrc522.PICC_IsNewCardPresent()) {
{ return;
String clientId = "FabReader_"; }
clientId += String(FABREADERID);
Serial.println("Connecting MQTT ..."); // Select one of the cards
if (mqtt->connect(clientId.c_str())) if ( ! mfrc522.PICC_ReadCardSerial()) {
{ return;
Serial.println("MQTT connected"); }
char id[6] = "00000";
sprintf(id, "%05d", FABREADERID);
mqtt->publish("fabreader", id);
char topic_requestOTA[] = "fabreader/00000/requestOTA"; if (mfrc522.uid.sak != 0x20) {
sprintf(topic_requestOTA, "fabreader/%05d/requestOTA", FABREADERID); // Dump debug info about the card; PICC_HaltA() is automatically called
mqtt->subscribe(topic_requestOTA); mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
return;
}
char topic_stopOTA[] = "fabreader/00000/stopOTA"; // Show an extra line
sprintf(topic_stopOTA, "fabreader/%05d/stopOTA", FABREADERID); Serial.println();
mqtt->subscribe(topic_stopOTA);
} else {
Serial.print("failed, rc=");
Serial.print(mqtt->state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) DESFire::mifare_desfire_tag tag;
{ DESFire::StatusCode response;
Serial.println("Receive Message");
Serial.println(topic);
if(ota->hasActiveOTA())
{
ota->continueOTA(topic, payload, length);
}
}
void setup() tag.pcb = 0x0A;
{ tag.cid = 0x00;
Serial.begin(115200); memset(tag.selected_application, 0, 3);
Serial.print("\n\n\n");
Serial.println("Booting ..."); // Make sure none DESFire status codes have DESFireStatus code to OK
response.desfire = DESFire::MF_OPERATION_OK;
byte ats[16];
byte atsLength = 16;
response.mfrc522 = mfrc522.PICC_RequestATS(ats, &atsLength);
if ( ! mfrc522.IsStatusCodeOK(response)) {
Serial.println(F("Failed to get ATS!"));
Serial.println(mfrc522.GetStatusCodeName(response));
Serial.println(response.mfrc522);
pinMode(PIN_BUZZER, OUTPUT); mfrc522.PICC_HaltA();
pinMode(PIN_BUTTON, INPUT); return;
pinMode(PIN_ETH_SPI_SS, OUTPUT); }
digitalWrite(PIN_ETH_SPI_SS, HIGH);
Serial.println("Connecting NFC ..."); // TODO: Should do checks but since I know my DESFire allows and requires PPS...
nfc = new NFC(PIN_RFID_SPI_SS, PIN_RFID_RST); // PPS1 is ommitted and, therefore, 0x00 is used (106kBd)
if(!(nfc->rfid->PCD_PerformSelfTest())) response.mfrc522 = mfrc522.PICC_ProtocolAndParameterSelection(0x00, 0x11);
{ if ( ! mfrc522.IsStatusCodeOK(response)) {
Serial.println("NFC Test failed"); Serial.println(F("Failed to perform protocol and parameter selection (PPS)!"));
} Serial.println(mfrc522.GetStatusCodeName(response));
Serial.println("NFC connected"); mfrc522.PICC_HaltA();
return;
}
setup_wifi(); // MIFARE DESFire should respond to a GetVersion command
DESFire::MIFARE_DESFIRE_Version_t desfireVersion;
response = mfrc522.MIFARE_DESFIRE_GetVersion(&tag, &desfireVersion);
if ( ! mfrc522.IsStatusCodeOK(response)) {
Serial.println(F("Failed to get a response for GetVersion!"));
Serial.println(mfrc522.GetStatusCodeName(response));
mfrc522.PICC_HaltA();
return;
}
// Dump MIFARE DESFire version information.
// NOTE: KEEP YOUR CARD CLOSE TO THE READER!
// This method takes some time and the card will be read
// once output ends! If you remove the card too fast
// a timeout will occur!
mfrc522.PICC_DumpMifareDesfireVersion(&tag, &desfireVersion);
mqtt = new PubSubClient(espClient); mfrc522.PICC_DumpMifareDesfireMasterKey(&tag);
mqtt->setServer(MQTT_BROKER, 1883);
mqtt->setCallback(callback);
ota = new OTAProxy(mqtt, nfc, FABREADERID); DESFire::mifare_desfire_aid_t aids[MIFARE_MAX_APPLICATION_COUNT];
} byte applicationCount = 0;
response = mfrc522.MIFARE_DESFIRE_GetApplicationIds(&tag, aids, &applicationCount);
if ( ! mfrc522.IsStatusCodeOK(response)) {
Serial.println(F("Failed to get application IDs!"));
Serial.println(mfrc522.GetStatusCodeName(response));
mfrc522.PICC_HaltA();
return;
}
void loop() // Dump all applications
{ for (byte aidIndex = 0; aidIndex < applicationCount; aidIndex++) {
if (!mqtt->connected()) mfrc522.PICC_DumpMifareDesfireApplication(&tag, &(aids[aidIndex]));
{ }
reconnect();
} // Call PICC_HaltA()
mqtt->loop(); mfrc522.PICC_HaltA();
Serial.println();
if(ota->hasActiveOTA() && nfc->isCardLost())
{
ota->cancelOTA();
}
if(!ota->hasActiveOTA())
{
ota->startOTA();
}
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,168 @@
#include <Arduino.h>
#include <ArduinoLog.h>
#include "config.h"
#include "pins.h"
#include "nfc.h"
#include "otaproxy.h"
#include "helpers.h"
#include "Desfire.h"
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#include <SPI.h>
#include <SSD1306Wire.h>
WiFiClient espClient;
//Config_Data config;
PubSubClient* mqtt;
NFC* nfc;
OTAProxy* ota;
void setup_wifi()
{
delay(10);
Serial.println("Connecting Wifi ...");
WiFi.mode(WIFI_STA);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
randomSeed(micros());
Serial.println("WiFi connected");
}
void reconnect()
{
while (!mqtt->connected())
{
String clientId = "FabReader_";
clientId += String(FABREADERID);
Serial.println("Connecting MQTT ...");
if (mqtt->connect(clientId.c_str()))
{
Serial.println("MQTT connected");
char id[6] = "00000";
sprintf(id, "%05d", FABREADERID);
mqtt->publish("fabreader", id);
char topic_requestOTA[] = "fabreader/00000/requestOTA";
sprintf(topic_requestOTA, "fabreader/%05d/requestOTA", FABREADERID);
mqtt->subscribe(topic_requestOTA);
char topic_stopOTA[] = "fabreader/00000/stopOTA";
sprintf(topic_stopOTA, "fabreader/%05d/stopOTA", FABREADERID);
mqtt->subscribe(topic_stopOTA);
} else {
Serial.print("failed, rc=");
Serial.print(mqtt->state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.println("Receive Message");
Serial.println(topic);
if(ota->hasActiveOTA())
{
ota->continueOTA(topic, payload, length);
}
}
void setup()
{
Serial.begin(115200);
Serial.print("\n\n\n");
Serial.println("Booting ...");
pinMode(PIN_BUZZER, OUTPUT);
pinMode(PIN_BUTTON, INPUT);
pinMode(PIN_ETH_SPI_SS, OUTPUT);
digitalWrite(PIN_ETH_SPI_SS, HIGH);
Serial.println("Connecting NFC ...");
nfc = new NFC(PIN_RFID_SPI_SS, PIN_RFID_RST);
if(!(nfc->rfid->PCD_PerformSelfTest()))
{
Serial.println("NFC Test failed");
}
Serial.println("NFC connected");
// setup_wifi();
// mqtt = new PubSubClient(espClient);
// mqtt->setServer(MQTT_BROKER, 1883);
// mqtt->setCallback(callback);
// ota = new OTAProxy(mqtt, nfc, FABREADERID);
}
void loop()
{
if(!(nfc->hasCardSelected()) && nfc->hasNewCard() && nfc->selectCard())
{
// DESFire::mifare_desfire_tag tag;
// tag.pcb = 0x0A;
// tag.cid = 0x00;
// DESFire::mifare_desfire_aid_t aid;
// aid.data[0] = 0x42;
// aid.data[1] = 0x41;
// aid.data[2] = 0x46;
// DESFire::StatusCode status = nfc->rfid->MIFARE_DESFIRE_SelectApplication(&tag, &aid);
// Serial.printf("%02x\n", status.mfrc522);
char command_h[APDU_BUFFER_SIZE*2] = "905a00000342414600";
byte command[APDU_BUFFER_SIZE] = { 0 };
byte command_len = strlen(command_h)/2;
byte response[APDU_BUFFER_SIZE] = { 0 };
byte response_len = 0;
char response_h[APDU_BUFFER_SIZE*2] = { 0 };
Serial.print("Command: ");
Serial.println(command_h);
chars2bytes(command_h, command, true);
MFRC522::StatusCode status = nfc->Transceive(command, command_len, response, &response_len);
Serial.printf("PICC_Tranceive: 0x%02x\n", status);
// bytes2chars(response, response_len, response_h, true);
// Serial.print("Response: ");
// Serial.println(response_h);
}
if(nfc->hasCardSelected() && nfc->isCardLost())
{
nfc->deselectCard();
}
// if (!mqtt->connected())
// {
// reconnect();
// }
// mqtt->loop();
// if(ota->hasActiveOTA() && nfc->isCardLost())
// {
// ota->cancelOTA();
// }
// if(!ota->hasActiveOTA() && nfc->hasNewCard())
// {
// ota->startOTA();
// }
}