API reference¶
This reference is generated from the docstrings in the source code, so it always matches the installed version. Everything below can be imported from the top-level package:
from mifarepy import (
MifareReader, SectorAuth, CardInfo,
GNetPlusError, InvalidMessage,
QueryMessage, ResponseMessage, Message, gencrc,
)
Reader¶
MifareReader
¶
MifareReader(port: str = '/dev/ttyUSB0', baudrate: int = 19200, deviceaddr: int = 0, *, value_ops: ValueOps = 'auto', **kwargs: Any)
Class for interfacing with the RFID card reader.
Can be used as a context manager to ensure the serial port is closed:
Initialize the RFID reader connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
port
|
str
|
Serial port name (e.g., '/dev/ttyUSB0'). |
'/dev/ttyUSB0'
|
baudrate
|
int
|
Baudrate for interfacing with the device. Don't change this unless you know what you're doing. |
19200
|
deviceaddr
|
int
|
Device address (default: 0). |
0
|
value_ops
|
ValueOps
|
How value-block arithmetic is performed.
|
'auto'
|
**kwargs
|
Any
|
Extra keyword arguments passed to |
{}
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the serial port cannot be opened. |
close
¶
Reset auto mode then close the underlying serial port.
Disabling auto mode before closing ensures the reader is left in a clean, command-driven state so the next session does not receive spurious EVN events or NAK responses from a lingering event mode.
sendmsg
¶
Construct and send a QueryMessage to the RFID reader.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function
|
int
|
@see Message.function |
required |
data
|
bytes
|
@see Message.data |
b''
|
readmsg
¶
readmsg(sink_events: bool = False) -> ResponseMessage
Read a message, optionally ignoring EVN (event) messages which are device-driven.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sink_events
|
bool
|
If True, silently discard EVN messages. |
False
|
Returns:
| Type | Description |
|---|---|
ResponseMessage
|
Constructed ResponseMessage instance. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If a NAK response is received. |
get_sn
¶
Get the serial number of the card currently in the RF field.
Deprecated
Use get_uid() (returns '0xAABBCCDD' string) or
get_uid_int() (returns unsigned integer) instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endian
|
str
|
|
'little'
|
as_string
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Union[str, int]
|
Card UID as hex string or integer. |
get_uid
¶
Return the 4-byte UID of the card currently in the RF field as a
zero-padded upper-case hex string (e.g. '0xEDCEF8C3').
Internally runs REQUEST → ANTI_COLLISION. Does not call SELECT;
use scan_tag() or select_card() when you need the card
to be in an active/authenticated state.
Returns:
| Type | Description |
|---|---|
str
|
UID string like |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If no card is present or the reader returns NAK. |
get_uid_int
¶
Return the 4-byte UID of the card currently in the RF field as an unsigned 32-bit integer (little-endian byte order).
Returns:
| Type | Description |
|---|---|
int
|
Unsigned 32-bit UID integer. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If no card is present or the reader returns NAK. |
request_all
¶
Enumerate all cards in field (REQUEST_ALL + ANTI_COLLISION), including cards in HALT state. Useful for multi-card scanning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endian
|
str
|
|
'little'
|
as_string
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Union[str, int]
|
Card UID as hex string or integer. |
get_second_sn
¶
Retrieve the secondary serial number (7-byte UID for MIFARE UltraLight / DESFire and other ISO 14443-3 compliant cards).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
as_string
|
bool
|
If |
True
|
Returns:
| Type | Description |
|---|---|
Union[str, bytes]
|
Secondary serial number as hex string or bytes. |
select_card
¶
Run REQUEST → ANTI_COLLISION → SELECT_CARD to bring a card into the active state ready for authentication and block operations.
Called automatically by authenticate_sector() before every
key-load / authenticate sequence, so you normally do not need to
call this directly. It is still public for advanced multi-card
workflows (see example 08).
Returns:
| Type | Description |
|---|---|
bytes
|
ACK payload bytes from the SELECT_CARD response. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If any step returns a NAK. |
ping
¶
Send a POLLING heartbeat to the reader and return True if it
responds with ACK.
Use this to verify the serial connection is alive without interacting with any card. The reader responds even when no card is present.
Returns:
| Type | Description |
|---|---|
bool
|
|
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the reader explicitly NAKs (unusual). |
is_card_present
¶
Non-blocking check: send a single REQUEST and return whether any card responded.
Does not select or authenticate the card — use scan_tag()
or select_card() for that.
Returns:
| Type | Description |
|---|---|
bool
|
|
scan_tag
¶
scan_tag() -> CardInfo
One-shot card detection: REQUEST → ANTI_COLLISION → SELECT_CARD.
Returns a CardInfo dataclass with the
UID available in multiple representations. The card is left in
the active state so you can immediately call
authenticate_sector() / read_block() etc.
Usage example:
Returns:
| Type | Description |
|---|---|
CardInfo
|
|
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If no card is present or any step fails. |
wait_for_card
¶
Check if a card is already present; if not, wait for a card-insert event.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Maximum time to wait in seconds (default: 10). |
10.0
|
Returns:
| Type | Description |
|---|---|
str
|
Card serial number string. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no card is detected within the timeout. |
wait_for_card_async
async
¶
Async variant of wait_for_card. Does not block the event loop —
serial I/O runs in a thread-pool executor.
Suitable for use inside asyncio-based applications (FastAPI,
Django async views, automation scripts using asyncio.run).
Usage example:
import asyncio
from mifarepy import MifareReader
async def main():
with MifareReader('/dev/ttyUSB0') as reader:
uid = await reader.wait_for_card_async(timeout=15)
print('Card:', uid)
asyncio.run(main())
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Maximum seconds to wait (default: 10). |
10.0
|
Returns:
| Type | Description |
|---|---|
str
|
Card UID as hex string. |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If no card is detected within the timeout. |
get_version
¶
Get product version string.
Returns:
| Type | Description |
|---|---|
str
|
Firmware/hardware version string from the connected reader. |
set_auto_mode
¶
Toggle auto mode — whether the device emits EVN events when a card enters field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
True to enable, False to disable. |
True
|
Returns:
| Type | Description |
|---|---|
bytes
|
Confirmed mode byte from the device. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the device reports failure to set the mode. |
halt
¶
Send HALT to deselect the current card and put it into HALT state.
The card will not respond to subsequent REQUEST commands (only REQUEST_ALL). Call this after finishing operations on a card in multi-card scenarios.
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the reader returns a NAK. |
rf_power
¶
Switch the RF field power on or off.
Turning the RF field off and back on can reset cards that are in an inconsistent state without physically removing them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on
|
bool
|
True to power on the RF field, False to power it off. |
required |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the reader returns a NAK. |
authenticate_sector
¶
authenticate_sector(sector: int, key: bytes, key_type: str = 'A', timeout: float = 1.0, flush: bool = True) -> None
Load a key into the reader and authenticate the specified MIFARE Classic sector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sector
|
int
|
Sector number to authenticate (0-15 for 1K; 0-39 for 4K). |
required |
key
|
bytes
|
6-byte authentication key. |
required |
key_type
|
str
|
'A' for Key A (0x60) or 'B' for Key B (0x61). |
'A'
|
timeout
|
float
|
Timeout in seconds for reader responses. |
1.0
|
flush
|
bool
|
Whether to flush the input buffer before reading responses. |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If key_type is invalid or key length is not 6 bytes. |
GNetPlusError
|
If the reader returns NAK during key load or authentication. |
authenticate_sector_cached
¶
authenticate_sector_cached(sector: int, key_type: Literal['A', 'B'] = 'A', timeout: float = 1.0) -> None
Authenticate a sector using a key that is already loaded in the reader.
Skips the SAVE_KEY step (opcode 0x2B) and jumps straight to
AUTHENTICATE_KEY (opcode 0x2E). This is faster when the same key
has already been loaded by a previous authenticate_sector() call
in the same session.
Warning
The reader only stores one key internally. If any other sector
was authenticated (or the reader was reset) since the last
SAVE_KEY, call authenticate_sector() instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sector
|
int
|
Sector to authenticate (0-15 for 1K; 0-39 for 4K). |
required |
key_type
|
Literal['A', 'B']
|
|
'A'
|
timeout
|
float
|
Timeout in seconds for the reader response. |
1.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
GNetPlusError
|
If the reader returns NAK. |
read_block
¶
Read a single 16-byte block from the currently authenticated sector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector (0-3). |
required |
raw
|
bool
|
If True returns bytes; if False returns hex string. |
False
|
Returns:
| Type | Description |
|---|---|
Union[bytes, str]
|
Block data as bytes (raw=True) or hex string (raw=False). |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the read fails. |
write_block
¶
Write a 16-byte block to the currently authenticated sector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector (0-3). |
required |
data
|
Union[str, bytes]
|
Data to write -- exactly 16 bytes or a 32-character hex string. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Reader's echoed data in hex format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is not exactly 16 bytes. |
GNetPlusError
|
If the write fails. |
read_value
¶
Read a signed 32-bit value from a MIFARE value block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector (0-2). |
required |
Returns:
| Type | Description |
|---|---|
int
|
Signed 32-bit integer stored in the value block. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the read fails. |
write_value
¶
Write a signed 32-bit value to a MIFARE value block.
Delegates to CREATE_VALUE_BLOCK (0x28) which both creates and updates value blocks and is universally supported across all GNetPlus firmware versions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector (0-2). |
required |
value
|
int
|
Signed 32-bit integer to store. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value is outside signed 32-bit range. |
GNetPlusError
|
If the write fails. |
create_value_block
¶
Initialize a block as a MIFARE value block with the GNetPlus redundant format (value stored three times: twice normal, once inverted).
Must authenticate the sector before calling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector (0-2). |
required |
initial_value
|
int
|
Signed 32-bit starting value (default: 0). |
0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If initial_value is outside signed 32-bit range. |
GNetPlusError
|
If the operation fails. |
increment_value
¶
Add delta to a MIFARE value block.
Reads the current value and writes the new one (read-modify-write).
With value_ops='native' the reader's SET_VALUE command
(increment + transfer) is sent instead and the result is read back
to confirm it; a NAK or a wrong result raises GNetPlusError.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector. |
required |
delta
|
int
|
Positive integer amount to add. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If delta ≤ 0 or if the result overflows int32. |
GNetPlusError
|
If the reader returns a NAK. |
decrement_value
¶
Subtract delta from a MIFARE value block.
Reads the current value and writes the new one (read-modify-write),
so the block's access conditions must allow writing. With
value_ops='native' the reader's SET_VALUE command (decrement +
transfer) is sent instead, which also works on decrement-only blocks
(for example prepaid balances) if your reader's firmware computes it
correctly; see increment_value().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Block index relative to the authenticated sector. |
required |
delta
|
int
|
Positive integer amount to subtract. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If delta ≤ 0 or if the result underflows int32. |
GNetPlusError
|
If the reader returns a NAK. |
transfer
¶
Copy the value in source_block to dest_block.
Uses the card's RESTORE (load source into the transfer buffer) and TRANSFER (write buffer to destination) commands, then verifies the destination. Both blocks must be value blocks in the authenticated sector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_block
|
int
|
Value block to copy from. |
required |
dest_block
|
int
|
Value block to copy to. |
required |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If either block cannot be read or written. |
restore
¶
Re-commit a value block: RESTORE it into the transfer buffer and TRANSFER it back, rewriting the block in valid value format.
Useful to repair a value block after an interrupted operation, as long as its value can still be read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
block
|
int
|
Value block relative to the authenticated sector. |
required |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If the reader returns a NAK. |
read_sector
¶
read_sector(sector: Optional[int] = None, raw: bool = False, combine: bool = False) -> Union[dict[int, Union[str, bytes]], Union[str, bytes]]
Read every data block of the authenticated sector (the trailer is skipped).
That is blocks 0-2 for sectors 0-31, and blocks 0-14 for the large sectors 32-39 of a MIFARE Classic 4K card.
Authenticate the sector with authenticate_sector before calling this.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sector
|
Optional[int]
|
Sector whose layout to use. Defaults to the sector most recently authenticated on this reader (or a 4-block sector if none has been). It does not authenticate for you. |
None
|
raw
|
bool
|
If True returns bytes; otherwise hex strings. |
False
|
combine
|
bool
|
If True concatenates all data blocks into a single value. |
False
|
Returns:
| Type | Description |
|---|---|
Union[dict[int, Union[str, bytes]], Union[str, bytes]]
|
Dict mapping relative block index to data, or the combined value. |
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If any block read fails. |
write_sector
¶
write_sector(data: Union[str, bytes, dict[int, Union[str, bytes]]], sector: Optional[int] = None) -> None
Write data blocks of the authenticated sector. The trailer is never written.
Supported data shapes (n = number of data blocks: 3, or 15 for 4K sectors 32-39): - 16 bytes / 32-char hex -- the same blob written to every data block. - 16 × k bytes (k ≤ n) -- split into 16-byte chunks for blocks 0 … k-1. - dict mapping data-block indices to 16-byte blobs or hex strings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[str, bytes, dict[int, Union[str, bytes]]]
|
The data to write, in one of the shapes above. |
required |
sector
|
Optional[int]
|
Sector whose layout to use. Defaults to the most recently authenticated sector. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is an invalid size or a dict key is not a data block. |
GNetPlusError
|
If any write fails. |
write_sector_uniform
¶
Write the same 16 bytes to every data block of the authenticated sector.
This is an explicit, intent-revealing alias for the 16-byte dispatch
path of write_sector(). Use it when you deliberately want every
data block in the sector to hold identical content (e.g. bulk wipe /
factory-reset workflows).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Union[str, bytes]
|
Exactly 16 bytes or a 32-character hex string. |
required |
sector
|
Optional[int]
|
Sector whose layout to use. Defaults to the most recently authenticated sector. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is not exactly 16 bytes. |
GNetPlusError
|
If any block write fails. |
read_blocks
¶
read_blocks(mapping: dict[int, list[int]], raw: bool = False, combine: bool = False, keys: Optional[Union[bytes, dict[int, bytes]]] = None, key_types: Union[str, dict[int, str]] = 'A', timeout: Union[float, dict[int, float]] = 1.0, flush: Union[bool, dict[int, bool]] = True, auth: Optional[dict[int, SectorAuth]] = None) -> Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]
Read multiple blocks across sectors with optional per-sector authentication.
Authentication can be supplied two ways (mutually exclusive; auth
takes precedence when both are given):
New style — auth dict of SectorAuth:
results = reader.read_blocks(
{1: [0, 1], 2: [0]},
auth={
1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
},
)
Legacy style — keys + key_types + timeout + flush
(still fully supported).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[int, list[int]]
|
|
required |
raw
|
bool
|
|
False
|
combine
|
bool
|
|
False
|
keys
|
Optional[Union[bytes, dict[int, bytes]]]
|
Global 6-byte key or |
None
|
key_types
|
Union[str, dict[int, str]]
|
|
'A'
|
timeout
|
Union[float, dict[int, float]]
|
Auth timeout globally or per-sector dict. |
1.0
|
flush
|
Union[bool, dict[int, bool]]
|
Buffer-flush flag globally or per-sector dict. |
True
|
auth
|
Optional[dict[int, SectorAuth]]
|
|
None
|
Returns:
| Type | Description |
|---|---|
Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]
|
|
Raises:
| Type | Description |
|---|---|
GNetPlusError
|
If authentication or any block read fails. |
write_blocks
¶
write_blocks(mapping: dict[int, Union[bytes, str, dict[int, Union[str, bytes]]]], keys: Optional[Union[bytes, dict[int, bytes]]] = None, key_types: Union[str, dict[int, str]] = 'A', timeout: Union[float, dict[int, float]] = 1.0, flush: Union[bool, dict[int, bool]] = True, auth: Optional[dict[int, SectorAuth]] = None) -> None
Write multiple blocks across sectors with optional per-sector authentication.
Authentication can be supplied two ways (mutually exclusive; auth
takes precedence when both are given):
New style — auth dict of SectorAuth:
reader.write_blocks(
{1: b' ' * 48, 2: {0: b'ª' * 16}},
auth={
1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
},
)
Legacy style — keys + key_types + timeout + flush
(still fully supported).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mapping
|
dict[int, Union[bytes, str, dict[int, Union[str, bytes]]]]
|
|
required |
keys
|
Optional[Union[bytes, dict[int, bytes]]]
|
Global 6-byte key or |
None
|
key_types
|
Union[str, dict[int, str]]
|
|
'A'
|
timeout
|
Union[float, dict[int, float]]
|
Auth timeout globally or per-sector dict. |
1.0
|
flush
|
Union[bool, dict[int, bool]]
|
Buffer-flush flag globally or per-sector dict. |
True
|
auth
|
Optional[dict[int, SectorAuth]]
|
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If any block data is not exactly 16 bytes. |
GNetPlusError
|
If authentication or any block write fails. |
Data types¶
SectorAuth
dataclass
¶
Per-sector authentication configuration for read_blocks()
and write_blocks().
Pass a dict[sector, SectorAuth] to the auth keyword argument of
those methods to supply per-sector keys in a discoverable, IDE-friendly
way instead of the legacy keys= / key_types= dict juggling.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
bytes
|
6-byte MIFARE authentication key. |
key_type |
Literal['A', 'B']
|
|
timeout |
float
|
Per-sector auth timeout in seconds (default |
flush |
bool
|
Flush the serial input buffer before reading (default |
Usage example:
from mifarepy import SectorAuth
reader.read_blocks(
{1: [0, 1], 2: [0]},
auth={
1: SectorAuth(key=bytes.fromhex('FFFFFFFFFFFF')),
2: SectorAuth(key=bytes.fromhex('A0A1A2A3A4A5'), key_type='B'),
},
)
CardInfo
dataclass
¶
Information about a card detected and selected in the RF field.
Returned by scan_tag(). Provides the UID
in multiple representations so callers can use whatever is most convenient
without extra conversion.
Attributes:
| Name | Type | Description |
|---|---|---|
uid |
str
|
UID formatted as |
uid_int |
int
|
Unsigned 32-bit integer. |
uid_bytes |
bytes
|
Raw 4-byte response from ANTI_COLLISION (little-endian byte order). |
Usage example:
card = reader.scan_tag()
print(card) # '0xEDCEF8C3'
print(card.uid_int) # 3989956803
print(card.uid_bytes.hex()) # 'c3f8ceed'
Card layout¶
layout
¶
MIFARE Classic memory-layout helpers.
MIFARE Classic 1K has 16 sectors of 4 blocks. MIFARE Classic 4K has 40 sectors: 0-31 have 4 blocks each, 32-39 have 16 blocks each. The last block of every sector is its sector trailer (keys + access bits).
Block numbers passed to MifareReader.read_block() / write_block() are
relative to the authenticated sector; these helpers translate between
relative and absolute numbering and tell you which blocks hold data.
from mifarepy import layout
layout.blocks_in_sector(5) # 4
layout.blocks_in_sector(35) # 16
layout.data_blocks(35) # range(0, 15)
layout.trailer_block(35) # 15 (relative)
layout.absolute_block(35, 0) # 176
layout.sector_of(176) # (35, 0)
blocks_in_sector
¶
Return how many blocks sector has (4, or 16 for 4K sectors 32-39).
trailer_block
¶
Return the relative block number of sector's trailer (3 or 15).
data_blocks
¶
Return the relative block numbers that hold data (excludes the trailer).
absolute_block
¶
Convert a relative block within sector to an absolute block number.
sector_of
¶
Convert an absolute block number to (sector, relative_block).
is_trailer
¶
Return True if relative block is the trailer of sector.
Errors¶
GNetPlusError
¶
Bases: Exception
Exception thrown when receiving a NAK (negative acknowledge) response.
Attributes:
| Name | Type | Description |
|---|---|---|
raw |
Raw NAK payload bytes from the reader. |
|
code_description |
str
|
Human-readable description of the NAK code if known. |
InvalidMessage
¶
Bases: Exception
Raised when an invalid message is received from the RFID reader.
Attributes:
| Name | Type | Description |
|---|---|---|
raw_bytes |
The partial bytes that were read from the serial port before the error occurred. Useful for low-level debugging. |
Low-level protocol¶
These classes build and parse GNetPlus frames. You only need them to send
commands that MifareReader does not wrap. See the
protocol reference.
Message
¶
Base class representing a message for the RFID reader.
Initialize a message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
address
|
int
|
8-bit device address (use 0 unless specified). |
required |
function
|
int
|
8-bit function code representing the message type. |
required |
data
|
Union[bytes, str]
|
Message payload (bytes or string). |
required |
sendto
¶
Sends this message to the provided serial port.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serial_port
|
Serial
|
Serial port to send the message. |
required |
readfrom
classmethod
¶
Reads a message from the serial port and constructs a Message instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
serial_port
|
Serial
|
Serial interface to read from. |
required |
Returns:
| Type | Description |
|---|---|
_MessageT
|
Constructed Message instance. |
Raises:
| Type | Description |
|---|---|
InvalidMessage
|
If message is incomplete or invalid. |
QueryMessage
¶
Bases: Message
A query message sent from the host to the reader.
Function codes follow the GNetPlus common command table (0x00-0x1F) and the MIFARE application command table (0x20-0x3F).
ResponseMessage
¶
Bases: Message
Message received from the RFID reader.
to_error
¶
to_error() -> Optional[GNetPlusError]
Convert a NAK response into a GNetPlusError with code description.
Returns:
| Type | Description |
|---|---|
Optional[GNetPlusError]
|
GNetPlusError if this is a NAK response, else None. |
gencrc
¶
Generate a 16-bit CRC checksum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
msg_bytes
|
bytes
|
bytes containing message for checksum |
required |
Returns:
| Type | Description |
|---|---|
int
|
16-bit integer containing CRC checksum |