From 0574027a975c3e45ca7c3dbb93e5d3705d54be84 Mon Sep 17 00:00:00 2001 From: Benjamin Braatz Date: Mon, 22 Aug 2022 21:14:09 +0200 Subject: [PATCH] Different approach: Only short-lived operation in executor --- controlpi_plugins/nfc.py | 52 +++++++++++++--------------------------- 1 file changed, 16 insertions(+), 36 deletions(-) diff --git a/controlpi_plugins/nfc.py b/controlpi_plugins/nfc.py index dbd601c..98e1890 100644 --- a/controlpi_plugins/nfc.py +++ b/controlpi_plugins/nfc.py @@ -53,44 +53,24 @@ class NFCReader(BasePlugin): 'card': card})) def _poll_reader(self, loop) -> None: - while loop.is_running(): - card = "" - loop.call_soon_threadsafe( - self._set_state, False, "") - readers = smartcard.System.readers() - while not readers and loop.is_running(): - time.sleep(10) - readers = smartcard.System.readers() + readers = smartcard.System.readers() + if readers: reader = readers[0] connection = reader.createConnection() - while loop.is_running(): - time.sleep(0.5) - try: - connection.connect() - data, sw1, sw2 = connection.transmit([0xFF, 0xCA, 0x00, - 0x00, 0x00]) - identifier = bytes(data).hex() - if identifier != card: - if card: - loop.call_soon_threadsafe( - self._set_state, False, "") - card = identifier - if card: - loop.call_soon_threadsafe( - self._set_state, True, card) - except smartcard.Exceptions.NoCardException: - if card: - card = "" - loop.call_soon_threadsafe( - self._set_state, False, "") - except smartcard.Exceptions.CardConnectionException: - if card: - card = "" - loop.call_soon_threadsafe( - self._set_state, False, "") - break + try: + connection.connect() + data, sw1, sw2 = connection.transmit([0xFF, 0xCA, 0x00, + 0x00, 0x00]) + card = bytes(data).hex() + loop.call_soon_threadsafe(self._set_state, True, card) + except Exception: + loop.call_soon_threadsafe(self._set_state, False, "") + else: + loop.call_soon_threadsafe(self._set_state, False, "") async def run(self) -> None: """Run no code proactively.""" - loop = asyncio.get_running_loop() - loop.run_in_executor(None, self._poll_reader, loop) + while True: + loop = asyncio.get_running_loop() + loop.run_in_executor(None, self._poll_reader, loop) + await asyncio.sleep(0.5) -- 2.34.1