Building applications¶
The pieces most card applications need: knowing when a card arrives, keeping running after the USB cable is pulled, sharing one reader between threads, storing named data on the card, and a balance that survives a card snatched away mid-write.
Card events¶
card_events() polls the reader and yields an event each time a card arrives
or leaves. A card resting on the reader is reported once.
from mifarepy import MifareReader
with MifareReader.auto() as reader:
for event in reader.card_events():
if event.kind == 'arrived':
print('Card', event.uid)
elif event.kind == 'removed':
print('Gone', event.uid)
event.kind |
When | event.uid |
|---|---|---|
arrived |
A card was placed on the reader | the card's UID |
removed |
It was taken away (missing for two polls in a row) | the card's UID |
disconnected |
The reader stopped answering, e.g. the USB cable was pulled | None |
reconnected |
The reader is back | None |
Every event also has event.time. Options: interval (seconds between polls,
default 0.25), removal_polls (default 2, so a flicker at the edge of the
field is ignored), reconnect, reconnect_interval, and stop, a
threading.Event that ends the loop.
In asyncio code use cards(), which runs the serial I/O in a worker thread:
mifarepy watch --removals prints the same events on the command line.
When the USB cable is pulled¶
card_events() and cards() notice when the reader stops answering, report
disconnected, and reopen it every second until it is back. A reader made
with MifareReader.auto() is searched for again, because Linux may give it a
new name (/dev/ttyUSB0 becomes /dev/ttyUSB1).
Outside an event loop, call reconnect() yourself:
import serial
try:
uid = reader.get_uid()
except (serial.SerialException, OSError):
reader.reconnect(attempts=30, interval=1.0) # raises ReaderConnectionError if it never comes back
Sharing a reader between threads¶
Every MifareReader method holds the reader's lock while it talks to the
reader, so several threads can share one reader without mixing up frames.
When several calls belong together, hold the reader for all of them with
session(). Otherwise another thread could authenticate a different sector
between your authentication and your read:
The schema and wallet below use sessions for you.
Named fields: card schemas¶
Describe what your card holds once, then read and write it by name:
import datetime as dt
from mifarepy.schema import CardSchema, Field
STUDENT = CardSchema(
Field('student_id', sector=1, block=0, type='uint32'),
Field('active', sector=1, block=0, offset=4, type='bool'),
Field('name', sector=1, block=1, type='str', length=16),
Field('valid_until', sector=1, block=2, type='date'),
)
STUDENT.write(reader, {'student_id': 1042, 'name': 'Ayesha Khan',
'valid_until': dt.date(2027, 6, 30), 'active': True})
print(STUDENT.read(reader))
# {'student_id': 1042, 'active': True, 'name': 'Ayesha Khan', 'valid_until': datetime.date(2027, 6, 30)}
| Type | Bytes | Python value |
|---|---|---|
uint8, uint16, uint32, uint64 |
1, 2, 4, 8 | int, 0 and up |
int8, int16, int32, int64 |
1, 2, 4, 8 | int, signed |
bool |
1 | bool |
date |
2 | datetime.date (days since 2000-01-01) |
datetime |
4 | datetime.datetime (seconds since 1970, stored in UTC) |
str |
length |
str, zero-padded, UTF-8 by default |
bytes |
length |
bytes, zero-padded |
- A field sits inside one 16-byte data block, at
offset. Integers are little-endian unlessbyteorder='big'. - The schema refuses overlapping fields, fields in a sector trailer and the manufacturer block, and values that don't fit, before anything is written.
write()only changes the fields you pass: it reads each block, changes those bytes, writes it and reads it back.- Pass
keys=(aKeyRing, a list, or one key) when the sectors don't use the factory key.
A wallet that survives a pulled card¶
If a card leaves the field while a block is being written, that block can end
up half old, half new. A Wallet keeps the balance twice, in a main block and
a backup block, and repairs whichever copy an interrupted change damaged:
from mifarepy.wallet import InsufficientFundsError, Wallet
wallet = Wallet(reader, sector=2, keys=ring) # main copy in block 0, backup in block 1
wallet.create(0) # once, on a new card
wallet.top_up(500) # returns the new balance
try:
wallet.spend(120)
except InsufficientFundsError as exc:
print('Only', exc.balance, 'left')
print(wallet.balance()) # 380
How it stays consistent:
- Each copy is a MIFARE value block, so a half-written copy fails its own check. A counter in the block's address byte goes up with every change.
- A change writes the main block, reads it back, then writes the backup.
- When reading, a damaged main block means the change didn't happen: the
backup is copied back. A damaged or older backup means it did: the main
block is copied over it.
wallet.last_recoverysays what was repaired.
Balances are whole numbers from 0 to 2,147,483,647: store cents, not dollars.
max_balance= caps top-ups.
Which key may change the balance
Every change writes both blocks, so the key needs the write right. With
the value access preset, that is Key B.
The card is not the bank
Anyone who can copy a card can copy its balance. For real money, keep the authoritative balance on your server and use the card balance for offline use and display.
Testing all of this without a reader¶
The simulator can do what goes wrong in real life:
from mifarepy import MifareReader, NoCardError
from mifarepy.simulator import SimulatedCard
from mifarepy.wallet import Wallet
card = SimulatedCard()
reader = MifareReader.simulated(card)
wallet = Wallet(reader, sector=1)
wallet.create(500)
reader.serial.tear_next_write(keep=6) # the next block write stops after 6 bytes
try:
wallet.spend(200)
except NoCardError:
pass # the card "left" mid-write
reader.serial.place_card(card)
assert wallet.balance() == 500 # the spend didn't happen, and the main block is repaired
reader.serial.unplug() and replug() act like pulling and reconnecting the
USB cable, for testing card_events() and reconnect().