Home | History | Annotate | Download | only in pn532
      1 /*
      2  * Author: Jon Trulson <jtrulson (at) ics.com>
      3  * Copyright (c) 2015 Intel Corporation.
      4  *
      5  * This code is heavily based on the Adafruit-PN532 library at
      6  * https://github.com/adafruit/Adafruit-PN532, which is licensed under
      7  * the BSD license. See upm/src/pn532/license.txt
      8  *
      9  * Permission is hereby granted, free of charge, to any person obtaining
     10  * a copy of this software and associated documentation files (the
     11  * "Software"), to deal in the Software without restriction, including
     12  * without limitation the rights to use, copy, modify, merge, publish,
     13  * distribute, sublicense, and/or sell copies of the Software, and to
     14  * permit persons to whom the Software is furnished to do so, subject to
     15  * the following conditions:
     16  *
     17  * The above copyright notice and this permission notice shall be
     18  * included in all copies or substantial portions of the Software.
     19  *
     20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
     21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
     22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     23  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
     24  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
     25  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
     26  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     27  */
     28 
     29 #include <unistd.h>
     30 #include <math.h>
     31 #include <iostream>
     32 #include <string>
     33 #include <stdexcept>
     34 
     35 #include "pn532.h"
     36 
     37 using namespace upm;
     38 using namespace std;
     39 
     40 
     41 #define PN532_PACKBUFFSIZ 64
     42 static uint8_t pn532_packetbuffer[PN532_PACKBUFFSIZ];
     43 
     44 static uint8_t pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
     45 static uint32_t pn532_firmwarerev = 0x00320106;
     46 
     47 PN532::PN532(int irq, int reset, int bus, uint8_t address):
     48   m_gpioIRQ(irq), m_gpioReset(reset), m_i2c(bus)
     49 {
     50   m_addr = address;
     51   m_uidLen = 0;
     52   m_inListedTag = 0;
     53   m_SAK = 0;
     54   m_ATQA = 0;
     55   m_isrInstalled = false;
     56   m_irqRcvd = false;
     57 
     58   memset(m_uid, 0, 7);
     59   memset(m_key, 0, 6);
     60 
     61   // turn off debugging by default
     62   pn532Debug(false);
     63   mifareDebug(false);
     64 
     65   mraa::Result rv;
     66   if ( (rv = m_i2c.address(m_addr)) != mraa::SUCCESS)
     67     {
     68       throw std::runtime_error(std::string(__FUNCTION__) +
     69                                ": I2c.address() failed");
     70       return;
     71     }
     72 
     73   m_gpioIRQ.dir(mraa::DIR_IN);
     74   m_gpioReset.dir(mraa::DIR_OUT);
     75 }
     76 
     77 PN532::~PN532()
     78 {
     79   if (m_isrInstalled)
     80     m_gpioIRQ.isrExit();
     81 }
     82 
     83 bool PN532::init()
     84 {
     85   m_gpioReset.write(1);
     86   m_gpioReset.write(0);
     87   usleep(400000);
     88 
     89   // install an interrupt handler
     90   m_gpioIRQ.isr(mraa::EDGE_FALLING, dataReadyISR, this);
     91   m_isrInstalled = true;
     92 
     93   m_gpioReset.write(1);
     94 
     95   return true;
     96 }
     97 
     98 /**************************************************************************/
     99 /*!
    100     @brief  Prints a hexadecimal value in plain characters
    101 
    102     @param  data      Pointer to the byte data
    103     @param  numBytes  Data length in bytes
    104 */
    105 /**************************************************************************/
    106 static void PrintHex(const uint8_t * data, const uint32_t numBytes)
    107 {
    108   uint32_t szPos;
    109   for (szPos=0; szPos < numBytes; szPos++)
    110     {
    111       fprintf(stderr, "0x%02x ", data[szPos] & 0xff);
    112     }
    113   fprintf(stderr, "\n");
    114 }
    115 
    116 /**************************************************************************/
    117 /*!
    118     @brief  Prints a hexadecimal value in plain characters, along with
    119             the char equivalents in the following format
    120 
    121             00 00 00 00 00 00  ......
    122 
    123     @param  data      Pointer to the byte data
    124     @param  numBytes  Data length in bytes
    125 */
    126 /**************************************************************************/
    127 static void PrintHexChar(const uint8_t * data, const uint32_t numBytes)
    128 {
    129   uint32_t szPos;
    130   for (szPos=0; szPos < numBytes; szPos++)
    131     {
    132       fprintf(stderr, "0x%02x ", data[szPos] & 0xff);
    133     }
    134   fprintf(stderr, "  ");
    135   for (szPos=0; szPos < numBytes; szPos++)
    136     {
    137       if (data[szPos] <= 0x1F)
    138         fprintf(stderr, ".");
    139       else
    140         fprintf(stderr, "%c ", (char)data[szPos]);
    141     }
    142   fprintf(stderr, "\n");
    143 }
    144 
    145 
    146 /**************************************************************************/
    147 /*!
    148   @brief  Checks the firmware version of the PN5xx chip
    149 
    150   @returns  The chip's firmware version and ID
    151 */
    152 /**************************************************************************/
    153 uint32_t PN532::getFirmwareVersion()
    154 {
    155   uint32_t response = 0;
    156 
    157   pn532_packetbuffer[0] = CMD_GETFIRMWAREVERSION;
    158 
    159   if (! sendCommandCheckAck(pn532_packetbuffer, 1))
    160     return 0;
    161 
    162   // read data packet
    163   readData(pn532_packetbuffer, 12);
    164 
    165   int offset = 7;  // Skip the ready byte when using I2C
    166 
    167   response <<= 8;
    168   response |= pn532_packetbuffer[offset++];
    169   response <<= 8;
    170   response |= pn532_packetbuffer[offset++];
    171   response <<= 8;
    172   response |= pn532_packetbuffer[offset++];
    173 
    174   if (response != pn532_firmwarerev)
    175     fprintf(stderr,
    176             "Warning: firmware revision 0x%08x does not match expected rev 0x%08x\n",
    177             response, pn532_firmwarerev);
    178 
    179   return response;
    180 }
    181 
    182 
    183 /**************************************************************************/
    184 /*!
    185   @brief  Sends a command and waits a specified period for the ACK
    186 
    187   @param  cmd       Pointer to the command buffer
    188   @param  cmdlen    The size of the command in bytes
    189   @param  timeout   timeout before giving up
    190 
    191   @returns  1 if everything is OK, 0 if timeout occured before an
    192   ACK was recieved
    193 */
    194 /**************************************************************************/
    195 // default timeout of one second
    196 bool PN532::sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen,
    197                                 uint16_t timeout)
    198 {
    199   uint16_t timer = 0;
    200 
    201   // clear any outstanding irq's
    202   isReady();
    203 
    204   // write the command
    205   writeCommand(cmd, cmdlen);
    206 
    207   // Wait for chip to say its ready!
    208   if (!waitForReady(timeout)) {
    209     cerr << __FUNCTION__ << ": Not ready, timeout" << endl;
    210     return false;
    211   }
    212 
    213   if (m_pn532Debug)
    214     cerr << __FUNCTION__ << ": IRQ received" << endl;
    215 
    216   // read acknowledgement
    217   if (!readAck()) {
    218     if (m_pn532Debug)
    219       cerr << __FUNCTION__ << ": No ACK frame received!" << endl;
    220 
    221     return false;
    222   }
    223 
    224   return true; // ack'd command
    225 }
    226 
    227 /**************************************************************************/
    228 /*!
    229   @brief  Configures the SAM (Secure Access Module)
    230 */
    231 /**************************************************************************/
    232 bool PN532::SAMConfig(void)
    233 {
    234   pn532_packetbuffer[0] = CMD_SAMCONFIGURATION;
    235   pn532_packetbuffer[1] = 0x01; // normal mode;
    236   pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
    237   pn532_packetbuffer[3] = 0x01; // use IRQ pin!
    238 
    239   if (! sendCommandCheckAck(pn532_packetbuffer, 4))
    240     return false;
    241 
    242   // read data packet
    243   readData(pn532_packetbuffer, 8);
    244 
    245   int offset = 6;
    246   return  (pn532_packetbuffer[offset] == 0x15);
    247 }
    248 
    249 /**************************************************************************/
    250 /*!
    251   Sets the MxRtyPassiveActivation byte of the RFConfiguration register
    252 
    253   @param  maxRetries    0xFF to wait forever, 0x00..0xFE to timeout
    254   after mxRetries
    255 
    256   @returns 1 if everything executed properly, 0 for an error
    257 */
    258 /**************************************************************************/
    259 bool PN532::setPassiveActivationRetries(uint8_t maxRetries)
    260 {
    261   pn532_packetbuffer[0] = CMD_RFCONFIGURATION;
    262   pn532_packetbuffer[1] = 5;    // Config item 5 (MaxRetries)
    263   pn532_packetbuffer[2] = 0xFF; // MxRtyATR (default = 0xFF)
    264   pn532_packetbuffer[3] = 0x01; // MxRtyPSL (default = 0x01)
    265   pn532_packetbuffer[4] = maxRetries;
    266 
    267   if (m_mifareDebug)
    268     cerr << __FUNCTION__ << ": Setting MxRtyPassiveActivation to "
    269          << (int)maxRetries << endl;
    270 
    271   if (! sendCommandCheckAck(pn532_packetbuffer, 5))
    272     return false;  // no ACK
    273 
    274   return true;
    275 }
    276 
    277 /***** ISO14443A Commands ******/
    278 
    279 /**************************************************************************/
    280 /*!
    281   Waits for an ISO14443A target to enter the field
    282 
    283   @param  cardBaudRate  Baud rate of the card
    284   @param  uid           Pointer to the array that will be populated
    285   with the card's UID (up to 7 bytes)
    286   @param  uidLength     Pointer to the variable that will hold the
    287   length of the card's UID.
    288 
    289   @returns 1 if everything executed properly, 0 for an error
    290 */
    291 /**************************************************************************/
    292 bool PN532::readPassiveTargetID(BAUD_T cardbaudrate, uint8_t * uid,
    293                                 uint8_t * uidLength, uint16_t timeout)
    294 {
    295   pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET;
    296   pn532_packetbuffer[1] = 1;  // max 1 cards at once (we can set this
    297                               // to 2 later)
    298   pn532_packetbuffer[2] = cardbaudrate;
    299 
    300   if (!sendCommandCheckAck(pn532_packetbuffer, 3, timeout))
    301     {
    302       if (m_pn532Debug)
    303         cerr << __FUNCTION__ << ": No card(s) read" << endl;
    304 
    305       return false;  // no cards read
    306     }
    307 
    308   // wait for a card to enter the field (only possible with I2C)
    309   if (m_pn532Debug)
    310     cerr << __FUNCTION__ << ": Waiting for IRQ (indicates card presence)" << endl;
    311 
    312   if (!waitForReady(timeout)) {
    313     if (m_pn532Debug)
    314       cerr << __FUNCTION__ << ": IRQ Timeout" << endl;
    315 
    316     return false;
    317   }
    318 
    319   // read data packet
    320   readData(pn532_packetbuffer, 20);
    321 
    322   // check some basic stuff
    323 
    324   /* ISO14443A card response should be in the following format:
    325 
    326      byte            Description
    327      -------------   ------------------------------------------
    328      b0..6           Frame header and preamble
    329      b7              Tags Found
    330      b8              Tag Number (only one used in this example)
    331      b9..10          SENS_RES
    332      b11             SEL_RES
    333      b12             NFCID Length
    334      b13..NFCIDLen   NFCID                                      */
    335 
    336   // SENS_RES   SEL_RES     Manufacturer/Card Type    NFCID Len
    337   // --------   -------     -----------------------   ---------
    338   // 00 04      08          NXP Mifare Classic 1K     4 bytes
    339   // 00 02      18          NXP Mifare Classic 4K     4 bytes
    340 
    341   if (m_mifareDebug)
    342     cerr << __FUNCTION__ << ": Found " <<  (int)pn532_packetbuffer[7] << " tags"
    343          << endl;
    344 
    345   // only one card can be handled currently
    346   if (pn532_packetbuffer[7] != 1)
    347     return false;
    348 
    349   uint16_t sens_res = pn532_packetbuffer[9];
    350   sens_res <<= 8;
    351   sens_res |= pn532_packetbuffer[10];
    352 
    353   // store these for later retrieval, they can be used to more accurately
    354   // ID the type of card.
    355 
    356   m_ATQA = sens_res;
    357   m_SAK = pn532_packetbuffer[11]; // SEL_RES
    358 
    359   if (m_mifareDebug)
    360     {
    361       fprintf(stderr, "ATQA: 0x%04x\n", m_ATQA);
    362       fprintf(stderr, "SAK: 0x%02x\n", m_SAK);
    363     }
    364 
    365   /* Card appears to be Mifare Classic */
    366   // JET: How so?
    367 
    368   *uidLength = pn532_packetbuffer[12];
    369   if (m_mifareDebug)
    370     fprintf(stderr, "UID: ");
    371 
    372   for (uint8_t i=0; i < pn532_packetbuffer[12]; i++)
    373     {
    374       uid[i] = pn532_packetbuffer[13+i];
    375       if (m_mifareDebug)
    376         fprintf(stderr, "0x%02x ", uid[i]);
    377     }
    378   if (m_mifareDebug)
    379     fprintf(stderr, "\n");
    380 
    381   return true;
    382 }
    383 
    384 /**************************************************************************/
    385 /*!
    386   @brief  Exchanges an APDU with the currently inlisted peer
    387 
    388   @param  send            Pointer to data to send
    389   @param  sendLength      Length of the data to send
    390   @param  response        Pointer to response data
    391   @param  responseLength  Pointer to the response data length
    392 */
    393 /**************************************************************************/
    394 bool PN532::inDataExchange(uint8_t * send, uint8_t sendLength,
    395                            uint8_t * response, uint8_t * responseLength)
    396 {
    397   if (sendLength > PN532_PACKBUFFSIZ-2) {
    398     if (m_pn532Debug)
    399       cerr << __FUNCTION__ << ": APDU length too long for packet buffer"
    400            << endl;
    401 
    402     return false;
    403   }
    404   uint8_t i;
    405 
    406   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; // 0x40
    407   pn532_packetbuffer[1] = m_inListedTag;
    408   for (i=0; i<sendLength; ++i) {
    409     pn532_packetbuffer[i+2] = send[i];
    410   }
    411 
    412   if (!sendCommandCheckAck(pn532_packetbuffer,sendLength+2,1000)) {
    413     if (m_pn532Debug)
    414       cerr << __FUNCTION__ << ": Could not send ADPU" << endl;
    415 
    416     return false;
    417   }
    418 
    419   if (!waitForReady(1000)) {
    420     if (m_pn532Debug)
    421       cerr << __FUNCTION__ << ": Response never received for ADPU..." << endl;
    422 
    423     return false;
    424   }
    425 
    426   readData(pn532_packetbuffer, sizeof(pn532_packetbuffer));
    427 
    428   if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 &&
    429       pn532_packetbuffer[2] == 0xff)
    430     {
    431 
    432       uint8_t length = pn532_packetbuffer[3];
    433       if (pn532_packetbuffer[4]!=(uint8_t)(~length+1))
    434         {
    435           if (m_pn532Debug)
    436             fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length,
    437                     (~length)+1);
    438 
    439           return false;
    440         }
    441       if (pn532_packetbuffer[5]==PN532_PN532TOHOST &&
    442           pn532_packetbuffer[6]==RSP_INDATAEXCHANGE)
    443         {
    444           if ((pn532_packetbuffer[7] & 0x3f)!=0)
    445             {
    446               if (m_pn532Debug)
    447                 cerr << __FUNCTION__ << ": Status code indicates an error"
    448                      << endl;
    449 
    450               return false;
    451             }
    452 
    453           length -= 3;
    454 
    455           if (length > *responseLength) {
    456             length = *responseLength; // silent truncation...
    457           }
    458 
    459           for (i=0; i<length; ++i) {
    460             response[i] = pn532_packetbuffer[8+i];
    461           }
    462           *responseLength = length;
    463 
    464           return true;
    465         }
    466       else {
    467         fprintf(stderr, "Don't know how to handle this command: 0x%02x\n",
    468                 pn532_packetbuffer[6]);
    469         return false;
    470       }
    471     }
    472   else {
    473     cerr << __FUNCTION__ << ": Preamble missing" << endl;
    474     return false;
    475   }
    476 }
    477 
    478 /**************************************************************************/
    479 /*!
    480   @brief  'InLists' a passive target. PN532 acting as reader/initiator,
    481   peer acting as card/responder.
    482 */
    483 /**************************************************************************/
    484 bool PN532::inListPassiveTarget()
    485 {
    486   m_inListedTag = 0;
    487 
    488   pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET;
    489   pn532_packetbuffer[1] = 1;
    490   pn532_packetbuffer[2] = 0;
    491 
    492   if (m_pn532Debug)
    493     cerr << __FUNCTION__ << ": About to inList passive target" << endl;
    494 
    495   if (!sendCommandCheckAck(pn532_packetbuffer,3,1000)) {
    496     if (m_pn532Debug)
    497       cerr << __FUNCTION__ << ": Could not send inlist message" << endl;
    498 
    499     return false;
    500   }
    501 
    502   if (!waitForReady(30000)) {
    503     return false;
    504   }
    505 
    506   readData(pn532_packetbuffer, sizeof(pn532_packetbuffer));
    507 
    508   if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 &&
    509       pn532_packetbuffer[2] == 0xff) {
    510 
    511     uint8_t length = pn532_packetbuffer[3];
    512     if (pn532_packetbuffer[4]!=(uint8_t)(~length+1)) {
    513       if (m_pn532Debug)
    514         fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length,
    515                 (~length)+1);
    516 
    517       return false;
    518     }
    519     if (pn532_packetbuffer[5]==PN532_PN532TOHOST &&
    520         pn532_packetbuffer[6]==RSP_INLISTPASSIVETARGET) {
    521       if (pn532_packetbuffer[7] != 1) {
    522         cerr << __FUNCTION__ << ": Unhandled number of tags inlisted: "
    523              << (int)pn532_packetbuffer[7] << endl;
    524         return false;
    525       }
    526 
    527       m_inListedTag = pn532_packetbuffer[8];
    528       if (m_pn532Debug)
    529         cerr << __FUNCTION__ << ": Tag number: " << (int)m_inListedTag << endl;
    530 
    531       return true;
    532     } else {
    533       if (m_pn532Debug)
    534         cerr << __FUNCTION__ << ": Unexpected response to inlist passive host"
    535              << endl;
    536 
    537       return false;
    538     }
    539   }
    540   else {
    541     if (m_pn532Debug)
    542       cerr << __FUNCTION__ << ": Preamble missing" << endl;
    543 
    544     return false;
    545   }
    546 
    547   return true;
    548 }
    549 
    550 
    551 /***** Mifare Classic Functions ******/
    552 /*  MIFARE CLASSIC DESCRIPTION
    553     ==========================
    554 
    555     Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_classic.c
    556 
    557     MIFARE Classic cards come in 1K and 4K varieties.  While several
    558     varieties of chips exist, the two main chipsets used are described
    559     in the following publicly accessible documents:
    560 
    561         MF1S503x Mifare Classic 1K data sheet:
    562         http://www.nxp.com/documents/data_sheet/MF1S503x.pdf
    563 
    564         MF1S70yyX MIFARE Classic 4K data sheet:
    565         http://www.nxp.com/documents/data_sheet/MF1S70YYX.pdf
    566 
    567     Mifare Classic cards typically have a a 4-byte NUID, though you may
    568     find cards with 7 byte IDs as well
    569 
    570     EEPROM MEMORY
    571     =============
    572     Mifare Classic cards have either 1K or 4K of EEPROM memory. Each
    573     memory block can be configured with different access conditions,
    574     with two seperate authentication keys present in each block.
    575 
    576     The two main Mifare Classic card types are organised as follows:
    577 
    578         1K Cards: 16 sectors of 4 blocks (0..15)
    579         4K Cards: 32 sectors of 4 blocks (0..31) and
    580                   8 sectors of 16 blocks (32..39)
    581 
    582     4 block sectors
    583     ===============
    584     Sector  Block   Bytes                                                           Description
    585     ------  -----   -----                                                           -----------
    586                     0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
    587 
    588     1       3       [-------KEY A-------]   [Access Bits]   [-------KEY A-------]   Sector Trailer 1
    589             2       [                            Data                           ]   Data
    590             1       [                            Data                           ]   Data
    591             0       [                            Data                           ]   Data
    592 
    593     0       3       [-------KEY A-------]   [Access Bits]   [-------KEY A-------]   Sector Trailer 1
    594             2       [                            Data                           ]   Data
    595             1       [                            Data                           ]   Data
    596             0       [                     Manufacturer Data                     ]   Manufacturer Block
    597 
    598     Sector Trailer (Block 3)
    599     ------------------------
    600     The sector trailer block contains the two secret keys (Key A and Key B), as well
    601     as the access conditions for the four blocks.  It has the following structure:
    602 
    603         Sector Trailer Bytes
    604         --------------------------------------------------------------
    605         0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
    606         [       Key A       ]   [Access Bits]   [       Key B       ]
    607 
    608     For more information in using Keys to access the clock contents, see
    609     Accessing Data Blocks further below.
    610 
    611     Data Blocks (Blocks 0..2)
    612     -------------------------
    613     Data blocks are 16 bytes wide and, depending on the permissions set in the
    614     access bits, can be read from and written to. You are free to use the 16 data
    615     bytes in any way you wish.  You can easily store text input, store four 32-bit
    616     integer values, a 16 character uri, etc.
    617 
    618     Data Blocks as "Value Blocks"
    619     -----------------------------
    620     An alternative to storing random data in the 16 byte-wide blocks is to
    621     configure them as "Value Blocks".  Value blocks allow performing electronic
    622     purse functions (valid commands are: read, write, increment, decrement,
    623     restore, transfer).
    624 
    625     Each Value block contains a single signed 32-bit value, and this value is
    626     stored 3 times for data integrity and security reasons.  It is stored twice
    627     non-inverted, and once inverted.  The last 4 bytes are used for a 1-byte
    628     address, which is stored 4 times (twice non-inverted, and twice inverted).
    629 
    630     Data blocks configured as "Value Blocks" have the following structure:
    631 
    632         Value Block Bytes
    633         --------------------------------------------------------------
    634         0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
    635         [   Value   ]   [   ~Value  ]   [   Value   ]   [A  ~A  A   ~A]
    636 
    637     Manufacturer Block (Sector 0, Block 0)
    638     --------------------------------------
    639     Sector 0 is special since it contains the Manufacturer Block. This block
    640     contains the manufacturer data, and is read-only.  It should be avoided
    641     unless you know what you are doing.
    642 
    643     16 block sectors
    644     ================
    645     16 block sectors are identical to 4 block sectors, but with more data blocks.  The same
    646     structure described in the 4 block sectors above applies.
    647 
    648     Sector  Block   Bytes                                                           Description
    649     ------  -----   -----                                                           ----------
    650                     0   1   2   3   4   5   6   7   8   9   10  11  12  13  14  15
    651 
    652     32      15      [-------KEY A-------]   [Access Bits]   [-------KEY B-------]   Sector Trailer 32
    653             14      [                            Data                           ]   Data
    654             13      [                            Data                           ]   Data
    655             ...
    656             2       [                            Data                           ]   Data
    657             1       [                            Data                           ]   Data
    658             0       [                            Data                           ]   Data
    659 
    660     ACCESSING DATA BLOCKS
    661     =====================
    662 
    663     Before you can access the cards, you must following two steps:
    664 
    665     1.) You must retrieve the 7 byte UID or the 4-byte NUID of the card.
    666         This can be done using pn532_mifareclassic_WaitForPassiveTarget()
    667         below, which will return the appropriate ID.
    668 
    669     2.) You must authenticate the sector you wish to access according to the
    670         access rules defined in the Sector Trailer block for that sector.
    671         This can be done using pn532_mifareclassic_AuthenticateBlock(),
    672         passing in the appropriate key value.
    673 
    674         Most new cards have a default Key A of 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF,
    675         but some common values worth trying are:
    676 
    677             0XFF 0XFF 0XFF 0XFF 0XFF 0XFF
    678             0XD3 0XF7 0XD3 0XF7 0XD3 0XF7
    679             0XA0 0XA1 0XA2 0XA3 0XA4 0XA5
    680             0XB0 0XB1 0XB2 0XB3 0XB4 0XB5
    681             0X4D 0X3A 0X99 0XC3 0X51 0XDD
    682             0X1A 0X98 0X2C 0X7E 0X45 0X9A
    683             0XAA 0XBB 0XCC 0XDD 0XEE 0XFF
    684             0X00 0X00 0X00 0X00 0X00 0X00
    685             0XAB 0XCD 0XEF 0X12 0X34 0X56
    686 
    687     3.) Once authenication has succeeded, and depending on the sector
    688         permissions, you can then read/write/increment/decrement the
    689         contents of the specific block, using one of the helper functions
    690         included in this module.
    691 
    692 */
    693 /**************************************************************************/
    694 /*!
    695   Indicates whether the specified block number is the first block
    696   in the sector (block 0 relative to the current sector)
    697 */
    698 /**************************************************************************/
    699 bool PN532::mifareclassic_IsFirstBlock (uint32_t uiBlock)
    700 {
    701   // Test if we are in the small or big sectors
    702   if (uiBlock < 128)
    703     return ((uiBlock) % 4 == 0);
    704   else
    705     return ((uiBlock) % 16 == 0);
    706 }
    707 
    708 /**************************************************************************/
    709 /*!
    710   Indicates whether the specified block number is the sector trailer
    711 */
    712 /**************************************************************************/
    713 bool PN532::mifareclassic_IsTrailerBlock (uint32_t uiBlock)
    714 {
    715   // Test if we are in the small or big sectors
    716   if (uiBlock < 128)
    717     return ((uiBlock + 1) % 4 == 0);
    718   else
    719     return ((uiBlock + 1) % 16 == 0);
    720 }
    721 
    722 /**************************************************************************/
    723 /*!
    724   Tries to authenticate a block of memory on a MIFARE card using the
    725   INDATAEXCHANGE command.  See section 7.3.8 of the PN532 User Manual
    726   for more information on sending MIFARE and other commands.
    727 
    728   @param  uid           Pointer to a byte array containing the card UID
    729   @param  uidLen        The length (in bytes) of the card's UID (Should
    730   be 4 for MIFARE Classic)
    731   @param  blockNumber   The block number to authenticate.  (0..63 for
    732   1KB cards, and 0..255 for 4KB cards).
    733   @param  keyNumber     Which key type to use during authentication
    734   (0 = MIFARE_CMD_AUTH_A, 1 = MIFARE_CMD_AUTH_B)
    735   @param  keyData       Pointer to a byte array containing the 6 byte
    736   key value
    737 
    738   @returns 1 if everything executed properly, 0 for an error
    739 */
    740 /**************************************************************************/
    741 bool PN532::mifareclassic_AuthenticateBlock (uint8_t * uid, uint8_t uidLen,
    742                                              uint32_t blockNumber,
    743                                              uint8_t keyNumber,
    744                                              uint8_t * keyData)
    745 {
    746   uint8_t len;
    747   uint8_t i;
    748 
    749   // Hang on to the key and uid data
    750   memcpy (m_key, keyData, 6);
    751   memcpy (m_uid, uid, uidLen);
    752   m_uidLen = uidLen;
    753 
    754   if (m_mifareDebug)
    755     {
    756       fprintf(stderr, "Trying to authenticate card ");
    757       PrintHex(m_uid, m_uidLen);
    758       fprintf(stderr, "Using authentication KEY %c: ",
    759               keyNumber ? 'B' : 'A');
    760       PrintHex(m_key, 6);
    761     }
    762 
    763   // Prepare the authentication command //
    764   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE;   /* Data Exchange Header */
    765   pn532_packetbuffer[1] = 1;                              /* Max card numbers */
    766   pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_B : MIFARE_CMD_AUTH_A;
    767   pn532_packetbuffer[3] = blockNumber;                    /* Block
    768                                                              Number
    769                                                              (1K =
    770                                                              0..63, 4K
    771                                                              =
    772                                                              0..255 */
    773   memcpy (pn532_packetbuffer+4, m_key, 6);
    774   for (i = 0; i < m_uidLen; i++)
    775     {
    776       pn532_packetbuffer[10+i] = m_uid[i];                /* 4 byte card ID */
    777     }
    778 
    779   if (! sendCommandCheckAck(pn532_packetbuffer, 10+m_uidLen))
    780     return false;
    781 
    782   if (!waitForReady(1000)) {
    783     if (m_pn532Debug)
    784       cerr << __FUNCTION__ << ": timeout waiting auth..." << endl;
    785 
    786     return false;
    787   }
    788 
    789   // Read the response packet
    790   readData(pn532_packetbuffer, 12);
    791 
    792   // check if the response is valid and we are authenticated???
    793   // for an auth success it should be bytes 5-7: 0xD5 0x41 0x00
    794   // Mifare auth error is technically byte 7: 0x14 but anything other
    795   // and 0x00 is not good
    796   if (pn532_packetbuffer[7] != 0x00)
    797     {
    798       if (m_pn532Debug)
    799         {
    800           fprintf(stderr, "Authentication failed: ");
    801           PrintHexChar(pn532_packetbuffer, 12);
    802         }
    803 
    804       return false;
    805     }
    806 
    807   return true;
    808 }
    809 
    810 /**************************************************************************/
    811 /*!
    812   Tries to read an entire 16-byte data block at the specified block
    813   address.
    814 
    815   @param  blockNumber   The block number to authenticate.  (0..63 for
    816   1KB cards, and 0..255 for 4KB cards).
    817   @param  data          Pointer to the byte array that will hold the
    818   retrieved data (if any)
    819 
    820   @returns 1 if everything executed properly, 0 for an error
    821 */
    822 /**************************************************************************/
    823 bool PN532::mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data)
    824 {
    825   if (m_mifareDebug)
    826     cerr << __FUNCTION__ << ": Trying to read 16 bytes from block "
    827          << (int)blockNumber << endl;
    828 
    829   /* Prepare the command */
    830   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE;
    831   pn532_packetbuffer[1] = 1;                      /* Card number */
    832   pn532_packetbuffer[2] = MIFARE_CMD_READ;        /* Mifare Read
    833                                                      command = 0x30 */
    834   pn532_packetbuffer[3] = blockNumber;            /* Block Number
    835                                                      (0..63 for 1K,
    836                                                      0..255 for 4K) */
    837 
    838   /* Send the command */
    839   if (! sendCommandCheckAck(pn532_packetbuffer, 4))
    840     {
    841       if (m_mifareDebug)
    842         cerr << __FUNCTION__ << ": Failed to receive ACK for read command"
    843              << endl;
    844 
    845       return false;
    846     }
    847 
    848   /* Read the response packet */
    849   readData(pn532_packetbuffer, 26);
    850 
    851   /* If byte 8 isn't 0x00 we probably have an error */
    852   if (pn532_packetbuffer[7] != 0x00)
    853     {
    854       if (m_mifareDebug)
    855         {
    856           fprintf(stderr, "Unexpected response: ");
    857           PrintHexChar(pn532_packetbuffer, 26);
    858         }
    859       return false;
    860     }
    861 
    862   /* Copy the 16 data bytes to the output buffer        */
    863   /* Block content starts at byte 9 of a valid response */
    864   memcpy (data, pn532_packetbuffer+8, 16);
    865 
    866   /* Display data for debug if requested */
    867   if (m_mifareDebug)
    868     {
    869       fprintf(stderr, "Block %d: ", blockNumber);
    870       PrintHexChar(data, 16);
    871     }
    872 
    873   return true;
    874 }
    875 
    876 /**************************************************************************/
    877 /*!
    878   Tries to write an entire 16-byte data block at the specified block
    879   address.
    880 
    881   @param  blockNumber   The block number to authenticate.  (0..63 for
    882   1KB cards, and 0..255 for 4KB cards).
    883   @param  data          The byte array that contains the data to write.
    884 
    885   @returns 1 if everything executed properly, 0 for an error
    886 */
    887 /**************************************************************************/
    888 bool PN532::mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t * data)
    889 {
    890   if (m_mifareDebug)
    891     fprintf(stderr, "Trying to write 16 bytes to block %d\n", blockNumber);
    892 
    893   /* Prepare the first command */
    894   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE;
    895   pn532_packetbuffer[1] = 1;                      /* Card number */
    896   pn532_packetbuffer[2] = MIFARE_CMD_WRITE;       /* Mifare Write
    897                                                      command = 0xA0 */
    898   pn532_packetbuffer[3] = blockNumber;            /* Block Number
    899                                                      (0..63 for 1K,
    900                                                      0..255 for 4K) */
    901   memcpy (pn532_packetbuffer+4, data, 16);          /* Data Payload */
    902 
    903   /* Send the command */
    904   if (! sendCommandCheckAck(pn532_packetbuffer, 20))
    905     {
    906       if (m_mifareDebug)
    907         cerr << __FUNCTION__ << ": Failed to receive ACK for write command"
    908              << endl;
    909 
    910       return false;
    911     }
    912   usleep(10000);
    913 
    914   /* Read the response packet */
    915   readData(pn532_packetbuffer, 26);
    916 
    917   return true;
    918 }
    919 
    920 /**************************************************************************/
    921 /*!
    922   Formats a Mifare Classic card to store NDEF Records
    923 
    924   @returns 1 if everything executed properly, 0 for an error
    925 */
    926 /**************************************************************************/
    927 bool PN532::mifareclassic_FormatNDEF (void)
    928 {
    929   uint8_t sectorbuffer1[16] = {0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1,
    930                                0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
    931   uint8_t sectorbuffer2[16] = {0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1,
    932                                0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1};
    933   uint8_t sectorbuffer3[16] = {0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77,
    934                                0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
    935 
    936   // Note 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 must be used for key A
    937   // for the MAD sector in NDEF records (sector 0)
    938 
    939   // Write block 1 and 2 to the card
    940   if (!(mifareclassic_WriteDataBlock (1, sectorbuffer1)))
    941     return false;
    942   if (!(mifareclassic_WriteDataBlock (2, sectorbuffer2)))
    943     return false;
    944   // Write key A and access rights card
    945   if (!(mifareclassic_WriteDataBlock (3, sectorbuffer3)))
    946     return false;
    947 
    948   // Seems that everything was OK (?!)
    949   return true;
    950 }
    951 
    952 /**************************************************************************/
    953 /*!
    954   Writes an NDEF URI Record to the specified sector (1..15)
    955 
    956   Note that this function assumes that the Mifare Classic card is
    957   already formatted to work as an "NFC Forum Tag" and uses a MAD1
    958   file system.  You can use the NXP TagWriter app on Android to
    959   properly format cards for this.
    960 
    961   @param  sectorNumber  The sector that the URI record should be written
    962   to (can be 1..15 for a 1K card)
    963   @param  uriIdentifier The uri identifier code (0 = none, 0x01 =
    964   "http://www.", etc.)
    965   @param  url           The uri text to write (max 38 characters).
    966 
    967   @returns 1 if everything executed properly, 0 for an error
    968 */
    969 /**************************************************************************/
    970 bool PN532::mifareclassic_WriteNDEFURI (uint8_t sectorNumber,
    971                                         NDEF_URI_T uriIdentifier,
    972                                         const char * url)
    973 {
    974   if (!url)
    975     return false;
    976 
    977   // Figure out how long the string is
    978   uint8_t len = strlen(url);
    979 
    980   // Make sure we're within a 1K limit for the sector number
    981   if ((sectorNumber < 1) || (sectorNumber > 15))
    982     return false;
    983 
    984   // Make sure the URI payload is between 1 and 38 chars
    985   if ((len < 1) || (len > 38))
    986     return false;
    987 
    988   // Note 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 must be used for key A
    989   // in NDEF records
    990 
    991   // Setup the sector buffer (w/pre-formatted TLV wrapper and NDEF message)
    992   uint8_t sectorbuffer1[16] = {0x00, 0x00, 0x03, static_cast<uint8_t>(len+5),
    993                                0xD1, 0x01, static_cast<uint8_t>(len+1),
    994                                0x55, static_cast<uint8_t>(uriIdentifier), 0x00, 0x00, 0x00, 0x00,
    995                                0x00, 0x00, 0x00};
    996   uint8_t sectorbuffer2[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    997                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    998                                0x00, 0x00};
    999   uint8_t sectorbuffer3[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   1000                                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
   1001                                0x00, 0x00};
   1002   uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F,
   1003                                0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF,
   1004                                0xFF, 0xFF};
   1005   if (len <= 6)
   1006     {
   1007       // Unlikely we'll get a url this short, but why not ...
   1008       memcpy (sectorbuffer1+9, url, len);
   1009       sectorbuffer1[len+9] = 0xFE;
   1010     }
   1011   else if (len == 7)
   1012     {
   1013       // 0xFE needs to be wrapped around to next block
   1014       memcpy (sectorbuffer1+9, url, len);
   1015       sectorbuffer2[0] = 0xFE;
   1016     }
   1017   else if ((len > 7) && (len <= 22))
   1018     {
   1019       // Url fits in two blocks
   1020       memcpy (sectorbuffer1+9, url, 7);
   1021       memcpy (sectorbuffer2, url+7, len-7);
   1022       sectorbuffer2[len-7] = 0xFE;
   1023     }
   1024   else if (len == 23)
   1025     {
   1026       // 0xFE needs to be wrapped around to final block
   1027       memcpy (sectorbuffer1+9, url, 7);
   1028       memcpy (sectorbuffer2, url+7, len-7);
   1029       sectorbuffer3[0] = 0xFE;
   1030     }
   1031   else
   1032     {
   1033       // Url fits in three blocks
   1034       memcpy (sectorbuffer1+9, url, 7);
   1035       memcpy (sectorbuffer2, url+7, 16);
   1036       memcpy (sectorbuffer3, url+23, len-24);
   1037       sectorbuffer3[len-23] = 0xFE;
   1038     }
   1039 
   1040   // Now write all three blocks back to the card
   1041   if (!(mifareclassic_WriteDataBlock (sectorNumber*4, sectorbuffer1)))
   1042     return false;
   1043   if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+1, sectorbuffer2)))
   1044     return false;
   1045   if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+2, sectorbuffer3)))
   1046     return false;
   1047   if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+3, sectorbuffer4)))
   1048     return false;
   1049 
   1050   // Seems that everything was OK (?!)
   1051   return true;
   1052 }
   1053 
   1054 
   1055 /***** NTAG2xx/ultralight Functions ******/
   1056 
   1057 // Ultralight tags are limited to 64 pages max, with ntag2XX tags can
   1058 // have up to 231 pages.
   1059 
   1060 /*  MIFARE ULTRALIGHT DESCRIPTION
   1061     =============================
   1062 
   1063     Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_ultralight.c
   1064 
   1065     MIFARE Ultralight cards typically contain 512 bits (64 bytes) of
   1066     memory, including 4 bytes (32-bits) of OTP (One Time Programmable)
   1067     memory where the individual bits can be written but not erased.
   1068 
   1069         MF0ICU1 Mifare Ultralight Functional Specification:
   1070         http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf
   1071 
   1072 
   1073     Mifare Ultralight cards have a 7-byte UID
   1074 
   1075     EEPROM MEMORY
   1076     =============
   1077     Mifare Ultralight cards have 512 bits (64 bytes) of EEPROM memory,
   1078     including 4 byte (32 bits) of OTP memory.  Unlike Mifare Classic cards,
   1079     there is no authentication on a per block level, although the blocks
   1080     can be set to "read-only" mode using Lock Bytes (described below).
   1081 
   1082     EEPROM memory is organised into 16 pages of four bytes eachs, in
   1083     the following order
   1084 
   1085     Page   Description
   1086     ----   ------------
   1087     0      Serial Number (4 bytes)
   1088     1      Serial Number (4 bytes)
   1089     2      Byte 0:    Serial Number
   1090            Byte 1:    Internal Memory
   1091            Byte 2..3: lock bytes
   1092     3      One-time programmable memory (4 bytes)
   1093     4..15  User memory (4 bytes)
   1094 
   1095     Lock Bytes (Page 2)
   1096     -------------------
   1097     Bytes 2 and 3 of page 2 are referred to as "Lock Bytes".  Each
   1098     page from 0x03 and higher can individually locked by setting the
   1099     corresponding locking bit to "1" to prevent further write access,
   1100     effectively making the memory read only.
   1101 
   1102     For information on the lock byte mechanism, refer to section 8.5.2 of
   1103     the datasheet (referenced above).
   1104 
   1105     OTP Bytes (Page 3)
   1106     ------------------
   1107     Page 3 is the OTP memory, and by default all bits on this page are
   1108     set to 0.  These bits can be bitwise modified using the Mifare WRITE
   1109     command, and individual bits can be set to 1, but can not be changed
   1110     back to 0.
   1111 
   1112     Data Pages (Pages 4..15)
   1113     ------------------------
   1114     Pages 4 to 15 are can be freely read from and written to,
   1115     provided there is no conflict with the Lock Bytes described above.
   1116 
   1117     After production, the bytes have the following default values:
   1118 
   1119     Page    Byte Values
   1120     ----    ----------------------
   1121             0     1     2     3
   1122     4       0xFF  0xFF  0xFF  0xFF
   1123     5..15   0x00  0x00  0x00  0x00
   1124 
   1125     ACCESSING DATA BLOCKS
   1126     =====================
   1127 
   1128     Before you can access the cards, you must following two steps:
   1129 
   1130     1.) 'Connect' to a Mifare Ultralight card and retrieve the 7 byte
   1131         UID of the card.
   1132 
   1133     2.) Memory can be read and written directly once a passive mode
   1134         connection has been made.  No authentication is required for
   1135         Mifare Ultralight cards.
   1136 
   1137 */
   1138 
   1139 
   1140 /**************************************************************************/
   1141 /*!
   1142   Tries to read an entire 4-byte page at the specified address.
   1143 
   1144   @param  page        The page number (0..63 in most cases)
   1145   @param  buffer      Pointer to the byte array that will hold the
   1146   retrieved data (if any)
   1147 */
   1148 /**************************************************************************/
   1149 bool PN532::ntag2xx_ReadPage (uint8_t page, uint8_t * buffer)
   1150 {
   1151   // TAG Type       PAGES   USER START    USER STOP
   1152   // --------       -----   ----------    ---------
   1153   // NTAG 203       42      4             39
   1154   // NTAG 213       45      4             39
   1155   // NTAG 215       135     4             129
   1156   // NTAG 216       231     4             225
   1157 
   1158   if (page >= 231)
   1159     {
   1160       cerr << __FUNCTION__ << ": Page value out of range" << endl;
   1161       return false;
   1162     }
   1163 
   1164   if (m_mifareDebug)
   1165     fprintf(stderr, "Reading page %d\n", page);
   1166 
   1167   /* Prepare the command */
   1168   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE;
   1169   pn532_packetbuffer[1] = 1;                   /* Card number */
   1170   pn532_packetbuffer[2] = MIFARE_CMD_READ;     /* Mifare Read command = 0x30 */
   1171   pn532_packetbuffer[3] = page;                /* Page Number (0..63
   1172                                                   in most cases) */
   1173 
   1174   /* Send the command */
   1175   if (! sendCommandCheckAck(pn532_packetbuffer, 4))
   1176     {
   1177       if (m_mifareDebug)
   1178         cerr << __FUNCTION__ << ": Failed to receive ACK for write command"
   1179              << endl;
   1180 
   1181       return false;
   1182     }
   1183 
   1184   /* Read the response packet */
   1185   readData(pn532_packetbuffer, 26);
   1186 
   1187   if (m_mifareDebug)
   1188     {
   1189       fprintf(stderr, "Received: \n");
   1190       PrintHexChar(pn532_packetbuffer, 26);
   1191     }
   1192 
   1193   /* If byte 8 isn't 0x00 we probably have an error */
   1194   if (pn532_packetbuffer[7] == 0x00)
   1195     {
   1196       /* Copy the 4 data bytes to the output buffer         */
   1197       /* Block content starts at byte 9 of a valid response */
   1198       /* Note that the command actually reads 16 byte or 4  */
   1199       /* pages at a time ... we simply discard the last 12  */
   1200       /* bytes                                              */
   1201       memcpy (buffer, pn532_packetbuffer+8, 4);
   1202     }
   1203   else
   1204     {
   1205       if (m_mifareDebug)
   1206         {
   1207           fprintf(stderr, "Unexpected response reading block: \n");
   1208           PrintHexChar(pn532_packetbuffer, 26);
   1209         }
   1210 
   1211       return false;
   1212     }
   1213 
   1214   /* Display data for debug if requested */
   1215   if (m_mifareDebug)
   1216     {
   1217       fprintf(stderr, "Page %d:\n", page);
   1218       PrintHexChar(buffer, 4);
   1219     }
   1220 
   1221   // Return OK signal
   1222   return true;
   1223 }
   1224 
   1225 /**************************************************************************/
   1226 /*!
   1227   Tries to write an entire 4-byte page at the specified block
   1228   address.
   1229 
   1230   @param  page          The page number to write.  (0..63 for most cases)
   1231   @param  data          The byte array that contains the data to write.
   1232   Should be exactly 4 bytes long.
   1233 
   1234   @returns 1 if everything executed properly, 0 for an error
   1235 */
   1236 /**************************************************************************/
   1237 bool PN532::ntag2xx_WritePage (uint8_t page, uint8_t * data)
   1238 {
   1239   // TAG Type       PAGES   USER START    USER STOP
   1240   // --------       -----   ----------    ---------
   1241   // NTAG 203       42      4             39
   1242   // NTAG 213       45      4             39
   1243   // NTAG 215       135     4             129
   1244   // NTAG 216       231     4             225
   1245 
   1246   if ((page < 4) || (page > 225))
   1247     {
   1248       cerr << __FUNCTION__ << ": Page value out of range" << endl;
   1249       return false;
   1250     }
   1251 
   1252   if (m_mifareDebug)
   1253     fprintf(stderr, "Trying to write 4 byte page %d\n", page);
   1254 
   1255   /* Prepare the first command */
   1256   pn532_packetbuffer[0] = CMD_INDATAEXCHANGE;
   1257   pn532_packetbuffer[1] = 1;    /* Card number */
   1258   pn532_packetbuffer[2] = MIFARE_ULTRALIGHT_CMD_WRITE; /* Mifare
   1259                                                           Ultralight
   1260                                                           Write
   1261                                                           command =
   1262                                                           0xA2 */
   1263   pn532_packetbuffer[3] = page; /* Page Number (0..63 for most cases) */
   1264   memcpy (pn532_packetbuffer+4, data, 4); /* Data Payload */
   1265 
   1266   /* Send the command */
   1267   if (! sendCommandCheckAck(pn532_packetbuffer, 8))
   1268     {
   1269       if (m_mifareDebug)
   1270         cerr << __FUNCTION__ << ": Failed to receive ACK for write command"
   1271              << endl;
   1272 
   1273       // Return Failed Signal
   1274       return false;
   1275     }
   1276   usleep(10000);
   1277 
   1278   /* Read the response packet */
   1279   readData(pn532_packetbuffer, 26);
   1280 
   1281   // Return OK Signal
   1282   return true;
   1283 }
   1284 
   1285 /**************************************************************************/
   1286 /*!
   1287   Writes an NDEF URI Record starting at the specified page (4..nn)
   1288 
   1289   Note that this function assumes that the NTAG2xx card is
   1290   already formatted to work as an "NFC Forum Tag".
   1291 
   1292   @param  uriIdentifier The uri identifier code (0 = none, 0x01 =
   1293   "http://www.", etc.)
   1294   @param  url           The uri text to write (null-terminated string).
   1295   @param  dataLen       The size of the data area for overflow checks.
   1296 
   1297   @returns 1 if everything executed properly, 0 for an error
   1298 */
   1299 /**************************************************************************/
   1300 bool PN532::ntag2xx_WriteNDEFURI (NDEF_URI_T uriIdentifier, char * url,
   1301                                   uint8_t dataLen)
   1302 {
   1303   uint8_t pageBuffer[4] = { 0, 0, 0, 0 };
   1304 
   1305   // Remove NDEF record overhead from the URI data (pageHeader below)
   1306   uint8_t wrapperSize = 12;
   1307 
   1308   // Figure out how long the string is
   1309   uint8_t len = strlen(url);
   1310 
   1311   // Make sure the URI payload will fit in dataLen (include 0xFE trailer)
   1312   if ((len < 1) || (len+1 > (dataLen-wrapperSize)))
   1313     return false;
   1314 
   1315   // Setup the record header
   1316   // See NFCForum-TS-Type-2-Tag_1.1.pdf for details
   1317   uint8_t pageHeader[12] =
   1318     {
   1319       /* NDEF Lock Control TLV (must be first and always present) */
   1320       0x01,         /* Tag Field (0x01 = Lock Control TLV) */
   1321       0x03,         /* Payload Length (always 3) */
   1322       0xA0,         /* The position inside the tag of the lock bytes
   1323                        (upper 4 = page address, lower 4 = byte
   1324                        offset) */
   1325       0x10,         /* Size in bits of the lock area */
   1326       0x44,         /* Size in bytes of a page and the number of bytes
   1327                        each lock bit can lock (4 bit + 4 bits) */
   1328       /* NDEF Message TLV - URI Record */
   1329       0x03,         /* Tag Field (0x03 = NDEF Message) */
   1330       static_cast<uint8_t>(len+5),
   1331                     /* Payload Length (not including 0xFE trailer) */
   1332       0xD1,         /* NDEF Record Header (TNF=0x1:Well known record +
   1333                        SR + ME + MB) */
   1334       0x01,         /* Type Length for the record type indicator */
   1335       static_cast<uint8_t>(len+1),
   1336                     /* Payload len */
   1337       0x55,         /* Record Type Indicator (0x55 or 'U' = URI Record) */
   1338       static_cast<uint8_t>(uriIdentifier)
   1339                     /* URI Prefix (ex. 0x01 = "http://www.") */
   1340     };
   1341 
   1342   // Write 12 byte header (three pages of data starting at page 4)
   1343   memcpy (pageBuffer, pageHeader, 4);
   1344   if (!(ntag2xx_WritePage (4, pageBuffer)))
   1345     return false;
   1346   memcpy (pageBuffer, pageHeader+4, 4);
   1347   if (!(ntag2xx_WritePage (5, pageBuffer)))
   1348     return false;
   1349   memcpy (pageBuffer, pageHeader+8, 4);
   1350   if (!(ntag2xx_WritePage (6, pageBuffer)))
   1351     return false;
   1352 
   1353   // Write URI (starting at page 7)
   1354   uint8_t currentPage = 7;
   1355   char * urlcopy = url;
   1356   while (len)
   1357     {
   1358       if (len < 4)
   1359         {
   1360           memset(pageBuffer, 0, 4);
   1361           memcpy(pageBuffer, urlcopy, len);
   1362           pageBuffer[len] = 0xFE; // NDEF record footer
   1363           if (!(ntag2xx_WritePage (currentPage, pageBuffer)))
   1364             return false;
   1365           // DONE!
   1366           return true;
   1367         }
   1368       else if (len == 4)
   1369         {
   1370           memcpy(pageBuffer, urlcopy, len);
   1371           if (!(ntag2xx_WritePage (currentPage, pageBuffer)))
   1372             return false;
   1373           memset(pageBuffer, 0, 4);
   1374           pageBuffer[0] = 0xFE; // NDEF record footer
   1375           currentPage++;
   1376           if (!(ntag2xx_WritePage (currentPage, pageBuffer)))
   1377             return false;
   1378           // DONE!
   1379           return true;
   1380         }
   1381       else
   1382         {
   1383           // More than one page of data left
   1384           memcpy(pageBuffer, urlcopy, 4);
   1385           if (!(ntag2xx_WritePage (currentPage, pageBuffer)))
   1386             return false;
   1387           currentPage++;
   1388           urlcopy+=4;
   1389           len-=4;
   1390         }
   1391     }
   1392 
   1393   // Seems that everything was OK (?!)
   1394   return true;
   1395 }
   1396 
   1397 
   1398 /**************************************************************************/
   1399 /*!
   1400   @brief  Tries to read/verify the ACK packet
   1401 */
   1402 /**************************************************************************/
   1403 bool PN532::readAck()
   1404 {
   1405   uint8_t ackbuff[6];
   1406 
   1407   readData(ackbuff, 6);
   1408 
   1409   return (0 == memcmp((char *)ackbuff, (char *)pn532ack, 6));
   1410 }
   1411 
   1412 
   1413 /**************************************************************************/
   1414 /*!
   1415   @brief  Return true if the PN532 is ready with a response.
   1416 */
   1417 /**************************************************************************/
   1418 bool PN532::isReady()
   1419 {
   1420   // ALWAYS clear the m_irqRcvd flag if set.
   1421   if (m_irqRcvd)
   1422     {
   1423       m_irqRcvd = false;
   1424       return true;
   1425     }
   1426 
   1427   return false;
   1428 }
   1429 
   1430 /**************************************************************************/
   1431 /*!
   1432   @brief  Waits until the PN532 is ready.
   1433 
   1434   @param  timeout   Timeout before giving up
   1435 */
   1436 /**************************************************************************/
   1437 bool PN532::waitForReady(uint16_t timeout)
   1438 {
   1439   uint16_t timer = 0;
   1440   while(!isReady())
   1441     {
   1442       if (timeout != 0)
   1443         {
   1444           timer += 10;
   1445           if (timer > timeout)
   1446             {
   1447               return false;
   1448             }
   1449         }
   1450       usleep(10000);
   1451     }
   1452   return true;
   1453 }
   1454 
   1455 /**************************************************************************/
   1456 /*!
   1457   @brief  Reads n bytes of data from the PN532 via SPI or I2C.
   1458 
   1459   @param  buff      Pointer to the buffer where data will be written
   1460   @param  n         Number of bytes to be read
   1461 */
   1462 /**************************************************************************/
   1463 void PN532::readData(uint8_t* buff, uint8_t n)
   1464 {
   1465   uint8_t buf[n + 2];
   1466   int rv;
   1467 
   1468   memset(buf, 0, n+2);
   1469   usleep(2000);
   1470   if (m_i2c.address(m_addr) != mraa::SUCCESS)
   1471     {
   1472       throw std::runtime_error(std::string(__FUNCTION__) +
   1473                                ": mraa_i2c_address() failed");
   1474       return;
   1475     }
   1476 
   1477   rv = m_i2c.read(buf, n + 2);
   1478 
   1479   if (m_pn532Debug)
   1480     {
   1481       cerr << __FUNCTION__ << ": read returned " << rv << "bytes" << endl;
   1482 
   1483       fprintf(stderr, "(raw) buf (%d) = ", rv);
   1484       PrintHex(buf, rv);
   1485       fprintf(stderr, "\n");
   1486     }
   1487 
   1488   for (int i=0; i<n; i++)
   1489     buff[i] = buf[i+1];
   1490 
   1491   if (m_pn532Debug)
   1492     {
   1493       fprintf(stderr, "(returned) buf (%d) = \n", n);
   1494       PrintHex(buff, n);
   1495       fprintf(stderr, "\n");
   1496     }
   1497 }
   1498 
   1499 /**************************************************************************/
   1500 /*!
   1501   @brief  Writes a command to the PN532, automatically inserting the
   1502   preamble and required frame details (checksum, len, etc.)
   1503 
   1504   @param  cmd       Pointer to the command buffer
   1505   @param  cmdlen    Command length in bytes
   1506 */
   1507 /**************************************************************************/
   1508 void PN532::writeCommand(uint8_t* cmd, uint8_t cmdlen)
   1509 {
   1510   // I2C command write.
   1511 
   1512   cmdlen++;
   1513 
   1514   usleep(2000);     // 2ms max in case board needs to wake up
   1515 
   1516   // command + packet wrapper
   1517   uint8_t buf[cmdlen + 8];
   1518   memset(buf, 0, cmdlen + 8);
   1519   int offset = 0;
   1520 
   1521   if (m_pn532Debug)
   1522     cerr << __FUNCTION__ << ": Sending: " << endl;
   1523 
   1524   uint8_t checksum = PN532_PREAMBLE + PN532_PREAMBLE + PN532_STARTCODE2;
   1525   buf[offset++] = PN532_PREAMBLE;
   1526   buf[offset++] = PN532_PREAMBLE;
   1527   buf[offset++] = PN532_STARTCODE2;
   1528 
   1529   buf[offset++] = cmdlen;
   1530   buf[offset++] = ~cmdlen + 1;
   1531 
   1532   buf[offset++] = PN532_HOSTTOPN532;
   1533   checksum += PN532_HOSTTOPN532;
   1534 
   1535   for (uint8_t i=0; i<cmdlen - 1; i++)
   1536     {
   1537       buf[offset++] = cmd[i];
   1538       checksum += cmd[i];
   1539     }
   1540 
   1541   buf[offset++] = ~checksum;
   1542   buf[offset] = PN532_POSTAMBLE;
   1543 
   1544   if (m_i2c.address(m_addr) != mraa::SUCCESS)
   1545     {
   1546       throw std::runtime_error(std::string(__FUNCTION__) +
   1547                                ": mraa_i2c_address() failed");
   1548       return;
   1549     }
   1550 
   1551   if (m_i2c.write(buf, cmdlen + 8 - 1) != mraa::SUCCESS)
   1552     {
   1553       throw std::runtime_error(std::string(__FUNCTION__) +
   1554                                ": mraa_i2c_write() failed");
   1555       return;
   1556     }
   1557 
   1558   if (m_pn532Debug)
   1559     {
   1560       cerr << __FUNCTION__ << ": cmdlen + 8 = " << cmdlen + 8
   1561            <<", offset = " << offset << endl;
   1562 
   1563       PrintHex(buf, cmdlen + 8);
   1564     }
   1565 }
   1566 
   1567 void PN532::dataReadyISR(void *ctx)
   1568 {
   1569   upm::PN532 *This = (upm::PN532 *)ctx;
   1570 
   1571   // if debugging is enabled, indicate when an interrupt occurred, and
   1572   // a previously triggered interrupt was still set.
   1573   if (This->m_pn532Debug)
   1574     if (This->m_irqRcvd)
   1575       cerr << __FUNCTION__ << ": INFO: Unhandled IRQ detected." << endl;
   1576 
   1577   This->m_irqRcvd = true;
   1578 }
   1579 
   1580 PN532::TAG_TYPE_T PN532::tagType()
   1581 {
   1582   // This is really just a guess, ATQA and SAK could in theory be used
   1583   // to refine the detection.
   1584 
   1585   if (m_uidLen == 4)
   1586     return TAG_TYPE_MIFARE_CLASSIC;
   1587   else if (m_uidLen == 7)
   1588     return TAG_TYPE_NFC2;
   1589   else
   1590     return TAG_TYPE_UNKNOWN;
   1591 }
   1592