PN532 NFC library for Seeed Studio's NFC Shield

Fork of PN532 by Yihui Xiong

Revision:
5:51f820fbd18a
Parent:
3:4189a10038e6
diff -r 0774b8298eb8 -r 51f820fbd18a MifareUltralight.cpp
--- a/MifareUltralight.cpp	Thu Nov 21 04:41:47 2013 +0000
+++ b/MifareUltralight.cpp	Tue Oct 07 15:09:46 2014 +0000
@@ -77,6 +77,61 @@
 
 }
 
+bool MifareUltralight::write(NdefMessage& m, uint8_t * uid, unsigned int uidLength)
+{
+
+     if (isUnformatted())
+    {
+        printf("WARNING: Tag is not formatted.\r\n");
+        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
+
+    while (position < bufferSize){ //bufferSize is always times pagesize so no "last chunk" check
+        // write page
+        if (!nfc->mifareultralight_WritePage(page, src))
+            return false;
+        page++;
+        src+=ULTRALIGHT_PAGE_SIZE;
+        position+=ULTRALIGHT_PAGE_SIZE;
+    }
+    return true;
+}
 bool MifareUltralight::isUnformatted()
 {
     uint8_t page = 4;