From bc9630c9279de8b8424d7eefafed2f2cdc8728ae Mon Sep 17 00:00:00 2001 From: Ondrej Mikle Date: Sat, 19 Jul 2014 14:56:15 +0200 Subject: [PATCH] Explicit open() and close() on device. --- brmdoor_nfc.cpp | 41 +++++++++++++++++++++++++++++++---------- brmdoor_nfc.h | 8 ++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/brmdoor_nfc.cpp b/brmdoor_nfc.cpp index c5ce1c2..fc8405b 100644 --- a/brmdoor_nfc.cpp +++ b/brmdoor_nfc.cpp @@ -8,18 +8,33 @@ using namespace std; -NFCDevice::NFCDevice() +NFCDevice::NFCDevice(): + pollNr(20), + pollPeriod(2), + _nfcContext(NULL), + _nfcDevice(NULL), + _opened(false) { - pollNr = 20; - pollPeriod = 2; - - _nfcContext = NULL; - nfc_init(&_nfcContext); if (_nfcContext == NULL) { throw NFCError("Unable to init libnfc (malloc)"); } + open(); +} + +NFCDevice::~NFCDevice() +{ + close(); + nfc_exit(_nfcContext); +} + +void NFCDevice::open() +{ + if (opened()) { + return; + } + _nfcDevice = nfc_open(_nfcContext, NULL); if (_nfcDevice == NULL) { @@ -27,16 +42,22 @@ NFCDevice::NFCDevice() } if (nfc_initiator_init(_nfcDevice) < 0) { - nfc_close(_nfcDevice); + close(); throw NFCError("NFC initiator error"); } + _opened = true; } -NFCDevice::~NFCDevice() +void NFCDevice::close() { - //nfc_close(_nfcDevice); - nfc_exit(_nfcContext); + if (!opened()) { + return; + } + + nfc_close(_nfcDevice); + _nfcDevice = NULL; + _opened = false; } std::string NFCDevice::scanUID() diff --git a/brmdoor_nfc.h b/brmdoor_nfc.h index add9c06..a3ec02a 100644 --- a/brmdoor_nfc.h +++ b/brmdoor_nfc.h @@ -18,6 +18,12 @@ public: std::string scanUID(); + void open(); + + bool opened() const {return _opened;} + + void close(); + uint8_t pollNr; uint8_t pollPeriod; @@ -32,6 +38,8 @@ protected: nfc_device *_nfcDevice; + bool _opened; + };