Skip to main content

Pure Python library to work with RFID R200 devices via serial communication

Project description

R200 RFID Module Python Library

A Python library for interfacing with R200 RFID modules via serial communication.

Features

  • Partial R200 Protocol Support: Implements the parts of the R200 RFID module communication protocol
  • Object-Oriented Design: Clean, maintainable code with abstract interfaces
  • Type Safety: Full type hints for better IDE support and code reliability
  • Error Handling: Comprehensive error handling with descriptive messages
  • Debug Support: Optional debug output for troubleshooting
  • Cross-Platform: Works on Linux, Windows, and macOS
  • Sync and Async: Supports both synchronous and asynchronous interfaces

Installation

Install from PyPI

pip install rfid-r200

Development Installation

git clone https://github.com/jredrejo/rfid-r200.git
cd rfid-r200
uv pip install -e .[dev,test]
uv sync --group dev

Quick Start Examples

# Run synchronous example
uv run src/main.py

# Run asynchronous example
uv run src/main_async.py

Quick Start

Synchronous Example

from rfid_r200 import R200
import binascii

# Initialize the RFID module
rfid = R200("/dev/ttyUSB0", 115200, debug=True)  # Linux
# rfid = R200("COM3", 115200, debug=True)  # Windows

try:
    # Read RFID tags
    tags, errors = rfid.read_tags()

    print(f"Found {len(tags)} tags:")
    for i, tag in enumerate(tags):
        epc_hex = binascii.hexlify(bytes(tag.epc)).decode()
        print(f"Tag {i+1}: EPC={epc_hex}, RSSI={tag.rssi}")

finally:
    rfid.close()

Asynchronous Example

from rfid_r200 import AsyncR200
import binascii
import asyncio

async def main():
    # Initialize the RFID module
    rfid = AsyncR200("/dev/ttyUSB0", 115200, debug=True)
    
    try:
        # Read RFID tags
        tags, errors = await rfid.read_tags()
        
        print(f"Found {len(tags)} tags:")
        for i, tag in enumerate(tags):
            epc_hex = binascii.hexlify(bytes(tag.epc)).decode()
            print(f"Tag {i+1}: EPC={epc_hex}, RSSI={tag.rssi}")
    finally:
        await rfid.close()

asyncio.run(main())

Using as Context Manager

from rfid_r200 import R200

# Automatically closes the port when exiting the block
with R200("/dev/ttyUSB0") as rfid:
    tags, errors = rfid.read_tags()
    for tag in tags:
        print(f"Found tag: {tag.epc}")

API Reference

Synchronous Interface (R200)

from rfid_r200 import R200

Asynchronous Interface (AsyncR200)

from rfid_r200 import AsyncR200

R200 / AsyncR200 Constructor

R200(port: str, speed: int = 115200, debug: bool = False, timeout: float = 1.0)
  • port: Serial port name (e.g., "/dev/ttyUSB0", "COM3")
  • speed: Baud rate (default: 115200)
  • debug: Enable debug output (default: False)
  • timeout: Serial port timeout in seconds (default: 1.0)

Methods

read_tags() -> List[R200PoolResponse]

Read all RFID tags in range. Returns a list of R200PoolResponse objects.

tags = rfid.read_tags()
for tag in tags:
    print(f"EPC: {binascii.hexlify(bytes(tag.epc)).decode()}")
    print(f"RSSI: {tag.rssi}")
send_command(command: int, parameters: List[int] = None) -> None

Send a raw command to the R200 module.

# Get module info
rfid.send_command(CMD_GET_MODULE_INFO)
responses = rfid.receive()
receive() -> List[R200Response]

Receive responses from the R200 module.

close() -> None

Close the serial port connection.

Data Structures

R200PoolResponse

Contains RFID tag information:

  • rssi: int - Signal strength
  • pc: int - Protocol Control word
  • epc: List[int] - Electronic Product Code
  • crc: int - Cyclic Redundancy Check

R200Response

Raw response from the module:

  • type: int - Frame type
  • command: int - Command code
  • checksum: int - Checksum value
  • checksum_ok: bool - Checksum validation result
  • params: List[int] - Response parameters

Available Commands

The library includes constants for all R200 commands:

  • CMD_GET_MODULE_INFO - Get module information
  • CMD_SINGLE_POLL_INSTRUCTION - Single tag poll
  • CMD_MULTIPLE_POLL_INSTRUCTION - Multiple tag poll
  • CMD_READ_LABEL - Read tag data
  • CMD_WRITE_LABEL - Write tag data
  • CMD_LOCK_LABEL - Lock tag
  • CMD_KILL_TAG - Kill tag
  • And many more...

Error Handling

The library provides comprehensive error handling:

try:
    tags = rfid.read_tags()
except RuntimeError as e:
    print(f"RFID Error: {e}")
except ValueError as e:
    print(f"Data Error: {e}")

Common error messages:

  • "No tags detected" - No RFID tags in range
  • "Can't execute command" - Invalid command or parameters
  • "Read failed" - Tag read operation failed

Advanced Usage

Custom Command Example

# Send custom command with parameters
rfid.send_command(CMD_SET_TRANSMIT_POWER, [0x1E])  # Set power to 30dBm
responses = rfid.receive()

for resp in responses:
    if resp.checksum_ok:
        print(f"Command executed successfully")
    else:
        print(f"Checksum error")

Working with Multiple Modules

# Handle multiple RFID readers
readers = []
ports = ["/dev/ttyUSB0", "/dev/ttyUSB1"]

for port in ports:
    try:
        reader = R200(port, 115200)
        readers.append(reader)
    except Exception as e:
        print(f"Failed to initialize {port}: {e}")

# Read from all readers
all_tags = []
for reader in readers:
    try:
        tags = reader.read_tags()
        all_tags.extend(tags)
    except Exception as e:
        print(f"Error reading tags: {e}")

# Clean up
for reader in readers:
    reader.close()

Troubleshooting

Common Issues

  1. Permission Denied: Ensure your user has permission to access the serial port

    sudo usermod -a -G dialout $USER  # Linux
    
  2. Port Not Found: Verify the correct port name

    ls /dev/tty*  # Linux
    
  3. No Response: Check connections and baud rate settings

  4. Checksum Errors: Enable debug mode to inspect raw communication

    rfid = R200("/dev/ttyUSB0", debug=True)
    

Debug Output

Enable debug mode to see raw serial communication:

Sent: aa00220003220a0add
Buffer: aa01220011001e9f12041e008bb2d1234567890123dd

Development

Setup Development Environment

# Install dependencies with uv
uv pip install -e .[dev,test]
uv sync --group dev

# Install pre-commit hooks
uv tool install pre-commit --with pre-commit-uv
pre-commit install

Development Commands

# Run tests
make test

# Type checking
make type-check

# Code formatting
make format

# Linting
make lint

# All quality checks
make check

# Build package
make build

# Full development cycle
make dev

See Makefile for all available commands.

License

GNU General Public License v3.0

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rfid_r200-0.1.1.tar.gz (28.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rfid_r200-0.1.1-py3-none-any.whl (27.0 kB view details)

Uploaded Python 3

File details

Details for the file rfid_r200-0.1.1.tar.gz.

File metadata

  • Download URL: rfid_r200-0.1.1.tar.gz
  • Upload date:
  • Size: 28.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for rfid_r200-0.1.1.tar.gz
Algorithm Hash digest
SHA256 8574f1b8b3616571dd7f84e13db6a8d4b40813186d7e6704cd7318499ec2e120
MD5 4545e483b9741f222af9eb82d85d40c3
BLAKE2b-256 1f5f9910f6359225144144bbeffe067c92cf9440be003ca69d8f7221d61e05fa

See more details on using hashes here.

File details

Details for the file rfid_r200-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: rfid_r200-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 27.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for rfid_r200-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 36c296e4d4bbef09f2cf41adb2ef0e6c6dce74d4c0f9f922e241ae53931682fa
MD5 5c612f0400f37bab278d058f0578b78e
BLAKE2b-256 1207fe82e1ec1f1d7f049f3316c1aeac94c7af14866144accf82d22b2eec8c0f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page