Skip to content

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:

with MifareReader('/dev/ttyUSB0') as reader:
    uid = reader.get_sn()

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' (default) increments and decrements by read-modify-write, and uses the native RESTORE / TRANSFER commands for transfer() / restore(), verifying the result and falling back to read-modify-write if they fail. 'native' uses only the native commands, including SET_VALUE for increment/decrement; 'software' uses only read-modify-write (the behaviour before 3.1).

'auto'
**kwargs Any

Extra keyword arguments passed to serial.Serial.

{}

Raises:

Type Description
RuntimeError

If the serial port cannot be opened.

close

close() -> None

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

sendmsg(function: int, data: bytes = b'') -> None

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_sn(endian: str = 'little', as_string: bool = True) -> Union[str, int]

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

'big' or 'little'. Selects byte order for the 4-byte UID from the ANTI_COLLISION response.

'little'
as_string bool

If True returns '0xAABBCCDD' hex string; otherwise an unsigned integer.

True

Returns:

Type Description
Union[str, int]

Card UID as hex string or integer.

get_uid

get_uid() -> str

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 '0xAABBCCDD'.

Raises:

Type Description
GNetPlusError

If no card is present or the reader returns NAK.

get_uid_int

get_uid_int() -> 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

request_all(endian: str = 'little', as_string: bool = True) -> Union[str, int]

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

'big' or 'little' byte order for the 4-byte UID.

'little'
as_string bool

If True returns hex string; otherwise integer.

True

Returns:

Type Description
Union[str, int]

Card UID as hex string or integer.

get_second_sn

get_second_sn(as_string: Literal[True]) -> str
get_second_sn(as_string: Literal[False]) -> bytes
get_second_sn(as_string: bool = ...) -> Union[str, bytes]
get_second_sn(as_string: bool = True) -> Union[str, bytes]

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 hex string; otherwise raw bytes.

True

Returns:

Type Description
Union[str, bytes]

Secondary serial number as hex string or bytes.

select_card

select_card() -> bytes

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

ping() -> bool

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

True if the reader acknowledged the POLLING command.

Raises:

Type Description
GNetPlusError

If the reader explicitly NAKs (unusual).

is_card_present

is_card_present() -> bool

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

True if a card is in the RF field, False otherwise.

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:

card = reader.scan_tag()
print(card)            # '0xEDCEF8C3'
print(card.uid_int)    # 3989956803

Returns:

Type Description
CardInfo

CardInfo with uid, uid_int, and uid_bytes.

Raises:

Type Description
GNetPlusError

If no card is present or any step fails.

wait_for_card

wait_for_card(timeout: float = 10.0) -> str

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

wait_for_card_async(timeout: float = 10.0) -> str

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_version() -> str

Get product version string.

Returns:

Type Description
str

Firmware/hardware version string from the connected reader.

set_auto_mode

set_auto_mode(enabled: bool = True) -> bytes

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

halt() -> None

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

rf_power(on: bool) -> None

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' for Key A (0x60) or 'B' for Key B (0x61).

'A'
timeout float

Timeout in seconds for the reader response.

1.0

Raises:

Type Description
ValueError

If key_type is invalid.

GNetPlusError

If the reader returns NAK.

read_block

read_block(block: int, raw: Literal[True]) -> bytes
read_block(block: int, raw: Literal[False] = ...) -> str
read_block(block: int, raw: bool = ...) -> Union[bytes, str]
read_block(block: int, raw: bool = False) -> Union[bytes, str]

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_block(block: int, data: Union[str, bytes]) -> str

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_value(block: int) -> int

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_value(block: int, value: int) -> None

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

create_value_block(block: int, initial_value: int = 0) -> None

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

increment_value(block: int, delta: int) -> None

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

decrement_value(block: int, delta: int) -> None

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

transfer(source_block: int, dest_block: int) -> None

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

restore(block: int) -> None

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_sector_uniform(data: Union[str, bytes], sector: Optional[int] = None) -> None

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]]

{sector: [block, ...]} blocks to read per sector.

required
raw bool

True → bytes; False → hex strings.

False
combine bool

True → concatenate all results into one value.

False
keys Optional[Union[bytes, dict[int, bytes]]]

Global 6-byte key or {sector: key} per-sector.

None
key_types Union[str, dict[int, str]]

'A'/'B' globally or per-sector dict.

'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]]

{sector: SectorAuth} — new-style per-sector auth.

None

Returns:

Type Description
Union[dict[int, dict[int, Union[str, bytes]]], Union[str, bytes]]

{sector: {block: data}} or combined bytes/hex string.

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]]]]

{sector: blob_or_dict} data to write per sector.

required
keys Optional[Union[bytes, dict[int, bytes]]]

Global 6-byte key or {sector: key} per-sector.

None
key_types Union[str, dict[int, str]]

'A'/'B' globally or per-sector dict.

'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]]

{sector: SectorAuth} — new-style per-sector auth.

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

SectorAuth(key: bytes, key_type: Literal['A', 'B'] = 'A', timeout: float = 1.0, flush: bool = True)

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']

'A' (default) or 'B'.

timeout float

Per-sector auth timeout in seconds (default 1.0).

flush bool

Flush the serial input buffer before reading (default True).

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

CardInfo(uid: str, uid_int: int, uid_bytes: bytes)

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 '0xAABBCCDD' (always uppercase, zero-padded).

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

blocks_in_sector(sector: int) -> int

Return how many blocks sector has (4, or 16 for 4K sectors 32-39).

trailer_block

trailer_block(sector: int) -> int

Return the relative block number of sector's trailer (3 or 15).

data_blocks

data_blocks(sector: int) -> range

Return the relative block numbers that hold data (excludes the trailer).

absolute_block

absolute_block(sector: int, block: int) -> int

Convert a relative block within sector to an absolute block number.

sector_of

sector_of(absolute: int) -> tuple[int, int]

Convert an absolute block number to (sector, relative_block).

is_trailer

is_trailer(sector: int, block: int) -> bool

Return True if relative block is the trailer of sector.

Errors

GNetPlusError

GNetPlusError(message: str, raw: bytes = b'')

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

InvalidMessage(message: str, raw_bytes: bytes = b'')

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

Message(address: int, function: int, data: Union[bytes, str])

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

sendto(serial_port: Serial) -> None

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

readfrom(serial_port: Serial) -> _MessageT

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

QueryMessage(address: int, function: int, data: Union[bytes, str])

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).

POLLING class-attribute instance-attribute

POLLING = 0

GET_VERSION class-attribute instance-attribute

GET_VERSION = 1

SET_SLAVE_ADDR class-attribute instance-attribute

SET_SLAVE_ADDR = 2

LOGON class-attribute instance-attribute

LOGON = 3

LOGOFF class-attribute instance-attribute

LOGOFF = 4

SET_PASSWORD class-attribute instance-attribute

SET_PASSWORD = 5

CLASSNAME class-attribute instance-attribute

CLASSNAME = 6

SET_DATETIME class-attribute instance-attribute

SET_DATETIME = 7

GET_DATETIME class-attribute instance-attribute

GET_DATETIME = 8

GET_REGISTER class-attribute instance-attribute

GET_REGISTER = 9

SET_REGISTER class-attribute instance-attribute

SET_REGISTER = 10

RECORD_COUNT class-attribute instance-attribute

RECORD_COUNT = 11

GET_FIRST_RECORD class-attribute instance-attribute

GET_FIRST_RECORD = 12

GET_NEXT_RECORD class-attribute instance-attribute

GET_NEXT_RECORD = 13

ERASE_ALL_RECORDS class-attribute instance-attribute

ERASE_ALL_RECORDS = 14

ADD_RECORD class-attribute instance-attribute

ADD_RECORD = 15

RECOVER_ALL_RECORDS class-attribute instance-attribute

RECOVER_ALL_RECORDS = 16

DO class-attribute instance-attribute

DO = 17

DI class-attribute instance-attribute

DI = 18

ANALOG_INPUT class-attribute instance-attribute

ANALOG_INPUT = 19

THERMOMETER class-attribute instance-attribute

THERMOMETER = 20

GET_NODE class-attribute instance-attribute

GET_NODE = 21

GET_SN class-attribute instance-attribute

GET_SN = 22

SILENT_MODE class-attribute instance-attribute

SILENT_MODE = 23

RESERVE class-attribute instance-attribute

RESERVE = 24

ENABLE_AUTO_MODE class-attribute instance-attribute

ENABLE_AUTO_MODE = 25

GET_TIME_ADJUST class-attribute instance-attribute

GET_TIME_ADJUST = 26

ECHO class-attribute instance-attribute

ECHO = 27

SET_TIME_ADJUST class-attribute instance-attribute

SET_TIME_ADJUST = 28

DEBUG class-attribute instance-attribute

DEBUG = 29

RESET class-attribute instance-attribute

RESET = 30

GO_TO_ISP class-attribute instance-attribute

GO_TO_ISP = 31

REQUEST class-attribute instance-attribute

REQUEST = 32

ANTI_COLLISION class-attribute instance-attribute

ANTI_COLLISION = 33

SELECT_CARD class-attribute instance-attribute

SELECT_CARD = 34

AUTHENTICATE class-attribute instance-attribute

AUTHENTICATE = 35

READ_BLOCK class-attribute instance-attribute

READ_BLOCK = 36

WRITE_BLOCK class-attribute instance-attribute

WRITE_BLOCK = 37

SET_VALUE class-attribute instance-attribute

SET_VALUE = 38

READ_VALUE class-attribute instance-attribute

READ_VALUE = 39

CREATE_VALUE_BLOCK class-attribute instance-attribute

CREATE_VALUE_BLOCK = 40

ACCESS_CONDITION class-attribute instance-attribute

ACCESS_CONDITION = 41

HALT class-attribute instance-attribute

HALT = 42

SAVE_KEY class-attribute instance-attribute

SAVE_KEY = 43

GET_SECOND_SN class-attribute instance-attribute

GET_SECOND_SN = 44

GET_ACCESS_CONDITION class-attribute instance-attribute

GET_ACCESS_CONDITION = 45

AUTHENTICATE_KEY class-attribute instance-attribute

AUTHENTICATE_KEY = 46

REQUEST_ALL class-attribute instance-attribute

REQUEST_ALL = 47

SET_VALUEEX class-attribute instance-attribute

SET_VALUEEX = 50

TRANSFER class-attribute instance-attribute

TRANSFER = 51

RESTORE class-attribute instance-attribute

RESTORE = 52

GET_SECTOR class-attribute instance-attribute

GET_SECTOR = 61

RF_POWER_ONOFF class-attribute instance-attribute

RF_POWER_ONOFF = 62

AUTO_MODE class-attribute instance-attribute

AUTO_MODE = 63

ResponseMessage

ResponseMessage(address: int, function: int, data: Union[bytes, str])

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

gencrc(msg_bytes: bytes) -> int

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