Commit 0d88e226 authored by Jakob Moser's avatar Jakob Moser
Browse files

Make CardReader a context manager, and specify close method in spec

parent 26039000
Loading
Loading
Loading
Loading
+16 −2
Original line number Diff line number Diff line
from __future__ import annotations

from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Protocol
from contextlib import AbstractContextManager
from typing import Any


class CardReader(Protocol):
class CardReader(AbstractContextManager, ABC):
    @abstractmethod
    def read_id(self) -> int:
        """
        Read the UID of the MIFARE Ultralight card that is presented.
@@ -14,6 +17,7 @@ class CardReader(Protocol):
        """
        ...

    @abstractmethod
    def on_card_presented(self, handle_card: Callable[[CardReader], None]) -> None:
        """
        Register the function handle_card so that it is called whenever a MIFARE Ultralight card is presented.
@@ -22,3 +26,13 @@ class CardReader(Protocol):
        last registered function, or all of them.
        """
        ...

    @abstractmethod
    def close(self) -> None:
        """
        Close the card reader, doing anything that is necessary to clean up after use (e.g., releasing GPIO pins).
        """
        ...

    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
        self.close()
+0 −1
Original line number Diff line number Diff line
@@ -41,5 +41,4 @@ class Mfrc522CardReader(CardReader):
        raise NotImplementedError()

    def close(self) -> None:
        # TODO Maybe integrate this better
        GPIO.cleanup()
+0 −1
Original line number Diff line number Diff line
@@ -39,7 +39,6 @@ class Pirc522CardReader(CardReader):
        # TODO Call handle method

    def close(self) -> None:
        # TODO Maybe integrate this better
        # Always stop crypto1 when done working
        self._reader.stop_crypto()