adafruit / Adafruit_CircuitPython_PN532

CircuitPython driver for the PN532 NFC/RFID Breakout and PN532 NFC/RFID Shield
MIT License
92 stars 47 forks source link

Read/write .vcf into mifare cards using pn532 RFID/NFC shield #14

Closed marienelle96 closed 5 years ago

marienelle96 commented 5 years ago

I was wondering if we can write .vcf files into the cards using PN532 and this library? I'm hoping someone might lend a hand. Really bugged out searching for solutions to this. Thanks!

tgikal commented 5 years ago

It's all about getting the formatting correct, and having enough room for the data.

There is quite a bit of information on formatting on the vCard Wikipedia page.

Just playing around I have this script working on a RaspberryPi, with a NTAG215 and a NFC vCard app on my phone:

import board
import busio
from digitalio import DigitalInOut
from adafruit_pn532.spi import PN532_SPI
# SPI connection:
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
cs_pin = DigitalInOut(board.D22) # CHANGED TO D22 from D5
pn532 = PN532_SPI(spi, cs_pin, debug=False)

# Configure PN532 to communicate with MiFare cards
pn532.SAM_configuration()

print('Waiting for RFID/NFC card!')
while True:
    # Check if a card is available to read
    uid = pn532.read_passive_target(timeout=0.5)
    print('.', end="")

s =  '''text/x-vcardBEGIN:VCARD
VERSION:3.0
N:Gump;Forrest;;Mr.;
FN:Forrest Gump
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
TEL;WORK:+11115551212
ADR;WORK:;;100 Waters Edge,Baytown;LA;30314;United States of America
EMAIL:forrestgump@example.com
END:VCARD'''

"""
NTAG215 135 pages total
Pages 0,1,2,3 are tag and setup infomation
Pages 4 through 129 should have 504 user bytes available
Last 5 pages are locking information
"""
max_page = 129
max_data = 504
print("writing data:", end = "")

# Header telling the reader this is a vCard (at least this what my phone's writer did)
header = bytearray(b'\x03\xff\x01\xaa\xc2\x0c\x00\x00\x01\x98')

termination = bytearray(b'\xFE') # Standard message termination

data =  header + bytearray(bytes(s, 'utf-8')) + termination

# Clear out the rest of the card
data = data + bytearray(b'\x00'*(max_data-len(data))) 
print(len(data), "bytes of data")

# Write 4 byte pages.
page = 4
for x in range(0,len(data),4):
    pn532.ntag2xx_write_block(page, data[x:x+4])
    page += 1

print('Wrote data in pages 4 to ' + str(page) + ', now trying to read that data:')

r = bytearray()
for x in range(4, max_page + 1):
    r += pn532.ntag2xx_read_block(x)
    if b'\xFE' in r:
        break

print(r)
kattni commented 5 years ago

Thanks @tgikal for the example! Closing this issue.