-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreader.py
79 lines (61 loc) · 2.33 KB
/
reader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import logging
from MFRC522 import MFRC522
class Card(object):
def __init__(self, cid=None, block=0, content=None):
self.cid = cid
self.block = block
self.content = content
def __str__(self):
return '(%r@%r, %r)' % (self.cid, self.block, self.content)
def __repr__(self):
return 'Card(%r, %r, %r)' % (self.cid, self.block, self.content)
def read_card(block=56, sector=None, key=None):
if key is None:
key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]
if isinstance(key, str):
logging.debug(key)
try:
new_key = []
for i in range(0, 12, 2):
# split key into aa, bb, cc, ... format
new_key.append(int(key[i: i+2], 16))
key = new_key
except Exception as e:
raise Exception('[Key format error] %s' % e)
# If sector is set, ignore block
if sector is not None:
block = sector * 4 # 4 blocks per sector
sector = None
with MFRC522.MFRC522Reader() as reader:
card = Card(block=block)
# Scan for cards
(status, TagType) = reader.MFRC522_Request(reader.PICC_REQIDL)
# If a card is found
if status == reader.MI_OK:
logging.debug("Card detacted")
else:
return None
# Get the cid of the card
status, cid = reader.MFRC522_Anticoll()
if status != reader.MI_OK:
logging.error('fail to read card id')
raise Exception('Card error')
# If we have the cid, prepare to read the content
card.cid = '%02x%02x%02x%02x' % (cid[0], cid[1], cid[2], cid[3])
logging.debug("card found (%s)", card.cid)
reader.MFRC522_SelectTag(cid)
status = reader.MFRC522_Auth(reader.PICC_AUTHENT1A, block, key, cid)
# read the content
if status != reader.MI_OK:
logging.error('fail to read card content')
raise Exception('Card error')
data = reader.MFRC522_Read(block)
card.content = "".join([chr(i) for i in data if i != 0])
logging.debug('get card content (%s)', card.content)
# stop raeding
reader.MFRC522_StopCrypto1()
return card
if __name__ == '__main__':
while True:
card = read_card(block=0, key=[0xff, 0xff, 0xff, 0xff, 0xff, 0xff])
print(card)