-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrfid.py
64 lines (49 loc) · 1.83 KB
/
rfid.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
import CHIP_IO.GPIO as GPIO
import spidev
from MFRC522 import MFRC522
import time
class MFRC522_SPI():
"""
A class that handles reading/writing to an MFRC522 RFID card reader
"""
POLLING_INTERVAL = 1.0
def __init__(self, spi_bus, spi_device, reset_pin=None):
self.spi_bus = spi_bus
self.spi_device = spi_device
self.reset_pin = reset_pin
def initialize(self):
self.reader = MFRC522.Reader(self.spi_bus, self.spi_device, self.reset_pin)
self.current_uid = None
self.listening = False
def cleanup(self):
self.listening = False
GPIO.output(self.reset_pin, GPIO.LOW)
GPIO.cleanup()
def listen(self, onnewcard):
"""
Listen for changes, calling onnewcard when we get a new card or one changes
"""
self.listening = True
while self.listening:
uid, data = self.read_card()
#"Debounce" when we sometimes can't read a card
if uid is None and self.current_uid is not None:
time.sleep(self.POLLING_INTERVAL)
uid, data = self.read_card()
if uid == self.current_uid:
time.sleep(self.POLLING_INTERVAL)
continue
self.current_uid = uid
onnewcard(uid, None)
time.sleep(self.POLLING_INTERVAL)
def read_card(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 or uid is None:
return None, None
#convert list of ints to hex string
card_id = "".join(["%0.2X" % (val) for val in uid])
#TODO: Figure out how to get data later
return card_id, None