// RFID sensor libraries and definitions #include #include "MFRC522.h" #define RST_PIN 4 // RST-PIN for RC522 - RFID - SPI #define SS_PIN 16 // SDA-PIN for RC522 - RFID - SPI MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance #ifdef USE_PN532_HSU #define XSNS_40 40 uint8_t pn532_model = 0; // Used to maintain detection flag uint8_t pn532_command = 0; // Used to carry command code between functions uint8_t pn532_scantimer = 0; // Used to prevent multiple successful reads within 2 second window uint8_t pn532_packetbuffer[64]; // Global buffer used to store packet #ifdef USE_PN532_DATA_FUNCTION uint8_t pn532_function = 0; uint8_t pn532_newdata[16]; uint8_t pn532_newdata_len = 0; #endif // USE_PN532_DATA_FUNCTION void dump_byte_array(byte *buffer, byte bufferSize) { for (byte i = 0; i < bufferSize; i++) { Serial.print(buffer[i] < 0x10 ? " 0" : " "); Serial.print(buffer[i], HEX); } } void PN532_Init(void) { if (PinUsed(GPIO_PN532_RXD) && PinUsed(GPIO_PN532_TXD)) { SPI.begin(); // Init SPI bus mfrc522.PCD_Init(); // if (mfrc522.PCD_Init()== 1) { // Init MFRC522 pn532_model = 1; AddLog_P(LOG_LEVEL_INFO,"NFC: PN532 NFC Reader detected"); // } } } void array_to_string(byte array[], unsigned int len, char buffer[]) { for (unsigned int i = 0; i < len; i++) { byte nib1 = (array[i] >> 4) & 0x0F; byte nib2 = (array[i] >> 0) & 0x0F; buffer[i*2+0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA; buffer[i*2+1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA; } buffer[len*2] = '\0'; } void PN532_ScanForTag(void) { if (!pn532_model) { return; } if (mfrc522.PICC_IsNewCardPresent()){ mfrc522.PICC_ReadCardSerial(); char uids[15]; // ToHex_P((unsigned char*)mfrc522.uid, mfrc522.uid.size, uids, sizeof(uids)); // dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size); char str[32] = ""; array_to_string(mfrc522.uid.uidByte, 4, str); ResponseTime_P(PSTR(",\"PN532\":{\"UID\":\"%s\"}}"), str); MqttPublishTeleSensor(); pn532_scantimer = 7; // Ignore tags found for two seconds } } #ifdef USE_PN532_DATA_FUNCTION bool PN532_Command(void) { bool serviced = true; uint8_t paramcount = 0; serviced = false; return serviced; } #endif // USE_PN532_DATA_FUNCTION bool Xsns40(uint8_t function) { bool result = false; switch (function) { case FUNC_INIT: PN532_Init(); result = true; break; case FUNC_EVERY_50_MSECOND: break; case FUNC_EVERY_100_MSECOND: break; case FUNC_EVERY_250_MSECOND: if (pn532_scantimer > 0) { pn532_scantimer--; } else { PN532_ScanForTag(); } break; case FUNC_EVERY_SECOND: break; #ifdef USE_PN532_DATA_FUNCTION case FUNC_COMMAND_SENSOR: if (XSNS_40 == XdrvMailbox.index) { result = PN532_Command(); } break; #endif } return result; } #endif // USE_PN532_HSU