1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- //
- // Created by robin on 6/28/15.
- //
-
- #include <winscard.h>
- #include <vector>
- #include <string.h>
- #include "ScReader.h"
-
- thread_local LPSCARDCONTEXT ScReader::_context = nullptr;
- thread_local LONG ScReader::_lastResult = SCARD_S_SUCCESS;
-
- ScReader::~ScReader()
- {
- disconnect();
- }
-
- bool ScReader::establishContext()
- {
- if (!freeContext())
- return false;
- _context = new SCARDCONTEXT[1];
- _lastResult = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, _context);
- return _lastResult == SCARD_S_SUCCESS;
- }
-
- bool ScReader::freeContext()
- {
- if (!_context)
- return true;
- _lastResult = SCardReleaseContext(*_context);
- delete[] _context;
- _context = nullptr;
- return _lastResult == SCARD_S_SUCCESS;
- }
-
- bool ScReader::connect(DWORD shareMode, DWORD protocols, DWORD disposition)
- {
- if (!disconnect(disposition))
- return false;
- _card = new SCARDCONTEXT[1];
- _proto = new DWORD[1];
- _lastResult = SCardConnect(*_context, _name.c_str(), shareMode, protocols, _card, _proto);
- if (*_proto == SCARD_PROTOCOL_T0)
- _sendPci = *SCARD_PCI_T0;
- if (*_proto == SCARD_PROTOCOL_T1)
- _sendPci = *SCARD_PCI_T1;
- return _lastResult == SCARD_S_SUCCESS;
- }
-
- bool ScReader::disconnect(DWORD disposition)
- {
- if (!_card)
- return true;
- _lastResult = SCardDisconnect(*_card, disposition);
- delete[] _proto;
- _proto = nullptr;
- delete[] _card;
- _card = nullptr;
- return _lastResult == SCARD_S_SUCCESS;
- }
-
- std::shared_ptr<ScResult> ScReader::transmit(const ScCommand& command, DWORD size)
- {
- auto data = command.getData();
- auto resBuffer = new BYTE[size];
- _lastResult = SCardTransmit(*_card, &_sendPci, (BYTE*)data.data(), data.size(), nullptr, resBuffer, &size);
- if (_lastResult == SCARD_S_SUCCESS)
- return std::make_shared<ScResult>(std::string((char*)resBuffer, size));
- return std::make_shared<ScResult>("");
- }
-
- std::vector<std::shared_ptr<ScReader>> ScReader::getReaders()
- {
- std::vector<std::shared_ptr<ScReader>> readers;
- DWORD readerCount = SCARD_AUTOALLOCATE;
- LPTSTR readersNames = nullptr;
- _lastResult = SCardListReaders(*_context, nullptr, (LPTSTR)&readersNames, &readerCount);
- if (_lastResult == SCARD_S_SUCCESS)
- {
- LPTSTR reader = readersNames;
- while (*reader)
- {
- readers.push_back(std::make_shared<ScReader>(reader));
- reader += strlen(reader) + 1;
- }
- }
- SCardFreeMemory(*_context, readersNames);
- return readers;
- }
-
- LONG ScReader::getLastResult()
- {
- return _lastResult;
- }
|