<commit_before>import json
import gc
from mfrc522 import MFRC522

"""The number of banks available in the tag. Only one is active, and has its length stored in the lengths block"""
numBanks = 3
"""Default Mifare key which authenticates access to card sectors"""
key = b'\<KEY>'
"""Number of bytes per block"""
bytesPerBlock = 16
"""Number of total blocks in 1k Mifare Classic tag"""
numBlocks = 64
"""Number of data (non-auth) blocks"""
numDataBlocks = (numBlocks // 4) * 3 # Every fourth block is an auth block, not used for banking
"""Block 0 is manufacturer-protected, block 1 is lengthblock and block 2 kept for future"""
numReservedDataBlocks = 3
"""Remaining authorable blocks"""
safeBlocks = numDataBlocks - numReservedDataBlocks
"""Authorable blocks allocated to each bank"""
blocksPerBank = safeBlocks // numBanks

"""Reserved block for keeping the length of JSON banks"""
lengthsRealIndex = 1

def getRealIndex(safeIndex):
    safeIndex = safeIndex + numReservedDataBlocks  # offset to skip reserved editable blocks
    return ((safeIndex // 3) * 4) + (safeIndex % 3)  # calculate index, skipping auth blocks

class BankVault:
    def __init__(self, reader):
        #reader used to put a JSON byte array (up to 240 bytes) onto the 1k Mifare Classic tag
        self.rdr = reader
        #Buffer used for writing
        self.blockBuffer = bytearray(bytesPerBlock)
        # currently selected tag (avoid reauth)
        self.selectedTagUid = None

    # TODO CH add timeout here and in LaptopRfid
    def awaitPresence(self, expectTagUid=None):
        while True:
            try:
                print("Seeking...")
                (stat, tag_type) = self.rdr.request(MFRC522.REQIDL)  # check if antenna idle
                if stat is not MFRC522.OK: raise AssertionError("No tag")
                print("Separating...")
                (stat, tagUid) = self.rdr.anticoll()
                if stat is not MFRC522.OK: raise AssertionError("Collision")
                if expectTagUid is not None:
                    if not(tagUid == expectTagUid): raise AssertionError("Wrong Tag")
                return tagUid
            except Exception as e:
                eType = type(e)
                if eType == AssertionError:
                    pass
                elif eType == KeyboardInterrupt:
                    raise e
                else:
                    print(eType.__name__, end="")
                    print(e)
                    return None

    def awaitAbsence(self):
        errThreshold = 2
        errCount = 0
        while errCount < errThreshold:
            (stat, tag_type) = self.rdr.request(MFRC522.REQIDL)  # check if antenna idle
            if stat is MFRC522.OK:
                errCount = 0
            else:
                errCount += 1
        return

    # reimplemented as blocking via await presence
    def selectTag(self, tagUid=None):
        if tagUid is None or not(self.selectedTagUid==tagUid):
            if self.selectedTagUid is not None:
                print("Previous tag still selected")
                self.unselectTag()
            tagUid = self.awaitPresence(tagUid)
            if self.rdr.select_tag(tagUid) is not MFRC522.OK: raise AssertionError("Selection")
            self.selectedTagUid = tagUid
        else:
            print("Tag already selected")
        return self.selectedTagUid

    def unselectTag(self):
        self.selectedTagUid = None
        self.rdr.stop_crypto1()
<commit_msg>Changed vault logic to indicate moment for halt_a. Changed logic to not block if card different than expected. Prevented capturing of exceptions inside awaitPresence, allowing them to propagate to enclosing logic.<commit_after>import json
import gc
from mfrc522 import MFRC522

"""The number of banks available in the tag. Only one is active, and has its length stored in the lengths block"""
numBanks = 3
"""Default Mifare key which authenticates access to card sectors"""
key = b'\<KEY>'
"""Number of bytes per block"""
bytesPerBlock = 16
"""Number of total blocks in 1k Mifare Classic tag"""
numBlocks = 64
"""Number of data (non-auth) blocks"""
numDataBlocks = (numBlocks // 4) * 3 # Every fourth block is an auth block, not used for banking
"""Block 0 is manufacturer-protected, block 1 is lengthblock and block 2 kept for future"""
numReservedDataBlocks = 3
"""Remaining authorable blocks"""
safeBlocks = numDataBlocks - numReservedDataBlocks
"""Authorable blocks allocated to each bank"""
blocksPerBank = safeBlocks // numBanks

"""Reserved block for keeping the length of JSON banks"""
lengthsRealIndex = 1

def getRealIndex(safeIndex):
    safeIndex = safeIndex + numReservedDataBlocks  # offset to skip reserved editable blocks
    return ((safeIndex // 3) * 4) + (safeIndex % 3)  # calculate index, skipping auth blocks

class BankVault:
    def __init__(self, reader):
        #reader used to put a JSON byte array (up to 240 bytes) onto the 1k Mifare Classic tag
        self.rdr = reader
        #Buffer used for writing
        self.blockBuffer = bytearray(bytesPerBlock)
        # currently selected tag (avoid reauth)
        self.selectedTagUid = None

    # TODO CH add timeout here and in LaptopRfid
    # TODO CH change this to return None ASAP if there is no cardUid there
    def awaitPresence(self):
        while True:
            print("Seeking...")
            (stat, tag_type) = self.rdr.request(MFRC522.REQIDL)  # check if antenna idle
            if stat is not MFRC522.OK:
                print("No tag")
                continue
            else:
                print("Separating...")
                (stat, tagUid) = self.rdr.anticoll()
                if stat is not MFRC522.OK:
                    print("Collision")
                    continue
                return tagUid

    def awaitAbsence(self):
        errThreshold = 2
        errCount = 0
        while errCount < errThreshold:
            (stat, tag_type) = self.rdr.request(MFRC522.REQIDL)  # check if antenna idle
            if stat is MFRC522.OK:
                errCount = 0
            else:
                errCount += 1
        return

    # reimplemented as blocking via await presence
    def selectTag(self, expectTagUid=None):
        if expectTagUid is None or not(self.selectedTagUid==expectTagUid):
            if self.selectedTagUid is not None:
                self.unselectTag()
            tagUid = self.awaitPresence()
            if expectTagUid is not None and not(tagUid == expectTagUid): raise AssertionError("Wrong Tag")
            if self.rdr.select_tag(tagUid) is not MFRC522.OK: raise AssertionError("Selection")
            self.selectedTagUid = tagUid
        else:
            print("Tag already selected")
        return self.selectedTagUid

    def unselectTag(self):
        self.selectedTagUid = None
        # TODO need to add 'HaltA' here? see https://github.com/cefn/micropython-mfrc522/issues/1
        self.rdr.halt_a()
        self.rdr.stop_crypto1()

{'fraction_non_alphanumeric': 0.08082113120872811, 'fraction_numerical': 0.014642549526270457, 'mean_word_length': 2.341486810551559, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3462706', 'n_tokens_mistral': 2033, 'n_tokens_neox': 1899, 'n_words': 687}