-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
executable file
·568 lines (461 loc) · 21.7 KB
/
main.py
File metadata and controls
executable file
·568 lines (461 loc) · 21.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
"""
NFC Library - A high-level wrapper for NFC operations
This module provides a simplified interface for working with NFC readers and tags,
wrapping the lower-level nfcpy and ndef libraries to provide a more user-friendly experience
with robust error handling, automatic device detection, and configurable settings.
Usage:
from nfc_library import create_nfc_library
# Create an NFC library instance
nfc_lib = create_nfc_library()
# Get available devices
devices = nfc_lib.devices()
# Write to the first device
nfc_lib.write(devices[0], "Hello, NFC World!")
# Clean up resources
nfc_lib.stop()
Requirements:
- nfcpy
- ndef
- Python 3.6+
"""
import nfc
import ndef
import subprocess
import re
import json
import time
import os
import logging
import threading
from typing import List, Dict, Any, Optional, Union, Tuple, cast
class NFCLibrary:
"""
A high-level wrapper for NFC operations.
This class provides methods for detecting NFC readers and performing
tag operations such as writing NDEF messages with proper error handling
and configuration options.
Attributes:
logger (logging.Logger): Logger for recording operation details
config (Dict[str, Any]): Configuration settings for the library
active_device_id (str): ID of the currently active device
active_clf (nfc.ContactlessFrontend): Active NFC reader connection
is_connection_active (bool): Whether a connection is currently active
"""
def __init__(self, config_path: str = "config.json", logger: Optional[logging.Logger] = None):
"""
Initialize the NFC Library.
Args:
config_path (str): Path to the configuration JSON file
logger (logging.Logger, optional): Custom logger instance. If None,
a default logger will be created.
"""
# Set up logging
self.logger = logger or self._setup_default_logger()
self.logger.info("Initializing NFC Library")
self.config = self._load_config(config_path)
self.logger.debug(f"Loaded configuration: {self.config}")
self.active_device_id = None
self.active_clf = None
self.is_connection_active = False
self._tag_found = False
self._reader_lock = threading.Lock()
# Initialize devices
if not self.config["devices"]:
self.logger.info("No devices configured, performing auto-scan")
self._auto_scan_devices()
self.logger.info(f"Auto-scan found {len(self.config['devices'])} devices")
def _setup_default_logger(self) -> logging.Logger:
"""
Create and configure a default logger if none is provided.
Returns:
logging.Logger: Configured logger instance
"""
logger = logging.getLogger("nfc_library")
logger.setLevel(logging.INFO)
# Create console handler
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add handler to logger
logger.addHandler(handler)
return logger
def _load_config(self, config_path: str) -> Dict[str, Any]:
"""
Load configuration from a JSON file, with fallbacks to defaults.
Args:
config_path (str): Path to the configuration file
Returns:
Dict[str, Any]: Configuration dictionary
Raises:
json.JSONDecodeError: If the configuration file cannot be parsed
"""
if not os.path.exists(config_path):
self.logger.warning(f"Configuration file {config_path} not found. Using default configuration.")
# Create default configuration
default_config = {
"devices": [],
"lock_on_write": False,
"validate_writes": True,
"retry_count": 3,
"retry_delay": 0.5,
"timeout": 5.0
}
return default_config
try:
with open(config_path, 'r') as f:
config = json.load(f)
self.logger.info(f"Successfully loaded configuration from {config_path}")
except json.JSONDecodeError as e:
self.logger.error(f"Failed to parse configuration file: {e}")
raise
# Ensure all required fields exist
required_fields = [
"devices", "lock_on_write", "validate_writes",
"retry_count", "retry_delay", "timeout"
]
for field in required_fields:
if field not in config:
if field == "devices":
config[field] = []
elif field == "lock_on_write":
config[field] = False
elif field == "validate_writes":
config[field] = True
elif field == "retry_count":
config[field] = 3
elif field == "retry_delay":
config[field] = 0.5
elif field == "timeout":
config[field] = 5.0
self.logger.warning(f"Missing required field '{field}' in config. Using default value: {config[field]}")
return config
def _auto_scan_devices(self) -> None:
"""
Automatically scan and detect connected NFC readers.
Currently supports detecting ACR122U readers (USB ID 072f:2200).
Raises:
Exception: If an error occurs during the scan process
"""
self.logger.info("Starting automatic device scan")
try:
result = subprocess.run(["lsusb"], capture_output=True, text=True)
device_id = 1
for line in result.stdout.strip().split("\n"):
if "072f:2200" in line: # Match ACR122U
match = re.match(r"Bus (\d{3}) Device (\d{3})", line)
if match:
bus, dev = match.groups()
path = f"usb:{bus}:{dev}"
# Create a unique ID for the device
device_id_str = f"device_{device_id}"
device_id += 1
# Add the device to the configuration
device_info = {
"id": device_id_str,
"path": path,
"description": "ACR122U NFC Reader (Auto-detected)"
}
self.config["devices"].append(device_info)
self.logger.info(f"Detected device: {device_info}")
except Exception as e:
self.logger.error(f"Error during device scan: {e}")
raise
def devices(self) -> List[str]:
"""
Get a list of available NFC device IDs.
Returns:
List[str]: List of device IDs
"""
device_ids = [device["id"] for device in self.config["devices"]]
self.logger.debug(f"Available devices: {device_ids}")
return device_ids
def _find_device_path(self, device_id: str) -> Optional[str]:
"""
Find the path for a device by its ID.
Args:
device_id (str): Device ID to look up
Returns:
Optional[str]: Device path if found, None otherwise
"""
for device in self.config["devices"]:
if device["id"] == device_id:
self.logger.debug(f"Found path for device {device_id}: {device['path']}")
return device["path"]
self.logger.warning(f"No path found for device ID: {device_id}")
return None
def _ensure_device_active(self, device_id: str) -> bool:
"""
Ensure that the specified device is active and ready for operations.
If a different device is currently active, it will be closed first.
Args:
device_id (str): ID of the device to activate
Returns:
bool: True if the device is successfully activated, False otherwise
"""
# If this device is already active, nothing to do
if self.active_device_id == device_id and self.active_clf is not None and self.is_connection_active:
self.logger.debug(f"Device {device_id} is already active")
return True
# If a different device is active, close it
if self.active_clf is not None:
self.logger.info(f"Closing currently active device {self.active_device_id}")
try:
self.active_clf.close()
except Exception as e:
self.logger.error(f"Error closing device {self.active_device_id}: {e}")
finally:
self.active_clf = None
self.active_device_id = None
self.is_connection_active = False
# Get the path for the new device
device_path = self._find_device_path(device_id)
if not device_path:
self.logger.error(f"Invalid device ID: {device_id}")
return False
# Open the new device with manual timeout
try:
self.logger.info(f"Opening connection to device {device_id} at {device_path}")
# Use threading to implement timeout
result = {"clf": None, "success": False, "error": None}
def open_device():
try:
result["clf"] = nfc.ContactlessFrontend(device_path)
result["success"] = True
except Exception as e:
result["error"] = e
thread = threading.Thread(target=open_device)
thread.daemon = True
thread.start()
thread.join(timeout=self.config["timeout"])
if not result["success"]:
if thread.is_alive():
self.logger.error(f"Timeout while opening device {device_id}")
return False
elif result["error"]:
self.logger.error(f"Error opening device {device_id}: {result['error']}")
return False
self.active_clf = result["clf"]
self.active_device_id = device_id
self.is_connection_active = True
return True
except Exception as e:
self.logger.error(f"Error opening device {device_id}: {e}")
return False
def _create_ndef_message(self, message: Union[str, Dict, List]) -> Any:
"""
Create an NDEF message from various input formats.
Args:
message: The message to create. Can be:
- A string (simple text message)
- A dictionary with 'type' and 'value' keys
- A list of dictionaries with 'type' and 'value' keys
Returns:
List[ndef.Record]: List of NDEF records
Raises:
ValueError: If the message format is invalid or unsupported
"""
self.logger.debug(f"Creating NDEF message from: {message}")
if isinstance(message, str):
# Simple text message
self.logger.debug("Creating text record from string")
record = ndef.TextRecord(message)
return [record]
elif isinstance(message, dict):
# Single record with type specification
if "type" not in message or "value" not in message:
self.logger.error("Dictionary message missing required 'type' or 'value' keys")
raise ValueError("Dictionary message must have 'type' and 'value' keys")
if message["type"] == "text":
self.logger.debug(f"Creating text record: {message['value']}")
record = ndef.TextRecord(message["value"])
return [record]
elif message["type"] == "uri":
self.logger.debug(f"Creating URI record: {message['value']}")
record = ndef.UriRecord(message["value"])
return [record]
else:
self.logger.error(f"Unsupported record type: {message['type']}")
raise ValueError(f"Unsupported record type: {message['type']}")
elif isinstance(message, list):
# Multiple records
self.logger.debug(f"Creating {len(message)} records from list")
records = []
for i, record in enumerate(message):
if not isinstance(record, dict) or "type" not in record or "value" not in record:
self.logger.error(f"Record {i} in list is invalid")
raise ValueError("Each record in the list must be a dictionary with 'type' and 'value' keys")
if record["type"] == "text":
self.logger.debug(f"Creating text record {i}: {record['value']}")
records.append(ndef.TextRecord(record["value"]))
elif record["type"] == "uri":
self.logger.debug(f"Creating URI record {i}: {record['value']}")
records.append(ndef.UriRecord(record["value"]))
else:
self.logger.error(f"Unsupported record type in record {i}: {record['type']}")
raise ValueError(f"Unsupported record type: {record['type']}")
return records
else:
self.logger.error(f"Unsupported message type: {type(message)}")
raise ValueError("Message must be a string, dictionary, or list of records")
def _validate_write(self, tag, ndef_message: List) -> bool:
"""
Validate that a tag was written correctly by comparing the original message
with what was actually written to the tag.
Args:
tag: The NFC tag object
ndef_message (List): The original NDEF message
Returns:
bool: True if validation passed, False otherwise
"""
self.logger.debug("Validating tag write")
if not tag.ndef:
self.logger.error("Validation failed: Tag doesn't support NDEF")
return False
# Compare the written message with the original
original_records = ndef_message
written_records = tag.ndef.records
if len(original_records) != len(written_records):
self.logger.error(f"Validation failed: Record count mismatch - original: {len(original_records)}, written: {len(written_records)}")
return False
for i, (orig, written) in enumerate(zip(original_records, written_records)):
if orig.type != written.type or orig.data != written.data:
self.logger.error(f"Validation failed: Record {i} data mismatch")
return False
self.logger.info("Write validation successful")
return True
def write(self, device_id: str, message: Union[str, Dict, List]) -> bool:
"""
Write an NDEF message to a tag using the specified device.
Returns control immediately after successful write.
Args:
device_id (str): ID of the device to use
message: The message to write. Can be:
- A string (simple text message)
- A dictionary with 'type' and 'value' keys
- A list of dictionaries with 'type' and 'value' keys
Returns:
bool: True if the write was successful
Raises:
ValueError: If the device cannot be activated
Exception: If no tag is detected within the timeout period
Various exceptions from the underlying NFC libraries
"""
self.logger.info(f"Writing to device {device_id}")
# Reset the reader first to clear any lingering RF field state
self._reset_reader(device_id)
# Ensure the device is active
if not self._ensure_device_active(device_id):
raise ValueError(f"Failed to activate device {device_id}")
# Prepare the NDEF message
ndef_message = self._create_ndef_message(message)
# Use a threading lock to prevent concurrent tag detection
with self._reader_lock:
# Clear any previous detection state
self._tag_found = False
write_success = False
# Use an event to signal when writing is complete
write_completed = threading.Event()
# Define the on-connect callback with better state management
def on_tag_connect(tag):
nonlocal write_success
# Skip if we already processed a tag in this operation
if self._tag_found:
return True
self._tag_found = True
self.logger.info(f"Tag detected - UID: {tag.identifier.hex().upper()}")
try:
if not tag.ndef or not tag.ndef.is_writeable:
return True
# Write the message
self.logger.info("Writing NDEF message to tag")
tag.ndef.records = ndef_message
# Validate if needed
if self.config["validate_writes"]:
if not self._validate_write(tag, ndef_message):
return True
self.logger.info("Tag write successful")
write_success = True
# Signal completion and force termination
write_completed.set()
except Exception as e:
self.logger.error(f"Error during tag operation: {e}")
return True
# Start tag detection
try:
# Use direct connect rather than threading to avoid race conditions
self.active_clf.connect(
rdwr={'on-connect': on_tag_connect},
terminate=lambda: write_completed.is_set() or not self.is_connection_active
)
except Exception as e:
self.logger.error(f"Connection error: {e}")
if write_success:
self.logger.info("Returning control after successful write")
# Force field off immediately to prepare for next tag
self._force_field_off()
return True
raise Exception("No tag detected within timeout period")
def _reset_reader(self, device_id):
"""
Force a complete reset of the NFC reader to clear any lingering RF field state.
Args:
device_id (str): ID of the device to reset
"""
# If this device is active, close it first
if self.active_clf is not None:
try:
self.active_clf.close()
except Exception:
pass
self.active_clf = None
self.active_device_id = None
self.is_connection_active = False
# Small delay to ensure hardware reset
time.sleep(0.05)
def _force_field_off(self):
"""
Force the RF field to turn off.
This is a device-specific operation that may require direct communication
with the reader hardware. The current implementation is a placeholder.
"""
# For ACR122U readers, sending specific direct commands can force field off
# This requires pyscard integration
try:
if self.active_clf and hasattr(self.active_clf, 'device'):
# This will depend on your specific NFC library implementation
# For ACR122U with pyscard:
# self.active_clf.device.transmit([0xFF, 0x00, 0x00, 0x00, 0x00])
pass
except:
pass
def stop(self) -> None:
"""
Stop all active NFC connections and release resources.
This should be called when the library is no longer needed to ensure
proper cleanup of hardware resources.
"""
if self.active_clf is not None:
self.logger.info(f"Closing device {self.active_device_id}")
try:
self.active_clf.close()
except Exception as e:
self.logger.error(f"Error closing device {self.active_device_id}: {e}")
finally:
self.active_clf = None
self.active_device_id = None
self.is_connection_active = False
else:
self.logger.debug("No active device to close")
def create_nfc_library(config_path: str = "config.json", logger: Optional[logging.Logger] = None) -> NFCLibrary:
"""
Factory function to create an NFCLibrary instance.
This is the recommended way to create an NFCLibrary object.
Args:
config_path (str): Path to the configuration JSON file
logger (logging.Logger, optional): Custom logger instance
Returns:
NFCLibrary: A configured NFCLibrary instance
"""
return NFCLibrary(config_path, logger)