Added docstrings and license information.

Moved main.py contents to documentation as a simple example.
This commit is contained in:
2025-02-18 22:09:50 +01:00
parent ba4c5175eb
commit 5cda9891f5
3 changed files with 36 additions and 17 deletions

View File

@@ -1 +1,5 @@
'''
SPDX-License-Identifier: MIT
Copyright (c) 2025 Stefan Kratochwil (Kratochwil-LA@gmx.de)
'''
from nfc.nfc import Nfc

View File

@@ -1,12 +0,0 @@
import asyncio
from nfc import Nfc
async def main():
n = Nfc()
while True:
await asyncio.sleep_ms(500)
print(f'{n.get_last_uid()}')
asyncio.run(main())

View File

@@ -1,24 +1,49 @@
'''
SPDX-License-Identifier: MIT
Copyright (c) 2025 Stefan Kratochwil (Kratochwil-LA@gmx.de)
'''
import asyncio
import time
from mfrc522 import MFRC522
class Nfc:
'''
This class implements an asyncio task which continuously polls the mfrc522 nfc reader. If a new
nfc tag was detected, the uid of the tag is stored alongside with the current system time. This
information can be retrieved again.
Usage example:
import asyncio
from nfc import Nfc
async def main():
n = Nfc()
while True:
await asyncio.sleep_ms(500)
print(f'{n.get_last_uid()}')
asyncio.run(main())
'''
def __init__(self):
self.reader = MFRC522(spi_id=1, sck=10, miso=12, mosi=11, cs=13, rst=9, tocard_retries=10)
self.last_uid = None
self.last_uid_timestamp = None
self.task = asyncio.create_task(self._reader_poll_task())
@staticmethod
def uid_to_string(uid: list):
'''
Helper function to convert a nfc tag uid to a readable string.
'''
return '0x' + ''.join(f'{i:02x}' for i in uid)
async def _reader_poll_task(self, poll_interval_ms: int = 50) -> list:
print('reader_poll_task alive')
'''
Periodically polls the nfc reader. Stores tag uid and timestamp if a new tag was found.
'''
while True:
self.reader.init()
@@ -32,6 +57,8 @@ class Nfc:
await asyncio.sleep_ms(poll_interval_ms)
def get_last_uid(self):
'''
Returns the last read nfc tag uid alongside with the timestamp it was stored at.
'''
return self.last_uid, self.last_uid_timestamp