diff --git a/brmdoor_nfc.cpp b/brmdoor_nfc.cpp index 2b38486..c64ef82 100644 --- a/brmdoor_nfc.cpp +++ b/brmdoor_nfc.cpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -13,7 +14,8 @@ NFCDevice::NFCDevice() throw(NFCError): pollPeriod(2), _nfcContext(NULL), _nfcDevice(NULL), - _opened(false) + _opened(false), + _unloaded(false) { nfc_init(&_nfcContext); if (_nfcContext == NULL) { @@ -26,7 +28,7 @@ NFCDevice::NFCDevice() throw(NFCError): NFCDevice::~NFCDevice() { close(); - nfc_exit(_nfcContext); + unload(); } void NFCDevice::open() throw(NFCError) @@ -55,11 +57,26 @@ void NFCDevice::close() return; } + assert(_nfcDevice); + nfc_close(_nfcDevice); _nfcDevice = NULL; _opened = false; } +void NFCDevice::unload() +{ + if (_unloaded) { + return; + } + + assert(_nfcContext); + + nfc_exit(_nfcContext); + _nfcContext = NULL; + _unloaded = true; +} + std::string NFCDevice::scanUID() throw(NFCError) { int res; diff --git a/brmdoor_nfc.h b/brmdoor_nfc.h index 143c86b..bb1c649 100644 --- a/brmdoor_nfc.h +++ b/brmdoor_nfc.h @@ -71,12 +71,18 @@ public: /** Open device explicitly. May be useful after explicit close */ void open() throw(NFCError); - /** Returns true iff device was opened */ - bool opened() const {return _opened;} + /** Returns true iff device was opened and not unloaded. */ + bool opened() const {return _opened && !_unloaded;} /** Close reader. You need to reopen before reading again */ void close(); + /** + * Unload all structures, close device. It's kind of explicit destructor + * since we can't be sure the destructor will be called in Python. + */ + void unload(); + /** * Specifies the number of polling (0x01 – 0xFE: 1 up to 254 polling, 0xFF: * Endless polling) @@ -106,6 +112,9 @@ protected: /** Whether device has been successfully opened */ bool _opened; + /** Whether device and its internal libnfc structures have been unloaded */ + bool _unloaded; + }; diff --git a/runme.py b/runme.py index 428f59e..6ce3d84 100755 --- a/runme.py +++ b/runme.py @@ -11,5 +11,6 @@ try: print "Closing device" nfc.close() print "Device is opened:", nfc.opened() + nfc.unload() except NFCError, e: print "Reading UID failed:", e.what()