Commit a26923bc authored by Jakob Moser's avatar Jakob Moser
Browse files

Embed reader into PoolPay's CardReader framework

parent d574589e
Loading
Loading
Loading
Loading
+45 −0
Original line number Diff line number Diff line
from collections.abc import Callable, Sequence

import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

from poolpay.card.CardReader import CardReader


def split_to_bytes(value: int) -> Sequence[int]:
    """
    Take an int and split it into a big endian representation of individual bytes.

    >>> split = split_to_bytes(0xcafebabe)
    >>> [hex(i) for i in split]
    [0xca, 0xfe, 0xba, 0xbe]
    """
    split = []

    while value:
        # Get the byte at the smallest position
        smallest_byte = value & 0xFF
        split.append(smallest_byte)

        # Shift the value one byte to the right
        value = value >> 8

    # We need to reverse the list to achieve big endianness
    return split[::-1]


class Mfrc522CardReader(CardReader):
    def __init__(self) -> None:
        self._reader = SimpleMFRC522()

    def read_id(self) -> Sequence[int]:
        card_id, content = self._reader.read()

        return split_to_bytes(card_id)

    def on_card_presented(self, handle_card: Callable[[CardReader], None]) -> None:
        raise NotImplementedError()

    def close(self) -> None:
        # TODO Maybe integrate this better
        GPIO.cleanup()

read.py

deleted100755 → 0
+0 −13
Original line number Diff line number Diff line
#!/usr/bin/env python
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522()

try:
    id, content = reader.read()
    print("Id", id)
    print("Id (hex)", hex(id))
    print("Content", content)
finally:
    GPIO.cleanup()