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 strengthpc: int- Protocol Control wordepc: List[int]- Electronic Product Codecrc: int- Cyclic Redundancy Check
R200Response
Raw response from the module:
type: int- Frame typecommand: int- Command codechecksum: int- Checksum valuechecksum_ok: bool- Checksum validation resultparams: List[int]- Response parameters
Available Commands
The library includes constants for all R200 commands:
CMD_GET_MODULE_INFO- Get module informationCMD_SINGLE_POLL_INSTRUCTION- Single tag pollCMD_MULTIPLE_POLL_INSTRUCTION- Multiple tag pollCMD_READ_LABEL- Read tag dataCMD_WRITE_LABEL- Write tag dataCMD_LOCK_LABEL- Lock tagCMD_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
-
Permission Denied: Ensure your user has permission to access the serial port
sudo usermod -a -G dialout $USER # Linux
-
Port Not Found: Verify the correct port name
ls /dev/tty* # Linux
-
No Response: Check connections and baud rate settings
-
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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8574f1b8b3616571dd7f84e13db6a8d4b40813186d7e6704cd7318499ec2e120
|
|
| MD5 |
4545e483b9741f222af9eb82d85d40c3
|
|
| BLAKE2b-256 |
1f5f9910f6359225144144bbeffe067c92cf9440be003ca69d8f7221d61e05fa
|
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
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
36c296e4d4bbef09f2cf41adb2ef0e6c6dce74d4c0f9f922e241ae53931682fa
|
|
| MD5 |
5c612f0400f37bab278d058f0578b78e
|
|
| BLAKE2b-256 |
1207fe82e1ec1f1d7f049f3316c1aeac94c7af14866144accf82d22b2eec8c0f
|