forked from pimylifeup/MFRC522-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleMFRC522.py
93 lines (78 loc) · 2.8 KB
/
SimpleMFRC522.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# Code by Simon Monk https://github.com/simonmonk/
import MFRC522
import RPi.GPIO as GPIO
class SimpleMFRC522:
READER = None;
KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]
def __init__(self):
self.READER = MFRC522.MFRC522()
def read(self):
id, text = self.read_no_block()
while not id:
id, text = self.read_no_block()
return id, text
def read_id(self):
id = self.read_id_no_block()
while not id:
id = self.read_id_no_block()
return id
def read_id_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
return self.uid_to_num(uid)
def read_no_block(self):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
data = []
text_read = ''
if status == self.READER.MI_OK:
for block_num in self.BLOCK_ADDRS:
block = self.READER.MFRC522_Read(block_num)
if block:
data += block
if data:
text_read = ''.join(chr(i) for i in data)
self.READER.MFRC522_StopCrypto1()
return id, text_read
def write(self, text):
id, text_in = self.write_no_block(text)
while not id:
id, text_in = self.write_no_block(text)
return id, text_in
def write_no_block(self, text):
(status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL)
if status != self.READER.MI_OK:
return None, None
(status, uid) = self.READER.MFRC522_Anticoll()
if status != self.READER.MI_OK:
return None, None
id = self.uid_to_num(uid)
self.READER.MFRC522_SelectTag(uid)
status = self.READER.MFRC522_Auth(self.READER.PICC_AUTHENT1A, 11, self.KEY, uid)
self.READER.MFRC522_Read(11)
if status == self.READER.MI_OK:
data = bytearray()
data.extend(bytearray(text.ljust(len(self.BLOCK_ADDRS) * 16).encode('ascii')))
i = 0
for block_num in self.BLOCK_ADDRS:
self.READER.MFRC522_Write(block_num, data[(i*16):(i+1)*16])
i += 1
self.READER.MFRC522_StopCrypto1()
return id, text[0:(len(self.BLOCK_ADDRS) * 16)]
def uid_to_num(self, uid):
n = 0
for i in range(0, 5):
n = n * 256 + uid[i]
return n