From 548b57d82fa7d20da4c8708fb6f7f9e4ffb386e4 Mon Sep 17 00:00:00 2001 From: Declan Shanaghy Date: Tue, 19 May 2020 00:48:12 -0700 Subject: [PATCH 1/7] Add support in SimpleMFRC522 to read or write any sector --- mfrc522/MFRC522.py | 43 ++++++---- mfrc522/SimpleMFRC522.py | 171 ++++++++++++++++++++------------------- setup.py | 7 +- 3 files changed, 121 insertions(+), 100 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 1698351..6ec1b3a 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -26,6 +26,7 @@ import time import logging + class MFRC522: MAX_LEN = 16 @@ -125,7 +126,8 @@ class MFRC522: serNum = [] - def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, debugLevel='WARNING'): + def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, + debugLevel='WARNING'): self.spi = spidev.SpiDev() self.spi.open(bus, device) self.spi.max_speed_hz = spd @@ -136,18 +138,18 @@ def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, debugL self.logger.setLevel(level) gpioMode = GPIO.getmode() - + if gpioMode is None: GPIO.setmode(pin_mode) else: pin_mode = gpioMode - + if pin_rst == -1: if pin_mode == 11: pin_rst = 15 else: pin_rst = 22 - + GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) self.MFRC522_Init() @@ -256,7 +258,8 @@ def MFRC522_Request(self, reqMode): self.Write_MFRC522(self.BitFramingReg, 0x07) TagType.append(reqMode) - (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, TagType) + (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, + TagType) if ((status != self.MI_OK) | (backBits != 0x10)): status = self.MI_ERR @@ -274,7 +277,8 @@ def MFRC522_Anticoll(self): serNum.append(self.PICC_ANTICOLL) serNum.append(0x20) - (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, serNum) + (status, backData, backBits) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, + serNum) if (status == self.MI_OK): i = 0 @@ -312,14 +316,15 @@ def MFRC522_SelectTag(self, serNum): buf = [] buf.append(self.PICC_SElECTTAG) buf.append(0x70) - + for i in range(5): buf.append(serNum[i]) pOut = self.CalulateCRC(buf) buf.append(pOut[0]) buf.append(pOut[1]) - (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf) + (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, + buf) if (status == self.MI_OK) and (backLen == 0x18): self.logger.debug("Size: " + str(backData[0])) @@ -345,7 +350,8 @@ def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): buff.append(serNum[i]) # Now we start the authentication itself - (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, buff) + (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_AUTHENT, + buff) # Check if an error occurred if not (status == self.MI_OK): @@ -366,7 +372,8 @@ def MFRC522_Read(self, blockAddr): pOut = self.CalulateCRC(recvData) recvData.append(pOut[0]) recvData.append(pOut[1]) - (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData) + (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, + recvData) if not (status == self.MI_OK): self.logger.error("Error while reading!") @@ -383,11 +390,14 @@ def MFRC522_Write(self, blockAddr, writeData): crc = self.CalulateCRC(buff) buff.append(crc[0]) buff.append(crc[1]) - (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buff) - if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A): + (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, + buff) + if not (status == self.MI_OK) or not (backLen == 4) or not ( + (backData[0] & 0x0F) == 0x0A): status = self.MI_ERR - self.logger.debug("%s backdata &0x0F == 0x0A %s" % (backLen, backData[0] & 0x0F)) + self.logger.debug( + "%s backdata &0x0F == 0x0A %s" % (backLen, backData[0] & 0x0F)) if status == self.MI_OK: buf = [] for i in range(16): @@ -396,13 +406,14 @@ def MFRC522_Write(self, blockAddr, writeData): crc = self.CalulateCRC(buf) buf.append(crc[0]) buf.append(crc[1]) - (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf) - if not (status == self.MI_OK) or not (backLen == 4) or not ((backData[0] & 0x0F) == 0x0A): + (status, backData, backLen) = self.MFRC522_ToCard( + self.PCD_TRANSCEIVE, buf) + if not (status == self.MI_OK) or not (backLen == 4) or not ( + (backData[0] & 0x0F) == 0x0A): self.logger.error("Error while writing") if status == self.MI_OK: self.logger.debug("Data written") - def MFRC522_DumpClassic1K(self, key, uid): for i in range(64): status = self.MFRC522_Auth(self.PICC_AUTHENT1A, i, key, uid) diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 91eca06..3098492 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -2,89 +2,98 @@ from . import MFRC522 import RPi.GPIO as GPIO - + + class SimpleMFRC522: + DEFAULT_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] + _mfrc522 = MFRC522() + _key = None + + def __init__(self, key=None): + if key is None: + key = SimpleMFRC522.DEFAULT_KEY + self._key = key + + 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._mfrc522.MFRC522_Request( + self._mfrc522.PICC_REQIDL) + if status != self._mfrc522.MI_OK: + return None + (status, uid) = self._mfrc522.MFRC522_Anticoll() + if status != self._mfrc522.MI_OK: + return None + return self.uid_to_num(uid) + + def read(self, trailer=11, blocks=(8, 9, 10)): + id, text = self.read_no_block(trailer=trailer, blocks=blocks) + while not id: + id, text = self.read_no_block(trailer=trailer, blocks=blocks) + return id, text - READER = None - - KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] - BLOCK_ADDRS = [8, 9, 10] - - def __init__(self): - self.READER = MFRC522() - - def read(self): - id, text = self.read_no_block() - while not id: - id, text = self.read_no_block() - return id, text + def read_no_block(self, trailer=11, blocks=(8, 9, 10)): + (status, TagType) = self._mfrc522.MFRC522_Request( + self._mfrc522.PICC_REQIDL) + if status != self._mfrc522.MI_OK: + return None, None + (status, uid) = self._mfrc522.MFRC522_Anticoll() + if status != self._mfrc522.MI_OK: + return None, None + id = self.uid_to_num(uid) + self._mfrc522.MFRC522_SelectTag(uid) + status = self._mfrc522.MFRC522_Auth(self._mfrc522.PICC_AUTHENT1A, + trailer, self._key, uid) + data = [] + text_read = '' + if status == self._mfrc522.MI_OK: + for block_num in blocks: + block = self._mfrc522.MFRC522_Read(block_num) + if block: + data += block + if data: + text_read = ''.join(chr(i) for i in data) + self._mfrc522.MFRC522_StopCrypto1() + return id, text_read - def read_id(self): - id = self.read_id_no_block() - while not id: - id = self.read_id_no_block() - return id + def write(self, text, trailer=11, blocks=(8, 9, 10)): + id, text_in = self.write_no_block( + text, trailer=trailer, blocks=blocks) + while not id: + id, text_in = self.write_no_block( + text, trailer=trailer, blocks=blocks) + return id, text_in - def read_id_no_block(self): - (status, TagType) = self.READER.MFRC522_Request(self.READER.PICC_REQIDL) - if status != self.READER.MI_OK: - return None - (status, uid) = self.READER.MFRC522_Anticoll() - if status != self.READER.MI_OK: - return 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, trailer=11, blocks=(8, 9, 10)): + (status, TagType) = self._mfrc522.MFRC522_Request( + self._mfrc522.PICC_REQIDL) + if status != self._mfrc522.MI_OK: + return None, None + (status, uid) = self._mfrc522.MFRC522_Anticoll() + if status != self._mfrc522.MI_OK: + return None, None + id = self.uid_to_num(uid) + self._mfrc522.MFRC522_SelectTag(uid) + status = self._mfrc522.MFRC522_Auth( + self._mfrc522.PICC_AUTHENT1A, trailer, self._key, uid) + self._mfrc522.MFRC522_Read(trailer) + if status == self._mfrc522.MI_OK: + data = bytearray() + data.extend(bytearray(text.ljust(len(blocks) * 16).encode('ascii'))) + i = 0 + for block_num in blocks: + self._mfrc522.MFRC522_Write(block_num, + data[(i * 16):(i + 1) * 16]) + i += 1 + self._mfrc522.MFRC522_StopCrypto1() + return id, text[0:(len(blocks) * 16)] - 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 + def uid_to_num(self, uid): + n = 0 + for i in range(0, 5): + n = n * 256 + uid[i] + return n diff --git a/setup.py b/setup.py index eaeea22..b792e2a 100644 --- a/setup.py +++ b/setup.py @@ -5,10 +5,11 @@ setuptools.setup( name="mfrc522", - version="0.0.7", + version="0.0.8", author="Pi My Life Up", author_email="support@pimylifeup.com", - description="A library to integrate the MFRC522 RFID readers with the Raspberry Pi", + description="A library to integrate the MFRC522 RFID readers " + "with the Raspberry Pi", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/pimylifeup/MFRC522-python", @@ -16,7 +17,7 @@ install_requires=[ 'RPi.GPIO', 'spidev' - ], + ], classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", From afcbbf8cd89cbc5b4921fbfed75b40eb0fb0b4c5 Mon Sep 17 00:00:00 2001 From: Declan Shanaghy Date: Mon, 22 Jun 2020 10:35:39 -0700 Subject: [PATCH 2/7] Add parameter to allow multiple retries --- mfrc522/MFRC522.py | 29 ++++++----- mfrc522/SimpleMFRC522.py | 101 ++++++++++++++++++++++++++++++++------- setup.py | 2 +- 3 files changed, 99 insertions(+), 33 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 6ec1b3a..4fe8824 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -126,19 +126,19 @@ class MFRC522: serNum = [] - def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, - debugLevel='WARNING'): + def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, log_verbose=False): + self.logger = logging.getLogger(self.__class__.__name__) + if log_verbose: + self.logger.setLevel(logging.DEBUG) + else: + self.logger.setLevel(logging.INFO) + + self.logger.info('Setting up SPI') self.spi = spidev.SpiDev() self.spi.open(bus, device) self.spi.max_speed_hz = spd - self.logger = logging.getLogger('mfrc522Logger') - self.logger.addHandler(logging.StreamHandler()) - level = logging.getLevelName(debugLevel) - self.logger.setLevel(level) - gpioMode = GPIO.getmode() - if gpioMode is None: GPIO.setmode(pin_mode) else: @@ -150,8 +150,11 @@ def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, else: pin_rst = 22 + self.logger.info('Setting up RST') GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) + + self.logger.info('Setting up MFRC522') self.MFRC522_Init() def MFRC522_Reset(self): @@ -251,8 +254,6 @@ def MFRC522_ToCard(self, command, sendData): return (status, backData, backLen) def MFRC522_Request(self, reqMode): - status = None - backBits = None TagType = [] self.Write_MFRC522(self.BitFramingReg, 0x07) @@ -267,9 +268,7 @@ def MFRC522_Request(self, reqMode): return (status, backBits) def MFRC522_Anticoll(self): - backData = [] serNumCheck = 0 - serNum = [] self.Write_MFRC522(self.BitFramingReg, 0x00) @@ -312,7 +311,6 @@ def CalulateCRC(self, pIndata): return pOutData def MFRC522_SelectTag(self, serNum): - backData = [] buf = [] buf.append(self.PICC_SElECTTAG) buf.append(0x70) @@ -328,9 +326,9 @@ def MFRC522_SelectTag(self, serNum): if (status == self.MI_OK) and (backLen == 0x18): self.logger.debug("Size: " + str(backData[0])) - return backData[0] + return status, backData[0] else: - return 0 + return status, None def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): buff = [] @@ -356,6 +354,7 @@ def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): # Check if an error occurred if not (status == self.MI_OK): self.logger.error("AUTH ERROR!!") + if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0: self.logger.error("AUTH ERROR(status2reg & 0x08) != 0") diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 3098492..27e272d 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -1,24 +1,41 @@ # Code by Simon Monk https://github.com/simonmonk/ +import logging +import time + from . import MFRC522 import RPi.GPIO as GPIO +import sys class SimpleMFRC522: DEFAULT_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] - _mfrc522 = MFRC522() + + _log_verbose = None + _log = None + _mfrc522 = None _key = None - def __init__(self, key=None): + def __init__(self, key=None, log_verbose=False): + self._log = logging.getLogger(self.__class__.__name__) + self._log_verbose = log_verbose + if log_verbose: + self._log.setLevel(logging.DEBUG) + else: + self._log.setLevel(logging.INFO) + if key is None: key = SimpleMFRC522.DEFAULT_KEY self._key = key + self._mfrc522 = MFRC522(log_verbose=log_verbose) - def read_id(self): + def read_id(self, attempts=sys.maxsize): id = self.read_id_no_block() - while not id: + tries = 1 + while not id and tries < attempts: id = self.read_id_no_block() - return id + tries += 1 + return id, tries def read_id_no_block(self): (status, TagType) = self._mfrc522.MFRC522_Request( @@ -30,43 +47,93 @@ def read_id_no_block(self): return None return self.uid_to_num(uid) - def read(self, trailer=11, blocks=(8, 9, 10)): + def read(self, trailer=11, blocks=(8, 9, 10), attempts=sys.maxsize): id, text = self.read_no_block(trailer=trailer, blocks=blocks) - while not id: + tries = 1 + while not id and tries < attempts: id, text = self.read_no_block(trailer=trailer, blocks=blocks) - return id, text + tries += 1 + return id, text, tries + + def log_time(self, action, start): + end = time.time() + self._log.debug({ + 'action': action, + 'start': f'{start:.5f}', + 'end': f'{end:.5f}', + 'duration': f'{end - start:.5f}', + }) + + def log_error_with_time(self, error, status, start): + if self._log_verbose: + end = time.time() + self._log.error({ + 'error': error, + 'status': status, + 'start': f'{start:.5f}', + 'end': f'{end:.5f}', + 'duration': f'{end - start:.5f}', + }) def read_no_block(self, trailer=11, blocks=(8, 9, 10)): - (status, TagType) = self._mfrc522.MFRC522_Request( + start = time.time() + status, _ = self._mfrc522.MFRC522_Request( self._mfrc522.PICC_REQIDL) if status != self._mfrc522.MI_OK: + self.log_error_with_time('MFRC522_Request', status, start) return None, None - (status, uid) = self._mfrc522.MFRC522_Anticoll() + self.log_time('MFRC522_Request', start) + + start = time.time() + status, uid = self._mfrc522.MFRC522_Anticoll() if status != self._mfrc522.MI_OK: + self.log_error_with_time('MFRC522_Anticoll', status, start) return None, None - id = self.uid_to_num(uid) - self._mfrc522.MFRC522_SelectTag(uid) + self.log_time('MFRC522_Anticoll', start) + + start = time.time() + status, _ = self._mfrc522.MFRC522_SelectTag(uid) + if status != self._mfrc522.MI_OK: + self.log_error_with_time('MFRC522_SelectTag', status, start) + return None, None + self.log_time('MFRC522_SelectTag', start) + + start = time.time() status = self._mfrc522.MFRC522_Auth(self._mfrc522.PICC_AUTHENT1A, trailer, self._key, uid) + if status != self._mfrc522.MI_OK: + self.log_error_with_time('MFRC522_Auth', status, start) + return None, None + self.log_time('MFRC522_Auth', start) + data = [] text_read = '' if status == self._mfrc522.MI_OK: for block_num in blocks: + start = time.time() block = self._mfrc522.MFRC522_Read(block_num) + self.log_time('MFRC522_Read', start) if block: data += block if data: text_read = ''.join(chr(i) for i in data) + + start = time.time() self._mfrc522.MFRC522_StopCrypto1() + self.log_time('MFRC522_StopCrypto1', start) + + id = self.uid_to_num(uid) return id, text_read - def write(self, text, trailer=11, blocks=(8, 9, 10)): - id, text_in = self.write_no_block( + def write(self, text, trailer=11, blocks=(8, 9, 10), attempts=sys.maxsize): + id, text_out = self.write_no_block( text, trailer=trailer, blocks=blocks) - while not id: - id, text_in = self.write_no_block( + tries = 1 + while not id and tries < attempts: + id, text_out = self.write_no_block( text, trailer=trailer, blocks=blocks) - return id, text_in + tries += 1 + return id, text_out, tries def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): (status, TagType) = self._mfrc522.MFRC522_Request( diff --git a/setup.py b/setup.py index b792e2a..a59e839 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="mfrc522", - version="0.0.8", + version="0.0.9", author="Pi My Life Up", author_email="support@pimylifeup.com", description="A library to integrate the MFRC522 RFID readers " From aed7b8debc62187e2fe56e9752990b6b47a15be2 Mon Sep 17 00:00:00 2001 From: Declan Shanaghy Date: Tue, 24 Nov 2020 17:43:16 -0800 Subject: [PATCH 3/7] Allow user to specify pin mode --- mfrc522/MFRC522.py | 2 +- mfrc522/SimpleMFRC522.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 4fe8824..5cb6f03 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -126,7 +126,7 @@ class MFRC522: serNum = [] - def __init__(self, bus=0, device=0, spd=1000000, pin_mode=10, pin_rst=-1, log_verbose=False): + def __init__(self, bus=0, device=0, spd=1000000, pin_mode=GPIO.BOARD, pin_rst=-1, log_verbose=False): self.logger = logging.getLogger(self.__class__.__name__) if log_verbose: self.logger.setLevel(logging.DEBUG) diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 27e272d..0661a94 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -16,7 +16,7 @@ class SimpleMFRC522: _mfrc522 = None _key = None - def __init__(self, key=None, log_verbose=False): + def __init__(self, key=None, log_verbose=False, pin_mode=GPIO.BOARD): self._log = logging.getLogger(self.__class__.__name__) self._log_verbose = log_verbose if log_verbose: @@ -27,7 +27,7 @@ def __init__(self, key=None, log_verbose=False): if key is None: key = SimpleMFRC522.DEFAULT_KEY self._key = key - self._mfrc522 = MFRC522(log_verbose=log_verbose) + self._mfrc522 = MFRC522(log_verbose=log_verbose, pin_mode=pin_mode) def read_id(self, attempts=sys.maxsize): id = self.read_id_no_block() From 298050dbbf2283098c01071c50608146265f1695 Mon Sep 17 00:00:00 2001 From: Declan Shanaghy <375100+declanshanaghy@users.noreply.github.com> Date: Sun, 27 Apr 2025 22:45:45 -0700 Subject: [PATCH 4/7] Enhanced RFID Logging 1. Added detailed structured logging throughout MFRC522.py: - Added debug logging for all major operations with hex values - Improved error logging with detailed context - Added start/complete logging for all card operations 2. Improved SimpleMFRC522.py: - Changed default log_verbose to True - Added hex value formatting for status codes - Added more detailed debug logging - Enhanced error reporting These changes improve debugging capabilities for RFID operations by providing more context and structured logging information, making it easier to diagnose issues with card reading and writing. --- mfrc522/MFRC522.py | 159 ++++++++++++++++++++++++++++++++++++--- mfrc522/SimpleMFRC522.py | 67 ++++++++++++++--- 2 files changed, 203 insertions(+), 23 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 5cb6f03..2177f80 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -196,6 +196,12 @@ def MFRC522_ToCard(self, command, sendData): lastBits = None n = 0 + # Log command as hex value + self.logger.debug({ + 'action': 'MFRC522_ToCard_start', + 'command': f'0x{command:02X}' # Log command as hex value + }) + if command == self.PCD_AUTHENT: irqEn = 0x12 waitIRq = 0x10 @@ -251,11 +257,25 @@ def MFRC522_ToCard(self, command, sendData): else: status = self.MI_ERR + # Log status and command as hex values + self.logger.debug({ + 'action': 'MFRC522_ToCard_complete', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}', # Log status as hex value + 'backLen': backLen + }) + return (status, backData, backLen) def MFRC522_Request(self, reqMode): TagType = [] + # Log reqMode as hex value + self.logger.debug({ + 'action': 'MFRC522_Request_start', + 'reqMode': f'0x{reqMode:02X}' # Log reqMode as hex value + }) + self.Write_MFRC522(self.BitFramingReg, 0x07) TagType.append(reqMode) @@ -265,12 +285,25 @@ def MFRC522_Request(self, reqMode): if ((status != self.MI_OK) | (backBits != 0x10)): status = self.MI_ERR + # Log status and reqMode as hex values + self.logger.debug({ + 'action': 'MFRC522_Request_complete', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) + return (status, backBits) def MFRC522_Anticoll(self): serNumCheck = 0 serNum = [] + # Log start of anticoll + self.logger.debug({ + 'action': 'MFRC522_Anticoll_start', + 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value + }) + self.Write_MFRC522(self.BitFramingReg, 0x00) serNum.append(self.PICC_ANTICOLL) @@ -289,6 +322,12 @@ def MFRC522_Anticoll(self): else: status = self.MI_ERR + # Log status as hex value + self.logger.debug({ + 'action': 'MFRC522_Anticoll_complete', + 'status': f'0x{status:02X}' # Log status as hex value + }) + return (status, backData) def CalulateCRC(self, pIndata): @@ -315,6 +354,13 @@ def MFRC522_SelectTag(self, serNum): buf.append(self.PICC_SElECTTAG) buf.append(0x70) + # Log start of select tag + self.logger.debug({ + 'action': 'MFRC522_SelectTag_start', + 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value + 'select_tag': f'0x{self.PICC_SElECTTAG:02X}' # Log select tag as hex value + }) + for i in range(5): buf.append(serNum[i]) @@ -324,15 +370,32 @@ def MFRC522_SelectTag(self, serNum): (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, buf) + # Log status as hex value if (status == self.MI_OK) and (backLen == 0x18): - self.logger.debug("Size: " + str(backData[0])) + self.logger.debug({ + 'action': 'MFRC522_SelectTag_complete', + 'status': f'0x{status:02X}', # Log status as hex value + 'size': backData[0] + }) return status, backData[0] else: + self.logger.debug({ + 'action': 'MFRC522_SelectTag_failed', + 'status': f'0x{status:02X}' # Log status as hex value + }) return status, None def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): buff = [] + # Log start of auth with authMode as hex value + self.logger.debug({ + 'action': 'MFRC522_Auth_start', + 'authMode': f'0x{authMode:02X}', # Log authMode as hex value + 'blockAddr': BlockAddr, + 'command': f'0x{self.PCD_AUTHENT:02X}' # Log command as hex value + }) + # First byte should be the authMode (A or B) buff.append(authMode) @@ -353,10 +416,24 @@ def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): # Check if an error occurred if not (status == self.MI_OK): - self.logger.error("AUTH ERROR!!") + self.logger.error({ + 'error': "AUTH ERROR!!", + 'status': f'0x{status:02X}' # Log status as hex value + }) if not (self.Read_MFRC522(self.Status2Reg) & 0x08) != 0: - self.logger.error("AUTH ERROR(status2reg & 0x08) != 0") + status2reg = self.Read_MFRC522(self.Status2Reg) + self.logger.error({ + 'error': "AUTH ERROR(status2reg & 0x08) != 0", + 'status': f'0x{status:02X}', # Log status as hex value + 'status2reg': f'0x{status2reg:02X}' # Log status2reg as hex value + }) + + # Log completion with status as hex value + self.logger.debug({ + 'action': 'MFRC522_Auth_complete', + 'status': f'0x{status:02X}' # Log status as hex value + }) # Return the status return status @@ -371,13 +448,37 @@ def MFRC522_Read(self, blockAddr): pOut = self.CalulateCRC(recvData) recvData.append(pOut[0]) recvData.append(pOut[1]) + + # Log start of read operation + self.logger.debug({ + 'action': 'MFRC522_Read_start', + 'blockAddr': blockAddr, + 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value + }) + (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData) if not (status == self.MI_OK): - self.logger.error("Error while reading!") - + self.logger.error({ + 'error': "Error while reading!", + 'status': f'0x{status:02X}', # Log status as hex value + 'blockAddr': blockAddr + }) + + # Log completion with status as hex value + self.logger.debug({ + 'action': 'MFRC522_Read_complete', + 'status': f'0x{status:02X}', # Log status as hex value + 'blockAddr': blockAddr, + 'success': status == self.MI_OK + }) + if len(backData) == 16: - self.logger.debug("Sector " + str(blockAddr) + " " + str(backData)) + self.logger.debug({ + 'action': 'MFRC522_Read_data', + 'blockAddr': blockAddr, + 'data': str(backData) + }) return backData else: return None @@ -386,6 +487,15 @@ def MFRC522_Write(self, blockAddr, writeData): buff = [] buff.append(self.PICC_WRITE) buff.append(blockAddr) + + # Log start of write operation + self.logger.debug({ + 'action': 'MFRC522_Write_start', + 'blockAddr': blockAddr, + 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value + 'write_command': f'0x{self.PICC_WRITE:02X}' # Log write command as hex value + }) + crc = self.CalulateCRC(buff) buff.append(crc[0]) buff.append(crc[1]) @@ -394,9 +504,20 @@ def MFRC522_Write(self, blockAddr, writeData): if not (status == self.MI_OK) or not (backLen == 4) or not ( (backData[0] & 0x0F) == 0x0A): status = self.MI_ERR - - self.logger.debug( - "%s backdata &0x0F == 0x0A %s" % (backLen, backData[0] & 0x0F)) + self.logger.debug({ + 'action': 'MFRC522_Write_first_phase_failed', + 'status': f'0x{status:02X}', # Log status as hex value + 'backLen': backLen, + 'backData': str(backData) if backData else "None" + }) + + self.logger.debug({ + 'action': 'MFRC522_Write_first_phase', + 'backLen': backLen, + 'backData_check': f'0x{backData[0] & 0x0F:02X}', # Log as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) + if status == self.MI_OK: buf = [] for i in range(16): @@ -409,9 +530,19 @@ def MFRC522_Write(self, blockAddr, writeData): self.PCD_TRANSCEIVE, buf) if not (status == self.MI_OK) or not (backLen == 4) or not ( (backData[0] & 0x0F) == 0x0A): - self.logger.error("Error while writing") + self.logger.error({ + 'error': "Error while writing", + 'status': f'0x{status:02X}', # Log status as hex value + 'backLen': backLen, + 'backData': str(backData) if backData else "None" + }) if status == self.MI_OK: - self.logger.debug("Data written") + self.logger.debug({ + 'action': 'MFRC522_Write_complete', + 'status': f'0x{status:02X}', # Log status as hex value + 'blockAddr': blockAddr, + 'success': True + }) def MFRC522_DumpClassic1K(self, key, uid): for i in range(64): @@ -420,7 +551,11 @@ def MFRC522_DumpClassic1K(self, key, uid): if status == self.MI_OK: self.MFRC522_Read(i) else: - self.logger.error("Authentication error") + self.logger.error({ + 'error': "Authentication error", + 'status': f'0x{status:02X}', # Log status as hex value + 'block': i + }) def MFRC522_Init(self): self.MFRC522_Reset() diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 0661a94..62d5209 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -16,7 +16,7 @@ class SimpleMFRC522: _mfrc522 = None _key = None - def __init__(self, key=None, log_verbose=False, pin_mode=GPIO.BOARD): + def __init__(self, key=None, log_verbose=True, pin_mode=GPIO.BOARD): self._log = logging.getLogger(self.__class__.__name__) self._log_verbose = log_verbose if log_verbose: @@ -38,12 +38,21 @@ def read_id(self, attempts=sys.maxsize): return id, tries def read_id_no_block(self): - (status, TagType) = self._mfrc522.MFRC522_Request( - self._mfrc522.PICC_REQIDL) + reqMode = self._mfrc522.PICC_REQIDL + (status, TagType) = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: + self._log.error({ + 'action': 'read_id_no_block_request_failed', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return None (status, uid) = self._mfrc522.MFRC522_Anticoll() if status != self._mfrc522.MI_OK: + self._log.error({ + 'action': 'read_id_no_block_anticoll_failed', + 'status': f'0x{status:02X}' # Log status as hex value + }) return None return self.uid_to_num(uid) @@ -69,7 +78,7 @@ def log_error_with_time(self, error, status, start): end = time.time() self._log.error({ 'error': error, - 'status': status, + 'status': f'0x{status:02X}', # Log status as hex value 'start': f'{start:.5f}', 'end': f'{end:.5f}', 'duration': f'{end - start:.5f}', @@ -77,12 +86,22 @@ def log_error_with_time(self, error, status, start): def read_no_block(self, trailer=11, blocks=(8, 9, 10)): start = time.time() - status, _ = self._mfrc522.MFRC522_Request( - self._mfrc522.PICC_REQIDL) + reqMode = self._mfrc522.PICC_REQIDL + status, _ = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: self.log_error_with_time('MFRC522_Request', status, start) + self._log.debug({ + 'action': 'MFRC522_Request', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return None, None self.log_time('MFRC522_Request', start) + self._log.debug({ + 'action': 'MFRC522_Request_Success', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) start = time.time() status, uid = self._mfrc522.MFRC522_Anticoll() @@ -99,12 +118,23 @@ def read_no_block(self, trailer=11, blocks=(8, 9, 10)): self.log_time('MFRC522_SelectTag', start) start = time.time() - status = self._mfrc522.MFRC522_Auth(self._mfrc522.PICC_AUTHENT1A, - trailer, self._key, uid) + command = self._mfrc522.PICC_AUTHENT1A + status = self._mfrc522.MFRC522_Auth(command, + trailer, self._key, uid) if status != self._mfrc522.MI_OK: self.log_error_with_time('MFRC522_Auth', status, start) + self._log.debug({ + 'action': 'MFRC522_Auth_Failed', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return None, None self.log_time('MFRC522_Auth', start) + self._log.debug({ + 'action': 'MFRC522_Auth_Success', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) data = [] text_read = '' @@ -136,17 +166,32 @@ def write(self, text, trailer=11, blocks=(8, 9, 10), attempts=sys.maxsize): return id, text_out, tries def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): - (status, TagType) = self._mfrc522.MFRC522_Request( - self._mfrc522.PICC_REQIDL) + reqMode = self._mfrc522.PICC_REQIDL + (status, TagType) = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: + self._log.debug({ + 'action': 'write_no_block_request_failed', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return None, None (status, uid) = self._mfrc522.MFRC522_Anticoll() if status != self._mfrc522.MI_OK: + self._log.debug({ + 'action': 'write_no_block_anticoll_failed', + 'status': f'0x{status:02X}' # Log status as hex value + }) return None, None id = self.uid_to_num(uid) self._mfrc522.MFRC522_SelectTag(uid) + command = self._mfrc522.PICC_AUTHENT1A status = self._mfrc522.MFRC522_Auth( - self._mfrc522.PICC_AUTHENT1A, trailer, self._key, uid) + command, trailer, self._key, uid) + self._log.debug({ + 'action': 'write_no_block_auth', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) self._mfrc522.MFRC522_Read(trailer) if status == self._mfrc522.MI_OK: data = bytearray() From 1ffaff6dc192c4dba49da989565d70f83ff76482 Mon Sep 17 00:00:00 2001 From: Declan Shanaghy <375100+declanshanaghy@users.noreply.github.com> Date: Sun, 27 Apr 2025 23:57:27 -0700 Subject: [PATCH 5/7] Fix RFID card read/write reliability by improving error handling and reducing verbose logging --- mfrc522/MFRC522.py | 188 +++++++++++++++++++++------------------ mfrc522/SimpleMFRC522.py | 72 ++++++++------- 2 files changed, 140 insertions(+), 120 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 2177f80..6c73368 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -128,10 +128,10 @@ class MFRC522: def __init__(self, bus=0, device=0, spd=1000000, pin_mode=GPIO.BOARD, pin_rst=-1, log_verbose=False): self.logger = logging.getLogger(self.__class__.__name__) - if log_verbose: - self.logger.setLevel(logging.DEBUG) - else: - self.logger.setLevel(logging.INFO) + # Don't change the logger's level based on log_verbose + # This ensures that ERROR messages are always logged at ERROR level + # The log_verbose flag will be used by individual log statements + self.log_verbose = log_verbose self.logger.info('Setting up SPI') self.spi = spidev.SpiDev() @@ -197,10 +197,11 @@ def MFRC522_ToCard(self, command, sendData): n = 0 # Log command as hex value - self.logger.debug({ - 'action': 'MFRC522_ToCard_start', - 'command': f'0x{command:02X}' # Log command as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_ToCard_start', + 'command': f'0x{command:02X}' # Log command as hex value + }) if command == self.PCD_AUTHENT: irqEn = 0x12 @@ -258,12 +259,13 @@ def MFRC522_ToCard(self, command, sendData): status = self.MI_ERR # Log status and command as hex values - self.logger.debug({ - 'action': 'MFRC522_ToCard_complete', - 'command': f'0x{command:02X}', # Log command as hex value - 'status': f'0x{status:02X}', # Log status as hex value - 'backLen': backLen - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_ToCard_complete', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}', # Log status as hex value + 'backLen': backLen + }) return (status, backData, backLen) @@ -271,10 +273,11 @@ def MFRC522_Request(self, reqMode): TagType = [] # Log reqMode as hex value - self.logger.debug({ - 'action': 'MFRC522_Request_start', - 'reqMode': f'0x{reqMode:02X}' # Log reqMode as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Request_start', + 'reqMode': f'0x{reqMode:02X}' # Log reqMode as hex value + }) self.Write_MFRC522(self.BitFramingReg, 0x07) @@ -286,11 +289,12 @@ def MFRC522_Request(self, reqMode): status = self.MI_ERR # Log status and reqMode as hex values - self.logger.debug({ - 'action': 'MFRC522_Request_complete', - 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Request_complete', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return (status, backBits) @@ -299,10 +303,11 @@ def MFRC522_Anticoll(self): serNum = [] # Log start of anticoll - self.logger.debug({ - 'action': 'MFRC522_Anticoll_start', - 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Anticoll_start', + 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value + }) self.Write_MFRC522(self.BitFramingReg, 0x00) @@ -323,10 +328,11 @@ def MFRC522_Anticoll(self): status = self.MI_ERR # Log status as hex value - self.logger.debug({ - 'action': 'MFRC522_Anticoll_complete', - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Anticoll_complete', + 'status': f'0x{status:02X}' # Log status as hex value + }) return (status, backData) @@ -355,11 +361,12 @@ def MFRC522_SelectTag(self, serNum): buf.append(0x70) # Log start of select tag - self.logger.debug({ - 'action': 'MFRC522_SelectTag_start', - 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value - 'select_tag': f'0x{self.PICC_SElECTTAG:02X}' # Log select tag as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_SelectTag_start', + 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value + 'select_tag': f'0x{self.PICC_SElECTTAG:02X}' # Log select tag as hex value + }) for i in range(5): buf.append(serNum[i]) @@ -372,14 +379,15 @@ def MFRC522_SelectTag(self, serNum): # Log status as hex value if (status == self.MI_OK) and (backLen == 0x18): - self.logger.debug({ - 'action': 'MFRC522_SelectTag_complete', - 'status': f'0x{status:02X}', # Log status as hex value - 'size': backData[0] - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_SelectTag_complete', + 'status': f'0x{status:02X}', # Log status as hex value + 'size': backData[0] + }) return status, backData[0] else: - self.logger.debug({ + self.logger.error({ 'action': 'MFRC522_SelectTag_failed', 'status': f'0x{status:02X}' # Log status as hex value }) @@ -389,12 +397,13 @@ def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): buff = [] # Log start of auth with authMode as hex value - self.logger.debug({ - 'action': 'MFRC522_Auth_start', - 'authMode': f'0x{authMode:02X}', # Log authMode as hex value - 'blockAddr': BlockAddr, - 'command': f'0x{self.PCD_AUTHENT:02X}' # Log command as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Auth_start', + 'authMode': f'0x{authMode:02X}', # Log authMode as hex value + 'blockAddr': BlockAddr, + 'command': f'0x{self.PCD_AUTHENT:02X}' # Log command as hex value + }) # First byte should be the authMode (A or B) buff.append(authMode) @@ -430,10 +439,11 @@ def MFRC522_Auth(self, authMode, BlockAddr, Sectorkey, serNum): }) # Log completion with status as hex value - self.logger.debug({ - 'action': 'MFRC522_Auth_complete', - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Auth_complete', + 'status': f'0x{status:02X}' # Log status as hex value + }) # Return the status return status @@ -450,11 +460,12 @@ def MFRC522_Read(self, blockAddr): recvData.append(pOut[1]) # Log start of read operation - self.logger.debug({ - 'action': 'MFRC522_Read_start', - 'blockAddr': blockAddr, - 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Read_start', + 'blockAddr': blockAddr, + 'command': f'0x{self.PCD_TRANSCEIVE:02X}' # Log command as hex value + }) (status, backData, backLen) = self.MFRC522_ToCard(self.PCD_TRANSCEIVE, recvData) @@ -466,19 +477,21 @@ def MFRC522_Read(self, blockAddr): }) # Log completion with status as hex value - self.logger.debug({ - 'action': 'MFRC522_Read_complete', - 'status': f'0x{status:02X}', # Log status as hex value - 'blockAddr': blockAddr, - 'success': status == self.MI_OK - }) - - if len(backData) == 16: + if self.log_verbose: self.logger.debug({ - 'action': 'MFRC522_Read_data', + 'action': 'MFRC522_Read_complete', + 'status': f'0x{status:02X}', # Log status as hex value 'blockAddr': blockAddr, - 'data': str(backData) + 'success': status == self.MI_OK }) + + if len(backData) == 16: + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Read_data', + 'blockAddr': blockAddr, + 'data': str(backData) + }) return backData else: return None @@ -489,12 +502,13 @@ def MFRC522_Write(self, blockAddr, writeData): buff.append(blockAddr) # Log start of write operation - self.logger.debug({ - 'action': 'MFRC522_Write_start', - 'blockAddr': blockAddr, - 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value - 'write_command': f'0x{self.PICC_WRITE:02X}' # Log write command as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Write_start', + 'blockAddr': blockAddr, + 'command': f'0x{self.PCD_TRANSCEIVE:02X}', # Log command as hex value + 'write_command': f'0x{self.PICC_WRITE:02X}' # Log write command as hex value + }) crc = self.CalulateCRC(buff) buff.append(crc[0]) @@ -504,19 +518,20 @@ def MFRC522_Write(self, blockAddr, writeData): if not (status == self.MI_OK) or not (backLen == 4) or not ( (backData[0] & 0x0F) == 0x0A): status = self.MI_ERR - self.logger.debug({ + self.logger.error({ 'action': 'MFRC522_Write_first_phase_failed', 'status': f'0x{status:02X}', # Log status as hex value 'backLen': backLen, 'backData': str(backData) if backData else "None" }) - self.logger.debug({ - 'action': 'MFRC522_Write_first_phase', - 'backLen': backLen, - 'backData_check': f'0x{backData[0] & 0x0F:02X}', # Log as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Write_first_phase', + 'backLen': backLen, + 'backData_check': f'0x{backData[0] & 0x0F:02X}', # Log as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) if status == self.MI_OK: buf = [] @@ -537,12 +552,13 @@ def MFRC522_Write(self, blockAddr, writeData): 'backData': str(backData) if backData else "None" }) if status == self.MI_OK: - self.logger.debug({ - 'action': 'MFRC522_Write_complete', - 'status': f'0x{status:02X}', # Log status as hex value - 'blockAddr': blockAddr, - 'success': True - }) + if self.log_verbose: + self.logger.debug({ + 'action': 'MFRC522_Write_complete', + 'status': f'0x{status:02X}', # Log status as hex value + 'blockAddr': blockAddr, + 'success': True + }) def MFRC522_DumpClassic1K(self, key, uid): for i in range(64): diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 62d5209..5646700 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -19,10 +19,9 @@ class SimpleMFRC522: def __init__(self, key=None, log_verbose=True, pin_mode=GPIO.BOARD): self._log = logging.getLogger(self.__class__.__name__) self._log_verbose = log_verbose - if log_verbose: - self._log.setLevel(logging.DEBUG) - else: - self._log.setLevel(logging.INFO) + # Don't change the logger's level based on log_verbose + # This ensures that ERROR messages are always logged at ERROR level + # Instead, we'll use log_verbose to determine whether to log DEBUG messages if key is None: key = SimpleMFRC522.DEFAULT_KEY @@ -65,13 +64,14 @@ def read(self, trailer=11, blocks=(8, 9, 10), attempts=sys.maxsize): return id, text, tries def log_time(self, action, start): - end = time.time() - self._log.debug({ - 'action': action, - 'start': f'{start:.5f}', - 'end': f'{end:.5f}', - 'duration': f'{end - start:.5f}', - }) + if self._log_verbose: + end = time.time() + self._log.debug({ + 'action': action, + 'start': f'{start:.5f}', + 'end': f'{end:.5f}', + 'duration': f'{end - start:.5f}', + }) def log_error_with_time(self, error, status, start): if self._log_verbose: @@ -90,18 +90,20 @@ def read_no_block(self, trailer=11, blocks=(8, 9, 10)): status, _ = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: self.log_error_with_time('MFRC522_Request', status, start) - self._log.debug({ - 'action': 'MFRC522_Request', - 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self._log_verbose: + self._log.debug({ + 'action': 'MFRC522_Request', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) return None, None self.log_time('MFRC522_Request', start) - self._log.debug({ - 'action': 'MFRC522_Request_Success', - 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self._log_verbose: + self._log.debug({ + 'action': 'MFRC522_Request_Success', + 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) start = time.time() status, uid = self._mfrc522.MFRC522_Anticoll() @@ -123,18 +125,19 @@ def read_no_block(self, trailer=11, blocks=(8, 9, 10)): trailer, self._key, uid) if status != self._mfrc522.MI_OK: self.log_error_with_time('MFRC522_Auth', status, start) - self._log.debug({ + self._log.error({ 'action': 'MFRC522_Auth_Failed', 'command': f'0x{command:02X}', # Log command as hex value 'status': f'0x{status:02X}' # Log status as hex value }) return None, None self.log_time('MFRC522_Auth', start) - self._log.debug({ - 'action': 'MFRC522_Auth_Success', - 'command': f'0x{command:02X}', # Log command as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self._log_verbose: + self._log.debug({ + 'action': 'MFRC522_Auth_Success', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) data = [] text_read = '' @@ -169,7 +172,7 @@ def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): reqMode = self._mfrc522.PICC_REQIDL (status, TagType) = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: - self._log.debug({ + self._log.error({ 'action': 'write_no_block_request_failed', 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value 'status': f'0x{status:02X}' # Log status as hex value @@ -177,7 +180,7 @@ def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): return None, None (status, uid) = self._mfrc522.MFRC522_Anticoll() if status != self._mfrc522.MI_OK: - self._log.debug({ + self._log.error({ 'action': 'write_no_block_anticoll_failed', 'status': f'0x{status:02X}' # Log status as hex value }) @@ -187,11 +190,12 @@ def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): command = self._mfrc522.PICC_AUTHENT1A status = self._mfrc522.MFRC522_Auth( command, trailer, self._key, uid) - self._log.debug({ - 'action': 'write_no_block_auth', - 'command': f'0x{command:02X}', # Log command as hex value - 'status': f'0x{status:02X}' # Log status as hex value - }) + if self._log_verbose: + self._log.debug({ + 'action': 'write_no_block_auth', + 'command': f'0x{command:02X}', # Log command as hex value + 'status': f'0x{status:02X}' # Log status as hex value + }) self._mfrc522.MFRC522_Read(trailer) if status == self._mfrc522.MI_OK: data = bytearray() From c54129c44e318627e0a7a3be1b302a1cbb601f0c Mon Sep 17 00:00:00 2001 From: Declan Shanaghy <375100+declanshanaghy@users.noreply.github.com> Date: Mon, 28 Apr 2025 17:20:04 -0700 Subject: [PATCH 6/7] Added more logging --- mfrc522/MFRC522.py | 6 +++--- mfrc522/SimpleMFRC522.py | 3 ++- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index 6c73368..fcf1526 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -133,7 +133,7 @@ def __init__(self, bus=0, device=0, spd=1000000, pin_mode=GPIO.BOARD, pin_rst=-1 # The log_verbose flag will be used by individual log statements self.log_verbose = log_verbose - self.logger.info('Setting up SPI') + self.logger.debug('Setting up SPI') self.spi = spidev.SpiDev() self.spi.open(bus, device) self.spi.max_speed_hz = spd @@ -150,11 +150,11 @@ def __init__(self, bus=0, device=0, spd=1000000, pin_mode=GPIO.BOARD, pin_rst=-1 else: pin_rst = 22 - self.logger.info('Setting up RST') + self.logger.debug('Setting up RST') GPIO.setup(pin_rst, GPIO.OUT) GPIO.output(pin_rst, 1) - self.logger.info('Setting up MFRC522') + self.logger.debug('Setting up MFRC522') self.MFRC522_Init() def MFRC522_Reset(self): diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index 5646700..de09ed1 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -40,7 +40,8 @@ def read_id_no_block(self): reqMode = self._mfrc522.PICC_REQIDL (status, TagType) = self._mfrc522.MFRC522_Request(reqMode) if status != self._mfrc522.MI_OK: - self._log.error({ + # This error indicates no card present + self._log.debug({ 'action': 'read_id_no_block_request_failed', 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value 'status': f'0x{status:02X}' # Log status as hex value From abab018fe1501bac6d7cbf511a14d20bef06cd6a Mon Sep 17 00:00:00 2001 From: Declan Shanaghy <375100+declanshanaghy@users.noreply.github.com> Date: Tue, 29 Apr 2025 23:25:41 -0700 Subject: [PATCH 7/7] tweak logging --- mfrc522/MFRC522.py | 2 +- mfrc522/SimpleMFRC522.py | 33 +++++++++++++++------------------ 2 files changed, 16 insertions(+), 19 deletions(-) diff --git a/mfrc522/MFRC522.py b/mfrc522/MFRC522.py index fcf1526..f2fee7c 100644 --- a/mfrc522/MFRC522.py +++ b/mfrc522/MFRC522.py @@ -387,7 +387,7 @@ def MFRC522_SelectTag(self, serNum): }) return status, backData[0] else: - self.logger.error({ + self.logger.debug({ 'action': 'MFRC522_SelectTag_failed', 'status': f'0x{status:02X}' # Log status as hex value }) diff --git a/mfrc522/SimpleMFRC522.py b/mfrc522/SimpleMFRC522.py index de09ed1..903aee6 100644 --- a/mfrc522/SimpleMFRC522.py +++ b/mfrc522/SimpleMFRC522.py @@ -11,22 +11,18 @@ class SimpleMFRC522: DEFAULT_KEY = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] - _log_verbose = None _log = None _mfrc522 = None _key = None - def __init__(self, key=None, log_verbose=True, pin_mode=GPIO.BOARD): + def __init__(self, key=None, pin_mode=GPIO.BOARD): self._log = logging.getLogger(self.__class__.__name__) - self._log_verbose = log_verbose - # Don't change the logger's level based on log_verbose - # This ensures that ERROR messages are always logged at ERROR level - # Instead, we'll use log_verbose to determine whether to log DEBUG messages if key is None: key = SimpleMFRC522.DEFAULT_KEY self._key = key - self._mfrc522 = MFRC522(log_verbose=log_verbose, pin_mode=pin_mode) + self._mfrc522 = MFRC522(log_verbose=self._log.isEnabledFor(logging.DEBUG), + pin_mode=pin_mode) def read_id(self, attempts=sys.maxsize): id = self.read_id_no_block() @@ -65,7 +61,7 @@ def read(self, trailer=11, blocks=(8, 9, 10), attempts=sys.maxsize): return id, text, tries def log_time(self, action, start): - if self._log_verbose: + if self._log.isEnabledFor(logging.DEBUG): end = time.time() self._log.debug({ 'action': action, @@ -75,9 +71,9 @@ def log_time(self, action, start): }) def log_error_with_time(self, error, status, start): - if self._log_verbose: + if self._log.isEnabledFor(logging.DEBUG): end = time.time() - self._log.error({ + self._log.debug({ 'error': error, 'status': f'0x{status:02X}', # Log status as hex value 'start': f'{start:.5f}', @@ -89,17 +85,18 @@ def read_no_block(self, trailer=11, blocks=(8, 9, 10)): start = time.time() reqMode = self._mfrc522.PICC_REQIDL status, _ = self._mfrc522.MFRC522_Request(reqMode) + self.log_time('MFRC522_Request', start) if status != self._mfrc522.MI_OK: - self.log_error_with_time('MFRC522_Request', status, start) - if self._log_verbose: - self._log.debug({ - 'action': 'MFRC522_Request', + # This error indicates no card present, no need for error logging + if self._log.isEnabledFor(logging.DEBUG): + self._log.error({ + 'action': 'MFRC522_Request_failed', 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value 'status': f'0x{status:02X}' # Log status as hex value }) return None, None - self.log_time('MFRC522_Request', start) - if self._log_verbose: + + if self._log.isEnabledFor(logging.DEBUG): self._log.debug({ 'action': 'MFRC522_Request_Success', 'reqMode': f'0x{reqMode:02X}', # Log reqMode as hex value @@ -133,7 +130,7 @@ def read_no_block(self, trailer=11, blocks=(8, 9, 10)): }) return None, None self.log_time('MFRC522_Auth', start) - if self._log_verbose: + if self._log.isEnabledFor(logging.DEBUG): self._log.debug({ 'action': 'MFRC522_Auth_Success', 'command': f'0x{command:02X}', # Log command as hex value @@ -191,7 +188,7 @@ def write_no_block(self, text, trailer=11, blocks=(8, 9, 10)): command = self._mfrc522.PICC_AUTHENT1A status = self._mfrc522.MFRC522_Auth( command, trailer, self._key, uid) - if self._log_verbose: + if self._log.isEnabledFor(logging.DEBUG): self._log.debug({ 'action': 'write_no_block_auth', 'command': f'0x{command:02X}', # Log command as hex value