Make fit for beta release (#51)

* removed

* edited a lot of stuff
This commit is contained in:
Valentin Heiserer
2024-04-26 01:41:50 +02:00
committed by GitHub
parent 2e5a42b6d3
commit 539e29dc56
94 changed files with 843 additions and 8636 deletions

View File

@@ -26,10 +26,6 @@ jobs:
run: npm install
working-directory: Frontend
- name: Create .env file
run: echo "VITE_APP_WEBSOCKET_IP=localhost" > .env
working-directory: Frontend
- name: Build Frontend
run: npm run build
working-directory: Frontend

View File

@@ -1,25 +0,0 @@
// redefine some stuff so code works on Due
// http://arduino.cc/forum/index.php?&topic=153761.0
#ifndef Due_h
#define Due_h
#if defined(__SAM3X8E__)
#define PROGMEM
#define pgm_read_byte(x) (*((char *)x))
// #define pgm_read_word(x) (*((short *)(x & 0xfffffffe)))
#define pgm_read_word(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x)))
#define pgm_read_byte_near(x) (*((char *)x))
#define pgm_read_byte_far(x) (*((char *)x))
// #define pgm_read_word_near(x) (*((short *)(x & 0xfffffffe))
// #define pgm_read_word_far(x) (*((short *)(x & 0xfffffffe)))
#define pgm_read_word_near(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x)))
#define pgm_read_word_far(x) ( ((*((unsigned char *)x + 1)) << 8) + (*((unsigned char *)x))))
#define PSTR(x) x
#if defined F
#undef F
#endif
#define F(X) (X)
#endif
#endif

View File

@@ -1,29 +0,0 @@
Software License Agreement (BSD License)
Copyright (c) 2013-2014, Don Coleman
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,405 +0,0 @@
#include "MifareClassic.h"
#define BLOCK_SIZE 16
#define LONG_TLV_SIZE 4
#define SHORT_TLV_SIZE 2
#define MIFARE_CLASSIC ("Mifare Classic")
MifareClassic::MifareClassic(PN532& nfcShield)
{
_nfcShield = &nfcShield;
}
MifareClassic::~MifareClassic()
{
}
NfcTag MifareClassic::read(byte *uid, unsigned int uidLength)
{
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
int currentBlock = 4;
int messageStartIndex = 0;
int messageLength = 0;
byte data[BLOCK_SIZE];
// read first block to get message length
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (success)
{
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, data);
if (success)
{
if (!decodeTlv(data, messageLength, messageStartIndex)) {
return NfcTag(uid, uidLength, "ERROR"); // TODO should the error message go in NfcTag?
}
}
else
{
Serial.print(F("Error. Failed read block "));Serial.println(currentBlock);
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
}
else
{
Serial.println(F("Tag is not NDEF formatted."));
// TODO set tag.isFormatted = false
return NfcTag(uid, uidLength, MIFARE_CLASSIC);
}
// this should be nested in the message length loop
int index = 0;
int bufferSize = getBufferSize(messageLength);
uint8_t buffer[bufferSize];
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Message Length "));Serial.println(messageLength);
Serial.print(F("Buffer Size "));Serial.println(bufferSize);
#endif
while (index < bufferSize)
{
// authenticate on every sector
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
// TODO error handling
}
}
// read the data
success = _nfcShield->mifareclassic_ReadDataBlock(currentBlock, &buffer[index]);
if (success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Block "));Serial.print(currentBlock);Serial.print(" ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Read failed "));Serial.println(currentBlock);
// TODO handle errors here
}
index += BLOCK_SIZE;
currentBlock++;
// skip the trailer block
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return NfcTag(uid, uidLength, MIFARE_CLASSIC, &buffer[messageStartIndex], messageLength);
}
int MifareClassic::getBufferSize(int messageLength)
{
int bufferSize = messageLength;
// TLV header is 2 or 4 bytes, TLV terminator is 1 byte.
if (messageLength < 0xFF)
{
bufferSize += SHORT_TLV_SIZE + 1;
}
else
{
bufferSize += LONG_TLV_SIZE + 1;
}
// bufferSize needs to be a multiple of BLOCK_SIZE
if (bufferSize % BLOCK_SIZE != 0)
{
bufferSize = ((bufferSize / BLOCK_SIZE) + 1) * BLOCK_SIZE;
}
return bufferSize;
}
// skip null tlvs (0x0) before the real message
// technically unlimited null tlvs, but we assume
// T & L of TLV in the first block we read
int MifareClassic::getNdefStartIndex(byte *data)
{
for (int i = 0; i < BLOCK_SIZE; i++)
{
if (data[i] == 0x0)
{
// do nothing, skip
}
else if (data[i] == 0x3)
{
return i;
}
else
{
Serial.print("Unknown TLV ");Serial.println(data[i], HEX);
return -2;
}
}
return -1;
}
// Decode the NDEF data length from the Mifare TLV
// Leading null TLVs (0x0) are skipped
// Assuming T & L of TLV will be in the first block
// messageLength and messageStartIndex written to the parameters
// success or failure status is returned
//
// { 0x3, LENGTH }
// { 0x3, 0xFF, LENGTH, LENGTH }
bool MifareClassic::decodeTlv(byte *data, int &messageLength, int &messageStartIndex)
{
int i = getNdefStartIndex(data);
if (i < 0 || data[i] != 0x3)
{
Serial.println(F("Error. Can't decode message length."));
return false;
}
else
{
if (data[i+1] == 0xFF)
{
messageLength = ((0xFF & data[i+2]) << 8) | (0xFF & data[i+3]);
messageStartIndex = i + LONG_TLV_SIZE;
}
else
{
messageLength = data[i+1];
messageStartIndex = i + SHORT_TLV_SIZE;
}
}
return true;
}
// Intialized NDEF tag contains one empty NDEF TLV 03 00 FE - AN1304 6.3.1
// We are formatting in read/write mode with a NDEF TLV 03 03 and an empty NDEF record D0 00 00 FE - AN1304 6.3.2
boolean MifareClassic::formatNDEF(byte * uid, unsigned int uidLength)
{
uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
uint8_t emptyNdefMesg[16] = {0x03, 0x03, 0xD0, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t sectorbuffer0[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
boolean success = _nfcShield->mifareclassic_AuthenticateBlock (uid, uidLength, 0, 0, keya);
if (!success)
{
Serial.println(F("Unable to authenticate block 0 to enable card formatting!"));
return false;
}
success = _nfcShield->mifareclassic_FormatNDEF();
if (!success)
{
Serial.println(F("Unable to format the card for NDEF"));
}
else
{
for (int i=4; i<64; i+=4) {
success = _nfcShield->mifareclassic_AuthenticateBlock (uid, uidLength, i, 0, keya);
if (success) {
if (i == 4) // special handling for block 4
{
if (!(_nfcShield->mifareclassic_WriteDataBlock (i, emptyNdefMesg)))
{
Serial.print(F("Unable to write block "));Serial.println(i);
}
}
else
{
if (!(_nfcShield->mifareclassic_WriteDataBlock (i, sectorbuffer0)))
{
Serial.print(F("Unable to write block "));Serial.println(i);
}
}
if (!(_nfcShield->mifareclassic_WriteDataBlock (i+1, sectorbuffer0)))
{
Serial.print(F("Unable to write block "));Serial.println(i+1);
}
if (!(_nfcShield->mifareclassic_WriteDataBlock (i+2, sectorbuffer0)))
{
Serial.print(F("Unable to write block "));Serial.println(i+2);
}
if (!(_nfcShield->mifareclassic_WriteDataBlock (i+3, sectorbuffer4)))
{
Serial.print(F("Unable to write block "));Serial.println(i+3);
}
} else {
unsigned int iii=uidLength;
Serial.print(F("Unable to authenticate block "));Serial.println(i);
_nfcShield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&iii);
}
}
}
return success;
}
#define NR_SHORTSECTOR (32) // Number of short sectors on Mifare 1K/4K
#define NR_LONGSECTOR (8) // Number of long sectors on Mifare 4K
#define NR_BLOCK_OF_SHORTSECTOR (4) // Number of blocks in a short sector
#define NR_BLOCK_OF_LONGSECTOR (16) // Number of blocks in a long sector
// Determine the sector trailer block based on sector number
#define BLOCK_NUMBER_OF_SECTOR_TRAILER(sector) (((sector)<NR_SHORTSECTOR)? \
((sector)*NR_BLOCK_OF_SHORTSECTOR + NR_BLOCK_OF_SHORTSECTOR-1):\
(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR + NR_BLOCK_OF_LONGSECTOR-1))
boolean MifareClassic::formatMifare(byte * uid, unsigned int uidLength)
{
// The default Mifare Classic key
uint8_t KEY_DEFAULT_KEYAB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
uint8_t blockBuffer[16]; // Buffer to store block contents
uint8_t blankAccessBits[3] = { 0xff, 0x07, 0x80 };
uint8_t idx = 0;
uint8_t numOfSector = 16; // Assume Mifare Classic 1K for now (16 4-block sectors)
boolean success = false;
for (idx = 0; idx < numOfSector; idx++)
{
// Step 1: Authenticate the current sector using key B 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
success = _nfcShield->mifareclassic_AuthenticateBlock (uid, uidLength, BLOCK_NUMBER_OF_SECTOR_TRAILER(idx), 1, (uint8_t *)KEY_DEFAULT_KEYAB);
if (!success)
{
Serial.print(F("Authentication failed for sector ")); Serial.println(idx);
return false;
}
// Step 2: Write to the other blocks
if (idx == 0)
{
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))
{
Serial.print(F("Unable to write to sector ")); Serial.println(idx);
}
}
else
{
memset(blockBuffer, 0, sizeof(blockBuffer));
// this block has not to be overwritten for block 0. It contains Tag id and other unique data.
if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer)))
{
Serial.print(F("Unable to write to sector ")); Serial.println(idx);
}
if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))
{
Serial.print(F("Unable to write to sector ")); Serial.println(idx);
}
}
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 1, blockBuffer)))
{
Serial.print(F("Unable to write to sector ")); Serial.println(idx);
}
// Step 3: Reset both keys to 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
memcpy(blockBuffer, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));
memcpy(blockBuffer + 6, blankAccessBits, sizeof(blankAccessBits));
blockBuffer[9] = 0x69;
memcpy(blockBuffer + 10, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));
// Step 4: Write the trailer block
if (!(_nfcShield->mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)), blockBuffer)))
{
Serial.print(F("Unable to write trailer block of sector ")); Serial.println(idx);
}
}
return true;
}
boolean MifareClassic::write(NdefMessage& m, byte * uid, unsigned int uidLength)
{
uint8_t encoded[m.getEncodedSize()];
m.encode(encoded);
uint8_t buffer[getBufferSize(sizeof(encoded))];
memset(buffer, 0, sizeof(buffer));
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("sizeof(encoded) "));Serial.println(sizeof(encoded));
Serial.print(F("sizeof(buffer) "));Serial.println(sizeof(buffer));
#endif
if (sizeof(encoded) < 0xFF)
{
buffer[0] = 0x3;
buffer[1] = sizeof(encoded);
memcpy(&buffer[2], encoded, sizeof(encoded));
buffer[2+sizeof(encoded)] = 0xFE; // terminator
}
else
{
buffer[0] = 0x3;
buffer[1] = 0xFF;
buffer[2] = ((sizeof(encoded) >> 8) & 0xFF);
buffer[3] = (sizeof(encoded) & 0xFF);
memcpy(&buffer[4], encoded, sizeof(encoded));
buffer[4+sizeof(encoded)] = 0xFE; // terminator
}
// Write to tag
int index = 0;
int currentBlock = 4;
uint8_t key[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 }; // this is Sector 1 - 15 key
while (index < sizeof(buffer))
{
if (_nfcShield->mifareclassic_IsFirstBlock(currentBlock))
{
int success = _nfcShield->mifareclassic_AuthenticateBlock(uid, uidLength, currentBlock, 0, key);
if (!success)
{
Serial.print(F("Error. Block Authentication failed for "));Serial.println(currentBlock);
return false;
}
}
int write_success = _nfcShield->mifareclassic_WriteDataBlock (currentBlock, &buffer[index]);
if (write_success)
{
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Wrote block "));Serial.print(currentBlock);Serial.print(" - ");
_nfcShield->PrintHexChar(&buffer[index], BLOCK_SIZE);
#endif
}
else
{
Serial.print(F("Write failed "));Serial.println(currentBlock);
return false;
}
index += BLOCK_SIZE;
currentBlock++;
if (_nfcShield->mifareclassic_IsTrailerBlock(currentBlock))
{
// can't write to trailer block
#ifdef MIFARE_CLASSIC_DEBUG
Serial.print(F("Skipping block "));Serial.println(currentBlock);
#endif
currentBlock++;
}
}
return true;
}

View File

@@ -1,25 +0,0 @@
#ifndef MifareClassic_h
#define MifareClassic_h
#include <Due.h>
#include <PN532.h>
#include <Ndef.h>
#include <NfcTag.h>
class MifareClassic
{
public:
MifareClassic(PN532& nfcShield);
~MifareClassic();
NfcTag read(byte *uid, unsigned int uidLength);
boolean write(NdefMessage& ndefMessage, byte *uid, unsigned int uidLength);
boolean formatNDEF(byte * uid, unsigned int uidLength);
boolean formatMifare(byte * uid, unsigned int uidLength);
private:
PN532* _nfcShield;
int getBufferSize(int messageLength);
int getNdefStartIndex(byte *data);
bool decodeTlv(byte *data, int &messageLength, int &messageStartIndex);
};
#endif

View File

@@ -1,251 +0,0 @@
#include <MifareUltralight.h>
#define ULTRALIGHT_PAGE_SIZE 4
#define ULTRALIGHT_READ_SIZE 4 // we should be able to read 16 bytes at a time
#define ULTRALIGHT_DATA_START_PAGE 4
#define ULTRALIGHT_MESSAGE_LENGTH_INDEX 1
#define ULTRALIGHT_DATA_START_INDEX 2
#define ULTRALIGHT_MAX_PAGE 63
#define NFC_FORUM_TAG_TYPE_2 ("NFC Forum Type 2")
MifareUltralight::MifareUltralight(PN532& nfcShield)
{
nfc = &nfcShield;
ndefStartIndex = 0;
messageLength = 0;
}
MifareUltralight::~MifareUltralight()
{
}
NfcTag MifareUltralight::read(byte * uid, unsigned int uidLength)
{
if (isUnformatted())
{
Serial.println(F("WARNING: Tag is not formatted."));
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2);
}
readCapabilityContainer(); // meta info for tag
findNdefMessage();
calculateBufferSize();
if (messageLength == 0) { // data is 0x44 0x03 0x00 0xFE
NdefMessage message = NdefMessage();
message.addEmptyRecord();
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, message);
}
boolean success;
uint8_t page;
uint8_t index = 0;
byte buffer[bufferSize];
for (page = ULTRALIGHT_DATA_START_PAGE; page < ULTRALIGHT_MAX_PAGE; page++)
{
// read the data
success = nfc->mifareultralight_ReadPage(page, &buffer[index]);
if (success)
{
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Page "));Serial.print(page);Serial.print(" ");
nfc->PrintHexChar(&buffer[index], ULTRALIGHT_PAGE_SIZE);
#endif
}
else
{
Serial.print(F("Read failed "));Serial.println(page);
// TODO error handling
messageLength = 0;
break;
}
if (index >= (messageLength + ndefStartIndex))
{
break;
}
index += ULTRALIGHT_PAGE_SIZE;
}
NdefMessage ndefMessage = NdefMessage(&buffer[ndefStartIndex], messageLength);
return NfcTag(uid, uidLength, NFC_FORUM_TAG_TYPE_2, ndefMessage);
}
boolean MifareUltralight::isUnformatted()
{
uint8_t page = 4;
byte data[ULTRALIGHT_READ_SIZE];
boolean success = nfc->mifareultralight_ReadPage (page, data);
if (success)
{
return (data[0] == 0xFF && data[1] == 0xFF && data[2] == 0xFF && data[3] == 0xFF);
}
else
{
Serial.print(F("Error. Failed read page "));Serial.println(page);
return false;
}
}
// page 3 has tag capabilities
void MifareUltralight::readCapabilityContainer()
{
byte data[ULTRALIGHT_PAGE_SIZE];
int success = nfc->mifareultralight_ReadPage (3, data);
if (success)
{
// See AN1303 - different rules for Mifare Family byte2 = (additional data + 48)/8
tagCapacity = data[2] * 8;
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Tag capacity "));Serial.print(tagCapacity);Serial.println(F(" bytes"));
#endif
// TODO future versions should get lock information
}
}
// read enough of the message to find the ndef message length
void MifareUltralight::findNdefMessage()
{
int page;
byte data[12]; // 3 pages
byte* data_ptr = &data[0];
// the nxp read command reads 4 pages, unfortunately adafruit give me one page at a time
boolean success = true;
for (page = 4; page < 6; page++)
{
success = success && nfc->mifareultralight_ReadPage(page, data_ptr);
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Page "));Serial.print(page);Serial.print(F(" - "));
nfc->PrintHexChar(data_ptr, 4);
#endif
data_ptr += ULTRALIGHT_PAGE_SIZE;
}
if (success)
{
if (data[0] == 0x03)
{
messageLength = data[1];
ndefStartIndex = 2;
}
else if (data[5] == 0x3) // page 5 byte 1
{
// TODO should really read the lock control TLV to ensure byte[5] is correct
messageLength = data[6];
ndefStartIndex = 7;
}
}
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("messageLength "));Serial.println(messageLength);
Serial.print(F("ndefStartIndex "));Serial.println(ndefStartIndex);
#endif
}
// buffer is larger than the message, need to handle some data before and after
// message and need to ensure we read full pages
void MifareUltralight::calculateBufferSize()
{
// TLV terminator 0xFE is 1 byte
bufferSize = messageLength + ndefStartIndex + 1;
if (bufferSize % ULTRALIGHT_READ_SIZE != 0)
{
// buffer must be an increment of page size
bufferSize = ((bufferSize / ULTRALIGHT_READ_SIZE) + 1) * ULTRALIGHT_READ_SIZE;
}
}
boolean MifareUltralight::write(NdefMessage& m, byte * uid, unsigned int uidLength)
{
if (isUnformatted())
{
Serial.println(F("WARNING: Tag is not formatted."));
return false;
}
readCapabilityContainer(); // meta info for tag
messageLength = m.getEncodedSize();
ndefStartIndex = messageLength < 0xFF ? 2 : 4;
calculateBufferSize();
if(bufferSize>tagCapacity) {
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Encoded Message length exceeded tag Capacity "));Serial.println(tagCapacity);
#endif
return false;
}
uint8_t encoded[bufferSize];
uint8_t * src = encoded;
unsigned int position = 0;
uint8_t page = ULTRALIGHT_DATA_START_PAGE;
// Set message size. With ultralight should always be less than 0xFF but who knows?
encoded[0] = 0x3;
if (messageLength < 0xFF)
{
encoded[1] = messageLength;
}
else
{
encoded[1] = 0xFF;
encoded[2] = ((messageLength >> 8) & 0xFF);
encoded[3] = (messageLength & 0xFF);
}
m.encode(encoded+ndefStartIndex);
// this is always at least 1 byte copy because of terminator.
memset(encoded+ndefStartIndex+messageLength,0,bufferSize-ndefStartIndex-messageLength);
encoded[ndefStartIndex+messageLength] = 0xFE; // terminator
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("messageLength "));Serial.println(messageLength);
Serial.print(F("Tag Capacity "));Serial.println(tagCapacity);
nfc->PrintHex(encoded,bufferSize);
#endif
while (position < bufferSize){ //bufferSize is always times pagesize so no "last chunk" check
// write page
if (!nfc->mifareultralight_WritePage(page, src))
return false;
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Wrote page "));Serial.print(page);Serial.print(F(" - "));
nfc->PrintHex(src,ULTRALIGHT_PAGE_SIZE);
#endif
page++;
src+=ULTRALIGHT_PAGE_SIZE;
position+=ULTRALIGHT_PAGE_SIZE;
}
return true;
}
// Mifare Ultralight can't be reset to factory state
// zero out tag data like the NXP Tag Write Android application
boolean MifareUltralight::clean()
{
readCapabilityContainer(); // meta info for tag
uint8_t pages = (tagCapacity / ULTRALIGHT_PAGE_SIZE) + ULTRALIGHT_DATA_START_PAGE;
// factory tags have 0xFF, but OTP-CC blocks have already been set so we use 0x00
uint8_t data[4] = { 0x00, 0x00, 0x00, 0x00 };
for (int i = ULTRALIGHT_DATA_START_PAGE; i < pages; i++) {
#ifdef MIFARE_ULTRALIGHT_DEBUG
Serial.print(F("Wrote page "));Serial.print(i);Serial.print(F(" - "));
nfc->PrintHex(data, ULTRALIGHT_PAGE_SIZE);
#endif
if (!nfc->mifareultralight_WritePage(i, data)) {
return false;
}
}
return true;
}

View File

@@ -1,28 +0,0 @@
#ifndef MifareUltralight_h
#define MifareUltralight_h
#include <PN532.h>
#include <NfcTag.h>
#include <Ndef.h>
class MifareUltralight
{
public:
MifareUltralight(PN532& nfcShield);
~MifareUltralight();
NfcTag read(byte *uid, unsigned int uidLength);
boolean write(NdefMessage& ndefMessage, byte *uid, unsigned int uidLength);
boolean clean();
private:
PN532* nfc;
unsigned int tagCapacity;
unsigned int messageLength;
unsigned int bufferSize;
unsigned int ndefStartIndex;
boolean isUnformatted();
void readCapabilityContainer();
void findNdefMessage();
void calculateBufferSize();
};
#endif

View File

@@ -1,57 +0,0 @@
#include "Ndef.h"
// Borrowed from Adafruit_NFCShield_I2C
void PrintHex(const byte * data, const long numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
Serial.print("0x");
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos]&0xff, HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.println("");
}
// Borrowed from Adafruit_NFCShield_I2C
void PrintHexChar(const byte * data, const long numBytes)
{
uint32_t szPos;
for (szPos=0; szPos < numBytes; szPos++)
{
// Append leading 0 for small values
if (data[szPos] <= 0xF)
Serial.print("0");
Serial.print(data[szPos], HEX);
if ((numBytes > 1) && (szPos != numBytes - 1))
{
Serial.print(" ");
}
}
Serial.print(" ");
for (szPos=0; szPos < numBytes; szPos++)
{
if (data[szPos] <= 0x1F)
Serial.print(".");
else
Serial.print((char)data[szPos]);
}
Serial.println("");
}
// Note if buffer % blockSize != 0, last block will not be written
void DumpHex(const byte * data, const long numBytes, const unsigned int blockSize)
{
int i;
for (i = 0; i < (numBytes / blockSize); i++)
{
PrintHexChar(data, blockSize);
data += blockSize;
}
}

View File

@@ -1,16 +0,0 @@
#ifndef Ndef_h
#define Ndef_h
/* NOTE: To use the Ndef library in your code, don't include Ndef.h
See README.md for details on which files to include in your sketch.
*/
#include <Arduino.h>
#define NULL (void *)0
void PrintHex(const byte *data, const long numBytes);
void PrintHexChar(const byte *data, const long numBytes);
void DumpHex(const byte *data, const long numBytes, const int blockSize);
#endif

View File

@@ -1,274 +0,0 @@
#include <NdefMessage.h>
NdefMessage::NdefMessage(void)
{
_recordCount = 0;
}
NdefMessage::NdefMessage(const byte * data, const int numBytes)
{
#ifdef NDEF_DEBUG
Serial.print(F("Decoding "));Serial.print(numBytes);Serial.println(F(" bytes"));
PrintHexChar(data, numBytes);
//DumpHex(data, numBytes, 16);
#endif
_recordCount = 0;
int index = 0;
while (index <= numBytes)
{
// decode tnf - first byte is tnf with bit flags
// see the NFDEF spec for more info
byte tnf_byte = data[index];
bool mb = (tnf_byte & 0x80) != 0;
bool me = (tnf_byte & 0x40) != 0;
bool cf = (tnf_byte & 0x20) != 0;
bool sr = (tnf_byte & 0x10) != 0;
bool il = (tnf_byte & 0x8) != 0;
byte tnf = (tnf_byte & 0x7);
NdefRecord record = NdefRecord();
record.setTnf(tnf);
index++;
int typeLength = data[index];
int payloadLength = 0;
if (sr)
{
index++;
payloadLength = data[index];
}
else
{
payloadLength =
((0xFF & data[++index]) << 24)
| ((0xFF & data[++index]) << 16)
| ((0xFF & data[++index]) << 8)
| (0xFF & data[++index]);
}
int idLength = 0;
if (il)
{
index++;
idLength = data[index];
}
index++;
record.setType(&data[index], typeLength);
index += typeLength;
if (il)
{
record.setId(&data[index], idLength);
index += idLength;
}
record.setPayload(&data[index], payloadLength);
index += payloadLength;
addRecord(record);
if (me) break; // last message
}
}
NdefMessage::NdefMessage(const NdefMessage& rhs)
{
_recordCount = rhs._recordCount;
for (int i = 0; i < _recordCount; i++)
{
_records[i] = rhs._records[i];
}
}
NdefMessage::~NdefMessage()
{
}
NdefMessage& NdefMessage::operator=(const NdefMessage& rhs)
{
if (this != &rhs)
{
// delete existing records
for (int i = 0; i < _recordCount; i++)
{
// TODO Dave: is this the right way to delete existing records?
_records[i] = NdefRecord();
}
_recordCount = rhs._recordCount;
for (int i = 0; i < _recordCount; i++)
{
_records[i] = rhs._records[i];
}
}
return *this;
}
unsigned int NdefMessage::getRecordCount()
{
return _recordCount;
}
int NdefMessage::getEncodedSize()
{
int size = 0;
for (int i = 0; i < _recordCount; i++)
{
size += _records[i].getEncodedSize();
}
return size;
}
// TODO change this to return uint8_t*
void NdefMessage::encode(uint8_t* data)
{
// assert sizeof(data) >= getEncodedSize()
uint8_t* data_ptr = &data[0];
for (int i = 0; i < _recordCount; i++)
{
_records[i].encode(data_ptr, i == 0, (i + 1) == _recordCount);
// TODO can NdefRecord.encode return the record size?
data_ptr += _records[i].getEncodedSize();
}
}
boolean NdefMessage::addRecord(NdefRecord& record)
{
if (_recordCount < MAX_NDEF_RECORDS)
{
_records[_recordCount] = record;
_recordCount++;
return true;
}
else
{
Serial.println(F("WARNING: Too many records. Increase MAX_NDEF_RECORDS."));
return false;
}
}
void NdefMessage::addMimeMediaRecord(String mimeType, String payload)
{
byte payloadBytes[payload.length() + 1];
payload.getBytes(payloadBytes, sizeof(payloadBytes));
addMimeMediaRecord(mimeType, payloadBytes, payload.length());
}
void NdefMessage::addMimeMediaRecord(String mimeType, uint8_t* payload, int payloadLength)
{
NdefRecord r = NdefRecord();
r.setTnf(TNF_MIME_MEDIA);
byte type[mimeType.length() + 1];
mimeType.getBytes(type, sizeof(type));
r.setType(type, mimeType.length());
r.setPayload(payload, payloadLength);
addRecord(r);
}
void NdefMessage::addTextRecord(String text)
{
addTextRecord(text, "en");
}
void NdefMessage::addTextRecord(String text, String encoding)
{
NdefRecord r = NdefRecord();
r.setTnf(TNF_WELL_KNOWN);
uint8_t RTD_TEXT[1] = { 0x54 }; // TODO this should be a constant or preprocessor
r.setType(RTD_TEXT, sizeof(RTD_TEXT));
// X is a placeholder for encoding length
// TODO is it more efficient to build w/o string concatenation?
String payloadString = "X" + encoding + text;
byte payload[payloadString.length() + 1];
payloadString.getBytes(payload, sizeof(payload));
// replace X with the real encoding length
payload[0] = encoding.length();
r.setPayload(payload, payloadString.length());
addRecord(r);
}
void NdefMessage::addUriRecord(String uri)
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_WELL_KNOWN);
uint8_t RTD_URI[1] = { 0x55 }; // TODO this should be a constant or preprocessor
r->setType(RTD_URI, sizeof(RTD_URI));
// X is a placeholder for identifier code
String payloadString = "X" + uri;
byte payload[payloadString.length() + 1];
payloadString.getBytes(payload, sizeof(payload));
// add identifier code 0x0, meaning no prefix substitution
payload[0] = 0x0;
r->setPayload(payload, payloadString.length());
addRecord(*r);
delete(r);
}
void NdefMessage::addEmptyRecord()
{
NdefRecord* r = new NdefRecord();
r->setTnf(TNF_EMPTY);
addRecord(*r);
delete(r);
}
NdefRecord NdefMessage::getRecord(int index)
{
if (index > -1 && index < _recordCount)
{
return _records[index];
}
else
{
return NdefRecord(); // would rather return NULL
}
}
NdefRecord NdefMessage::operator[](int index)
{
return getRecord(index);
}
void NdefMessage::print()
{
Serial.print(F("\nNDEF Message "));Serial.print(_recordCount);Serial.print(F(" record"));
_recordCount == 1 ? Serial.print(", ") : Serial.print("s, ");
Serial.print(getEncodedSize());Serial.println(F(" bytes"));
int i;
for (i = 0; i < _recordCount; i++)
{
_records[i].print();
}
}

View File

@@ -1,39 +0,0 @@
#ifndef NdefMessage_h
#define NdefMessage_h
#include <Ndef.h>
#include <NdefRecord.h>
#define MAX_NDEF_RECORDS 4
class NdefMessage
{
public:
NdefMessage(void);
NdefMessage(const byte *data, const int numBytes);
NdefMessage(const NdefMessage& rhs);
~NdefMessage();
NdefMessage& operator=(const NdefMessage& rhs);
int getEncodedSize(); // need so we can pass array to encode
void encode(byte *data);
boolean addRecord(NdefRecord& record);
void addMimeMediaRecord(String mimeType, String payload);
void addMimeMediaRecord(String mimeType, byte *payload, int payloadLength);
void addTextRecord(String text);
void addTextRecord(String text, String encoding);
void addUriRecord(String uri);
void addEmptyRecord();
unsigned int getRecordCount();
NdefRecord getRecord(int index);
NdefRecord operator[](int index);
void print();
private:
NdefRecord _records[MAX_NDEF_RECORDS];
unsigned int _recordCount;
};
#endif

View File

@@ -1,352 +0,0 @@
#include "NdefRecord.h"
NdefRecord::NdefRecord()
{
//Serial.println("NdefRecord Constructor 1");
_tnf = 0;
_typeLength = 0;
_payloadLength = 0;
_idLength = 0;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
}
NdefRecord::NdefRecord(const NdefRecord& rhs)
{
//Serial.println("NdefRecord Constructor 2 (copy)");
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
_type = (byte *)NULL;
_payload = (byte *)NULL;
_id = (byte *)NULL;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
// TODO NdefRecord::NdefRecord(tnf, type, payload, id)
NdefRecord::~NdefRecord()
{
//Serial.println("NdefRecord Destructor");
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
}
NdefRecord& NdefRecord::operator=(const NdefRecord& rhs)
{
//Serial.println("NdefRecord ASSIGN");
if (this != &rhs)
{
// free existing
if (_typeLength)
{
free(_type);
}
if (_payloadLength)
{
free(_payload);
}
if (_idLength)
{
free(_id);
}
_tnf = rhs._tnf;
_typeLength = rhs._typeLength;
_payloadLength = rhs._payloadLength;
_idLength = rhs._idLength;
if (_typeLength)
{
_type = (byte*)malloc(_typeLength);
memcpy(_type, rhs._type, _typeLength);
}
if (_payloadLength)
{
_payload = (byte*)malloc(_payloadLength);
memcpy(_payload, rhs._payload, _payloadLength);
}
if (_idLength)
{
_id = (byte*)malloc(_idLength);
memcpy(_id, rhs._id, _idLength);
}
}
return *this;
}
// size of records in bytes
int NdefRecord::getEncodedSize()
{
int size = 2; // tnf + typeLength
if (_payloadLength > 0xFF)
{
size += 4;
}
else
{
size += 1;
}
if (_idLength)
{
size += 1;
}
size += (_typeLength + _payloadLength + _idLength);
return size;
}
void NdefRecord::encode(byte *data, bool firstRecord, bool lastRecord)
{
// assert data > getEncodedSize()
uint8_t* data_ptr = &data[0];
*data_ptr = getTnfByte(firstRecord, lastRecord);
data_ptr += 1;
*data_ptr = _typeLength;
data_ptr += 1;
if (_payloadLength <= 0xFF) { // short record
*data_ptr = _payloadLength;
data_ptr += 1;
} else { // long format
// 4 bytes but we store length as an int
data_ptr[0] = 0x0; // (_payloadLength >> 24) & 0xFF;
data_ptr[1] = 0x0; // (_payloadLength >> 16) & 0xFF;
data_ptr[2] = (_payloadLength >> 8) & 0xFF;
data_ptr[3] = _payloadLength & 0xFF;
data_ptr += 4;
}
if (_idLength)
{
*data_ptr = _idLength;
data_ptr += 1;
}
//Serial.println(2);
memcpy(data_ptr, _type, _typeLength);
data_ptr += _typeLength;
memcpy(data_ptr, _payload, _payloadLength);
data_ptr += _payloadLength;
if (_idLength)
{
memcpy(data_ptr, _id, _idLength);
data_ptr += _idLength;
}
}
byte NdefRecord::getTnfByte(bool firstRecord, bool lastRecord)
{
int value = _tnf;
if (firstRecord) { // mb
value = value | 0x80;
}
if (lastRecord) { //
value = value | 0x40;
}
// chunked flag is always false for now
// if (cf) {
// value = value | 0x20;
// }
if (_payloadLength <= 0xFF) {
value = value | 0x10;
}
if (_idLength) {
value = value | 0x8;
}
return value;
}
byte NdefRecord::getTnf()
{
return _tnf;
}
void NdefRecord::setTnf(byte tnf)
{
_tnf = tnf;
}
unsigned int NdefRecord::getTypeLength()
{
return _typeLength;
}
int NdefRecord::getPayloadLength()
{
return _payloadLength;
}
unsigned int NdefRecord::getIdLength()
{
return _idLength;
}
String NdefRecord::getType()
{
char type[_typeLength + 1];
memcpy(type, _type, _typeLength);
type[_typeLength] = '\0'; // null terminate
return String(type);
}
// this assumes the caller created type correctly
void NdefRecord::getType(uint8_t* type)
{
memcpy(type, _type, _typeLength);
}
void NdefRecord::setType(const byte * type, const unsigned int numBytes)
{
if(_typeLength)
{
free(_type);
}
_type = (uint8_t*)malloc(numBytes);
memcpy(_type, type, numBytes);
_typeLength = numBytes;
}
// assumes the caller sized payload properly
void NdefRecord::getPayload(byte *payload)
{
memcpy(payload, _payload, _payloadLength);
}
void NdefRecord::setPayload(const byte * payload, const int numBytes)
{
if (_payloadLength)
{
free(_payload);
}
_payload = (byte*)malloc(numBytes);
memcpy(_payload, payload, numBytes);
_payloadLength = numBytes;
}
String NdefRecord::getId()
{
char id[_idLength + 1];
memcpy(id, _id, _idLength);
id[_idLength] = '\0'; // null terminate
return String(id);
}
void NdefRecord::getId(byte *id)
{
memcpy(id, _id, _idLength);
}
void NdefRecord::setId(const byte * id, const unsigned int numBytes)
{
if (_idLength)
{
free(_id);
}
_id = (byte*)malloc(numBytes);
memcpy(_id, id, numBytes);
_idLength = numBytes;
}
void NdefRecord::print()
{
Serial.println(F(" NDEF Record"));
Serial.print(F(" TNF 0x"));Serial.print(_tnf, HEX);Serial.print(" ");
switch (_tnf) {
case TNF_EMPTY:
Serial.println(F("Empty"));
break;
case TNF_WELL_KNOWN:
Serial.println(F("Well Known"));
break;
case TNF_MIME_MEDIA:
Serial.println(F("Mime Media"));
break;
case TNF_ABSOLUTE_URI:
Serial.println(F("Absolute URI"));
break;
case TNF_EXTERNAL_TYPE:
Serial.println(F("External"));
break;
case TNF_UNKNOWN:
Serial.println(F("Unknown"));
break;
case TNF_UNCHANGED:
Serial.println(F("Unchanged"));
break;
case TNF_RESERVED:
Serial.println(F("Reserved"));
break;
default:
Serial.println();
}
Serial.print(F(" Type Length 0x"));Serial.print(_typeLength, HEX);Serial.print(" ");Serial.println(_typeLength);
Serial.print(F(" Payload Length 0x"));Serial.print(_payloadLength, HEX);;Serial.print(" ");Serial.println(_payloadLength);
if (_idLength)
{
Serial.print(F(" Id Length 0x"));Serial.println(_idLength, HEX);
}
Serial.print(F(" Type "));PrintHexChar(_type, _typeLength);
// TODO chunk large payloads so this is readable
Serial.print(F(" Payload "));PrintHexChar(_payload, _payloadLength);
if (_idLength)
{
Serial.print(F(" Id "));PrintHexChar(_id, _idLength);
}
Serial.print(F(" Record is "));Serial.print(getEncodedSize());Serial.println(" bytes");
}

View File

@@ -1,58 +0,0 @@
#ifndef NdefRecord_h
#define NdefRecord_h
#include <Due.h>
#include <Arduino.h>
#include <Ndef.h>
#define TNF_EMPTY 0x0
#define TNF_WELL_KNOWN 0x01
#define TNF_MIME_MEDIA 0x02
#define TNF_ABSOLUTE_URI 0x03
#define TNF_EXTERNAL_TYPE 0x04
#define TNF_UNKNOWN 0x05
#define TNF_UNCHANGED 0x06
#define TNF_RESERVED 0x07
class NdefRecord
{
public:
NdefRecord();
NdefRecord(const NdefRecord& rhs);
~NdefRecord();
NdefRecord& operator=(const NdefRecord& rhs);
int getEncodedSize();
void encode(byte *data, bool firstRecord, bool lastRecord);
unsigned int getTypeLength();
int getPayloadLength();
unsigned int getIdLength();
byte getTnf();
void getType(byte *type);
void getPayload(byte *payload);
void getId(byte *id);
// convenience methods
String getType();
String getId();
void setTnf(byte tnf);
void setType(const byte *type, const unsigned int numBytes);
void setPayload(const byte *payload, const int numBytes);
void setId(const byte *id, const unsigned int numBytes);
void print();
private:
byte getTnfByte(bool firstRecord, bool lastRecord);
byte _tnf; // 3 bit
unsigned int _typeLength;
int _payloadLength;
unsigned int _idLength;
byte *_type;
byte *_payload;
byte *_id;
};
#endif

View File

@@ -1,194 +0,0 @@
#include <NfcAdapter.h>
NfcAdapter::NfcAdapter(PN532Interface &interface)
{
shield = new PN532(interface);
}
NfcAdapter::~NfcAdapter(void)
{
delete shield;
}
void NfcAdapter::begin(boolean verbose)
{
shield->begin();
uint32_t versiondata = shield->getFirmwareVersion();
if (! versiondata)
{
Serial.print(F("Didn't find PN53x board"));
while (1); // halt
}
if (verbose)
{
Serial.print(F("Found chip PN5")); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print(F("Firmware ver. ")); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
}
// configure board to read RFID tags
shield->SAMConfig();
}
boolean NfcAdapter::tagPresent(unsigned long timeout)
{
uint8_t success;
uidLength = 0;
if (timeout == 0)
{
success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength);
}
else
{
success = shield->readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, (uint8_t*)&uidLength, timeout);
}
return success;
}
boolean NfcAdapter::erase()
{
boolean success;
NdefMessage message = NdefMessage();
message.addEmptyRecord();
return write(message);
}
boolean NfcAdapter::format()
{
boolean success;
if (uidLength == 4)
{
MifareClassic mifareClassic = MifareClassic(*shield);
success = mifareClassic.formatNDEF(uid, uidLength);
}
else
{
Serial.print(F("Unsupported Tag."));
success = false;
}
return success;
}
boolean NfcAdapter::clean()
{
uint8_t type = guessTagType();
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
#ifdef NDEF_DEBUG
Serial.println(F("Cleaning Mifare Classic"));
#endif
MifareClassic mifareClassic = MifareClassic(*shield);
return mifareClassic.formatMifare(uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
#ifdef NDEF_DEBUG
Serial.println(F("Cleaning Mifare Ultralight"));
#endif
MifareUltralight ultralight = MifareUltralight(*shield);
return ultralight.clean();
}
else
{
Serial.print(F("No driver for card type "));Serial.println(type);
return false;
}
}
NfcTag NfcAdapter::read()
{
uint8_t type = guessTagType();
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Classic"));
#endif
MifareClassic mifareClassic = MifareClassic(*shield);
return mifareClassic.read(uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
#ifdef NDEF_DEBUG
Serial.println(F("Reading Mifare Ultralight"));
#endif
MifareUltralight ultralight = MifareUltralight(*shield);
return ultralight.read(uid, uidLength);
}
else if (type == TAG_TYPE_UNKNOWN)
{
Serial.print(F("Can not determine tag type"));
return NfcTag(uid, uidLength);
}
else
{
Serial.print(F("No driver for card type "));Serial.println(type);
// TODO should set type here
return NfcTag(uid, uidLength);
}
}
boolean NfcAdapter::write(NdefMessage& ndefMessage)
{
boolean success;
uint8_t type = guessTagType();
if (type == TAG_TYPE_MIFARE_CLASSIC)
{
#ifdef NDEF_DEBUG
Serial.println(F("Writing Mifare Classic"));
#endif
MifareClassic mifareClassic = MifareClassic(*shield);
success = mifareClassic.write(ndefMessage, uid, uidLength);
}
else if (type == TAG_TYPE_2)
{
#ifdef NDEF_DEBUG
Serial.println(F("Writing Mifare Ultralight"));
#endif
MifareUltralight mifareUltralight = MifareUltralight(*shield);
success = mifareUltralight.write(ndefMessage, uid, uidLength);
}
else if (type == TAG_TYPE_UNKNOWN)
{
Serial.print(F("Can not determine tag type"));
success = false;
}
else
{
Serial.print(F("No driver for card type "));Serial.println(type);
success = false;
}
return success;
}
// TODO this should return a Driver MifareClassic, MifareUltralight, Type 4, Unknown
// Guess Tag Type by looking at the ATQA and SAK values
// Need to follow spec for Card Identification. Maybe AN1303, AN1305 and ???
unsigned int NfcAdapter::guessTagType()
{
// 4 byte id - Mifare Classic
// - ATQA 0x4 && SAK 0x8
// 7 byte id
// - ATQA 0x44 && SAK 0x8 - Mifare Classic
// - ATQA 0x44 && SAK 0x0 - Mifare Ultralight NFC Forum Type 2
// - ATQA 0x344 && SAK 0x20 - NFC Forum Type 4
if (uidLength == 4)
{
return TAG_TYPE_MIFARE_CLASSIC;
}
else
{
return TAG_TYPE_2;
}
}

View File

@@ -1,45 +0,0 @@
#ifndef NfcAdapter_h
#define NfcAdapter_h
#include <PN532Interface.h>
#include <PN532.h>
#include <NfcTag.h>
#include <Ndef.h>
// Drivers
#include <MifareClassic.h>
#include <MifareUltralight.h>
#define TAG_TYPE_MIFARE_CLASSIC (0)
#define TAG_TYPE_1 (1)
#define TAG_TYPE_2 (2)
#define TAG_TYPE_3 (3)
#define TAG_TYPE_4 (4)
#define TAG_TYPE_UNKNOWN (99)
#define IRQ (2)
#define RESET (3) // Not connected by default on the NFC Shield
class NfcAdapter {
public:
NfcAdapter(PN532Interface &interface);
~NfcAdapter(void);
void begin(boolean verbose=true);
boolean tagPresent(unsigned long timeout=0); // tagAvailable
NfcTag read();
boolean write(NdefMessage& ndefMessage);
// erase tag by writing an empty NDEF record
boolean erase();
// format a tag as NDEF
boolean format();
// reset tag back to factory state
boolean clean();
private:
PN532* shield;
byte uid[7]; // Buffer to store the returned UID
unsigned int uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
unsigned int guessTagType();
};
#endif

View File

@@ -1,9 +0,0 @@
// eventually the NFC drivers should extend this class
class NfcDriver
{
public:
virtual NfcTag read(uint8_t * uid, int uidLength) = 0;
virtual boolean write(NdefMessage& message, uint8_t * uid, int uidLength) = 0;
// erase()
// format()
}

View File

@@ -1,121 +0,0 @@
#include <NfcTag.h>
NfcTag::NfcTag()
{
_uid = 0;
_uidLength = 0;
_tagType = "Unknown";
_ndefMessage = (NdefMessage*)NULL;
}
NfcTag::NfcTag(byte *uid, unsigned int uidLength)
{
_uid = uid;
_uidLength = uidLength;
_tagType = "Unknown";
_ndefMessage = (NdefMessage*)NULL;
}
NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType)
{
_uid = uid;
_uidLength = uidLength;
_tagType = tagType;
_ndefMessage = (NdefMessage*)NULL;
}
NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, NdefMessage& ndefMessage)
{
_uid = uid;
_uidLength = uidLength;
_tagType = tagType;
_ndefMessage = new NdefMessage(ndefMessage);
}
// I don't like this version, but it will use less memory
NfcTag::NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength)
{
_uid = uid;
_uidLength = uidLength;
_tagType = tagType;
_ndefMessage = new NdefMessage(ndefData, ndefDataLength);
}
NfcTag::~NfcTag()
{
delete _ndefMessage;
}
NfcTag& NfcTag::operator=(const NfcTag& rhs)
{
if (this != &rhs)
{
delete _ndefMessage;
_uid = rhs._uid;
_uidLength = rhs._uidLength;
_tagType = rhs._tagType;
// TODO do I need a copy here?
_ndefMessage = rhs._ndefMessage;
}
return *this;
}
uint8_t NfcTag::getUidLength()
{
return _uidLength;
}
void NfcTag::getUid(byte *uid, unsigned int uidLength)
{
memcpy(uid, _uid, _uidLength < uidLength ? _uidLength : uidLength);
}
String NfcTag::getUidString()
{
String uidString = "";
for (int i = 0; i < _uidLength; i++)
{
if (i > 0)
{
uidString += " ";
}
if (_uid[i] < 0xF)
{
uidString += "0";
}
uidString += String((unsigned int)_uid[i], (unsigned char)HEX);
}
uidString.toUpperCase();
return uidString;
}
String NfcTag::getTagType()
{
return _tagType;
}
boolean NfcTag::hasNdefMessage()
{
return (_ndefMessage != NULL);
}
NdefMessage NfcTag::getNdefMessage()
{
return *_ndefMessage;
}
void NfcTag::print()
{
Serial.print(F("NFC Tag - "));Serial.println(_tagType);
Serial.print(F("UID "));Serial.println(getUidString());
if (_ndefMessage == NULL)
{
Serial.println(F("\nNo NDEF Message"));
}
else
{
_ndefMessage->print();
}
}

View File

@@ -1,34 +0,0 @@
#ifndef NfcTag_h
#define NfcTag_h
#include <inttypes.h>
#include <Arduino.h>
#include <NdefMessage.h>
class NfcTag
{
public:
NfcTag();
NfcTag(byte *uid, unsigned int uidLength);
NfcTag(byte *uid, unsigned int uidLength, String tagType);
NfcTag(byte *uid, unsigned int uidLength, String tagType, NdefMessage& ndefMessage);
NfcTag(byte *uid, unsigned int uidLength, String tagType, const byte *ndefData, const int ndefDataLength);
~NfcTag(void);
NfcTag& operator=(const NfcTag& rhs);
uint8_t getUidLength();
void getUid(byte *uid, unsigned int uidLength);
String getUidString();
String getTagType();
boolean hasNdefMessage();
NdefMessage getNdefMessage();
void print();
private:
byte *_uid;
unsigned int _uidLength;
String _tagType; // Mifare Classic, NFC Forum Type {1,2,3,4}, Unknown
NdefMessage* _ndefMessage;
// TODO capacity
// TODO isFormatted
};
#endif

View File

@@ -1,133 +0,0 @@
# NDEF Library for Arduino
Read and Write NDEF messages on NFC Tags with Arduino.
NFC Data Exchange Format (NDEF) is a common data format that operates across all NFC devices, regardless of the underlying tag or device technology.
This code works with the [Adafruit NFC Shield](https://www.adafruit.com/products/789), [Seeed Studio NFC Shield v2.0](http://www.seeedstudio.com/depot/nfc-shield-v20-p-1370.html) and the [Seeed Studio NFC Shield](http://www.seeedstudio.com/depot/nfc-shield-p-916.html?cPath=73). The library supports I2C for the Adafruit shield and SPI with the Seeed shields. The Adafruit Shield can also be modified to use SPI. It should also work with the [Adafruit NFC Breakout Board](https://www.adafruit.com/products/364).
### Supports
- Reading from Mifare Classic Tags with 4 byte UIDs.
- Writing to Mifare Classic Tags with 4 byte UIDs.
- Reading from Mifare Ultralight tags.
- Writing to Mifare Ultralight tags.
- Peer to Peer with the Seeed Studio shield
### Requires
[Yihui Xiong's PN532 Library](https://github.com/Seeed-Studio/PN532)
## Getting Started
To use the Ndef library in your code, include the following in your sketch
For the Adafruit Shield using I2C
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
For the Seeed Shield using SPI
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
### NfcAdapter
The user interacts with the NfcAdapter to read and write NFC tags using the NFC shield.
Read a message from a tag
if (nfc.tagPresent()) {
NfcTag tag = nfc.read();
tag.print();
}
Write a message to a tag
if (nfc.tagPresent()) {
NdefMessage message = NdefMessage();
message.addTextRecord("Hello, Arduino!");
success = nfc.write(message);
}
Erase a tag. Tags are erased by writing an empty NDEF message. Tags are not zeroed out the old data may still be read off a tag using an application like [NXP's TagInfo](https://play.google.com/store/apps/details?id=com.nxp.taginfolite&hl=en).
if (nfc.tagPresent()) {
success = nfc.erase();
}
Format a Mifare Classic tag as NDEF.
if (nfc.tagPresent()) {
success = nfc.format();
}
Clean a tag. Cleaning resets a tag back to a factory-like state. For Mifare Classic, tag is zeroed and reformatted as Mifare Classic (non-NDEF). For Mifare Ultralight, the tag is zeroed and left empty.
if (nfc.tagPresent()) {
success = nfc.clean();
}
### NfcTag
Reading a tag with the shield, returns a NfcTag object. The NfcTag object contains meta data about the tag UID, technology, size. When an NDEF tag is read, the NfcTag object contains a NdefMessage.
### NdefMessage
A NdefMessage consist of one or more NdefRecords.
The NdefMessage object has helper methods for adding records.
ndefMessage.addTextRecord("hello, world");
ndefMessage.addUriRecord("http://arduino.cc");
The NdefMessage object is responsible for encoding NdefMessage into bytes so it can be written to a tag. The NdefMessage also decodes bytes read from a tag back into a NdefMessage object.
### NdefRecord
A NdefRecord carries a payload and info about the payload within a NdefMessage.
### Peer to Peer
Peer to Peer is provided by the LLCP and SNEP support in the [Seeed Studio library](https://github.com/Seeed-Studio/PN532). P2P requires SPI and has only been tested with the Seeed Studio shield. Peer to Peer was tested between Arduino and Android or BlackBerry 10. (Unfortunately Windows Phone 8 did not work.) See [P2P_Send](examples/P2P_Send/P2P_Send.ino) and [P2P_Receive](examples/P2P_Receive/P2P_Receive.ino) for more info.
### Specifications
This code is based on the "NFC Data Exchange Format (NDEF) Technical Specification" and the "Record Type Definition Technical Specifications" that can be downloaded from the [NFC Forum](http://www.nfc-forum.org/specs/spec_license).
### Tests
To run the tests, you'll need [ArduinoUnit](https://github.com/mmurdoch/arduinounit). To "install", I clone the repo to my home directory and symlink the source into ~/Documents/Arduino/libraries/ArduinoUnit.
$ cd ~
$ git clone git@github.com:mmurdoch/arduinounit.git
$ cd ~/Documents/Arduino/libraries/
$ ln -s ~/arduinounit/src ArduinoUnit
Tests can be run on an Uno without a NFC shield, since the NDEF logic is what is being tested.
## Warning
This software is in development. It works for the happy path. Error handling could use improvement. It runs out of memory, especially on the Uno board. Use small messages with the Uno. The Due board can write larger messages. Please submit patches.
## Book
Need more info? Check out my book [Beginning NFC: Near Field Communication with Arduino, Android, and PhoneGap](http://shop.oreilly.com/product/0636920021193.do)
![Beginning NFC](http://akamaicovers.oreilly.com/images/0636920021193/cat.gif)
## License
[BSD License](https://github.com/don/Ndef/blob/master/LICENSE.txt) (c) 2013-2014, Don Coleman

View File

@@ -1,45 +0,0 @@
// Clean resets a tag back to factory-like state
// For Mifare Classic, tag is zero'd and reformatted as Mifare Classic
// For Mifare Ultralight, tags is zero'd and left empty
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup(void) {
Serial.begin(9600);
Serial.println("NFC Tag Cleaner");
nfc.begin();
}
void loop(void) {
Serial.println("\nPlace a tag on the NFC reader to clean.");
if (nfc.tagPresent()) {
bool success = nfc.clean();
if (success) {
Serial.println("\nSuccess, tag restored to factory state.");
} else {
Serial.println("\nError, unable to clean tag.");
}
}
delay(5000);
}

View File

@@ -1,42 +0,0 @@
// Erases a NFC tag by writing an empty NDEF message
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup(void) {
Serial.begin(9600);
Serial.println("NFC Tag Eraser");
nfc.begin();
}
void loop(void) {
Serial.println("\nPlace a tag on the NFC reader to erase.");
if (nfc.tagPresent()) {
bool success = nfc.erase();
if (success) {
Serial.println("\nSuccess, tag contains an empty record.");
} else {
Serial.println("\nUnable to erase tag.");
}
}
delay(5000);
}

View File

@@ -1,44 +0,0 @@
// Formats a Mifare Classic tags as an NDEF tag
// This will fail if the tag is already formatted NDEF
// nfc.clean will turn a NDEF formatted Mifare Classic tag back to the Mifare Classic format
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup(void) {
Serial.begin(9600);
Serial.println("NDEF Formatter");
nfc.begin();
}
void loop(void) {
Serial.println("\nPlace an unformatted Mifare Classic tag on the reader.");
if (nfc.tagPresent()) {
bool success = nfc.format();
if (success) {
Serial.println("\nSuccess, tag formatted as NDEF.");
} else {
Serial.println("\nFormat failed.");
}
}
delay(5000);
}

View File

@@ -1,30 +0,0 @@
// Receive a NDEF message from a Peer
// Requires SPI. Tested with Seeed Studio NFC Shield v2
#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];
void setup() {
Serial.begin(9600);
Serial.println("NFC Peer to Peer Example - Receive Message");
}
void loop() {
Serial.println("Waiting for message from Peer");
int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf));
if (msgSize > 0) {
NdefMessage msg = NdefMessage(ndefBuf, msgSize);
msg.print();
Serial.println("\nSuccess");
} else {
Serial.println("Failed");
}
delay(3000);
}

View File

@@ -1,71 +0,0 @@
// Receive a NDEF message from a Peer and
// display the payload of the first record on a LCD
//
// SeeedStudio NFC shield http://www.seeedstudio.com/depot/NFC-Shield-V20-p-1370.html
// LCD using the Adafruit backpack http://adafru.it/292
// Adafruit Liquid Crystal library https://github.com/adafruit/LiquidCrystal
// Use a Android of BlackBerry phone to send a message to the NFC shield
#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"
#include "Wire.h"
#include "LiquidCrystal.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];
// Connect via i2c, default address #0 (A0-A2 not jumpered)
LiquidCrystal lcd(0);
void setup() {
Serial.begin(9600);
// set up the LCD's number of rows and columns:
lcd.begin(16, 2);
Serial.println("NFC Peer to Peer Example - Receive Message");
}
void loop() {
Serial.println("Waiting for message from a peer");
int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf));
if (msgSize > 0) {
NdefMessage msg = NdefMessage(ndefBuf, msgSize);
msg.print();
NdefRecord record = msg.getRecord(0);
int payloadLength = record.getPayloadLength();
byte payload[payloadLength];
record.getPayload(payload);
// The TNF and Type are used to determine how your application processes the payload
// There's no generic processing for the payload, it's returned as a byte[]
int startChar = 0;
if (record.getTnf() == TNF_WELL_KNOWN && record.getType() == "T") { // text message
// skip the language code
startChar = payload[0] + 1;
} else if (record.getTnf() == TNF_WELL_KNOWN && record.getType() == "U") { // URI
// skip the url prefix (future versions should decode)
startChar = 1;
}
// Force the data into a String (might fail for some content)
// Real code should use smarter processing
String payloadAsString = "";
for (int c = startChar; c < payloadLength; c++) {
payloadAsString += (char)payload[c];
}
// print on the LCD display
lcd.setCursor(0, 0);
lcd.print(payloadAsString);
Serial.println("\nSuccess");
} else {
Serial.println("Failed");
}
delay(3000);
}

View File

@@ -1,42 +0,0 @@
// Sends a NDEF Message to a Peer
// Requires SPI. Tested with Seeed Studio NFC Shield v2
#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];
void setup() {
Serial.begin(9600);
Serial.println("NFC Peer to Peer Example - Send Message");
}
void loop() {
Serial.println("Send a message to Peer");
NdefMessage message = NdefMessage();
message.addUriRecord("http://shop.oreilly.com/product/mobile/0636920021193.do");
//message.addUriRecord("http://arduino.cc");
//message.addUriRecord("https://github.com/don/NDEF");
int messageSize = message.getEncodedSize();
if (messageSize > sizeof(ndefBuf)) {
Serial.println("ndefBuf is too small");
while (1) {
}
}
message.encode(ndefBuf);
if (0 >= nfc.write(ndefBuf, messageSize)) {
Serial.println("Failed");
} else {
Serial.println("Success");
}
delay(3000);
}

View File

@@ -1,35 +0,0 @@
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup(void) {
Serial.begin(9600);
Serial.println("NDEF Reader");
nfc.begin();
}
void loop(void) {
Serial.println("\nScan a NFC tag\n");
if (nfc.tagPresent())
{
NfcTag tag = nfc.read();
tag.print();
}
delay(5000);
}

View File

@@ -1,86 +0,0 @@
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup(void) {
Serial.begin(9600);
Serial.println("NDEF Reader");
nfc.begin();
}
void loop(void) {
Serial.println("\nScan a NFC tag\n");
if (nfc.tagPresent())
{
NfcTag tag = nfc.read();
Serial.println(tag.getTagType());
Serial.print("UID: ");Serial.println(tag.getUidString());
if (tag.hasNdefMessage()) // every tag won't have a message
{
NdefMessage message = tag.getNdefMessage();
Serial.print("\nThis NFC Tag contains an NDEF Message with ");
Serial.print(message.getRecordCount());
Serial.print(" NDEF Record");
if (message.getRecordCount() != 1) {
Serial.print("s");
}
Serial.println(".");
// cycle through the records, printing some info from each
int recordCount = message.getRecordCount();
for (int i = 0; i < recordCount; i++)
{
Serial.print("\nNDEF Record ");Serial.println(i+1);
NdefRecord record = message.getRecord(i);
// NdefRecord record = message[i]; // alternate syntax
Serial.print(" TNF: ");Serial.println(record.getTnf());
Serial.print(" Type: ");Serial.println(record.getType()); // will be "" for TNF_EMPTY
// The TNF and Type should be used to determine how your application processes the payload
// There's no generic processing for the payload, it's returned as a byte[]
int payloadLength = record.getPayloadLength();
byte payload[payloadLength];
record.getPayload(payload);
// Print the Hex and Printable Characters
Serial.print(" Payload (HEX): ");
PrintHexChar(payload, payloadLength);
// Force the data into a String (might work depending on the content)
// Real code should use smarter processing
String payloadAsString = "";
for (int c = 0; c < payloadLength; c++) {
payloadAsString += (char)payload[c];
}
Serial.print(" Payload (as String): ");
Serial.println(payloadAsString);
// id is probably blank and will return ""
String uid = record.getId();
if (uid != "") {
Serial.print(" ID: ");Serial.println(uid);
}
}
}
}
delay(3000);
}

View File

@@ -1,40 +0,0 @@
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup() {
Serial.begin(9600);
Serial.println("NDEF Writer");
nfc.begin();
}
void loop() {
Serial.println("\nPlace a formatted Mifare Classic NFC tag on the reader.");
if (nfc.tagPresent()) {
NdefMessage message = NdefMessage();
message.addUriRecord("http://arduino.cc");
bool success = nfc.write(message);
if (success) {
Serial.println("Success. Try reading this tag with your phone.");
} else {
Serial.println("Write failed.");
}
}
delay(5000);
}

View File

@@ -1,41 +0,0 @@
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_SPI pn532spi(SPI, 10);
NfcAdapter nfc = NfcAdapter(pn532spi);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);
#endif
void setup() {
Serial.begin(9600);
Serial.println("NDEF Writer");
nfc.begin();
}
void loop() {
Serial.println("\nPlace a formatted Mifare Classic NFC tag on the reader.");
if (nfc.tagPresent()) {
NdefMessage message = NdefMessage();
message.addTextRecord("Hello, Arduino!");
message.addUriRecord("http://arduino.cc");
message.addTextRecord("Goodbye, Arduino!");
boolean success = nfc.write(message);
if (success) {
Serial.println("Success. Try reading this tag with your phone.");
} else {
Serial.println("Write failed");
}
}
delay(3000);
}

View File

@@ -1,55 +0,0 @@
#######################################
# Syntax Coloring Map For Ndef
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
MifareClassic KEYWORD1
MifareUltralight KEYWORD1
NdefMessage KEYWORD1
NdefRecord KEYWORD1
NfcAdapter KEYWORD1
NfcDriver KEYWORD1
NfcTag KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
addEmptyRecord KEYWORD2
addMimeMediaRecord KEYWORD2
addRecord KEYWORD2
addTextRecord KEYWORD2
addUriRecord KEYWORD2
begin KEYWORD2
encode KEYWORD2
erase KEYWORD2
format KEYWORD2
getEncodedSize KEYWORD2
getId KEYWORD2
getIdLength KEYWORD2
getNdefMessage KEYWORD2
getPayload KEYWORD2
getPayloadLength KEYWORD2
getRecord KEYWORD2
getRecordCount KEYWORD2
getTagType KEYWORD2
getTnf KEYWORD2
getType KEYWORD2
getTypeLength KEYWORD2
getUid KEYWORD2
getUidLength KEYWORD2
getUidString KEYWORD2
hasNdefMessage KEYWORD2
print KEYWORD2
read KEYWORD2
setId KEYWORD2
setPayload KEYWORD2
setTnf KEYWORD2
setType KEYWORD2
share KEYWORD2
tagPresent KEYWORD2
unshare KEYWORD2
write KEYWORD2

View File

@@ -1,200 +0,0 @@
#include <Wire.h>
#include <PN532.h>
#include <NdefMessage.h>
#include <NdefRecord.h>
#include <ArduinoUnit.h>
void leakCheck(void (*callback)())
{
int start = freeMemory();
(*callback)();
int end = freeMemory();
Serial.println((end - start), DEC);
}
// Custom Assertion
void assertNoLeak(void (*callback)())
{
int start = freeMemory();
(*callback)();
int end = freeMemory();
assertEqual(0, (start - end));
}
void record()
{
NdefRecord* r = new NdefRecord();
delete r;
}
void emptyRecord()
{
NdefRecord* r = new NdefRecord();
r->print();
delete r;
}
void textRecord()
{
NdefRecord* r = new NdefRecord();
r->setTnf(0x1);
uint8_t type[] = { 0x54 };
r->setType(type, sizeof(type));
uint8_t payload[] = { 0x1A, 0x1B, 0x1C };
r->setPayload(payload, sizeof(payload));
r->print();
delete r;
}
void recordMallocZero()
{
NdefRecord r = NdefRecord();
String type = r.getType();
String id = r.getId();
byte payload[r.getPayloadLength()];
r.getPayload(payload);
}
// this is OK
void emptyMessage()
{
NdefMessage* m = new NdefMessage();
delete m;
}
// this is OK
void printEmptyMessage()
{
NdefMessage* m = new NdefMessage();
m->print();
delete m;
}
// this is OK
void printEmptyMessageNoNew()
{
NdefMessage m = NdefMessage();
m.print();
}
void messageWithTextRecord()
{
NdefMessage m = NdefMessage();
m.addTextRecord("foo");
m.print();
}
void messageWithEmptyRecord()
{
NdefMessage m = NdefMessage();
NdefRecord r = NdefRecord();
m.addRecord(r);
m.print();
}
void messageWithoutHelper()
{
NdefMessage m = NdefMessage();
NdefRecord r = NdefRecord();
r.setTnf(1);
uint8_t type[] = { 0x54 };
r.setType(type, sizeof(type));
uint8_t payload[] = { 0x02, 0x65, 0x6E, 0x66, 0x6F, 0x6F };
r.setPayload(payload, sizeof(payload));
m.addRecord(r);
m.print();
}
void messageWithId()
{
NdefMessage m = NdefMessage();
NdefRecord r = NdefRecord();
r.setTnf(1);
uint8_t type[] = { 0x54 };
r.setType(type, sizeof(type));
uint8_t payload[] = { 0x02, 0x65, 0x6E, 0x66, 0x6F, 0x6F };
r.setPayload(payload, sizeof(payload));
uint8_t id[] = { 0x0, 0x0, 0x0 };
r.setId(id, sizeof(id));
m.addRecord(r);
m.print();
}
void message80()
{
NdefMessage message = NdefMessage();
message.addTextRecord("This record is 80 characters.X01234567890123456789012345678901234567890123456789");
//message.print();
}
void message100()
{
NdefMessage message = NdefMessage();
message.addTextRecord("This record is 100 characters.0123456789012345678901234567890123456789012345678901234567890123456789");
//message.print();
}
void message120()
{
NdefMessage message = NdefMessage();
message.addTextRecord("This record is 120 characters.012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789");
//message.print();
}
void setup() {
Serial.begin(9600);
Serial.println("\n");
Serial.println(F("========="));
Serial.println(freeMemory());
Serial.println(F("========="));
}
test(memoryKludgeEnd)
{
// TODO ensure the output matches start
Serial.println(F("========="));
Serial.print("End ");Serial.println(freeMemory());
Serial.println(F("========="));
}
test(recordLeaks)
{
assertNoLeak(&record);
assertNoLeak(&emptyRecord);
assertNoLeak(&textRecord);
}
test(recordAccessorLeaks)
{
assertNoLeak(&recordMallocZero);
}
test(messageLeaks)
{
assertNoLeak(&emptyMessage);
assertNoLeak(&printEmptyMessage);
assertNoLeak(&printEmptyMessageNoNew);
assertNoLeak(&messageWithTextRecord);
assertNoLeak(&messageWithEmptyRecord);
assertNoLeak(&messageWithoutHelper);
assertNoLeak(&messageWithId);
}
test(messageOneBigRecord)
{
assertNoLeak(&message80);
// The next 2 fail. Maybe out of memory? Look into helper methods
//assertNoLeak(&message100);
//assertNoLeak(&message120);
}
test(memoryKludgeStart)
{
Serial.println(F("---------"));
Serial.print("Start ");Serial.println(freeMemory());
Serial.println(F("---------"));
}
void loop() {
Test::run();
}

View File

@@ -1,238 +0,0 @@
#include <Wire.h>
#include <PN532.h>
#include <NdefMessage.h>
#include <NdefRecord.h>
#include <ArduinoUnit.h>
// Custom Assertion
void assertNoLeak(void (*callback)())
{
int start = freeMemory();
(*callback)();
int end = freeMemory();
assertEqual(0, (start - end));
}
void assertBytesEqual(const uint8_t* expected, const uint8_t* actual, int size) {
for (int i = 0; i < size; i++) {
// Serial.print("> ");Serial.print(expected[i]);Serial.print(" ");Serial.println(actual[i]);
assertEqual(expected[i], actual[i]);
}
}
void setup() {
Serial.begin(9600);
}
test(messageDelete)
{
int start = freeMemory();
NdefMessage* m1 = new NdefMessage();
m1->addTextRecord("Foo");
delete m1;
int end = freeMemory();
// Serial.print("Start ");Serial.println(start);
// Serial.print("End ");Serial.println(end);
assertEqual(0, (start-end));
}
test(assign)
{
int start = freeMemory();
if (true) // bogus block so automatic storage duration objects are deleted
{
NdefMessage* m1 = new NdefMessage();
m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union...");
NdefMessage* m2 = new NdefMessage();
*m2 = *m1;
NdefRecord r1 = m1->getRecord(0);
NdefRecord r2 = m2->getRecord(0);
assertEqual(r1.getTnf(), r2.getTnf());
assertEqual(r1.getTypeLength(), r2.getTypeLength());
assertEqual(r1.getPayloadLength(), r2.getPayloadLength());
assertEqual(r1.getIdLength(), r2.getIdLength());
byte p1[r1.getPayloadLength()];
byte p2[r2.getPayloadLength()];
r1.getPayload(p1);
r2.getPayload(p2);
int size = r1.getPayloadLength();
assertBytesEqual(p1, p2, size);
delete m2;
delete m1;
}
int end = freeMemory();
assertEqual(0, (start-end));
}
test(assign2)
{
int start = freeMemory();
if (true) // bogus block so automatic storage duration objects are deleted
{
NdefMessage m1 = NdefMessage();
m1.addTextRecord("We the People of the United States, in Order to form a more perfect Union...");
NdefMessage m2 = NdefMessage();
m2 = m1;
NdefRecord r1 = m1.getRecord(0);
NdefRecord r2 = m2.getRecord(0);
assertEqual(r1.getTnf(), r2.getTnf());
assertEqual(r1.getTypeLength(), r2.getTypeLength());
assertEqual(r1.getPayloadLength(), r2.getPayloadLength());
assertEqual(r1.getIdLength(), r2.getIdLength());
// TODO check type
byte p1[r1.getPayloadLength()];
byte p2[r2.getPayloadLength()];
r1.getPayload(p1);
r2.getPayload(p2);
int size = r1.getPayloadLength();
assertBytesEqual(p1, p2, size);
}
int end = freeMemory();
assertEqual(0, (start-end));
}
test(assign3)
{
int start = freeMemory();
if (true) // bogus block so automatic storage duration objects are deleted
{
NdefMessage* m1 = new NdefMessage();
m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union...");
NdefMessage* m2 = new NdefMessage();
*m2 = *m1;
delete m1;
NdefRecord r = m2->getRecord(0);
assertEqual(TNF_WELL_KNOWN, r.getTnf());
assertEqual(1, r.getTypeLength());
assertEqual(79, r.getPayloadLength());
assertEqual(0, r.getIdLength());
::String s = "We the People of the United States, in Order to form a more perfect Union...";
byte payload[s.length() + 1];
s.getBytes(payload, sizeof(payload));
byte p[r.getPayloadLength()];
r.getPayload(p);
assertBytesEqual(payload, p+3, s.length());
delete m2;
}
int end = freeMemory();
assertEqual(0, (start-end));
}
test(assign4)
{
int start = freeMemory();
if (true) // bogus block so automatic storage duration objects are deleted
{
NdefMessage* m1 = new NdefMessage();
m1->addTextRecord("We the People of the United States, in Order to form a more perfect Union...");
NdefMessage* m2 = new NdefMessage();
m2->addTextRecord("Record 1");
m2->addTextRecord("RECORD 2");
m2->addTextRecord("Record 3");
assertEqual(3, m2->getRecordCount());
*m2 = *m1;
assertEqual(1, m2->getRecordCount());
// NdefRecord ghost = m2->getRecord(1);
// ghost.print();
//
// NdefRecord ghost2 = m2->getRecord(3);
// ghost2.print();
//
// delete m1;
//
// NdefRecord r = m2->getRecord(0);
//
// assertEqual(TNF_WELL_KNOWN, r.getTnf());
// assertEqual(1, r.getTypeLength());
// assertEqual(79, r.getPayloadLength());
// assertEqual(0, r.getIdLength());
//
// String s = "We the People of the United States, in Order to form a more perfect Union...";
// byte payload[s.length() + 1];
// s.getBytes(payload, sizeof(payload));
//
// uint8_t* p = r.getPayload();
// int size = r.getPayloadLength();
// assertBytesEqual(payload, p+3, s.length());
// free(p);
delete m1;
delete m2;
}
int end = freeMemory();
assertEqual(0, (start-end));
}
// really a record test
test(doublePayload)
{
int start = freeMemory();
NdefRecord* r = new NdefRecord();
uint8_t p1[] = { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
r->setPayload(p1, sizeof(p1));
r->setPayload(p1, sizeof(p1));
delete r;
int end = freeMemory();
assertEqual(0, (start-end));
}
test(aaa_printFreeMemoryAtStart) // warning: relies on fact tests are run in alphabetical order
{
Serial.println(F("---------------------"));
Serial.print("Free Memory Start ");Serial.println(freeMemory());
Serial.println(F("---------------------"));
}
test(zzz_printFreeMemoryAtEnd) // warning: relies on fact tests are run in alphabetical order
{
// unfortunately the user needs to manually check this matches the start value
Serial.println(F("====================="));
Serial.print("Free Memory End ");Serial.println(freeMemory());
Serial.println(F("====================="));
}
void loop() {
Test::run();
}

View File

@@ -1,108 +0,0 @@
#include <Wire.h>
#include <PN532.h>
#include <NdefRecord.h>
#include <ArduinoUnit.h>
void assertBytesEqual(const uint8_t* expected, const uint8_t* actual, uint8_t size) {
for (int i = 0; i < size; i++) {
assertEqual(expected[i], actual[i]);
}
}
void setup() {
Serial.begin(9600);
}
test(accessors) {
NdefRecord record = NdefRecord();
record.setTnf(TNF_WELL_KNOWN);
uint8_t recordType[] = { 0x54 }; // "T" Text Record
assertEqual(0x54, recordType[0]);
record.setType(recordType, sizeof(recordType));
// 2 + "en" + "Unit Test"
uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 };
record.setPayload(payload, sizeof(payload));
assertEqual(TNF_WELL_KNOWN, record.getTnf());
assertEqual(sizeof(recordType), record.getTypeLength());
assertEqual(1, record.getTypeLength());
assertEqual(sizeof(payload), record.getPayloadLength());
assertEqual(12, record.getPayloadLength());
uint8_t typeCheck[record.getTypeLength()];
record.getType(typeCheck);
assertEqual(0x54, typeCheck[0]);
assertBytesEqual(recordType, typeCheck, sizeof(recordType));
uint8_t payloadCheck[record.getPayloadLength()];
record.getPayload(&payloadCheck[0]);
assertBytesEqual(payload, payloadCheck, sizeof(payload));
}
test(newaccessors) {
NdefRecord record = NdefRecord();
record.setTnf(TNF_WELL_KNOWN);
uint8_t recordType[] = { 0x54 }; // "T" Text Record
assertEqual(0x54, recordType[0]);
record.setType(recordType, sizeof(recordType));
// 2 + "en" + "Unit Test"
uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 };
record.setPayload(payload, sizeof(payload));
assertEqual(TNF_WELL_KNOWN, record.getTnf());
assertEqual(sizeof(recordType), record.getTypeLength());
assertEqual(1, record.getTypeLength());
assertEqual(sizeof(payload), record.getPayloadLength());
assertEqual(12, record.getPayloadLength());
::String typeCheck = record.getType();
assertTrue(typeCheck.equals("T"));
byte payloadCheck[record.getPayloadLength()];
record.getPayload(payloadCheck);
assertBytesEqual(payload, payloadCheck, sizeof(payload));
}
test(assignment)
{
NdefRecord record = NdefRecord();
record.setTnf(TNF_WELL_KNOWN);
uint8_t recordType[] = { 0x54 }; // "T" Text Record
assertEqual(0x54, recordType[0]);
record.setType(recordType, sizeof(recordType));
// 2 + "en" + "Unit Test"
uint8_t payload[] = { 0x02, 0x65, 0x6e, 0x55, 0x6e, 0x69, 0x74, 0x20, 0x54, 0x65, 0x73, 0x74 };
record.setPayload(payload, sizeof(payload));
NdefRecord record2 = NdefRecord();
record2 = record;
assertEqual(TNF_WELL_KNOWN, record.getTnf());
assertEqual(sizeof(recordType), record2.getTypeLength());
assertEqual(sizeof(payload), record2.getPayloadLength());
::String typeCheck = record.getType();
assertTrue(typeCheck.equals("T"));
byte payload2[record2.getPayloadLength()];
record2.getPayload(payload2);
assertBytesEqual(payload, payload2, sizeof(payload));
}
test(getEmptyPayload)
{
NdefRecord r = NdefRecord();
assertEqual(TNF_EMPTY, r.getTnf());
assertEqual(0, r.getPayloadLength());
byte payload[r.getPayloadLength()];
r.getPayload(payload);
byte empty[0];
assertBytesEqual(empty, payload, sizeof(payload));
}
void loop() {
Test::run();
}

View File

@@ -1,37 +0,0 @@
#include <Wire.h>
#include <PN532.h>
#include <NfcTag.h>
#include <ArduinoUnit.h>
void setup() {
Serial.begin(9600);
}
// Test for pull requests #14 and #16
test(getUid)
{
byte uid[4] = { 0x00, 0xFF, 0xAA, 0x17 };
byte uidFromTag[sizeof(uid)];
NfcTag tag = NfcTag(uid, sizeof(uid));
assertEqual(sizeof(uid), tag.getUidLength());
tag.getUid(uidFromTag, sizeof(uidFromTag));
// make sure the 2 uids are the same
for (int i = 0; i < sizeof(uid); i++) {
assertEqual(uid[i], uidFromTag[i]);
}
// check contents, to ensure the original uid wasn't overwritten
assertEqual(0x00, uid[0]);
assertEqual(0xFF, uid[1]);
assertEqual(0xAA, uid[2]);
assertEqual(0x17, uid[3]);
}
void loop() {
Test::run();
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,209 +0,0 @@
/**************************************************************************/
/*!
@file PN532.h
@author Adafruit Industries & Seeed Studio
@license BSD
*/
/**************************************************************************/
#ifndef __PN532_H__
#define __PN532_H__
#include <stdint.h>
#include "PN532Interface.h"
// PN532 Commands
#define PN532_COMMAND_DIAGNOSE (0x00)
#define PN532_COMMAND_GETFIRMWAREVERSION (0x02)
#define PN532_COMMAND_GETGENERALSTATUS (0x04)
#define PN532_COMMAND_READREGISTER (0x06)
#define PN532_COMMAND_WRITEREGISTER (0x08)
#define PN532_COMMAND_READGPIO (0x0C)
#define PN532_COMMAND_WRITEGPIO (0x0E)
#define PN532_COMMAND_SETSERIALBAUDRATE (0x10)
#define PN532_COMMAND_SETPARAMETERS (0x12)
#define PN532_COMMAND_SAMCONFIGURATION (0x14)
#define PN532_COMMAND_POWERDOWN (0x16)
#define PN532_COMMAND_RFCONFIGURATION (0x32)
#define PN532_COMMAND_RFREGULATIONTEST (0x58)
#define PN532_COMMAND_INJUMPFORDEP (0x56)
#define PN532_COMMAND_INJUMPFORPSL (0x46)
#define PN532_COMMAND_INLISTPASSIVETARGET (0x4A)
#define PN532_COMMAND_INATR (0x50)
#define PN532_COMMAND_INPSL (0x4E)
#define PN532_COMMAND_INDATAEXCHANGE (0x40)
#define PN532_COMMAND_INCOMMUNICATETHRU (0x42)
#define PN532_COMMAND_INDESELECT (0x44)
#define PN532_COMMAND_INRELEASE (0x52)
#define PN532_COMMAND_INSELECT (0x54)
#define PN532_COMMAND_INAUTOPOLL (0x60)
#define PN532_COMMAND_TGINITASTARGET (0x8C)
#define PN532_COMMAND_TGSETGENERALBYTES (0x92)
#define PN532_COMMAND_TGGETDATA (0x86)
#define PN532_COMMAND_TGSETDATA (0x8E)
#define PN532_COMMAND_TGSETMETADATA (0x94)
#define PN532_COMMAND_TGGETINITIATORCOMMAND (0x88)
#define PN532_COMMAND_TGRESPONSETOINITIATOR (0x90)
#define PN532_COMMAND_TGGETTARGETSTATUS (0x8A)
#define PN532_RESPONSE_INDATAEXCHANGE (0x41)
#define PN532_RESPONSE_INLISTPASSIVETARGET (0x4B)
#define PN532_MIFARE_ISO14443A (0x00)
// Mifare Commands
#define MIFARE_CMD_AUTH_A (0x60)
#define MIFARE_CMD_AUTH_B (0x61)
#define MIFARE_CMD_READ (0x30)
#define MIFARE_CMD_WRITE (0xA0)
#define MIFARE_CMD_WRITE_ULTRALIGHT (0xA2)
#define MIFARE_CMD_TRANSFER (0xB0)
#define MIFARE_CMD_DECREMENT (0xC0)
#define MIFARE_CMD_INCREMENT (0xC1)
#define MIFARE_CMD_STORE (0xC2)
// FeliCa Commands
#define FELICA_CMD_POLLING (0x00)
#define FELICA_CMD_REQUEST_SERVICE (0x02)
#define FELICA_CMD_REQUEST_RESPONSE (0x04)
#define FELICA_CMD_READ_WITHOUT_ENCRYPTION (0x06)
#define FELICA_CMD_WRITE_WITHOUT_ENCRYPTION (0x08)
#define FELICA_CMD_REQUEST_SYSTEM_CODE (0x0C)
// Prefixes for NDEF Records (to identify record type)
#define NDEF_URIPREFIX_NONE (0x00)
#define NDEF_URIPREFIX_HTTP_WWWDOT (0x01)
#define NDEF_URIPREFIX_HTTPS_WWWDOT (0x02)
#define NDEF_URIPREFIX_HTTP (0x03)
#define NDEF_URIPREFIX_HTTPS (0x04)
#define NDEF_URIPREFIX_TEL (0x05)
#define NDEF_URIPREFIX_MAILTO (0x06)
#define NDEF_URIPREFIX_FTP_ANONAT (0x07)
#define NDEF_URIPREFIX_FTP_FTPDOT (0x08)
#define NDEF_URIPREFIX_FTPS (0x09)
#define NDEF_URIPREFIX_SFTP (0x0A)
#define NDEF_URIPREFIX_SMB (0x0B)
#define NDEF_URIPREFIX_NFS (0x0C)
#define NDEF_URIPREFIX_FTP (0x0D)
#define NDEF_URIPREFIX_DAV (0x0E)
#define NDEF_URIPREFIX_NEWS (0x0F)
#define NDEF_URIPREFIX_TELNET (0x10)
#define NDEF_URIPREFIX_IMAP (0x11)
#define NDEF_URIPREFIX_RTSP (0x12)
#define NDEF_URIPREFIX_URN (0x13)
#define NDEF_URIPREFIX_POP (0x14)
#define NDEF_URIPREFIX_SIP (0x15)
#define NDEF_URIPREFIX_SIPS (0x16)
#define NDEF_URIPREFIX_TFTP (0x17)
#define NDEF_URIPREFIX_BTSPP (0x18)
#define NDEF_URIPREFIX_BTL2CAP (0x19)
#define NDEF_URIPREFIX_BTGOEP (0x1A)
#define NDEF_URIPREFIX_TCPOBEX (0x1B)
#define NDEF_URIPREFIX_IRDAOBEX (0x1C)
#define NDEF_URIPREFIX_FILE (0x1D)
#define NDEF_URIPREFIX_URN_EPC_ID (0x1E)
#define NDEF_URIPREFIX_URN_EPC_TAG (0x1F)
#define NDEF_URIPREFIX_URN_EPC_PAT (0x20)
#define NDEF_URIPREFIX_URN_EPC_RAW (0x21)
#define NDEF_URIPREFIX_URN_EPC (0x22)
#define NDEF_URIPREFIX_URN_NFC (0x23)
#define PN532_GPIO_VALIDATIONBIT (0x80)
#define PN532_GPIO_P30 (0)
#define PN532_GPIO_P31 (1)
#define PN532_GPIO_P32 (2)
#define PN532_GPIO_P33 (3)
#define PN532_GPIO_P34 (4)
#define PN532_GPIO_P35 (5)
// FeliCa consts
#define FELICA_READ_MAX_SERVICE_NUM 16
#define FELICA_READ_MAX_BLOCK_NUM 12 // for typical FeliCa card
#define FELICA_WRITE_MAX_SERVICE_NUM 16
#define FELICA_WRITE_MAX_BLOCK_NUM 10 // for typical FeliCa card
#define FELICA_REQ_SERVICE_MAX_NODE_NUM 32
class PN532
{
public:
PN532(PN532Interface &interface);
void begin(void);
// Generic PN532 functions
bool SAMConfig(void);
uint32_t getFirmwareVersion(void);
uint32_t readRegister(uint16_t reg);
uint32_t writeRegister(uint16_t reg, uint8_t val);
bool writeGPIO(uint8_t pinstate);
uint8_t readGPIO(void);
bool setPassiveActivationRetries(uint8_t maxRetries);
bool setRFField(uint8_t autoRFCA, uint8_t rFOnOff);
/**
* @brief Init PN532 as a target
* @param timeout max time to wait, 0 means no timeout
* @return > 0 success
* = 0 timeout
* < 0 failed
*/
int8_t tgInitAsTarget(uint16_t timeout = 0);
int8_t tgInitAsTarget(const uint8_t* command, const uint8_t len, const uint16_t timeout = 0);
int16_t tgGetData(uint8_t *buf, uint8_t len);
bool tgSetData(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int16_t inRelease(const uint8_t relevantTarget = 0);
// ISO14443A functions
bool inListPassiveTarget();
bool readPassiveTargetID(uint8_t cardbaudrate, uint8_t *uid, uint8_t *uidLength, uint16_t timeout = 1000);
bool inDataExchange(uint8_t *send, uint8_t sendLength, uint8_t *response, uint8_t *responseLength);
// Mifare Classic functions
bool mifareclassic_IsFirstBlock (uint32_t uiBlock);
bool mifareclassic_IsTrailerBlock (uint32_t uiBlock);
uint8_t mifareclassic_AuthenticateBlock (uint8_t *uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t *keyData);
uint8_t mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t *data);
uint8_t mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t *data);
uint8_t mifareclassic_FormatNDEF (void);
uint8_t mifareclassic_WriteNDEFURI (uint8_t sectorNumber, uint8_t uriIdentifier, const char *url);
// Mifare Ultralight functions
uint8_t mifareultralight_ReadPage (uint8_t page, uint8_t *buffer);
uint8_t mifareultralight_WritePage (uint8_t page, uint8_t *buffer);
// FeliCa Functions
int8_t felica_Polling(uint16_t systemCode, uint8_t requestCode, uint8_t *idm, uint8_t *pmm, uint16_t *systemCodeResponse, uint16_t timeout=1000);
int8_t felica_SendCommand (const uint8_t * command, uint8_t commandlength, uint8_t * response, uint8_t * responseLength);
int8_t felica_RequestService(uint8_t numNode, uint16_t *nodeCodeList, uint16_t *keyVersions) ;
int8_t felica_RequestResponse(uint8_t *mode);
int8_t felica_ReadWithoutEncryption (uint8_t numService, const uint16_t *serviceCodeList, uint8_t numBlock, const uint16_t *blockList, uint8_t blockData[][16]);
int8_t felica_WriteWithoutEncryption (uint8_t numService, const uint16_t *serviceCodeList, uint8_t numBlock, const uint16_t *blockList, uint8_t blockData[][16]);
int8_t felica_RequestSystemCode(uint8_t *numSystemCode, uint16_t *systemCodeList);
int8_t felica_Release();
// Help functions to display formatted text
static void PrintHex(const uint8_t *data, const uint32_t numBytes);
static void PrintHexChar(const uint8_t *pbtData, const uint32_t numBytes);
uint8_t *getBuffer(uint8_t *len) {
*len = sizeof(pn532_packetbuffer) - 4;
return pn532_packetbuffer;
};
private:
uint8_t _uid[7]; // ISO14443A uid
uint8_t _uidLen; // uid len
uint8_t _key[6]; // Mifare Classic key
uint8_t inListedTag; // Tg number of inlisted tag.
uint8_t _felicaIDm[8]; // FeliCa IDm (NFCID2)
uint8_t _felicaPMm[8]; // FeliCa PMm (PAD)
uint8_t pn532_packetbuffer[64];
PN532Interface *_interface;
};
#endif

View File

@@ -1,56 +0,0 @@
#ifndef __PN532_INTERFACE_H__
#define __PN532_INTERFACE_H__
#include <stdint.h>
#define PN532_PREAMBLE (0x00)
#define PN532_STARTCODE1 (0x00)
#define PN532_STARTCODE2 (0xFF)
#define PN532_POSTAMBLE (0x00)
#define PN532_HOSTTOPN532 (0xD4)
#define PN532_PN532TOHOST (0xD5)
#define PN532_ACK_WAIT_TIME (10) // ms, timeout of waiting for ACK
#define PN532_INVALID_ACK (-1)
#define PN532_TIMEOUT (-2)
#define PN532_INVALID_FRAME (-3)
#define PN532_NO_SPACE (-4)
#define REVERSE_BITS_ORDER(b) b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; \
b = (b & 0xCC) >> 2 | (b & 0x33) << 2; \
b = (b & 0xAA) >> 1 | (b & 0x55) << 1
class PN532Interface
{
public:
virtual void begin() = 0;
virtual void wakeup() = 0;
/**
* @brief write a command and check ack
* @param header packet header
* @param hlen length of header
* @param body packet body
* @param blen length of body
* @return 0 success
* not 0 failed
*/
virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0) = 0;
/**
* @brief read the response of a command, strip prefix and suffix
* @param buf to contain the response data
* @param len lenght to read
* @param timeout max time to wait, 0 means no timeout
* @return >=0 length of response without prefix and suffix
* <0 failed to read response
*/
virtual int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout = 1000) = 0;
};
#endif

View File

@@ -1,20 +0,0 @@
#ifndef __DEBUG_H__
#define __DEBUG_H__
//#define DEBUG
#include "Arduino.h"
#ifdef DEBUG
#define DMSG(args...) Serial.print(args)
#define DMSG_STR(str) Serial.println(str)
#define DMSG_HEX(num) Serial.print(' '); Serial.print((num>>4)&0x0F, HEX); Serial.print(num&0x0F, HEX)
#define DMSG_INT(num) Serial.print(' '); Serial.print(num)
#else
#define DMSG(args...)
#define DMSG_STR(str)
#define DMSG_HEX(num)
#define DMSG_INT(num)
#endif
#endif

View File

@@ -1,30 +0,0 @@
## NFC library for Arduino
This is an Arduino library for PN532 to use NFC technology.
It works with
+ [NFC Shield](http://goo.gl/Cac2OH)
+ [Xadow NFC](http://goo.gl/qBZMt0)
+ [PN532 NFC/RFID controller breakout board](http://goo.gl/tby9Sw)
### Features
+ Support I2C, SPI and HSU of PN532
+ Read/write Mifare Classic Card
+ Works with [Don's NDEF Library](http://goo.gl/jDjsXl)
+ Support Peer to Peer communication(exchange data with android 4.0+)
+ Support [mbed platform](http://goo.gl/kGPovZ)
### Getting Started
1. Download [zip file](http://goo.gl/F6beRM) and
extract the 4 folders(PN532, PN532_SPI, PN532_I2C and PN532_HSU) into Arduino's libraries.
2. Downlaod [Don's NDEF library](http://goo.gl/ewxeAe) and extract it intro Arduino's libraries.
3. Follow the examples of the two libraries.
### To do
+ Card emulation
### Contribution
It's based on [Adafruit_NFCShield_I2C](http://goo.gl/pk3FdB).
[Seeed Studio](http://goo.gl/zh1iQh) adds SPI interface and peer to peer communication support.
@Don writes the [NDEF library](http://goo.gl/jDjsXl) to make it more easy to use.
@JiapengLi adds HSU interface.

View File

@@ -1,255 +0,0 @@
/**************************************************************************/
/*!
@file emulatetag.cpp
@author Armin Wieser
@license BSD
*/
/**************************************************************************/
#include "emulatetag.h"
#include "PN532_debug.h"
#include <string.h>
#define MAX_TGREAD
// Command APDU
#define C_APDU_CLA 0
#define C_APDU_INS 1 // instruction
#define C_APDU_P1 2 // parameter 1
#define C_APDU_P2 3 // parameter 2
#define C_APDU_LC 4 // length command
#define C_APDU_DATA 5 // data
#define C_APDU_P1_SELECT_BY_ID 0x00
#define C_APDU_P1_SELECT_BY_NAME 0x04
// Response APDU
#define R_APDU_SW1_COMMAND_COMPLETE 0x90
#define R_APDU_SW2_COMMAND_COMPLETE 0x00
#define R_APDU_SW1_NDEF_TAG_NOT_FOUND 0x6a
#define R_APDU_SW2_NDEF_TAG_NOT_FOUND 0x82
#define R_APDU_SW1_FUNCTION_NOT_SUPPORTED 0x6A
#define R_APDU_SW2_FUNCTION_NOT_SUPPORTED 0x81
#define R_APDU_SW1_MEMORY_FAILURE 0x65
#define R_APDU_SW2_MEMORY_FAILURE 0x81
#define R_APDU_SW1_END_OF_FILE_BEFORE_REACHED_LE_BYTES 0x62
#define R_APDU_SW2_END_OF_FILE_BEFORE_REACHED_LE_BYTES 0x82
// ISO7816-4 commands
#define ISO7816_SELECT_FILE 0xA4
#define ISO7816_READ_BINARY 0xB0
#define ISO7816_UPDATE_BINARY 0xD6
typedef enum { NONE, CC, NDEF } tag_file; // CC ... Compatibility Container
bool EmulateTag::init(){
pn532.begin();
return pn532.SAMConfig();
}
void EmulateTag::setNdefFile(const uint8_t* ndef, const int16_t ndefLength){
if(ndefLength > (NDEF_MAX_LENGTH -2)){
DMSG("ndef file too large (> NDEF_MAX_LENGHT -2) - aborting");
return;
}
ndef_file[0] = ndefLength >> 8;
ndef_file[1] = ndefLength & 0xFF;
memcpy(ndef_file+2, ndef, ndefLength);
}
void EmulateTag::setUid(uint8_t* uid){
uidPtr = uid;
}
bool EmulateTag::emulate(const uint16_t tgInitAsTargetTimeout){
uint8_t command[] = {
PN532_COMMAND_TGINITASTARGET,
5, // MODE: PICC only, Passive only
0x04, 0x00, // SENS_RES
0x00, 0x00, 0x00, // NFCID1
0x20, // SEL_RES
0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0, // FeliCaParams
0,0,
0,0,0,0,0,0,0,0,0,0, // NFCID3t
0, // length of general bytes
0 // length of historical bytes
};
if(uidPtr != 0){ // if uid is set copy 3 bytes to nfcid1
memcpy(command + 4, uidPtr, 3);
}
if(1 != pn532.tgInitAsTarget(command,sizeof(command), tgInitAsTargetTimeout)){
DMSG("tgInitAsTarget failed or timed out!");
return false;
}
uint8_t compatibility_container[] = {
0, 0x0F,
0x20,
0, 0x54,
0, 0xFF,
0x04, // T
0x06, // L
0xE1, 0x04, // File identifier
((NDEF_MAX_LENGTH & 0xFF00) >> 8), (NDEF_MAX_LENGTH & 0xFF), // maximum NDEF file size
0x00, // read access 0x0 = granted
0x00 // write access 0x0 = granted | 0xFF = deny
};
if(tagWriteable == false){
compatibility_container[14] = 0xFF;
}
tagWrittenByInitiator = false;
uint8_t rwbuf[128];
uint8_t sendlen;
int16_t status;
tag_file currentFile = NONE;
uint16_t cc_size = sizeof(compatibility_container);
bool runLoop = true;
while(runLoop){
status = pn532.tgGetData(rwbuf, sizeof(rwbuf));
if(status < 0){
DMSG("tgGetData failed!\n");
pn532.inRelease();
return true;
}
uint8_t p1 = rwbuf[C_APDU_P1];
uint8_t p2 = rwbuf[C_APDU_P2];
uint8_t lc = rwbuf[C_APDU_LC];
uint16_t p1p2_length = ((int16_t) p1 << 8) + p2;
switch(rwbuf[C_APDU_INS]){
case ISO7816_SELECT_FILE:
switch(p1){
case C_APDU_P1_SELECT_BY_ID:
if(p2 != 0x0c){
DMSG("C_APDU_P2 != 0x0c\n");
setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
} else if(lc == 2 && rwbuf[C_APDU_DATA] == 0xE1 && (rwbuf[C_APDU_DATA+1] == 0x03 || rwbuf[C_APDU_DATA+1] == 0x04)){
setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
if(rwbuf[C_APDU_DATA+1] == 0x03){
currentFile = CC;
} else if(rwbuf[C_APDU_DATA+1] == 0x04){
currentFile = NDEF;
}
} else {
setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
}
break;
case C_APDU_P1_SELECT_BY_NAME:
const uint8_t ndef_tag_application_name_v2[] = {0, 0x7, 0xD2, 0x76, 0x00, 0x00, 0x85, 0x01, 0x01 };
if(0 == memcmp(ndef_tag_application_name_v2, rwbuf + C_APDU_P2, sizeof(ndef_tag_application_name_v2))){
setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
} else{
DMSG("function not supported\n");
setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
}
break;
}
break;
case ISO7816_READ_BINARY:
switch(currentFile){
case NONE:
setResponse(TAG_NOT_FOUND, rwbuf, &sendlen);
break;
case CC:
if( p1p2_length > NDEF_MAX_LENGTH){
setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
}else {
memcpy(rwbuf,compatibility_container + p1p2_length, lc);
setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
}
break;
case NDEF:
if( p1p2_length > NDEF_MAX_LENGTH){
setResponse(END_OF_FILE_BEFORE_REACHED_LE_BYTES, rwbuf, &sendlen);
}else {
memcpy(rwbuf, ndef_file + p1p2_length, lc);
setResponse(COMMAND_COMPLETE, rwbuf + lc, &sendlen, lc);
}
break;
}
break;
case ISO7816_UPDATE_BINARY:
if(!tagWriteable){
setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
} else{
if( p1p2_length > NDEF_MAX_LENGTH){
setResponse(MEMORY_FAILURE, rwbuf, &sendlen);
}
else{
memcpy(ndef_file + p1p2_length, rwbuf + C_APDU_DATA, lc);
setResponse(COMMAND_COMPLETE, rwbuf, &sendlen);
tagWrittenByInitiator = true;
uint16_t ndef_length = (ndef_file[0] << 8) + ndef_file[1];
if ((ndef_length > 0) && (updateNdefCallback != 0)) {
updateNdefCallback(ndef_file + 2, ndef_length);
}
}
}
break;
default:
DMSG("Command not supported!");
DMSG_HEX(rwbuf[C_APDU_INS]);
DMSG("\n");
setResponse(FUNCTION_NOT_SUPPORTED, rwbuf, &sendlen);
}
status = pn532.tgSetData(rwbuf, sendlen);
if(status < 0){
DMSG("tgSetData failed\n!");
pn532.inRelease();
return true;
}
}
pn532.inRelease();
return true;
}
void EmulateTag::setResponse(responseCommand cmd, uint8_t* buf, uint8_t* sendlen, uint8_t sendlenOffset){
switch(cmd){
case COMMAND_COMPLETE:
buf[0] = R_APDU_SW1_COMMAND_COMPLETE;
buf[1] = R_APDU_SW2_COMMAND_COMPLETE;
*sendlen = 2 + sendlenOffset;
break;
case TAG_NOT_FOUND:
buf[0] = R_APDU_SW1_NDEF_TAG_NOT_FOUND;
buf[1] = R_APDU_SW2_NDEF_TAG_NOT_FOUND;
*sendlen = 2;
break;
case FUNCTION_NOT_SUPPORTED:
buf[0] = R_APDU_SW1_FUNCTION_NOT_SUPPORTED;
buf[1] = R_APDU_SW2_FUNCTION_NOT_SUPPORTED;
*sendlen = 2;
break;
case MEMORY_FAILURE:
buf[0] = R_APDU_SW1_MEMORY_FAILURE;
buf[1] = R_APDU_SW2_MEMORY_FAILURE;
*sendlen = 2;
break;
case END_OF_FILE_BEFORE_REACHED_LE_BYTES:
buf[0] = R_APDU_SW1_END_OF_FILE_BEFORE_REACHED_LE_BYTES;
buf[1] = R_APDU_SW2_END_OF_FILE_BEFORE_REACHED_LE_BYTES;
*sendlen= 2;
break;
}
}

View File

@@ -1,71 +0,0 @@
/**************************************************************************/
/*!
@file emulatetag.h
@author Armin Wieser
@license BSD
Implemented using NFC forum documents & library of libnfc
*/
/**************************************************************************/
#ifndef __EMULATETAG_H__
#define __EMULATETAG_H__
#include "PN532.h"
#define NDEF_MAX_LENGTH 128 // altough ndef can handle up to 0xfffe in size, arduino cannot.
typedef enum {COMMAND_COMPLETE, TAG_NOT_FOUND, FUNCTION_NOT_SUPPORTED, MEMORY_FAILURE, END_OF_FILE_BEFORE_REACHED_LE_BYTES} responseCommand;
class EmulateTag{
public:
EmulateTag(PN532Interface &interface) : pn532(interface), uidPtr(0), tagWrittenByInitiator(false), tagWriteable(true), updateNdefCallback(0) { }
bool init();
bool emulate(const uint16_t tgInitAsTargetTimeout = 0);
/*
* @param uid pointer to byte array of length 3 (uid is 4 bytes - first byte is fixed) or zero for uid
*/
void setUid(uint8_t* uid = 0);
void setNdefFile(const uint8_t* ndef, const int16_t ndefLength);
void getContent(uint8_t** buf, uint16_t* length){
*buf = ndef_file + 2; // first 2 bytes = length
*length = (ndef_file[0] << 8) + ndef_file[1];
}
bool writeOccured(){
return tagWrittenByInitiator;
}
void setTagWriteable(bool setWriteable){
tagWriteable = setWriteable;
}
uint8_t* getNdefFilePtr(){
return ndef_file;
}
uint8_t getNdefMaxLength(){
return NDEF_MAX_LENGTH;
}
void attach(void (*func)(uint8_t *buf, uint16_t length)) {
updateNdefCallback = func;
};
private:
PN532 pn532;
uint8_t ndef_file[NDEF_MAX_LENGTH];
uint8_t* uidPtr;
bool tagWrittenByInitiator;
bool tagWriteable;
void (*updateNdefCallback)(uint8_t *ndef, uint16_t length);
void setResponse(responseCommand cmd, uint8_t* buf, uint8_t* sendlen, uint8_t sendlenOffset = 0);
};
#endif

View File

@@ -1,115 +0,0 @@
/**************************************************************************/
/*!
This example will attempt to connect to an FeliCa
card or tag and retrieve some basic information about it
that can be used to determine what type of card it is.
Note that you need the baud rate to be 115200 because we need to print
out the data and read from the card at the same time!
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#include <Arduino.h>
#if 1
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 0
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);
#endif
#include <PN532_debug.h>
uint8_t _prevIDm[8];
unsigned long _prevTime;
void setup(void)
{
Serial.begin(115200);
Serial.println("Hello!");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (!versiondata)
{
Serial.print("Didn't find PN53x board");
while (1) {delay(10);}; // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
memset(_prevIDm, 0, 8);
}
void loop(void)
{
uint8_t ret;
uint16_t systemCode = 0xFFFF;
uint8_t requestCode = 0x01; // System Code request
uint8_t idm[8];
uint8_t pmm[8];
uint16_t systemCodeResponse;
// Wait for an FeliCa type cards.
// When one is found, some basic information such as IDm, PMm, and System Code are retrieved.
Serial.print("Waiting for an FeliCa card... ");
ret = nfc.felica_Polling(systemCode, requestCode, idm, pmm, &systemCodeResponse, 5000);
if (ret != 1)
{
Serial.println("Could not find a card");
delay(500);
return;
}
if ( memcmp(idm, _prevIDm, 8) == 0 ) {
if ( (millis() - _prevTime) < 3000 ) {
Serial.println("Same card");
delay(500);
return;
}
}
Serial.println("Found a card!");
Serial.print(" IDm: ");
nfc.PrintHex(idm, 8);
Serial.print(" PMm: ");
nfc.PrintHex(pmm, 8);
Serial.print(" System Code: ");
Serial.print(systemCodeResponse, HEX);
Serial.print("\n");
memcpy(_prevIDm, idm, 8);
_prevTime = millis();
// Wait 1 second before continuing
Serial.println("Card access completed!\n");
delay(1000);
}

View File

@@ -1,165 +0,0 @@
/**************************************************************************/
/*!
This example will attempt to connect to an FeliCa
card or tag and retrieve some basic information about it
that can be used to determine what type of card it is.
Note that you need the baud rate to be 115200 because we need to print
out the data and read from the card at the same time!
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#include <Arduino.h>
#if 1
#include <SPI.h>
#include <PN532_SPI.h>
#include <PN532.h>
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 0
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);
#endif
#include <PN532_debug.h>
uint8_t _prevIDm[8];
unsigned long _prevTime;
void PrintHex8(const uint8_t d) {
Serial.print(" ");
Serial.print( (d >> 4) & 0x0F, HEX);
Serial.print( d & 0x0F, HEX);
}
void setup(void)
{
Serial.begin(115200);
Serial.println("Hello!");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (!versiondata)
{
Serial.print("Didn't find PN53x board");
while (1) {delay(10);}; // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
memset(_prevIDm, 0, 8);
}
void loop(void)
{
uint8_t ret;
uint16_t systemCode = 0xFFFF;
uint8_t requestCode = 0x01; // System Code request
uint8_t idm[8];
uint8_t pmm[8];
uint16_t systemCodeResponse;
// Wait for an FeliCa type cards.
// When one is found, some basic information such as IDm, PMm, and System Code are retrieved.
Serial.print("Waiting for an FeliCa card... ");
ret = nfc.felica_Polling(systemCode, requestCode, idm, pmm, &systemCodeResponse, 5000);
if (ret != 1)
{
Serial.println("Could not find a card");
delay(500);
return;
}
if ( memcmp(idm, _prevIDm, 8) == 0 ) {
if ( (millis() - _prevTime) < 3000 ) {
Serial.println("Same card");
delay(500);
return;
}
}
Serial.println("Found a card!");
Serial.print(" IDm: ");
nfc.PrintHex(idm, 8);
Serial.print(" PMm: ");
nfc.PrintHex(pmm, 8);
Serial.print(" System Code: ");
Serial.print(systemCodeResponse, HEX);
Serial.print("\n");
memcpy(_prevIDm, idm, 8);
_prevTime = millis();
uint8_t blockData[3][16];
uint16_t serviceCodeList[1];
uint16_t blockList[3];
Serial.println("Write Without Encryption command ");
serviceCodeList[0] = 0x0009;
blockList[0] = 0x8000;
unsigned long now = millis();
blockData[0][3] = now & 0xFF;
blockData[0][2] = (now >>= 8) & 0xFF;
blockData[0][1] = (now >>= 8) & 0xFF;
blockData[0][0] = (now >>= 8) & 0xFF;
Serial.print(" Writing current millis (");
PrintHex8(blockData[0][0]);
PrintHex8(blockData[0][1]);
PrintHex8(blockData[0][2]);
PrintHex8(blockData[0][3]);
Serial.print(" ) to Block 0 -> ");
ret = nfc.felica_WriteWithoutEncryption(1, serviceCodeList, 1, blockList, blockData);
if (ret != 1)
{
Serial.println("error");
} else {
Serial.println("OK!");
}
memset(blockData[0], 0, 16);
Serial.print("Read Without Encryption command -> ");
serviceCodeList[0] = 0x000B;
blockList[0] = 0x8000;
blockList[1] = 0x8001;
blockList[2] = 0x8002;
ret = nfc.felica_ReadWithoutEncryption(1, serviceCodeList, 3, blockList, blockData);
if (ret != 1)
{
Serial.println("error");
} else {
Serial.println("OK!");
for(int i=0; i<3; i++ ) {
Serial.print(" Block no. "); Serial.print(i, DEC); Serial.print(": ");
nfc.PrintHex(blockData[i], 16);
}
}
// Wait 1 second before continuing
Serial.println("Card access completed!\n");
delay(1000);
}

View File

@@ -1,145 +0,0 @@
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#endif
void setup()
{
Serial.begin(115200);
Serial.println("-------Peer to Peer HCE--------");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
//nfc.setPassiveActivationRetries(0xFF);
// configure board to read RFID tags
nfc.SAMConfig();
}
void loop()
{
bool success;
uint8_t responseLength = 32;
Serial.println("Waiting for an ISO14443A card");
// set shield to inListPassiveTarget
success = nfc.inListPassiveTarget();
if(success) {
Serial.println("Found something!");
uint8_t selectApdu[] = { 0x00, /* CLA */
0xA4, /* INS */
0x04, /* P1 */
0x00, /* P2 */
0x07, /* Length of AID */
0xF0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* AID defined on Android App */
0x00 /* Le */ };
uint8_t response[32];
success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength);
if(success) {
Serial.print("responseLength: "); Serial.println(responseLength);
nfc.PrintHexChar(response, responseLength);
do {
uint8_t apdu[] = "Hello from Arduino";
uint8_t back[32];
uint8_t length = 32;
success = nfc.inDataExchange(apdu, sizeof(apdu), back, &length);
if(success) {
Serial.print("responseLength: "); Serial.println(length);
nfc.PrintHexChar(back, length);
}
else {
Serial.println("Broken connection?");
}
}
while(success);
}
else {
Serial.println("Failed sending SELECT AID");
}
}
else {
Serial.println("Didn't find anything!");
}
delay(1000);
}
void printResponse(uint8_t *response, uint8_t responseLength) {
String respBuffer;
for (int i = 0; i < responseLength; i++) {
if (response[i] < 0x10)
respBuffer = respBuffer + "0"; //Adds leading zeros if hex value is smaller than 0x10
respBuffer = respBuffer + String(response[i], HEX) + " ";
}
Serial.print("response: "); Serial.println(respBuffer);
}
void setupNFC() {
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
}

View File

@@ -1,82 +0,0 @@
#include "emulatetag.h"
#include "NdefMessage.h"
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
EmulateTag nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
EmulateTag nfc(pn532hsu);
#endif
uint8_t ndefBuf[120];
NdefMessage message;
int messageSize;
uint8_t uid[3] = { 0x12, 0x34, 0x56 };
void setup()
{
Serial.begin(115200);
Serial.println("------- Emulate Tag --------");
message = NdefMessage();
message.addUriRecord("http://www.elechouse.com");
messageSize = message.getEncodedSize();
if (messageSize > sizeof(ndefBuf)) {
Serial.println("ndefBuf is too small");
while (1) { }
}
Serial.print("Ndef encoded message size: ");
Serial.println(messageSize);
message.encode(ndefBuf);
// comment out this command for no ndef message
nfc.setNdefFile(ndefBuf, messageSize);
// uid must be 3 bytes!
nfc.setUid(uid);
nfc.init();
}
void loop(){
// uncomment for overriding ndef in case a write to this tag occured
//nfc.setNdefFile(ndefBuf, messageSize);
// start emulation (blocks)
nfc.emulate();
// or start emulation with timeout
/*if(!nfc.emulate(1000)){ // timeout 1 second
Serial.println("timed out");
}*/
// deny writing to the tag
// nfc.setTagWriteable(false);
if(nfc.writeOccured()){
Serial.println("\nWrite occured !");
uint8_t* tag_buf;
uint16_t length;
nfc.getContent(&tag_buf, &length);
NdefMessage msg = NdefMessage(tag_buf, length);
msg.print();
}
delay(1000);
}

View File

@@ -1,99 +0,0 @@
/**************************************************************************/
/*!
This example will attempt to connect to an ISO14443A
card or tag and retrieve some basic information about it
that can be used to determine what type of card it is.
Note that you need the baud rate to be 115200 because we need to print
out the data and read from the card at the same time!
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
/* When the number after #if set as 1, it will be switch to SPI Mode*/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
/* When the number after #elif set as 1, it will be switch to HSU Mode*/
#elif 0
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
/* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>
PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);
#endif
void setup(void) {
Serial.begin(115200);
Serial.println("Hello!");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// Set the max number of retry attempts to read from a card
// This prevents us from waiting forever for a card, which is
// the default behaviour of the PN532.
nfc.setPassiveActivationRetries(0xFF);
// configure board to read RFID tags
nfc.SAMConfig();
Serial.println("Waiting for an ISO14443A card");
}
void loop(void) {
boolean success;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
// Wait for an ISO14443A type cards (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
if (success) {
Serial.println("Found a card!");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value: ");
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(" 0x");Serial.print(uid[i], HEX);
}
Serial.println("");
// Wait 1 second before continuing
delay(1000);
}
else
{
// PN532 probably timed out waiting for a card
Serial.println("Timed out waiting for a card");
}
}

View File

@@ -1,181 +0,0 @@
/**************************************************************************/
/*!
This example attempts to format a clean Mifare Classic 1K card as
an NFC Forum tag (to store NDEF messages that can be read by any
NFC enabled Android phone, etc.)
Note that you need the baud rate to be 115200 because we need to print
out the data and read from the card at the same time!
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#endif
/*
We can encode many different kinds of pointers to the card,
from a URL, to an Email address, to a phone number, and many more
check the library header .h file to see the large # of supported
prefixes!
*/
// For a http://www. url:
const char * url = "elechouse.com";
uint8_t ndefprefix = NDEF_URIPREFIX_HTTP_WWWDOT;
// for an email address
//const char * url = "mail@example.com";
//uint8_t ndefprefix = NDEF_URIPREFIX_MAILTO;
// for a phone number
//const char * url = "+1 212 555 1212";
//uint8_t ndefprefix = NDEF_URIPREFIX_TEL;
void setup(void) {
Serial.begin(115200);
Serial.println("Looking for PN532...");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
}
void loop(void) {
uint8_t success; // Flag to check if there was an error with the PN532
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
bool authenticated = false; // Flag to indicate if the sector is authenticated
// Use the default key
uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
Serial.println("");
Serial.println("PLEASE NOTE: Formatting your card for NDEF records will change the");
Serial.println("authentication keys. To reformat your NDEF tag as a clean Mifare");
Serial.println("Classic tag, use the mifareclassic_ndeftoclassic example!");
Serial.println("");
Serial.println("Place your Mifare Classic card on the reader to format with NDEF");
Serial.println("and press any key to continue ...");
// Wait for user input before proceeding
while (!Serial.available());
// a key was pressed1
while (Serial.available()) Serial.read();
// Wait for an ISO14443A type card (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success)
{
// Display some basic information about the card
Serial.println("Found an ISO14443A card");
Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print(" UID Value: ");
nfc.PrintHex(uid, uidLength);
for (uint8_t i = 0; i < uidLength; i++) {
Serial.print(uid[i], HEX);
Serial.print(' ');
}
Serial.println("");
// Make sure this is a Mifare Classic card
if (uidLength != 4)
{
Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!");
return;
}
// We probably have a Mifare Classic card ...
Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
// Try to format the card for NDEF data
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 0, 0, keya);
if (!success)
{
Serial.println("Unable to authenticate block 0 to enable card formatting!");
return;
}
success = nfc.mifareclassic_FormatNDEF();
if (!success)
{
Serial.println("Unable to format the card for NDEF");
return;
}
Serial.println("Card has been formatted for NDEF data using MAD1");
// Try to authenticate block 4 (first block of sector 1) using our key
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 4, 0, keya);
// Make sure the authentification process didn't fail
if (!success)
{
Serial.println("Authentication failed.");
return;
}
// Try to write a URL
Serial.println("Writing URI to sector 1 as an NDEF Message");
// Authenticated seems to have worked
// Try to write an NDEF record to sector 1
// Use 0x01 for the URI Identifier Code to prepend "http://www."
// to the url (and save some space). For information on URI ID Codes
// see http://www.ladyada.net/wiki/private/articlestaging/nfc/ndef
if (strlen(url) > 38)
{
// The length is also checked in the WriteNDEFURI function, but lets
// warn users here just in case they change the value and it's bigger
// than it should be
Serial.println("URI is too long ... must be less than 38 characters long");
return;
}
// URI is within size limits ... write it to the card and report success/failure
success = nfc.mifareclassic_WriteNDEFURI(1, ndefprefix, url);
if (success)
{
Serial.println("NDEF URI Record written to sector 1");
}
else
{
Serial.println("NDEF Record creation failed! :(");
}
}
// Wait a bit before trying again
Serial.println("\n\nDone!");
delay(1000);
Serial.flush();
while(Serial.available()) Serial.read();
}

View File

@@ -1,169 +0,0 @@
/**************************************************************************/
/*!
This example attempts to dump the contents of a Mifare Classic 1K card
Note that you need the baud rate to be 115200 because we need to print
out the data and read from the card at the same time!
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#endif
void setup(void) {
// has to be fast to dump the entire memory contents!
Serial.begin(115200);
Serial.println("Looking for PN532...");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
Serial.println("Waiting for an ISO14443A Card ...");
}
void loop(void) {
uint8_t success; // Flag to check if there was an error with the PN532
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
uint8_t currentblock; // Counter to keep track of which block we're on
bool authenticated = false; // Flag to indicate if the sector is authenticated
uint8_t data[16]; // Array to store block data during reads
// Keyb on NDEF and Mifare Classic should be the same
uint8_t keyuniversal[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
// Wait for an ISO14443A type cards (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success) {
// Display some basic information about the card
Serial.println("Found an ISO14443A card");
Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print(" UID Value: ");
for (uint8_t i = 0; i < uidLength; i++) {
Serial.print(uid[i], HEX);
Serial.print(' ');
}
Serial.println("");
if (uidLength == 4)
{
// We probably have a Mifare Classic card ...
Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
// Now we try to go through all 16 sectors (each having 4 blocks)
// authenticating each sector, and then dumping the blocks
for (currentblock = 0; currentblock < 64; currentblock++)
{
// Check if this is a new block so that we can reauthenticate
if (nfc.mifareclassic_IsFirstBlock(currentblock)) authenticated = false;
// If the sector hasn't been authenticated, do so first
if (!authenticated)
{
// Starting of a new sector ... try to to authenticate
Serial.print("------------------------Sector ");Serial.print(currentblock/4, DEC);Serial.println("-------------------------");
if (currentblock == 0)
{
// This will be 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF for Mifare Classic (non-NDEF!)
// or 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 for NDEF formatted cards using key a,
// but keyb should be the same for both (0xFF 0xFF 0xFF 0xFF 0xFF 0xFF)
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, currentblock, 1, keyuniversal);
}
else
{
// This will be 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF for Mifare Classic (non-NDEF!)
// or 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 for NDEF formatted cards using key a,
// but keyb should be the same for both (0xFF 0xFF 0xFF 0xFF 0xFF 0xFF)
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, currentblock, 1, keyuniversal);
}
if (success)
{
authenticated = true;
}
else
{
Serial.println("Authentication error");
}
}
// If we're still not authenticated just skip the block
if (!authenticated)
{
Serial.print("Block ");Serial.print(currentblock, DEC);Serial.println(" unable to authenticate");
}
else
{
// Authenticated ... we should be able to read the block now
// Dump the data into the 'data' array
success = nfc.mifareclassic_ReadDataBlock(currentblock, data);
if (success)
{
// Read successful
Serial.print("Block ");Serial.print(currentblock, DEC);
if (currentblock < 10)
{
Serial.print(" ");
}
else
{
Serial.print(" ");
}
// Dump the raw data
nfc.PrintHexChar(data, 16);
}
else
{
// Oops ... something happened
Serial.print("Block ");Serial.print(currentblock, DEC);
Serial.println(" unable to read this block");
}
}
}
}
else
{
Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!");
}
}
// Wait a bit before trying again
Serial.println("\n\nSend a character to run the mem dumper again!");
Serial.flush();
while (!Serial.available());
while (Serial.available()) {
Serial.read();
}
Serial.flush();
}

View File

@@ -1,183 +0,0 @@
/**************************************************************************/
/*!
This examples attempts to take a Mifare Classic 1K card that has been
formatted for NDEF messages using mifareclassic_formatndef, and resets
the authentication keys back to the Mifare Classic defaults
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#endif
#define NR_SHORTSECTOR (32) // Number of short sectors on Mifare 1K/4K
#define NR_LONGSECTOR (8) // Number of long sectors on Mifare 4K
#define NR_BLOCK_OF_SHORTSECTOR (4) // Number of blocks in a short sector
#define NR_BLOCK_OF_LONGSECTOR (16) // Number of blocks in a long sector
// Determine the sector trailer block based on sector number
#define BLOCK_NUMBER_OF_SECTOR_TRAILER(sector) (((sector)<NR_SHORTSECTOR)? \
((sector)*NR_BLOCK_OF_SHORTSECTOR + NR_BLOCK_OF_SHORTSECTOR-1):\
(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR + NR_BLOCK_OF_LONGSECTOR-1))
// Determine the sector's first block based on the sector number
#define BLOCK_NUMBER_OF_SECTOR_1ST_BLOCK(sector) (((sector)<NR_SHORTSECTOR)? \
((sector)*NR_BLOCK_OF_SHORTSECTOR):\
(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR))
// The default Mifare Classic key
static const uint8_t KEY_DEFAULT_KEYAB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
void setup(void) {
Serial.begin(115200);
Serial.println("Looking for PN532...");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
}
void loop(void) {
uint8_t success; // Flag to check if there was an error with the PN532
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
bool authenticated = false; // Flag to indicate if the sector is authenticated
uint8_t blockBuffer[16]; // Buffer to store block contents
uint8_t blankAccessBits[3] = { 0xff, 0x07, 0x80 };
uint8_t idx = 0;
uint8_t numOfSector = 16; // Assume Mifare Classic 1K for now (16 4-block sectors)
Serial.println("Place your NDEF formatted Mifare Classic 1K card on the reader");
Serial.println("and press any key to continue ...");
// Wait for user input before proceeding
while (!Serial.available());
while (Serial.available()) Serial.read();
// Wait for an ISO14443A type card (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success)
{
// We seem to have a tag ...
// Display some basic information about it
Serial.println("Found an ISO14443A card/tag");
Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print(" UID Value: ");
nfc.PrintHex(uid, uidLength);
Serial.println("");
// Make sure this is a Mifare Classic card
if (uidLength != 4)
{
Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!");
return;
}
Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
Serial.println("");
Serial.println("Reformatting card for Mifare Classic (please don't touch it!) ... ");
// Now run through the card sector by sector
for (idx = 0; idx < numOfSector; idx++)
{
// Step 1: Authenticate the current sector using key B 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, BLOCK_NUMBER_OF_SECTOR_TRAILER(idx), 1, (uint8_t *)KEY_DEFAULT_KEYAB);
if (!success)
{
Serial.print("Authentication failed for sector "); Serial.println(numOfSector);
return;
}
// Step 2: Write to the other blocks
if (idx == 16)
{
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer)))
{
Serial.print("Unable to write to sector "); Serial.println(numOfSector);
return;
}
}
if ((idx == 0) || (idx == 16))
{
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))
{
Serial.print("Unable to write to sector "); Serial.println(numOfSector);
return;
}
}
else
{
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer)))
{
Serial.print("Unable to write to sector "); Serial.println(numOfSector);
return;
}
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))
{
Serial.print("Unable to write to sector "); Serial.println(numOfSector);
return;
}
}
memset(blockBuffer, 0, sizeof(blockBuffer));
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 1, blockBuffer)))
{
Serial.print("Unable to write to sector "); Serial.println(numOfSector);
return;
}
// Step 3: Reset both keys to 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
memcpy(blockBuffer, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));
memcpy(blockBuffer + 6, blankAccessBits, sizeof(blankAccessBits));
blockBuffer[9] = 0x69;
memcpy(blockBuffer + 10, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));
// Step 4: Write the trailer block
if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)), blockBuffer)))
{
Serial.print("Unable to write trailer block of sector "); Serial.println(numOfSector);
return;
}
}
}
// Wait a bit before trying again
Serial.println("\n\nDone!");
delay(1000);
Serial.flush();
while(Serial.available()) Serial.read();
}

View File

@@ -1,156 +0,0 @@
/**************************************************************************/
/*!
Updates a sector that is already formatted for NDEF (using
mifareclassic_formatndef.pde for example), inserting a new url
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#endif
/*
We can encode many different kinds of pointers to the card,
from a URL, to an Email address, to a phone number, and many more
check the library header .h file to see the large # of supported
prefixes!
*/
// For a http://www. url:
const char * url = "elechouse.com";
uint8_t ndefprefix = NDEF_URIPREFIX_HTTP_WWWDOT;
// for an email address
//const char * url = "mail@example.com";
//uint8_t ndefprefix = NDEF_URIPREFIX_MAILTO;
// for a phone number
//const char * url = "+1 212 555 1212";
//uint8_t ndefprefix = NDEF_URIPREFIX_TEL;
void setup(void) {
Serial.begin(115200);
Serial.println("Looking for PN532...");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
}
void loop(void) {
uint8_t success; // Flag to check if there was an error with the PN532
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
bool authenticated = false; // Flag to indicate if the sector is authenticated
// Use the default NDEF keys (these would have have set by mifareclassic_formatndef.pde!)
uint8_t keya[6] = { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5 };
uint8_t keyb[6] = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7 };
Serial.println("Place your NDEF formatted Mifare Classic card on the reader to update the");
Serial.println("NDEF record and press any key to continue ...");
// Wait for user input before proceeding
while (!Serial.available());
// a key was pressed1
while (Serial.available()) Serial.read();
// Wait for an ISO14443A type card (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success)
{
// Display some basic information about the card
Serial.println("Found an ISO14443A card");
Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print(" UID Value: ");
nfc.PrintHex(uid, uidLength);
Serial.println("");
// Make sure this is a Mifare Classic card
if (uidLength != 4)
{
Serial.println("Ooops ... this doesn't seem to be a Mifare Classic card!");
return;
}
// We probably have a Mifare Classic card ...
Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
// Check if this is an NDEF card (using first block of sector 1 from mifareclassic_formatndef.pde)
// Must authenticate on the first key using 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7
success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, 4, 0, keyb);
if (!success)
{
Serial.println("Unable to authenticate block 4 ... is this card NDEF formatted?");
return;
}
Serial.println("Authentication succeeded (seems to be an NDEF/NFC Forum tag) ...");
// Authenticated seems to have worked
// Try to write an NDEF record to sector 1
// Use 0x01 for the URI Identifier Code to prepend "http://www."
// to the url (and save some space). For information on URI ID Codes
// see http://www.ladyada.net/wiki/private/articlestaging/nfc/ndef
if (strlen(url) > 38)
{
// The length is also checked in the WriteNDEFURI function, but lets
// warn users here just in case they change the value and it's bigger
// than it should be
Serial.println("URI is too long ... must be less than 38 characters!");
return;
}
Serial.println("Updating sector 1 with URI as NDEF Message");
// URI is within size limits ... write it to the card and report success/failure
success = nfc.mifareclassic_WriteNDEFURI(1, ndefprefix, url);
if (success)
{
Serial.println("NDEF URI Record written to sector 1");
Serial.println("");
}
else
{
Serial.println("NDEF Record creation failed! :(");
}
}
// Wait a bit before trying again
Serial.println("\n\nDone!");
delay(1000);
Serial.flush();
while(Serial.available()) Serial.read();
}

View File

@@ -1,50 +0,0 @@
// snep_test.ino
// send a SNEP message to adnroid and get a message from android
#include "SPI.h"
#include "PN532_SPI.h"
#include "llcp.h"
#include "snep.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
void setup()
{
Serial.begin(115200);
Serial.println("-------Peer to Peer--------");
}
uint8_t message[] = {
0xD2, 0xA, 0xB, 0x74,0x65, 0x78, 0x74, 0x2F, 0x70, 0x6C,
0x61, 0x69, 0x6E, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x77,
0x6F, 0x72, 0x6C, 0x64};
uint8_t buf[128];
void loop()
{
nfc.write(message, sizeof(message));
delay(3000);
int16_t len = nfc.read(buf, sizeof(buf));
if (len > 0) {
Serial.println("get a SNEP message:");
for (uint8_t i = 0; i < len; i++) {
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.print('\n');
for (uint8_t i = 0; i < len; i++) {
char c = buf[i];
if (c <= 0x1f || c > 0x7f) {
Serial.print('.');
} else {
Serial.print(c);
}
}
Serial.print('\n');
}
delay(3000);
}

View File

@@ -1,55 +0,0 @@
// send a NDEF message to adnroid or get a NDEF message
//
// note: [NDEF library](https://github.com/Don/NDEF) is needed.
#include "SPI.h"
#include "PN532_SPI.h"
#include "snep.h"
#include "NdefMessage.h"
PN532_SPI pn532spi(SPI, 10);
SNEP nfc(pn532spi);
uint8_t ndefBuf[128];
void setup()
{
Serial.begin(115200);
Serial.println("-------Peer to Peer--------");
}
void loop()
{
#if 1
Serial.println("Send a message to Android");
NdefMessage message = NdefMessage();
message.addUriRecord("http://www.seeedstudio.com");
int messageSize = message.getEncodedSize();
if (messageSize > sizeof(ndefBuf)) {
Serial.println("ndefBuf is too small");
while (1) {
}
}
message.encode(ndefBuf);
if (0 >= nfc.write(ndefBuf, messageSize)) {
Serial.println("Failed");
} else {
Serial.println("Success");
}
delay(3000);
#else
// it seems there are some issues to use NdefMessage to decode the received data from Android
Serial.println("Get a message from Android");
int msgSize = nfc.read(ndefBuf, sizeof(ndefBuf));
if (msgSize > 0) {
NdefMessage msg = NdefMessage(ndefBuf, msgSize);
msg.print();
Serial.println("\nSuccess");
} else {
Serial.println("failed");
}
delay(3000);
#endif
}

View File

@@ -1,158 +0,0 @@
/**************************************************************************/
/*!
This example will wait for any ISO14443A card or tag, and
depending on the size of the UID will attempt to read from it.
If the card has a 4-byte UID it is probably a Mifare
Classic card, and the following steps are taken:
- Authenticate block 4 (the first block of Sector 1) using
the default KEYA of 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF
- If authentication succeeds, we can then read any of the
4 blocks in that sector (though only block 4 is read here)
If the card has a 7-byte UID it is probably a Mifare
Ultralight card, and the 4 byte pages can be read directly.
Page 4 is read by default since this is the first 'general-
purpose' page on the tags.
To enable debug message, define DEBUG in PN532/PN532_debug.h
*/
/**************************************************************************/
#if 0
#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"
PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);
#elif 1
#include <PN532_HSU.h>
#include <PN532.h>
PN532_HSU pn532hsu(Serial1);
PN532 nfc(pn532hsu);
#else
#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
PN532_I2C pn532i2c(Wire);
PN532 nfc(pn532i2c);
#endif
void setup(void) {
Serial.begin(115200);
Serial.println("Hello!");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
// configure board to read RFID tags
nfc.SAMConfig();
Serial.println("Waiting for an ISO14443A Card ...");
}
void loop(void) {
uint8_t success;
uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 }; // Buffer to store the returned UID
uint8_t uidLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
// Wait for an ISO14443A type cards (Mifare, etc.). When one is found
// 'uid' will be populated with the UID, and uidLength will indicate
// if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
if (success) {
// Display some basic information about the card
Serial.println("Found an ISO14443A card");
Serial.print(" UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print(" UID Value: ");
nfc.PrintHex(uid, uidLength);
Serial.println("");
if (uidLength == 4)
{
// We probably have a Mifare Classic card ...
Serial.println("Seems to be a Mifare Classic card (4 byte UID)");
// Now we need to try to authenticate it for read/write access
// Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
Serial.println("Trying to authenticate block 4 with default KEYA value");
uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
// Start with block 4 (the first block of sector 1) since sector 0
// contains the manufacturer data and it's probably better just
// to leave it alone unless you know what you're doing
success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);
if (success)
{
Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
uint8_t data[16];
// If you want to write something to block 4 to test with, uncomment
// the following line and this text should be read back in a minute
// data = { 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0};
// success = nfc.mifareclassic_WriteDataBlock (4, data);
// Try to read the contents of block 4
success = nfc.mifareclassic_ReadDataBlock(4, data);
if (success)
{
// Data seems to have been read ... spit it out
Serial.println("Reading Block 4:");
nfc.PrintHexChar(data, 16);
Serial.println("");
// Wait a bit before reading the card again
delay(1000);
}
else
{
Serial.println("Ooops ... unable to read the requested block. Try another key?");
}
}
else
{
Serial.println("Ooops ... authentication failed: Try another key?");
}
}
if (uidLength == 7)
{
// We probably have a Mifare Ultralight card ...
Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");
// Try to read the first general-purpose user page (#4)
Serial.println("Reading page 4");
uint8_t data[32];
success = nfc.mifareultralight_ReadPage (4, data);
if (success)
{
// Data seems to have been read ... spit it out
nfc.PrintHexChar(data, 4);
Serial.println("");
// Wait a bit before reading the card again
delay(1000);
}
else
{
Serial.println("Ooops ... unable to read the requested page!?");
}
}
}
}

View File

@@ -1,27 +0,0 @@
Software License Agreement (BSD License)
Copyright (c) 2012, Adafruit Industries
Copyright (c) 2013, Seeed Technology Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holders nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -1,309 +0,0 @@
#include "llcp.h"
#include "PN532_debug.h"
// LLCP PDU Type Values
#define PDU_SYMM 0x00
#define PDU_PAX 0x01
#define PDU_CONNECT 0x04
#define PDU_DISC 0x05
#define PDU_CC 0x06
#define PDU_DM 0x07
#define PDU_I 0x0c
#define PDU_RR 0x0d
uint8_t LLCP::SYMM_PDU[2] = {0, 0};
inline uint8_t getPType(const uint8_t *buf)
{
return ((buf[0] & 0x3) << 2) + (buf[1] >> 6);
}
inline uint8_t getSSAP(const uint8_t *buf)
{
return buf[1] & 0x3f;
}
inline uint8_t getDSAP(const uint8_t *buf)
{
return buf[0] >> 2;
}
int8_t LLCP::activate(uint16_t timeout)
{
return link.activateAsTarget(timeout);
}
int8_t LLCP::waitForConnection(uint16_t timeout)
{
uint8_t type;
mode = 1;
ns = 0;
nr = 0;
// Get CONNECT PDU
DMSG("wait for a CONNECT PDU\n");
do {
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_CONNECT == type) {
break;
} else if (PDU_SYMM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return -2;
}
} else {
return -3;
}
} while (1);
// Put CC PDU
DMSG("put a CC(Connection Complete) PDU to response the CONNECT PDU\n");
ssap = getDSAP(headerBuf);
dsap = getSSAP(headerBuf);
headerBuf[0] = (dsap << 2) + ((PDU_CC >> 2) & 0x3);
headerBuf[1] = ((PDU_CC & 0x3) << 6) + ssap;
if (!link.write(headerBuf, 2)) {
return -2;
}
return 1;
}
int8_t LLCP::waitForDisconnection(uint16_t timeout)
{
uint8_t type;
// Get DISC PDU
DMSG("wait for a DISC PDU\n");
do {
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_DISC == type) {
break;
} else if (PDU_SYMM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return -2;
}
} else {
return -3;
}
} while (1);
// Put DM PDU
DMSG("put a DM(Disconnect Mode) PDU to response the DISC PDU\n");
// ssap = getDSAP(headerBuf);
// dsap = getSSAP(headerBuf);
headerBuf[0] = (dsap << 2) + (PDU_DM >> 2);
headerBuf[1] = ((PDU_DM & 0x3) << 6) + ssap;
if (!link.write(headerBuf, 2)) {
return -2;
}
return 1;
}
int8_t LLCP::connect(uint16_t timeout)
{
uint8_t type;
mode = 0;
dsap = LLCP_DEFAULT_DSAP;
ssap = LLCP_DEFAULT_SSAP;
ns = 0;
nr = 0;
// try to get a SYMM PDU
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_SYMM != type) {
return -1;
}
// put a CONNECT PDU
headerBuf[0] = (LLCP_DEFAULT_DSAP << 2) + (PDU_CONNECT >> 2);
headerBuf[1] = ((PDU_CONNECT & 0x03) << 6) + LLCP_DEFAULT_SSAP;
uint8_t body[] = " urn:nfc:sn:snep";
body[0] = 0x06;
body[1] = sizeof(body) - 2 - 1;
if (!link.write(headerBuf, 2, body, sizeof(body) - 1)) {
return -2;
}
// wait for a CC PDU
DMSG("wait for a CC PDU\n");
do {
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_CC == type) {
break;
} else if (PDU_SYMM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return -2;
}
} else {
return -3;
}
} while (1);
return 1;
}
int8_t LLCP::disconnect(uint16_t timeout)
{
uint8_t type;
// try to get a SYMM PDU
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_SYMM != type) {
return -1;
}
// put a DISC PDU
headerBuf[0] = (LLCP_DEFAULT_DSAP << 2) + (PDU_DISC >> 2);
headerBuf[1] = ((PDU_DISC & 0x03) << 6) + LLCP_DEFAULT_SSAP;
if (!link.write(headerBuf, 2)) {
return -2;
}
// wait for a DM PDU
DMSG("wait for a DM PDU\n");
do {
if (2 > link.read(headerBuf, headerBufLen)) {
return -1;
}
type = getPType(headerBuf);
if (PDU_CC == type) {
break;
} else if (PDU_DM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return -2;
}
} else {
return -3;
}
} while (1);
return 1;
}
bool LLCP::write(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
uint8_t type;
uint8_t buf[3];
if (mode) {
// Get a SYMM PDU
if (2 != link.read(buf, sizeof(buf))) {
return false;
}
}
if (headerBufLen < (hlen + 3)) {
return false;
}
for (int8_t i = hlen - 1; i >= 0; i--) {
headerBuf[i + 3] = header[i];
}
headerBuf[0] = (dsap << 2) + (PDU_I >> 2);
headerBuf[1] = ((PDU_I & 0x3) << 6) + ssap;
headerBuf[2] = (ns << 4) + nr;
if (!link.write(headerBuf, 3 + hlen, body, blen)) {
return false;
}
ns++;
// Get a RR PDU
int16_t status;
do {
status = link.read(headerBuf, headerBufLen);
if (2 > status) {
return false;
}
type = getPType(headerBuf);
if (PDU_RR == type) {
break;
} else if (PDU_SYMM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return false;
}
} else {
return false;
}
} while (1);
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return false;
}
return true;
}
int16_t LLCP::read(uint8_t *buf, uint8_t length)
{
uint8_t type;
uint16_t status;
// Get INFO PDU
do {
status = link.read(buf, length);
if (2 > status) {
return -1;
}
type = getPType(buf);
if (PDU_I == type) {
break;
} else if (PDU_SYMM == type) {
if (!link.write(SYMM_PDU, sizeof(SYMM_PDU))) {
return -2;
}
} else {
return -3;
}
} while (1);
uint8_t len = status - 3;
ssap = getDSAP(buf);
dsap = getSSAP(buf);
headerBuf[0] = (dsap << 2) + (PDU_RR >> 2);
headerBuf[1] = ((PDU_RR & 0x3) << 6) + ssap;
headerBuf[2] = (buf[2] >> 4) + 1;
if (!link.write(headerBuf, 3)) {
return -2;
}
for (uint8_t i = 0; i < len; i++) {
buf[i] = buf[i + 3];
}
nr++;
return len;
}

View File

@@ -1,75 +0,0 @@
#ifndef __LLCP_H__
#define __LLCP_H__
#include "mac_link.h"
#define LLCP_DEFAULT_TIMEOUT 20000
#define LLCP_DEFAULT_DSAP 0x04
#define LLCP_DEFAULT_SSAP 0x20
class LLCP {
public:
LLCP(PN532Interface &interface) : link(interface) {
headerBuf = link.getHeaderBuffer(&headerBufLen);
ns = 0;
nr = 0;
};
/**
* @brief Actiave PN532 as a target
* @param timeout max time to wait, 0 means no timeout
* @return > 0 success
* = 0 timeout
* < 0 failed
*/
int8_t activate(uint16_t timeout = 0);
int8_t waitForConnection(uint16_t timeout = LLCP_DEFAULT_TIMEOUT);
int8_t waitForDisconnection(uint16_t timeout = LLCP_DEFAULT_TIMEOUT);
int8_t connect(uint16_t timeout = LLCP_DEFAULT_TIMEOUT);
int8_t disconnect(uint16_t timeout = LLCP_DEFAULT_TIMEOUT);
/**
* @brief write a packet, the packet should be less than (255 - 2) bytes
* @param header packet header
* @param hlen length of header
* @param body packet body
* @param blen length of body
* @return true success
* false failed
*/
bool write(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
/**
* @brief read a packet, the packet will be less than (255 - 2) bytes
* @param buf the buffer to contain the packet
* @param len lenght of the buffer
* @return >=0 length of the packet
* <0 failed
*/
int16_t read(uint8_t *buf, uint8_t len);
uint8_t *getHeaderBuffer(uint8_t *len) {
uint8_t *buf = link.getHeaderBuffer(len);
len -= 3; // I PDU header has 3 bytes
return buf;
};
private:
MACLink link;
uint8_t mode;
uint8_t ssap;
uint8_t dsap;
uint8_t *headerBuf;
uint8_t headerBufLen;
uint8_t ns; // Number of I PDU Sent
uint8_t nr; // Number of I PDU Received
static uint8_t SYMM_PDU[2];
};
#endif // __LLCP_H__

View File

@@ -1,20 +0,0 @@
#include "mac_link.h"
#include "PN532_debug.h"
int8_t MACLink::activateAsTarget(uint16_t timeout)
{
pn532.begin();
pn532.SAMConfig();
return pn532.tgInitAsTarget(timeout);
}
bool MACLink::write(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
return pn532.tgSetData(header, hlen, body, blen);
}
int16_t MACLink::read(uint8_t *buf, uint8_t len)
{
return pn532.tgGetData(buf, len);
}

View File

@@ -1,51 +0,0 @@
#ifndef __MAC_LINK_H__
#define __MAC_LINK_H__
#include "PN532.h"
class MACLink {
public:
MACLink(PN532Interface &interface) : pn532(interface) {
};
/**
* @brief Activate PN532 as a target
* @param timeout max time to wait, 0 means no timeout
* @return > 0 success
* = 0 timeout
* < 0 failed
*/
int8_t activateAsTarget(uint16_t timeout = 0);
/**
* @brief write a PDU packet, the packet should be less than (255 - 2) bytes
* @param header packet header
* @param hlen length of header
* @param body packet body
* @param blen length of body
* @return true success
* false failed
*/
bool write(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
/**
* @brief read a PDU packet, the packet will be less than (255 - 2) bytes
* @param buf the buffer to contain the PDU packet
* @param len lenght of the buffer
* @return >=0 length of the PDU packet
* <0 failed
*/
int16_t read(uint8_t *buf, uint8_t len);
uint8_t *getHeaderBuffer(uint8_t *len) {
return pn532.getBuffer(len);
};
private:
PN532 pn532;
};
#endif // __MAC_LINK_H__

View File

@@ -1,106 +0,0 @@
#include "snep.h"
#include "PN532_debug.h"
int8_t SNEP::write(const uint8_t *buf, uint8_t len, uint16_t timeout)
{
if (0 >= llcp.activate(timeout)) {
DMSG("failed to activate PN532 as a target\n");
return -1;
}
if (0 >= llcp.connect(timeout)) {
DMSG("failed to set up a connection\n");
return -2;
}
// response a success SNEP message
headerBuf[0] = SNEP_DEFAULT_VERSION;
headerBuf[1] = SNEP_REQUEST_PUT;
headerBuf[2] = 0;
headerBuf[3] = 0;
headerBuf[4] = 0;
headerBuf[5] = len;
if (0 >= llcp.write(headerBuf, 6, buf, len)) {
return -3;
}
uint8_t rbuf[16];
if (6 > llcp.read(rbuf, sizeof(rbuf))) {
return -4;
}
// check SNEP version
if (SNEP_DEFAULT_VERSION != rbuf[0]) {
DMSG("The received SNEP message's major version is different\n");
// To-do: send Unsupported Version response
return -4;
}
// expect a put request
if (SNEP_RESPONSE_SUCCESS != rbuf[1]) {
DMSG("Expect a success response\n");
return -4;
}
llcp.disconnect(timeout);
return 1;
}
int16_t SNEP::read(uint8_t *buf, uint8_t len, uint16_t timeout)
{
if (0 >= llcp.activate(timeout)) {
DMSG("failed to activate PN532 as a target\n");
return -1;
}
if (0 >= llcp.waitForConnection(timeout)) {
DMSG("failed to set up a connection\n");
return -2;
}
uint16_t status = llcp.read(buf, len);
if (6 > status) {
return -3;
}
// check SNEP version
if (SNEP_DEFAULT_VERSION != buf[0]) {
DMSG("The received SNEP message's major version is different\n");
// To-do: send Unsupported Version response
return -4;
}
// expect a put request
if (SNEP_REQUEST_PUT != buf[1]) {
DMSG("Expect a put request\n");
return -4;
}
// check message's length
uint32_t length = (buf[2] << 24) + (buf[3] << 16) + (buf[4] << 8) + buf[5];
// length should not be more than 244 (header + body < 255, header = 6 + 3 + 2)
if (length > (status - 6)) {
DMSG("The SNEP message is too large: ");
DMSG_INT(length);
DMSG_INT(status - 6);
DMSG("\n");
return -4;
}
for (uint8_t i = 0; i < length; i++) {
buf[i] = buf[i + 6];
}
// response a success SNEP message
headerBuf[0] = SNEP_DEFAULT_VERSION;
headerBuf[1] = SNEP_RESPONSE_SUCCESS;
headerBuf[2] = 0;
headerBuf[3] = 0;
headerBuf[4] = 0;
headerBuf[5] = 0;
llcp.write(headerBuf, 6);
return length;
}

View File

@@ -1,49 +0,0 @@
#ifndef __SNEP_H__
#define __SNEP_H__
#include "llcp.h"
#define SNEP_DEFAULT_VERSION 0x10 // Major: 1, Minor: 0
#define SNEP_REQUEST_PUT 0x02
#define SNEP_REQUEST_GET 0x01
#define SNEP_RESPONSE_SUCCESS 0x81
#define SNEP_RESPONSE_REJECT 0xFF
class SNEP {
public:
SNEP(PN532Interface &interface) : llcp(interface) {
headerBuf = llcp.getHeaderBuffer(&headerBufLen);
};
/**
* @brief write a SNEP packet, the packet should be less than (255 - 2 - 3) bytes
* @param buf the buffer to contain the packet
* @param len lenght of the buffer
* @param timeout max time to wait, 0 means no timeout
* @return >0 success
* =0 timeout
* <0 failed
*/
int8_t write(const uint8_t *buf, uint8_t len, uint16_t timeout = 0);
/**
* @brief read a SNEP packet, the packet will be less than (255 - 2 - 3) bytes
* @param buf the buffer to contain the packet
* @param len lenght of the buffer
* @param timeout max time to wait, 0 means no timeout
* @return >=0 length of the packet
* <0 failed
*/
int16_t read(uint8_t *buf, uint8_t len, uint16_t timeout = 0);
private:
LLCP llcp;
uint8_t *headerBuf;
uint8_t headerBufLen;
};
#endif // __SNEP_H__

View File

@@ -1,196 +0,0 @@
#include "PN532_HSU.h"
#include "PN532_debug.h"
PN532_HSU::PN532_HSU(HardwareSerial &serial)
{
_serial = &serial;
command = 0;
}
void PN532_HSU::begin()
{
_serial->begin(115200);
}
void PN532_HSU::wakeup()
{
_serial->write(0x55);
_serial->write(0x55);
_serial->write(0);
_serial->write(0);
_serial->write(0);
/** dump serial buffer */
if(_serial->available()){
DMSG("Dump serial buffer: ");
}
while(_serial->available()){
uint8_t ret = _serial->read();
DMSG_HEX(ret);
}
}
int8_t PN532_HSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
/** dump serial buffer */
if(_serial->available()){
DMSG("Dump serial buffer: ");
}
while(_serial->available()){
uint8_t ret = _serial->read();
DMSG_HEX(ret);
}
command = header[0];
_serial->write(PN532_PREAMBLE);
_serial->write(PN532_STARTCODE1);
_serial->write(PN532_STARTCODE2);
uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA
_serial->write(length);
_serial->write(~length + 1); // checksum of length
_serial->write(PN532_HOSTTOPN532);
uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA
DMSG("\nWrite: ");
_serial->write(header, hlen);
for (uint8_t i = 0; i < hlen; i++) {
sum += header[i];
DMSG_HEX(header[i]);
}
_serial->write(body, blen);
for (uint8_t i = 0; i < blen; i++) {
sum += body[i];
DMSG_HEX(body[i]);
}
uint8_t checksum = ~sum + 1; // checksum of TFI + DATA
_serial->write(checksum);
_serial->write(PN532_POSTAMBLE);
return readAckFrame();
}
int16_t PN532_HSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout)
{
uint8_t tmp[3];
DMSG("\nRead: ");
/** Frame Preamble and Start Code */
if(receive(tmp, 3, timeout)<=0){
return PN532_TIMEOUT;
}
if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){
DMSG("Preamble error");
return PN532_INVALID_FRAME;
}
/** receive length and check */
uint8_t length[2];
if(receive(length, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( 0 != (uint8_t)(length[0] + length[1]) ){
DMSG("Length error");
return PN532_INVALID_FRAME;
}
length[0] -= 2;
if( length[0] > len){
return PN532_NO_SPACE;
}
/** receive command byte */
uint8_t cmd = command + 1; // response command
if(receive(tmp, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){
DMSG("Command error");
return PN532_INVALID_FRAME;
}
if(receive(buf, length[0], timeout) != length[0]){
return PN532_TIMEOUT;
}
uint8_t sum = PN532_PN532TOHOST + cmd;
for(uint8_t i=0; i<length[0]; i++){
sum += buf[i];
}
/** checksum and postamble */
if(receive(tmp, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( 0 != (uint8_t)(sum + tmp[0]) || 0 != tmp[1] ){
DMSG("Checksum error");
return PN532_INVALID_FRAME;
}
return length[0];
}
int8_t PN532_HSU::readAckFrame()
{
const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0};
uint8_t ackBuf[sizeof(PN532_ACK)];
DMSG("\nAck: ");
if( receive(ackBuf, sizeof(PN532_ACK), PN532_ACK_WAIT_TIME) <= 0 ){
DMSG("Timeout\n");
return PN532_TIMEOUT;
}
if( memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)) ){
DMSG("Invalid\n");
return PN532_INVALID_ACK;
}
return 0;
}
/**
@brief receive data .
@param buf --> return value buffer.
len --> length expect to receive.
timeout --> time of reveiving
@retval number of received bytes, 0 means no data received.
*/
int8_t PN532_HSU::receive(uint8_t *buf, int len, uint16_t timeout)
{
int read_bytes = 0;
int ret;
unsigned long start_millis;
while (read_bytes < len) {
start_millis = millis();
do {
ret = _serial->read();
if (ret >= 0) {
break;
}
} while((timeout == 0) || ((millis()- start_millis ) < timeout));
if (ret < 0) {
if(read_bytes){
return read_bytes;
}else{
return PN532_TIMEOUT;
}
}
buf[read_bytes] = (uint8_t)ret;
DMSG_HEX(ret);
read_bytes++;
}
return read_bytes;
}

View File

@@ -1,30 +0,0 @@
#ifndef __PN532_HSU_H__
#define __PN532_HSU_H__
#include "PN532Interface.h"
#include "Arduino.h"
#define PN532_HSU_DEBUG
#define PN532_HSU_READ_TIMEOUT (1000)
class PN532_HSU : public PN532Interface {
public:
PN532_HSU(HardwareSerial &serial);
void begin();
void wakeup();
virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout);
private:
HardwareSerial* _serial;
uint8_t command;
int8_t readAckFrame();
int8_t receive(uint8_t *buf, int len, uint16_t timeout=PN532_HSU_READ_TIMEOUT);
};
#endif

View File

@@ -1,225 +0,0 @@
/**
* @modified picospuch
*/
#include "PN532_I2C.h"
#include "PN532_debug.h"
#include "Arduino.h"
#define PN532_I2C_ADDRESS (0x48 >> 1)
PN532_I2C::PN532_I2C(TwoWire &wire)
{
_wire = &wire;
command = 0;
}
void PN532_I2C::begin()
{
_wire->begin();
}
void PN532_I2C::wakeup()
{
delay(500); // wait for all ready to manipulate pn532
}
int8_t PN532_I2C::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
command = header[0];
_wire->beginTransmission(PN532_I2C_ADDRESS);
write(PN532_PREAMBLE);
write(PN532_STARTCODE1);
write(PN532_STARTCODE2);
uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA
write(length);
write(~length + 1); // checksum of length
write(PN532_HOSTTOPN532);
uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA
DMSG("write: ");
for (uint8_t i = 0; i < hlen; i++) {
if (write(header[i])) {
sum += header[i];
DMSG_HEX(header[i]);
} else {
DMSG("\nToo many data to send, I2C doesn't support such a big packet\n"); // I2C max packet: 32 bytes
return PN532_INVALID_FRAME;
}
}
for (uint8_t i = 0; i < blen; i++) {
if (write(body[i])) {
sum += body[i];
DMSG_HEX(body[i]);
} else {
DMSG("\nToo many data to send, I2C doesn't support such a big packet\n"); // I2C max packet: 32 bytes
return PN532_INVALID_FRAME;
}
}
uint8_t checksum = ~sum + 1; // checksum of TFI + DATA
write(checksum);
write(PN532_POSTAMBLE);
_wire->endTransmission();
DMSG('\n');
return readAckFrame();
}
int16_t PN532_I2C::getResponseLength(uint8_t buf[], uint8_t len, uint16_t timeout) {
const uint8_t PN532_NACK[] = {0, 0, 0xFF, 0xFF, 0, 0};
uint16_t time = 0;
do {
if (_wire->requestFrom(PN532_I2C_ADDRESS, 6)) {
if (read() & 1) { // check first byte --- status
break; // PN532 is ready
}
}
delay(1);
time++;
if ((0 != timeout) && (time > timeout)) {
return -1;
}
} while (1);
if (0x00 != read() || // PREAMBLE
0x00 != read() || // STARTCODE1
0xFF != read() // STARTCODE2
) {
return PN532_INVALID_FRAME;
}
uint8_t length = read();
// request for last respond msg again
_wire->beginTransmission(PN532_I2C_ADDRESS);
for (uint16_t i = 0; i < sizeof(PN532_NACK); ++i) {
write(PN532_NACK[i]);
}
_wire->endTransmission();
return length;
}
int16_t PN532_I2C::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout)
{
uint16_t time = 0;
uint8_t length;
length = getResponseLength(buf, len, timeout);
// [RDY] 00 00 FF LEN LCS (TFI PD0 ... PDn) DCS 00
do {
if (_wire->requestFrom(PN532_I2C_ADDRESS, 6 + length + 2)) {
if (read() & 1) { // check first byte --- status
break; // PN532 is ready
}
}
delay(1);
time++;
if ((0 != timeout) && (time > timeout)) {
return -1;
}
} while (1);
if (0x00 != read() || // PREAMBLE
0x00 != read() || // STARTCODE1
0xFF != read() // STARTCODE2
) {
return PN532_INVALID_FRAME;
}
length = read();
if (0 != (uint8_t)(length + read())) { // checksum of length
return PN532_INVALID_FRAME;
}
uint8_t cmd = command + 1; // response command
if (PN532_PN532TOHOST != read() || (cmd) != read()) {
return PN532_INVALID_FRAME;
}
length -= 2;
if (length > len) {
return PN532_NO_SPACE; // not enough space
}
DMSG("read: ");
DMSG_HEX(cmd);
uint8_t sum = PN532_PN532TOHOST + cmd;
for (uint8_t i = 0; i < length; i++) {
buf[i] = read();
sum += buf[i];
DMSG_HEX(buf[i]);
}
DMSG('\n');
uint8_t checksum = read();
if (0 != (uint8_t)(sum + checksum)) {
DMSG("checksum is not ok\n");
return PN532_INVALID_FRAME;
}
read(); // POSTAMBLE
return length;
}
int8_t PN532_I2C::readAckFrame()
{
const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0};
uint8_t ackBuf[sizeof(PN532_ACK)];
DMSG("wait for ack at : ");
DMSG(millis());
DMSG('\n');
uint16_t time = 0;
do {
if (_wire->requestFrom(PN532_I2C_ADDRESS, sizeof(PN532_ACK) + 1)) {
if (read() & 1) { // check first byte --- status
break; // PN532 is ready
}
}
delay(1);
time++;
if (time > PN532_ACK_WAIT_TIME) {
DMSG("Time out when waiting for ACK\n");
return PN532_TIMEOUT;
}
} while (1);
DMSG("ready at : ");
DMSG(millis());
DMSG('\n');
for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) {
ackBuf[i] = read();
}
if (memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK))) {
DMSG("Invalid ACK\n");
return PN532_INVALID_ACK;
}
return 0;
}

View File

@@ -1,44 +0,0 @@
/**
* @modified picospuch
*/
#ifndef __PN532_I2C_H__
#define __PN532_I2C_H__
#include <Wire.h>
#include "PN532Interface.h"
class PN532_I2C : public PN532Interface {
public:
PN532_I2C(TwoWire &wire);
void begin();
void wakeup();
virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout);
private:
TwoWire* _wire;
uint8_t command;
int8_t readAckFrame();
int16_t getResponseLength(uint8_t buf[], uint8_t len, uint16_t timeout);
inline uint8_t write(uint8_t data) {
#if ARDUINO >= 100
return _wire->write(data);
#else
return _wire->send(data);
#endif
}
inline uint8_t read() {
#if ARDUINO >= 100
return _wire->read();
#else
return _wire->receive();
#endif
}
};
#endif

View File

@@ -1,210 +0,0 @@
#include "PN532_SPI.h"
#include "PN532_debug.h"
#include "Arduino.h"
#define STATUS_READ 2
#define DATA_WRITE 1
#define DATA_READ 3
PN532_SPI::PN532_SPI(SPIClass &spi, uint8_t ss)
{
command = 0;
_spi = &spi;
_ss = ss;
}
void PN532_SPI::begin()
{
pinMode(_ss, OUTPUT);
_spi->begin();
_spi->setDataMode(SPI_MODE0); // PN532 only supports mode0
_spi->setBitOrder(LSBFIRST);
#ifndef __SAM3X8E__
_spi->setClockDivider(SPI_CLOCK_DIV8); // set clock 2MHz(max: 5MHz)
#else
/** DUE spi library does not support SPI_CLOCK_DIV8 macro */
_spi->setClockDivider(42); // set clock 2MHz(max: 5MHz)
#endif
}
void PN532_SPI::wakeup()
{
digitalWrite(_ss, LOW);
delay(2);
digitalWrite(_ss, HIGH);
}
int8_t PN532_SPI::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
command = header[0];
writeFrame(header, hlen, body, blen);
uint8_t timeout = PN532_ACK_WAIT_TIME;
while (!isReady()) {
delay(1);
timeout--;
if (0 == timeout) {
DMSG("Time out when waiting for ACK\n");
return -2;
}
}
if (readAckFrame()) {
DMSG("Invalid ACK\n");
return PN532_INVALID_ACK;
}
return 0;
}
int16_t PN532_SPI::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout)
{
uint16_t time = 0;
while (!isReady()) {
delay(1);
time++;
if (timeout > 0 && time > timeout) {
return PN532_TIMEOUT;
}
}
digitalWrite(_ss, LOW);
delay(1);
int16_t result;
do {
write(DATA_READ);
if (0x00 != read() || // PREAMBLE
0x00 != read() || // STARTCODE1
0xFF != read() // STARTCODE2
) {
result = PN532_INVALID_FRAME;
break;
}
uint8_t length = read();
if (0 != (uint8_t)(length + read())) { // checksum of length
result = PN532_INVALID_FRAME;
break;
}
uint8_t cmd = command + 1; // response command
if (PN532_PN532TOHOST != read() || (cmd) != read()) {
result = PN532_INVALID_FRAME;
break;
}
DMSG("read: ");
DMSG_HEX(cmd);
length -= 2;
if (length > len) {
for (uint8_t i = 0; i < length; i++) {
DMSG_HEX(read()); // dump message
}
DMSG("\nNot enough space\n");
read();
read();
result = PN532_NO_SPACE; // not enough space
break;
}
uint8_t sum = PN532_PN532TOHOST + cmd;
for (uint8_t i = 0; i < length; i++) {
buf[i] = read();
sum += buf[i];
DMSG_HEX(buf[i]);
}
DMSG('\n');
uint8_t checksum = read();
if (0 != (uint8_t)(sum + checksum)) {
DMSG("checksum is not ok\n");
result = PN532_INVALID_FRAME;
break;
}
read(); // POSTAMBLE
result = length;
} while (0);
digitalWrite(_ss, HIGH);
return result;
}
boolean PN532_SPI::isReady()
{
digitalWrite(_ss, LOW);
write(STATUS_READ);
uint8_t status = read() & 1;
digitalWrite(_ss, HIGH);
return status;
}
void PN532_SPI::writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
digitalWrite(_ss, LOW);
delay(2); // wake up PN532
write(DATA_WRITE);
write(PN532_PREAMBLE);
write(PN532_STARTCODE1);
write(PN532_STARTCODE2);
uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA
write(length);
write(~length + 1); // checksum of length
write(PN532_HOSTTOPN532);
uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA
DMSG("write: ");
for (uint8_t i = 0; i < hlen; i++) {
write(header[i]);
sum += header[i];
DMSG_HEX(header[i]);
}
for (uint8_t i = 0; i < blen; i++) {
write(body[i]);
sum += body[i];
DMSG_HEX(body[i]);
}
uint8_t checksum = ~sum + 1; // checksum of TFI + DATA
write(checksum);
write(PN532_POSTAMBLE);
digitalWrite(_ss, HIGH);
DMSG('\n');
}
int8_t PN532_SPI::readAckFrame()
{
const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0};
uint8_t ackBuf[sizeof(PN532_ACK)];
digitalWrite(_ss, LOW);
delay(1);
write(DATA_READ);
for (uint8_t i = 0; i < sizeof(PN532_ACK); i++) {
ackBuf[i] = read();
}
digitalWrite(_ss, HIGH);
return memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK));
}

View File

@@ -1,36 +0,0 @@
#ifndef __PN532_SPI_H__
#define __PN532_SPI_H__
#include <SPI.h>
#include "PN532Interface.h"
class PN532_SPI : public PN532Interface {
public:
PN532_SPI(SPIClass &spi, uint8_t ss);
void begin();
void wakeup();
int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout);
private:
SPIClass* _spi;
uint8_t _ss;
uint8_t command;
boolean isReady();
void writeFrame(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int8_t readAckFrame();
inline void write(uint8_t data) {
_spi->transfer(data);
};
inline uint8_t read() {
return _spi->transfer(0);
};
};
#endif

View File

@@ -1,196 +0,0 @@
#include "PN532_SWHSU.h"
#include "PN532_debug.h"
PN532_SWHSU::PN532_SWHSU(SoftwareSerial &serial)
{
_serial = &serial;
command = 0;
}
void PN532_SWHSU::begin()
{
_serial->begin(115200);
}
void PN532_SWHSU::wakeup()
{
_serial->write(0x55);
_serial->write(0x55);
_serial->write((uint8_t) 0);
_serial->write((uint8_t) 0);
_serial->write((uint8_t) 0);
/** dump serial buffer */
if(_serial->available()){
DMSG("Dump serial buffer: ");
}
while(_serial->available()){
uint8_t ret = _serial->read();
DMSG_HEX(ret);
}
}
int8_t PN532_SWHSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen)
{
/** dump serial buffer */
if(_serial->available()){
DMSG("Dump serial buffer: ");
}
while(_serial->available()){
uint8_t ret = _serial->read();
DMSG_HEX(ret);
}
command = header[0];
_serial->write((uint8_t) PN532_PREAMBLE);
_serial->write((uint8_t) PN532_STARTCODE1);
_serial->write((uint8_t) PN532_STARTCODE2);
uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA
_serial->write(length);
_serial->write(~length + 1); // checksum of length
_serial->write((uint8_t) PN532_HOSTTOPN532);
uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA
DMSG("\nWrite: ");
_serial->write(header, hlen);
for (uint8_t i = 0; i < hlen; i++) {
sum += header[i];
DMSG_HEX(header[i]);
}
_serial->write(body, blen);
for (uint8_t i = 0; i < blen; i++) {
sum += body[i];
DMSG_HEX(body[i]);
}
uint8_t checksum = ~sum + 1; // checksum of TFI + DATA
_serial->write(checksum);
_serial->write((uint8_t) PN532_POSTAMBLE);
return readAckFrame();
}
int16_t PN532_SWHSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout)
{
uint8_t tmp[3];
DMSG("\nRead: ");
/** Frame Preamble and Start Code */
if(receive(tmp, 3, timeout)<=0){
return PN532_TIMEOUT;
}
if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){
DMSG("Preamble error");
return PN532_INVALID_FRAME;
}
/** receive length and check */
uint8_t length[2];
if(receive(length, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( 0 != (uint8_t)(length[0] + length[1]) ){
DMSG("Length error");
return PN532_INVALID_FRAME;
}
length[0] -= 2;
if( length[0] > len){
return PN532_NO_SPACE;
}
/** receive command byte */
uint8_t cmd = command + 1; // response command
if(receive(tmp, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){
DMSG("Command error");
return PN532_INVALID_FRAME;
}
if(receive(buf, length[0], timeout) != length[0]){
return PN532_TIMEOUT;
}
uint8_t sum = PN532_PN532TOHOST + cmd;
for(uint8_t i=0; i<length[0]; i++){
sum += buf[i];
}
/** checksum and postamble */
if(receive(tmp, 2, timeout) <= 0){
return PN532_TIMEOUT;
}
if( 0 != (uint8_t)(sum + tmp[0]) || 0 != tmp[1] ){
DMSG("Checksum error");
return PN532_INVALID_FRAME;
}
return length[0];
}
int8_t PN532_SWHSU::readAckFrame()
{
const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0};
uint8_t ackBuf[sizeof(PN532_ACK)];
DMSG("\nAck: ");
if( receive(ackBuf, sizeof(PN532_ACK), PN532_ACK_WAIT_TIME) <= 0 ){
DMSG("Timeout\n");
return PN532_TIMEOUT;
}
if( memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)) ){
DMSG("Invalid\n");
return PN532_INVALID_ACK;
}
return 0;
}
/**
@brief receive data .
@param buf --> return value buffer.
len --> length expect to receive.
timeout --> time of reveiving
@retval number of received bytes, 0 means no data received.
*/
int8_t PN532_SWHSU::receive(uint8_t *buf, int len, uint16_t timeout)
{
int read_bytes = 0;
int ret;
unsigned long start_millis;
while (read_bytes < len) {
start_millis = millis();
do {
ret = _serial->read();
if (ret >= 0) {
break;
}
} while((timeout == 0) || ((millis()- start_millis ) < timeout));
if (ret < 0) {
if(read_bytes){
return read_bytes;
}else{
return PN532_TIMEOUT;
}
}
buf[read_bytes] = (uint8_t)ret;
DMSG_HEX(ret);
read_bytes++;
}
return read_bytes;
}

View File

@@ -1,32 +0,0 @@
#ifndef __PN532_SWHSU_H__
#define __PN532_SWHSU_H__
#include <SoftwareSerial.h>
#include "PN532Interface.h"
#include "Arduino.h"
#define PN532_SWHSU_DEBUG
#define PN532_SWHSU_READ_TIMEOUT (1000)
class PN532_SWHSU : public PN532Interface {
public:
PN532_SWHSU(SoftwareSerial &serial);
void begin();
void wakeup();
virtual int8_t writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body = 0, uint8_t blen = 0);
int16_t readResponse(uint8_t buf[], uint8_t len, uint16_t timeout);
private:
SoftwareSerial* _serial;
uint8_t command;
int8_t readAckFrame();
int8_t receive(uint8_t *buf, int len, uint16_t timeout=PN532_SWHSU_READ_TIMEOUT);
};
#endif

View File

@@ -48,15 +48,13 @@ public class BackendServer implements MessageSender {
// Configure CORS settings
configureCors(context);
if (openFrontend) {
URL webContentUrl = getClass().getClassLoader().getResource("web-content");
if (webContentUrl == null) {
throw new RuntimeException("Unable to find 'web-content' directory");
}
String webContentPath = webContentUrl.toExternalForm();
context.setResourceBase(webContentPath);
context.addServlet(new ServletHolder("frontend", DefaultServlet.class), "/");
URL webContentUrl = getClass().getClassLoader().getResource("web-content");
if (webContentUrl == null) {
throw new RuntimeException("Unable to find 'web-content' directory");
}
String webContentPath = webContentUrl.toExternalForm();
context.setResourceBase(webContentPath);
context.addServlet(new ServletHolder("frontend", DefaultServlet.class), "/");
// Configure specific websocket behavior
JettyWebSocketServletContainerInitializer.configure(

View File

@@ -1,6 +1,5 @@
package org.schafkopf;
import com.google.gson.JsonObject;
import java.net.URI;
import java.util.concurrent.CountDownLatch;
import org.eclipse.jetty.websocket.api.Session;
@@ -13,7 +12,6 @@ import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.schafkopf.SchafkopfMessage.SchafkopfBaseMessage;
import org.schafkopf.SchafkopfMessage.SchafkopfMessageOrigin;
import org.schafkopf.SchafkopfMessage.SchafkopfMessageType;
/**
* Main Class that represents the Backend Server.
@@ -75,7 +73,6 @@ public class DedicatedServerConnection implements MessageSender {
try {
session.getRemote().sendString(
new SchafkopfMessage(SchafkopfMessageOrigin.BACKEND, message).getMessageAsString());
System.out.println("Sent message to server: " + message);
} catch (Exception e) {
System.err.println("Error sending message: " + e.getMessage());
}
@@ -116,26 +113,5 @@ public class DedicatedServerConnection implements MessageSender {
}
});
connectionThread.start();
start();
}
/**
* Class that represents one Frontend Connection.
*/
public void start() {
JsonObject messageObject = new JsonObject();
messageObject.addProperty("message_type", "START_GAME");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.START_GAME));
}
/**
* Class that represents one Frontend Connection.
*/
public void join() {
JsonObject messageObject = new JsonObject();
messageObject.addProperty("message_type", "JOIN_GAME");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.JOIN_GAME));
}
}

View File

@@ -32,49 +32,90 @@ public class SchafkopfClient implements MessageListener {
public void receiveMessage(String jsonMessage) {
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonMessage, JsonObject.class);
// Check if the origin is "frontend"
// Check if the origin is "frontend" or "dedicated_server"
String origin = jsonObject.get("origin").getAsString();
if (SchafkopfMessageOrigin.FRONTEND.toString().equals(origin)) {
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
if (SchafkopfMessageType.REQUEST_SERVER_CONNECTION.toString().equals(messageType)) {
switch (SchafkopfMessageOrigin.valueOf(origin)) {
case FRONTEND:
handleFrontendMessage(jsonObject);
break;
case DEDICATED_SERVER:
handleDedicatedServerMessage(jsonObject);
break;
default:
// Handle messages from unknown origins
System.out.println("Received message from unknown origin: " + origin);
break;
}
}
private void handleFrontendMessage(JsonObject jsonObject) {
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
switch (SchafkopfMessageType.valueOf(messageType)) {
case REQUEST_SERVER_CONNECTION:
dedicatedServerConnection = new DedicatedServerConnection(
content.get("serverAddress").getAsString(),
this);
} else if ("JOIN_GAME".equals(messageType)) {
dedicatedServerConnection.join();
} else if ("START_DEDICATED_GAME".equals(messageType)) {
dedicatedServerConnection.start();
} else if (SchafkopfMessageType.PLAYER_CARD.toString().equals(messageType)) {
break;
case PLAYER_CARD:
case CREATE_ONLINE_GAME:
case JOIN_ONLINE_GAME:
case SET_PLAYER_NAME:
dedicatedServerConnection.sendMessage(
new SchafkopfBaseMessage(SchafkopfMessageType.PLAYER_CARD, content));
}
new SchafkopfBaseMessage(SchafkopfMessageType.valueOf(messageType), content));
break;
case LIST_ONLINE_GAMES:
case GET_ONLINE_GAME:
case SET_STATUS_READY:
case LEAVE_ONLINE_GAME:
case START_DEDICATED_GAME:
dedicatedServerConnection.sendMessage(
new SchafkopfBaseMessage(SchafkopfMessageType.valueOf(messageType)));
break;
default:
// Handle unknown message types
System.out.println("Received unknown message type from frontend server: " + messageType);
break;
}
System.out.println("Received message from frontend server: " + jsonMessage);
System.out.println("Received message from frontend: " + jsonObject);
}
} else if (SchafkopfMessageOrigin.DEDICATED_SERVER.toString().equals(origin)) {
private void handleDedicatedServerMessage(JsonObject jsonObject) {
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
if (SchafkopfMessageType.GET_CARD_ONLINE_PLAYER.toString().equals(messageType)) {
System.out.println("Received get_card_online_player message from dedicated server.");
} else if (SchafkopfMessageType.GAME_STATE.toString().equals(messageType)) {
switch (SchafkopfMessageType.valueOf(messageType)) {
case GET_CARD_ONLINE_PLAYER:
case HEARTBEAT_ACK:
break;
case GAME_STATE:
case ONLINE_PLAYER_HAND:
case UNKNOWN_ERROR:
case INFO_MESSAGE:
case GET_ONLINE_GAME:
case LIST_ONLINE_GAMES:
backendServer.sendMessage(
new SchafkopfBaseMessage(SchafkopfMessage.SchafkopfMessageType.GAME_STATE, content));
} else if (SchafkopfMessageType.ONLINE_PLAYER_HAND.toString().equals(messageType)) {
new SchafkopfBaseMessage(SchafkopfMessageType.valueOf(messageType), content));
break;
case SERVER_CONNECTION_SUCCESSFUL:
case GAME_START_READY:
backendServer.sendMessage(
new SchafkopfBaseMessage(SchafkopfMessage.SchafkopfMessageType.ONLINE_PLAYER_HAND,
content));
} else if (SchafkopfMessageType.SERVER_CONNECTION_SUCCESSFUL.toString().equals(messageType)) {
System.out.println("Received server_connection_successful message from dedicated server.");
backendServer.sendMessage(new SchafkopfBaseMessage(
SchafkopfMessage.SchafkopfMessageType.SERVER_CONNECTION_SUCCESSFUL));
} else if (SchafkopfMessageType.HEARTBEAT_ACK.toString().equals(messageType)) {
return;
}
System.out.println("Received message from dedicated server: " + jsonMessage);
new SchafkopfBaseMessage(SchafkopfMessageType.valueOf(messageType)));
break;
default:
// Handle unknown message types
System.out.println("Received unknown message type from dedicated server: " + messageType);
break;
}
if (!messageType.equals("HEARTBEAT_ACK")) {
System.out.println("Received message from dedicated server: " + jsonObject);
}
}
}

View File

@@ -1,6 +1,5 @@
package org.schafkopf.player;
import org.schafkopf.BackendServer;
import org.schafkopf.cardreader.CardReader;
import org.schafkopf.karte.Karte;
import org.schafkopf.karte.KartenListe;
@@ -15,6 +14,7 @@ public class LocalPlayer extends Player {
private final CardReader cardReader;
public LocalPlayer(CardReader cardReader) {
super("Local Player");
this.cardReader = cardReader;
}
@@ -23,7 +23,9 @@ public class LocalPlayer extends Player {
return wartetAufKarte();
}
/** Waits for a Card and returns a Karte Object. */
/**
* Waits for a Card and returns a Karte Object.
*/
private Karte wartetAufKarte() {
String uid = null;
System.out.println("Starte Warten auf Karte");

View File

@@ -1,5 +1,6 @@
package org.schafkopf;
import com.google.gson.JsonArray;
import jakarta.servlet.DispatcherType;
import java.net.DatagramSocket;
import java.net.InetAddress;
@@ -16,6 +17,7 @@ import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlets.CrossOriginFilter;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.schafkopf.SchafkopfException.NoGameSessionException;
/**
* Main Class that represents the Backend Server.
@@ -29,8 +31,6 @@ public class DedicatedServer {
private final List<GameSession> gameSessions = new ArrayList<>();
private GameSession currentGameSession;
/**
* Creates an Instance of the Backend Server.
*/
@@ -73,10 +73,8 @@ public class DedicatedServer {
wsContainer.setMaxTextMessageSize(65535);
wsContainer.setIdleTimeout(Duration.ofDays(300000));
// Add websockets
wsContainer.addMapping("/*", new FrontendEndpointCreator(this));
wsContainer.addMapping("/*", new SchafkopfClientConnectionCreator(this));
});
currentGameSession = new GameSession();
}
/**
@@ -126,7 +124,44 @@ public class DedicatedServer {
return gameSessions;
}
public GameSession getCurrentGameSession() {
return currentGameSession;
/**
* The main entrypoint of the Application.
*/
public JsonArray getGameSessionsAsJson() throws NoGameSessionException {
if (gameSessions.isEmpty()) {
throw new NoGameSessionException();
}
JsonArray gameSessionsJson = new JsonArray();
for (GameSession gameSession : gameSessions) {
gameSessionsJson.add(gameSession.getJson());
}
return gameSessionsJson;
}
/**
* The main entrypoint of the Application.
*/
public GameSession getCurrentGameSession() throws NoGameSessionException {
if (gameSessions.isEmpty()) {
throw new NoGameSessionException();
}
return gameSessions.get(gameSessions.size() - 1);
}
/**
* The main entrypoint of the Application.
*/
public GameSession getGameSessionByName(String gameId) throws NoGameSessionException {
for (GameSession gameSession : gameSessions) {
if (gameSession.getServerName().equals(gameId)) {
return gameSession;
}
}
throw new NoGameSessionException();
}
public void removeGameSession(GameSession gameSession) {
gameSessions.remove(gameSession);
}
}

View File

@@ -1,68 +1,108 @@
package org.schafkopf;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
import org.schafkopf.SchafkopfException.NotEnoughPlayersException;
import org.schafkopf.SchafkopfException.PlayerNotReadyException;
import org.schafkopf.SchafkopfMessage.SchafkopfBaseMessage;
import org.schafkopf.SchafkopfMessage.SchafkopfMessageType;
import org.schafkopf.player.BotPlayer;
import org.schafkopf.player.OnlinePlayer;
import org.schafkopf.player.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The main entrypoint of the Application.
*/
public class GameSession implements MessageSender {
private static final Logger logger = LoggerFactory.getLogger(GameSession.class);
private Schafkopf schafkopf;
private List<Player> player;
private List<SchafkopfClientConnection> clients;
private Thread spielThread;
private String serverName;
private DedicatedServer dedicatedServer;
/**
* The main entrypoint of the Application.
*/
public GameSession() {
player = new ArrayList<>();
clients = new ArrayList<>();
public GameSession(String serverName, DedicatedServer dedicatedServer) {
this.dedicatedServer = dedicatedServer;
this.serverName = serverName;
this.clients = new ArrayList<>();
logger.info(serverName + " created.");
}
/**
* Class that represents one Frontend Connection.
*/
public void addPlayer(SchafkopfClientConnection client) {
if (this.player.size() >= 4) {
if (this.clients.size() >= 4) {
throw new RuntimeException("Game is full");
}
System.out.println("Adding player to game: " + client);
logger.info("Adding player to game: " + client);
clients.add(client);
OnlinePlayer onlinePlayer = new OnlinePlayer(client);
this.player.add(onlinePlayer);
OnlinePlayer onlinePlayer = new OnlinePlayer(client, client.getName());
client.setOnlinePlayer(onlinePlayer);
this.sendSessionInfo();
}
public Schafkopf getSchafkopf() {
return schafkopf;
/**
* Class that represents one Frontend Connection.
*/
public void removePlayer(SchafkopfClientConnection client) {
logger.info("Removing player from game: " + client);
clients.remove(client);
if (clients.isEmpty()) {
logger.info("No players left in game: " + serverName);
if (spielThread != null) {
spielThread.interrupt();
}
this.dedicatedServer.removeGameSession(this);
return;
}
this.sendSessionInfo();
}
void startGame() throws NotEnoughPlayersException {
int playerCount = this.player.size();
System.out.println("Starting game with " + playerCount + " players");
if (playerCount < 4) {
for (int i = 0; i < 4 - playerCount; i++) {
this.player.add(new BotPlayer());
void startGame() throws PlayerNotReadyException {
logger.info("Starting game: " + serverName + " with " + clients.size() + " players");
List<Player> players = new ArrayList<>();
for (SchafkopfClientConnection client : clients) {
players.add(client.getOnlinePlayer());
}
for (int i = players.size(); i < 4; i++) {
players.add(new BotPlayer("Bot " + i));
}
for (SchafkopfClientConnection client : clients) {
if (!client.isReady()) {
throw new PlayerNotReadyException();
}
}
System.out.println("Starting game with, now: " + this.player.size() + " players");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.GAME_START_READY));
//wait for 5 seconds
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
spielThread = new Thread(() -> {
try {
schafkopf = new Schafkopf(this.player.toArray(new Player[0]), this);
schafkopf = new Schafkopf(players.toArray(Player[]::new), this);
schafkopf.startGame();
clients.forEach(client -> client.resetReady());
} catch (NotEnoughPlayersException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
@@ -72,15 +112,65 @@ public class GameSession implements MessageSender {
spielThread.start();
// schafkopf = new Schafkopf(this.player.toArray(new Player[0]), this);
}
@Override
public void sendMessage(SchafkopfBaseMessage message) {
System.out.println("Sending message to Client: " + message);
for (SchafkopfClientConnection client : clients) {
client.sendMessage(message);
}
}
/**
* The main entrypoint of the Application.
*/
public JsonObject getJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("serverName", serverName);
jsonObject.addProperty("playerCount", getPlayerCount());
// Create an array to hold player information
JsonArray playersArray = new JsonArray();
for (SchafkopfClientConnection client : clients) {
JsonObject playerObject = new JsonObject();
playerObject.addProperty("playerName",
client.getName()); // Assuming you have a method to get player name
playerObject.addProperty("isReady",
client.isReady()); // Assuming you have a method to check player readiness
playersArray.add(playerObject);
}
for (int i = clients.size(); i < 4; i++) {
JsonObject playerObject = new JsonObject();
playerObject.addProperty("playerName",
"Bot " + i); // Assuming you have a method to get player name
playerObject.addProperty("isReady",
true);
playerObject.addProperty("isBot",
true);
playersArray.add(playerObject);
}
jsonObject.add("players", playersArray);
return jsonObject;
}
public String getServerName() {
return serverName;
}
public int getPlayerCount() {
return clients.size();
}
/**
* Class that represents one Frontend Connection.
*/
public void sendSessionInfo() {
JsonObject messageObject2 = new JsonObject();
messageObject2.add("game", this.getJson());
sendMessage(
new SchafkopfBaseMessage(SchafkopfMessageType.GET_ONLINE_GAME,
messageObject2));
}
}

View File

@@ -6,18 +6,21 @@ import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.WebSocketAdapter;
import org.schafkopf.SchafkopfException.NotEnoughPlayersException;
import org.schafkopf.SchafkopfException.NoGameSessionException;
import org.schafkopf.SchafkopfMessage.SchafkopfBaseMessage;
import org.schafkopf.SchafkopfMessage.SchafkopfMessageOrigin;
import org.schafkopf.SchafkopfMessage.SchafkopfMessageType;
import org.schafkopf.karte.Karte;
import org.schafkopf.player.OnlinePlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class that represents one Frontend Connection.
*/
public class SchafkopfClientConnection extends WebSocketAdapter implements MessageSender {
private static final Logger logger = LoggerFactory.getLogger(SchafkopfClientConnection.class);
private final CountDownLatch connectionLatch;
private final CountDownLatch closureLatch = new CountDownLatch(1);
private DedicatedServer dedicatedServer;
@@ -28,13 +31,15 @@ public class SchafkopfClientConnection extends WebSocketAdapter implements Messa
private OnlinePlayer onlinePlayer;
private boolean ready = false;
private String name = "player";
/**
* Class that represents one Frontend Connection.
*/
public SchafkopfClientConnection(DedicatedServer dedicatedServer) {
this.dedicatedServer = dedicatedServer;
this.connectionLatch = new CountDownLatch(1);
System.out.println("new ClientConnection created.");
}
@Override
@@ -42,8 +47,7 @@ public class SchafkopfClientConnection extends WebSocketAdapter implements Messa
this.session = session;
super.onWebSocketConnect(session);
String clientIp = session.getRemoteAddress().toString();
System.out.println("Endpoint connected from ip: " + clientIp);
logger.info("Endpoint connected from ip: " + clientIp);
connectionLatch.countDown();
dedicatedServer.addFrontendEndpoint(this);
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.SERVER_CONNECTION_SUCCESSFUL));
@@ -54,44 +58,82 @@ public class SchafkopfClientConnection extends WebSocketAdapter implements Messa
super.onWebSocketText(jsonMessage);
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonMessage, JsonObject.class);
// Check if the origin is "frontend"
// Check if the origin is "backend"
String origin = jsonObject.get("origin").getAsString();
if (SchafkopfMessageOrigin.BACKEND.toString().equals(origin)) {
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
if ("HEARTBEAT_SYN".equals(messageType)) {
if (!SchafkopfMessageOrigin.BACKEND.toString().equals(origin)) {
return;
}
JsonObject message = jsonObject.getAsJsonObject("message");
JsonObject content = message.getAsJsonObject("content");
String messageType = message.get("message_type").getAsString();
switch (SchafkopfMessageType.valueOf(messageType)) {
case HEARTBEAT_SYN:
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.HEARTBEAT_ACK));
return;
} else if (SchafkopfMessageType.JOIN_GAME.toString().equals(messageType)) {
gameSession = dedicatedServer.getCurrentGameSession();
dedicatedServer.getCurrentGameSession().addPlayer(this);
} else if ("START_GAME".equals(messageType)) {
System.out.println("Received START_GAME message from " + session.getRemoteAddress() + ".");
break;
case JOIN_ONLINE_GAME:
GameSession gameSession = null;
try {
dedicatedServer.getCurrentGameSession().startGame();
} catch (NotEnoughPlayersException e) {
gameSession = dedicatedServer.getGameSessionByName(
content.get("serverName").getAsString());
} catch (NoGameSessionException e) {
JsonObject messageObject = new JsonObject();
messageObject.addProperty("error",
"No GameSession with name \"" + content.get("serverName").getAsString()
+ "\" found.");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.UNKNOWN_ERROR,
"Not enough players to start the game."));
messageObject));
break;
}
} else if (SchafkopfMessageType.PLAYER_CARD.toString().equals(messageType)) {
joinGame(gameSession);
sendServerList();
JsonObject messageObject = new JsonObject();
messageObject.addProperty("message",
"Joined GameSession \"" + gameSession.getServerName() + "\".");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.INFO_MESSAGE,
messageObject));
break;
case START_DEDICATED_GAME:
try {
this.gameSession.startGame();
} catch (SchafkopfException e) {
sendError(e);
}
break;
case SET_PLAYER_NAME:
this.name = content.get("playerName").getAsString();
break;
case PLAYER_CARD:
onlinePlayer.receiveCard(Karte.valueOf(content.get("card").getAsString()));
} else if ("list_online_games".equals(messageType)) {
System.out.println(
"Received list_online_games message from " + session.getRemoteAddress() + ".");
}
System.out.println(
"Received message from Client " + session.getRemoteAddress() + " " + jsonMessage);
break;
case LIST_ONLINE_GAMES:
sendServerList();
break;
case GET_ONLINE_GAME:
this.gameSession.sendSessionInfo();
break;
case CREATE_ONLINE_GAME:
String servername = content.get("serverName").getAsString();
GameSession gameSession2 = new GameSession(servername, this.dedicatedServer);
dedicatedServer.addGameSession(gameSession2);
joinGame(gameSession2);
sendServerList();
break;
case SET_STATUS_READY:
ready = !ready;
this.gameSession.sendSessionInfo();
break;
case LEAVE_ONLINE_GAME:
this.gameSession.removePlayer(this);
this.gameSession = null;
sendServerList();
break;
default:
// Handle unknown message types
logger.warn("Received unknown message type: " + messageType);
break;
}
}
@@ -100,13 +142,20 @@ public class SchafkopfClientConnection extends WebSocketAdapter implements Messa
this.onlinePlayer = onlinePlayer;
}
public OnlinePlayer getOnlinePlayer() {
return this.onlinePlayer;
}
@Override
public void onWebSocketClose(int statusCode, String reason) {
if (this.gameSession != null) {
this.gameSession.removePlayer(this);
}
super.onWebSocketClose(statusCode, reason);
dedicatedServer.removeFrontendEndpoint(this);
System.out.println("Socket Closed: [" + statusCode + "] " + reason);
logger.warn("Socket Closed: [" + statusCode + "] " + reason);
closureLatch.countDown();
}
@@ -124,11 +173,61 @@ public class SchafkopfClientConnection extends WebSocketAdapter implements Messa
SchafkopfMessage schafkopfMessage = new SchafkopfMessage(
SchafkopfMessageOrigin.DEDICATED_SERVER,
message);
System.out.println("Sending message to Client: " + schafkopfMessage.getMessageAsString());
try {
getRemote().sendString(schafkopfMessage.getMessageAsString());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* The main entrypoint of the Application.
*/
public void joinGame(GameSession gameSession) {
if (this.gameSession != null) {
this.gameSession.removePlayer(this);
}
this.gameSession = gameSession;
gameSession.addPlayer(this);
}
private void sendServerList() {
JsonObject messageObject = new JsonObject();
try {
messageObject.add("games", dedicatedServer.getGameSessionsAsJson());
} catch (NoGameSessionException e) {
JsonObject error = new JsonObject();
error.addProperty("error",
"No GameSessions found.");
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.UNKNOWN_ERROR,
error));
return;
}
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.LIST_ONLINE_GAMES,
messageObject));
}
public boolean isReady() {
return ready;
}
public void resetReady() {
ready = false;
}
public String getName() {
return this.name;
}
/**
* Send a message to the connected FrontEnd.
*/
public void sendError(SchafkopfException e) {
JsonObject messageObject = new JsonObject();
messageObject.addProperty("error",
e.getMessage());
sendMessage(new SchafkopfBaseMessage(SchafkopfMessageType.UNKNOWN_ERROR,
messageObject));
}
}

View File

@@ -7,11 +7,11 @@ import org.eclipse.jetty.websocket.server.JettyWebSocketCreator;
/**
* Creater to make new Instances of the FrontendConnection.
*/
public class FrontendEndpointCreator implements JettyWebSocketCreator {
public class SchafkopfClientConnectionCreator implements JettyWebSocketCreator {
private DedicatedServer dedicatedServer;
public FrontendEndpointCreator(DedicatedServer dedicatedServer) {
public SchafkopfClientConnectionCreator(DedicatedServer dedicatedServer) {
this.dedicatedServer = dedicatedServer;
}

View File

@@ -41,7 +41,7 @@ public class GameState {
}
private GamePhase gamePhase;
private Integer currentPlayer; // Using Integer to allow for null
private String currentPlayer; // Using Integer to allow for null
private Karte card;
private KartenFarbe color;
private boolean trumpf;
@@ -52,7 +52,7 @@ public class GameState {
this.gamePhase = phase;
}
public GameState(GamePhase phase, Integer player) {
public GameState(GamePhase phase, String player) {
this.gamePhase = phase;
this.currentPlayer = player;
}
@@ -60,7 +60,7 @@ public class GameState {
/**
* GameState.
*/
public GameState(GamePhase phase, Integer player, Karte card, KartenFarbe color, boolean trumpf) {
public GameState(GamePhase phase, String player, Karte card, KartenFarbe color, boolean trumpf) {
this.gamePhase = phase;
this.currentPlayer = player;
this.card = card;
@@ -71,7 +71,7 @@ public class GameState {
/**
* GameState.
*/
public GameState(GamePhase phase, Integer player, Karte card) {
public GameState(GamePhase phase, String player, Karte card) {
this.gamePhase = phase;
this.currentPlayer = player;
this.card = card;

View File

@@ -28,7 +28,6 @@ public class Schafkopf {
private final Player[] player;
private GameState gameState = new GameState(GamePhase.GAME_STOP);
private Thread spielThread;
/**
* Constructor for the Schafkopf class.
@@ -100,8 +99,6 @@ public class Schafkopf {
gameState = new GameState(GamePhase.GAME_STOP);
setAndSendGameState(gameState);
}
spielThread.interrupt();
}
/**

View File

@@ -21,6 +21,31 @@ public class SchafkopfException extends Exception {
// You can also include additional constructors or methods if needed
}
/**
* The main entrypoint of the Application.
*/
public static class NoGameSessionException extends SchafkopfException {
public NoGameSessionException() {
super("No game session available");
}
// You can also include additional constructors or methods if needed
}
/**
* The main entrypoint of the Application.
*/
public static class PlayerNotReadyException extends SchafkopfException {
public PlayerNotReadyException() {
super("Not all Players are in Ready State");
}
// You can also include additional constructors or methods if needed
}
/**
* Class that represents one Frontend Connection.
*/

View File

@@ -13,22 +13,27 @@ public class SchafkopfMessage {
public static class SchafkopfBaseMessage {
private JsonObject message;
private SchafkopfMessageType messageType;
public SchafkopfBaseMessage(SchafkopfMessageType messageType, String content) {
this.messageType = messageType;
this.message = buildBaseMessage(messageType, content);
}
public SchafkopfBaseMessage(SchafkopfMessageType messageType, JsonObject content) {
this.messageType = messageType;
this.message = buildBaseMessage(messageType, content);
}
public SchafkopfBaseMessage(SchafkopfMessageType messageType) {
this.messageType = messageType;
this.message = buildBaseMessage(messageType);
}
public JsonObject getBaseMessage() {
return message;
}
}
JsonObject message;
@@ -118,6 +123,8 @@ public class SchafkopfMessage {
*/
public enum SchafkopfMessageType {
UNKNOWN_ERROR,
INFO_MESSAGE,
HEARTBEAT_SYN,
HEARTBEAT_ACK,
GET_CARD_ONLINE_PLAYER,
@@ -125,9 +132,17 @@ public class SchafkopfMessage {
GAME_STATE,
SERVER_CONNECTION_SUCCESSFUL,
REQUEST_SERVER_CONNECTION,
START_GAME,
JOIN_GAME,
PLAYER_CARD
JOIN_ONLINE_GAME,
START_DEDICATED_GAME,
PLAYER_CARD,
LIST_ONLINE_GAMES,
GET_ONLINE_GAME,
CREATE_ONLINE_GAME,
SET_STATUS_READY,
SET_PLAYER_NAME,
GAME_START_READY,
LEAVE_ONLINE_GAME
}
/**

View File

@@ -49,8 +49,9 @@ public class Spielablauf {
for (int i = 0; i < 4; i++) {
int currentPlayer = (i + startingPlayer) % 4;
logger.info("Spieler ist dran: {}", currentPlayer);
schafkopf.setAndSendGameState(new GameState(GamePhase.WAIT_FOR_CARD, currentPlayer));
logger.info("Spieler ist dran: {}", players[currentPlayer].getName());
schafkopf.setAndSendGameState(
new GameState(GamePhase.WAIT_FOR_CARD, players[currentPlayer].getName()));
Karte playedCard = players[currentPlayer].play(spiel, tischKarten, gespielteKarten);
tischKarten.addKarten(playedCard);
@@ -58,7 +59,7 @@ public class Spielablauf {
schafkopf.setAndSendGameState(
new GameState(
GamePhase.PLAYER_CARD,
currentPlayer,
players[currentPlayer].getName(),
playedCard,
tischKarten.getByIndex(0).getFarbe(),
spiel.isTrumpf(tischKarten.getByIndex(0))));
@@ -72,7 +73,8 @@ public class Spielablauf {
schafkopf.setAndSendGameState(
new GameState(
GamePhase.PLAYER_TRICK, winningPlayerIndex, tischKarten.getByIndex(stichSpieler)));
GamePhase.PLAYER_TRICK, players[winningPlayerIndex].getName(),
tischKarten.getByIndex(stichSpieler)));
try {
Thread.sleep(3000);

View File

@@ -13,8 +13,8 @@ public class BotPlayer extends Player {
private KartenListe eigeneKarten;
private KartenListe unbekannteKarten = KartenUtil.initializeSchafKopfCardDeck();
public BotPlayer() {
// TODO document why this constructor is empty
public BotPlayer(String name) {
super(name);
}
@Override

View File

@@ -20,7 +20,8 @@ public class OnlinePlayer extends Player {
private KartenListe karten = new KartenListe();
public OnlinePlayer(MessageSender messageSender) {
public OnlinePlayer(MessageSender messageSender, String name) {
super(name);
this.messageSender = messageSender;
}

View File

@@ -9,6 +9,16 @@ import org.schafkopf.spielcontroller.SpielController;
*/
public abstract class Player {
private String name;
protected Player(String name) {
this.name = name;
}
public String getName() {
return name;
}
public abstract Karte play(
SpielController spiel, KartenListe tischKarten, KartenListe gespielteKarten)
throws InterruptedException;

View File

@@ -1,7 +1,9 @@
<script lang="ts" setup>
import MessageBoard from "./components/MessageBoard.vue";
</script>
<template>
<router-view/>
<MessageBoard></MessageBoard>
</template>
<style lang="scss">
@import "bootstrap-icons/font/bootstrap-icons.css";

View File

@@ -74,34 +74,104 @@ export enum GamePhase {
export enum MessageType {
PLAYER_CARD = "PLAYER_CARD",
START_DEDICATED_GAME = "START_DEDICATED_GAME",
JOIN_GAME = "JOIN_GAME",
JOIN_ONLINE_GAME = "JOIN_ONLINE_GAME",
LEAVE_ONLINE_GAME = "LEAVE_ONLINE_GAME",
REQUEST_SERVER_CONNECTION = "REQUEST_SERVER_CONNECTION",
CREATE_ONLINE_GAME = "CREATE_ONLINE_GAME",
LIST_ONLINE_GAMES = "LIST_ONLINE_GAMES",
UNKNOWN_ERROR = "UNKNOWN_ERROR",
INFO_MESSAGE = "INFO_MESSAGE",
GET_ONLINE_GAME = "GET_ONLINE_GAME",
SET_STATUS_READY = "SET_STATUS_READY",
GAME_STATE = "GAME_STATE",
ONLINE_PLAYER_HAND = "ONLINE_PLAYER_HAND",
SERVER_CONNECTION_SUCCESSFUL = "SERVER_CONNECTION_SUCCESSFUL",
SET_PLAYER_NAME = "SET_PLAYER_NAME",
GAME_START_READY = "GAME_START_READY",
}
// Define the interface for an array of cards
export interface CardArray {
cards: Card[];
export interface CardArrayMessage {
message_type: MessageType.ONLINE_PLAYER_HAND;
content: { cards: Card[] };
}
export interface CardObject {
card: Card;
export interface CardMessage {
message_type: MessageType.PLAYER_CARD;
content: { card: Card };
}
// Define the interface for the game state
export interface GameState {
gamePhase: GamePhase;
currentPlayer?: number;
currentPlayer?: string;
card?: Card;
color?: KartenFarbe;
trumpf?: boolean;
}
export interface GameSession {
serverName: string;
playerCount: number;
players: OnlinePlayer[];
}
export interface OnlinePlayer {
playerName: string;
isReady: boolean;
isBot?: boolean;
}
export interface GameStateMessage {
message_type: MessageType.GAME_STATE;
content: GameState;
}
export interface GameListMessage {
message_type: MessageType.LIST_ONLINE_GAMES;
content: { games: GameSession[] };
}
export interface GameInfoMessage {
message_type: MessageType.GET_ONLINE_GAME;
content: { game: GameSession };
}
export interface JoinGameMessage {
message_type: MessageType.JOIN_ONLINE_GAME;
content: { serverName: string };
}
export interface ErrorMessage {
message_type: MessageType.UNKNOWN_ERROR;
content: { error: string };
}
export interface InfoMessage {
message_type: MessageType.INFO_MESSAGE;
content: { message: string };
}
export interface EmptyMessage {
message_type: string;
content: GameState | CardArray | CardObject;
message_type: MessageType.SERVER_CONNECTION_SUCCESSFUL | MessageType.GAME_START_READY | MessageType.REQUEST_SERVER_CONNECTION;
}
export interface SetPlayerNameMessage {
message_type: MessageType.SET_PLAYER_NAME;
content: { playerName: string }
}
// Define a union type for all possible message types
export type BackendMessage = EmptyMessage
export type BackendMessage =
GameListMessage
| JoinGameMessage
| ErrorMessage
| InfoMessage
| GameInfoMessage | GameStateMessage | CardArrayMessage | CardMessage | EmptyMessage | SetPlayerNameMessage;
export enum MessageBoardType {
ERROR = "alert-error",
WARNING = "alert-warning",
INFO = "alert-info",
SUCCESS = "alert-success"
}

View File

@@ -0,0 +1,51 @@
<script setup lang="ts">
import MessageComponent from "./MessageComponent.vue";
import {BackendMessage, MessageBoardType, MessageType} from "../BackendMessage.ts";
import {scg} from "ioc-service-container";
import {onMounted, ref} from "vue";
const backendConnection = scg("BackendConnection");
const socket = ref<WebSocket | null>();
const errorMessages = ref<{ message: string, type: MessageBoardType }[]>([]);
onMounted(() => {
socket.value = backendConnection.getWebSocket();
const messageListener = (message: string) => {
const message1: BackendMessage = JSON.parse(message);
if (message1.message_type === MessageType.UNKNOWN_ERROR && "error" in message1.content) {
errorMessages.value.push({message: message1.content.error, type: MessageBoardType.ERROR});
// Schedule removal for the newly added message
setTimeout(() => {
errorMessages.value.shift();
}, 3000); // Adjust 3000 to your desired delay in milliseconds
}
if (message1.message_type === MessageType.INFO_MESSAGE && "message" in message1.content) {
errorMessages.value.push({message: message1.content.message, type: MessageBoardType.INFO});
// Schedule removal for the newly added message
setTimeout(() => {
errorMessages.value.shift();
}, 3000); // Adjust 3000 to your desired delay in milliseconds
}
};
backendConnection.addMessageListener(messageListener);
});
</script>
<template>
<div class="fixed bottom-0 left-0 mx-auto px-8 py-2 w-screen flex flex-col gap-1">
<MessageComponent v-for="message in errorMessages" :message="message.message" :type="message.type">
message="Error! Task failed successfully." :type="MessageBoardType.WARNING">
</MessageComponent>
</div>
</template>
<style scoped lang="scss">
</style>

View File

@@ -0,0 +1,22 @@
<script setup lang="ts">
import {MessageBoardType} from "../BackendMessage.ts";
defineProps<{
message: string;
type: MessageBoardType;
}>();
</script>
<template>
<div role="alert" class="alert" :class="type">
<i class="bi bi-exclamation"></i>
<span>{{ message }}</span>
</div>
</template>
<style scoped lang="scss">
</style>

View File

@@ -7,6 +7,7 @@ import {setupService} from "./services/DependencyInjection.ts";
const routes = [
{path: '/', component: () => import('./pages/MainMenu.vue'),},
{path: '/online', component: () => import('./pages/OnlineGameList.vue'),},
{path: '/gamesession', component: () => import('./pages/GameSession.vue'),},
{path: '/localgame', component: () => import('./pages/LocalGame.vue'),},
{path: '/dedicatedgame', component: () => import('./pages/DedicatedGame.vue'),},
]
@@ -16,8 +17,7 @@ const router = createRouter({
routes,
})
const websocketIp = import.meta.env.VITE_APP_WEBSOCKET_IP;
setupService("ws://" + websocketIp + ":8080/schafkopf-events/");
setupService("ws://localhost:8080/schafkopf-events/");
const app = createApp(App)
app.use(router)

View File

@@ -3,43 +3,41 @@ import {onMounted, ref} from 'vue';
import {scg} from 'ioc-service-container';
import CardComp from '../components/CardComponent.vue';
import {BackendMessage, Card, GamePhase, GameState, MessageType} from "../BackendMessage";
import {BackendMessage, Card, GamePhase, GameSession, GameState, MessageType} from "../BackendMessage";
import {useRouter} from "vue-router";
const backendConnection = scg("BackendConnection");
const messageFromServer = ref<string[]>([]);
const gameStateText = ref<string>("Schafkopf");
const gameStateText = ref<string>("Spiel startet...");
const gameInfoText = ref<string>("");
const router = useRouter();
const socket = ref<WebSocket | null>();
const tableCards = ref<Card[]>([]);
const botCards = ref<Card[]>();
const trickCard = ref<Card>();
const gameState = ref<GameState>();
const showGameSelect = ref(true);
function startDedicated(): void {
backendConnection.sendMessage(MessageType.START_DEDICATED_GAME,);
}
function joinGame(): void {
backendConnection.sendMessage(MessageType.JOIN_GAME,);
}
const gameSession = ref<GameSession>({
serverName: "",
playerCount: 0,
players: []
});
function sendCard(cardInput: Card): void {
backendConnection.sendMessage(MessageType.PLAYER_CARD, {card: cardInput});
}
function showGameState(gamestate: GameState) {
async function showGameState(gamestate: GameState) {
switch (gamestate.gamePhase) {
case GamePhase.GAME_START:
gameStateText.value = "Spiel startet";
showGameSelect.value = false;
// botCards.value = 0;
break;
case GamePhase.TRICK_START:
gameStateText.value = "Runde startet";
@@ -48,13 +46,12 @@ function showGameState(gamestate: GameState) {
gameInfoText.value = "";
break;
case GamePhase.WAIT_FOR_CARD:
gameStateText.value = "Spieler " + gamestate.currentPlayer + " muss eine Karte legen.";
gameState.value = gamestate;
gameStateText.value = gamestate.currentPlayer + " muss eine Karte legen.";
break;
case GamePhase.PLAYER_CARD:
gameStateText.value = "Spieler " + gamestate.currentPlayer + " hat eine Karte gespielt.";
if (gamestate.currentPlayer === 0) {
// botCards.value.pop();
}
gameStateText.value = gamestate.currentPlayer + " hat eine Karte gespielt.";
if (gamestate.trumpf) {
gameInfoText.value = "TRUMPF";
} else {
@@ -65,11 +62,11 @@ function showGameState(gamestate: GameState) {
break;
case GamePhase.PLAYER_TRICK:
gameStateText.value = "Spieler " + gamestate.currentPlayer + " sticht.";
gameStateText.value = gamestate.currentPlayer + " sticht.";
trickCard.value = gamestate.card
break;
case GamePhase.GAME_STOP:
showGameSelect.value = true;
await router.push("/gamesession");
break;
default:
gameStateText.value = "Fehler";
@@ -83,32 +80,44 @@ onMounted(() => {
const messageListener = (message: string) => {
const message1: BackendMessage = JSON.parse(message);
console.log(message1)
if (message1.message_type === "GAME_STATE" && "gamePhase" in message1.content) {
if (message1.message_type === MessageType.GET_ONLINE_GAME) {
gameSession.value = message1.content.game;
console.log(message1.content)
}
if (message1.message_type === MessageType.GAME_STATE) {
console.log(message1.content)
showGameState(message1.content)
}
if (message1.message_type === "ONLINE_PLAYER_HAND" && "cards" in message1.content) {
if (message1.message_type === MessageType.ONLINE_PLAYER_HAND) {
botCards.value = message1.content.cards;
console.log(message1.content.cards)
}
};
backendConnection.addMessageListener(messageListener);
backendConnection.sendMessage(MessageType.GAME_START_READY);
backendConnection.sendMessage(MessageType.GET_ONLINE_GAME);
});
</script>
<template>
<div>
<div v-for="message in messageFromServer" :key="message">{{ message }}</div>
<div v-if="showGameSelect">
<div class="flex gap-2 place-content-center">
<button class="v-button" @click="startDedicated">Starten</button>
<button class="v-button" @click="joinGame">Join</button>
</div>
</div>
<div v-else>
<div>
<div class="flex gap-2 place-content-center">
<div class="text-sm breadcrumbs">
<ul>
<li v-for="player in gameSession.players">
<span
:class="{'text-primary': gameState!.currentPlayer === player.playerName}"
class="inline-flex gap-2 items-center">
<i v-if="!player.isBot" class="bi bi-person"></i>
<i v-else class="bi bi-robot"></i>
<p>{{ player.playerName }}</p>
</span>
</li>
</ul>
</div>
</div>
<h1 class=" top-52 text-white font-bold text-6xl absolute text-center w-full">{{ gameInfoText }}</h1>
<h1 class=" top-64 text-white font-bold text-6xl absolute text-center w-full">{{ gameStateText }}</h1>

View File

@@ -0,0 +1,112 @@
<script setup lang="ts">
import {scg} from "ioc-service-container";
import {BackendMessage, GameSession, MessageType} from "../BackendMessage.ts";
import {computed, onMounted, ref} from "vue";
import {useRouter} from "vue-router";
const backendConnection = scg("BackendConnection");
const socket = ref<WebSocket | null>();
const gameSession = ref<GameSession>({
serverName: "",
playerCount: 0,
players: []
});
const router = useRouter();
const allPlayersReady = computed(() => {
// Check if all players are ready by iterating through them
return gameSession.value.players.every(player => player.isReady);
});
onMounted(() => {
refreshGameInfo();
socket.value = backendConnection.getWebSocket();
const messageListener = async (message: string) => {
const message1: BackendMessage = JSON.parse(message);
console.log(message1)
if (message1.message_type === MessageType.GET_ONLINE_GAME && "game" in message1.content) {
gameSession.value = message1.content.game;
}
if (message1.message_type === MessageType.GAME_START_READY) {
// Resolve the Promise when the success message is received
await router.push("/dedicatedgame");
}
};
backendConnection.addMessageListener(messageListener);
});
function refreshGameInfo() {
backendConnection.sendMessage(MessageType.GET_ONLINE_GAME);
}
async function leaveGame() {
backendConnection.sendMessage(MessageType.LEAVE_ONLINE_GAME);
await router.push("/online");
}
function setStatusReady() {
backendConnection.sendMessage(MessageType.SET_STATUS_READY);
}
async function startDedicated() {
backendConnection.sendMessage(MessageType.START_DEDICATED_GAME);
const successMessageReceived = new Promise<void>((resolve) => {
const messageListener = (message: string) => {
const message1: BackendMessage = JSON.parse(message);
console.log(message)
if (message1.message_type === MessageType.GAME_START_READY) {
// Resolve the Promise when the success message is received
resolve();
}
};
backendConnection.addMessageListener(messageListener);
});
await successMessageReceived;
await router.push("/dedicatedgame");
}
</script>
<template>
<button class="btn btn-primary" @click="leaveGame()">Leave Game
</button>
<div class="flex flex-col gap-2 max-w-xl mx-auto">
<div class="flex flex-col gap-4 p-6 bg-base-200 rounded-box">
<h1 class="font-bold text-xl">{{ gameSession.serverName }}</h1>
<span>
Lorem ipsum dolor sit amet consectetur adipisicing elit In odit
</span>
<div class="flex justify-between items-center">
<span class="font-medium text-2xl">{{ gameSession.playerCount }}/4</span>
</div>
</div>
Spieler:
<div v-for="player in gameSession.players" class="flex flex-row gap-4 p-6 bg-base-200 rounded-box">
<p class="grow">{{ player.playerName }}</p>
<p v-if="player.isBot" class="text-warning"><i class="bi bi-robot"></i></p>
<p v-else-if="player.isReady" class="text-success">Bereit</p>
<p v-else class="text-error">Nicht bereit</p>
</div>
<button class="btn btn-primary" @click="setStatusReady()">Toggle Ready
</button>
<button :disabled="!allPlayersReady" class="btn btn-primary max-w-xl" @click="startDedicated()">Starten</button>
</div>
</template>
<style scoped lang="scss">
</style>

View File

@@ -6,12 +6,12 @@ import {BackendMessage, MessageType} from "../BackendMessage.ts";
const backendConnection = scg("BackendConnection");
const serverAddress = ref("10.6.9.57:8085")
const serverAddress = ref("dyn.heiserer.de:8085")
const isConnected = ref<boolean>(false);
const isPingInProgress = ref<boolean>(false);
const secondsRemaining = ref<number>(10);
const checkInterval: number = 10;
const checkInterval: number = 5;
const router = useRouter();
onBeforeMount(async () => {
@@ -58,8 +58,7 @@ async function openOnlineGameList() {
const successMessageReceived = new Promise<void>((resolve) => {
const messageListener = (message: string) => {
const message1: BackendMessage = JSON.parse(message);
console.log(message)
if (message1.message_type === "SERVER_CONNECTION_SUCCESSFUL") {
if (message1.message_type === MessageType.SERVER_CONNECTION_SUCCESSFUL) {
// Resolve the Promise when the success message is received
resolve();
}
@@ -105,7 +104,7 @@ async function openOnlineGameList() {
</div>
</div>
<a class="btn btn-primary">Spielen</a>
<button disabled class="btn btn-primary">Bald verfügbar</button>
</div>
<div class="flex flex-col gap-6 bg-base-200 rounded-box p-8">
@@ -175,7 +174,7 @@ async function openOnlineGameList() {
</div>
</div>
<a class="btn btn-primary">Spielen</a>
<button disabled class="btn btn-primary">Bald verfügbar</button>
</div>
</div>

View File

@@ -1,12 +1,92 @@
<script setup lang="ts">
import {scg} from "ioc-service-container";
import {BackendMessage, GameSession, MessageType} from "../BackendMessage.ts";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
const backendConnection = scg("BackendConnection");
const socket = ref<WebSocket | null>();
const gameList = ref<GameSession[]>([]);
const router = useRouter();
// Load playerName from localStorage or set default value if not present
const storedPlayerName = localStorage.getItem("playerName");
const playerName = ref<string>(storedPlayerName || "SchafkopfPlayer");
onMounted(() => {
backendConnection.sendMessage(MessageType.SET_PLAYER_NAME, {playerName: playerName.value});
refreshGameList();
socket.value = backendConnection.getWebSocket();
const messageListener = (message: string) => {
const message1: BackendMessage = JSON.parse(message);
if (message1.message_type === MessageType.LIST_ONLINE_GAMES && "games" in message1.content) {
console.log(message1)
gameList.value = message1.content.games;
}
};
backendConnection.addMessageListener(messageListener);
});
function refreshGameList() {
backendConnection.sendMessage(MessageType.LIST_ONLINE_GAMES);
}
async function createOnlineGame() {
const serverName = `Schafkopf_${new Date().getTime()}`; // Append timestamp to server name
backendConnection.sendMessage(MessageType.CREATE_ONLINE_GAME, {serverName: serverName});
await router.push("/gamesession");
}
async function joinGame(serverName: string) {
backendConnection.sendMessage(MessageType.JOIN_ONLINE_GAME, {serverName: serverName});
await router.push("/gamesession");
}
// function getServerByName(serverName: string): GameSession | undefined {
// return gameList.value.find(session => session.serverName === serverName);
// }
function sendPlayerName() {
backendConnection.sendMessage(MessageType.SET_PLAYER_NAME, {playerName: playerName.value});
localStorage.setItem("playerName", playerName.value);
}
</script>
<template>
<router-link to="/dedicatedgame">
<button class="btn btn-primary">Zum Spiel</button>
<router-link to="/">
<button class="btn btn-primary">zurück</button>
</router-link>
<button class="btn btn-primary" @click="refreshGameList()">Refresh Game
List
</button>
<input
v-model="playerName" type="text" placeholder="Type here" class="input input-bordered w-full max-w-xs"
@change="sendPlayerName()"/>
<div class="flex flex-col max-w-xl mx-auto gap-2">
<button class="btn btn-primary" @click="createOnlineGame()">Create Game</button>
<div v-for="game in gameList" :key="game.serverName" class="flex max-w-lg">
<div class="flex flex-col gap-4 p-6 bg-base-200 rounded-box">
<h1 class="font-bold text-xl">{{ game.serverName }}</h1>
<span>
Lorem ipsum dolor sit amet consectetur adipisicing elit In odit
</span>
<div class="flex justify-between items-center">
<span class="font-medium text-2xl">{{ game.playerCount }}/4</span>
<a class="btn btn-primary btn-sm" @click="joinGame(game.serverName)">Join</a>
</div>
</div>
</div>
</div>
</template>
<style scoped lang="scss">

View File

@@ -23,9 +23,9 @@ export class BackendConnection {
});
}
public sendMessage(messageType: MessageType, message?: any): void {
public sendMessage(messageType: MessageType, content?: any): void {
let jsonMessage;
if (message === undefined) {
if (content === undefined) {
jsonMessage = {
origin: "FRONTEND",
message: {
@@ -37,7 +37,7 @@ export class BackendConnection {
origin: "FRONTEND",
message: {
message_type: messageType,
content: message
content: content
}
};
}