Explicit unload() 'destructor'

This commit is contained in:
Ondrej Mikle 2014-07-19 20:09:05 +02:00
parent 3717cb2563
commit bbec77f248
3 changed files with 31 additions and 4 deletions

View file

@ -1,4 +1,5 @@
#include <string> #include <string>
#include <cassert>
#include <nfc/nfc.h> #include <nfc/nfc.h>
#include <nfc/nfc-types.h> #include <nfc/nfc-types.h>
@ -13,7 +14,8 @@ NFCDevice::NFCDevice() throw(NFCError):
pollPeriod(2), pollPeriod(2),
_nfcContext(NULL), _nfcContext(NULL),
_nfcDevice(NULL), _nfcDevice(NULL),
_opened(false) _opened(false),
_unloaded(false)
{ {
nfc_init(&_nfcContext); nfc_init(&_nfcContext);
if (_nfcContext == NULL) { if (_nfcContext == NULL) {
@ -26,7 +28,7 @@ NFCDevice::NFCDevice() throw(NFCError):
NFCDevice::~NFCDevice() NFCDevice::~NFCDevice()
{ {
close(); close();
nfc_exit(_nfcContext); unload();
} }
void NFCDevice::open() throw(NFCError) void NFCDevice::open() throw(NFCError)
@ -55,11 +57,26 @@ void NFCDevice::close()
return; return;
} }
assert(_nfcDevice);
nfc_close(_nfcDevice); nfc_close(_nfcDevice);
_nfcDevice = NULL; _nfcDevice = NULL;
_opened = false; _opened = false;
} }
void NFCDevice::unload()
{
if (_unloaded) {
return;
}
assert(_nfcContext);
nfc_exit(_nfcContext);
_nfcContext = NULL;
_unloaded = true;
}
std::string NFCDevice::scanUID() throw(NFCError) std::string NFCDevice::scanUID() throw(NFCError)
{ {
int res; int res;

View file

@ -71,12 +71,18 @@ public:
/** Open device explicitly. May be useful after explicit close */ /** Open device explicitly. May be useful after explicit close */
void open() throw(NFCError); void open() throw(NFCError);
/** Returns true iff device was opened */ /** Returns true iff device was opened and not unloaded. */
bool opened() const {return _opened;} bool opened() const {return _opened && !_unloaded;}
/** Close reader. You need to reopen before reading again */ /** Close reader. You need to reopen before reading again */
void close(); 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: * Specifies the number of polling (0x01 0xFE: 1 up to 254 polling, 0xFF:
* Endless polling) * Endless polling)
@ -106,6 +112,9 @@ protected:
/** Whether device has been successfully opened */ /** Whether device has been successfully opened */
bool _opened; bool _opened;
/** Whether device and its internal libnfc structures have been unloaded */
bool _unloaded;
}; };

View file

@ -11,5 +11,6 @@ try:
print "Closing device" print "Closing device"
nfc.close() nfc.close()
print "Device is opened:", nfc.opened() print "Device is opened:", nfc.opened()
nfc.unload()
except NFCError, e: except NFCError, e:
print "Reading UID failed:", e.what() print "Reading UID failed:", e.what()