79 lines
2.4 KiB
Python
79 lines
2.4 KiB
Python
import time
|
|
from datetime import datetime, timedelta
|
|
|
|
from smartcard.CardRequest import CardRequest
|
|
from smartcard.Exceptions import CardConnectionException, NoCardException
|
|
from smartcard.CardConnection import CardConnection
|
|
from smartcard.util import toHexString
|
|
|
|
from pynput.keyboard import Controller
|
|
|
|
from card_reader import read_card
|
|
|
|
|
|
class NfcReaderService:
|
|
def __init__(self) -> None:
|
|
self._is_running = True
|
|
self._last_uid = None
|
|
self._keyboard = Controller()
|
|
self._last_write = datetime(1900, 1, 1)
|
|
|
|
def run(self) -> None:
|
|
print("Reader ready.")
|
|
|
|
while self._is_running:
|
|
try:
|
|
time.sleep(0.1)
|
|
card_request = CardRequest(timeout=None)
|
|
print("Waiting for card...")
|
|
card_service = card_request.waitforcard()
|
|
connection = card_service.connection
|
|
print("Connected to card!")
|
|
|
|
try:
|
|
connection.connect(CardConnection.T1_protocol)
|
|
|
|
GET_UID = [0xFF, 0xCA, 0x00, 0x00, 0x00]
|
|
uid, sw1, sw2 = connection.transmit(GET_UID)
|
|
|
|
if sw1 != 0x90:
|
|
raise CardConnectionException("UID read failed")
|
|
|
|
uid_hex = toHexString(uid)
|
|
|
|
if uid_hex == self._last_uid:
|
|
connection.disconnect()
|
|
time.sleep(1)
|
|
self._last_uid = None
|
|
continue
|
|
|
|
self._last_uid = uid_hex
|
|
|
|
user_id = read_card(connection)
|
|
if user_id is not None:
|
|
now = datetime.now()
|
|
if now - self._last_write > timedelta(seconds=2):
|
|
self._keyboard.type(str(user_id))
|
|
self._last_write = now
|
|
|
|
except (CardConnectionException, NoCardException):
|
|
time.sleep(0.5)
|
|
|
|
finally:
|
|
try:
|
|
connection.disconnect()
|
|
except:
|
|
pass
|
|
|
|
time.sleep(0.5)
|
|
|
|
except (KeyboardInterrupt, SystemExit):
|
|
self.stop()
|
|
|
|
def stop(self) -> None:
|
|
self._is_running = False
|
|
|
|
if __name__ == "__main__":
|
|
service = NfcReaderService()
|
|
service.run()
|