123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- //
- // Created by robin on 6/28/15.
- //
-
- #include <winscard.h>
- #include <vector>
- #include "ScReader.h"
-
- LPSCARDCONTEXT ScReader::_context = nullptr;
-
- ScReader::~ScReader()
- {
- disconnect();
- }
-
- bool ScReader::establishContext()
- {
- if (!freeContext())
- return false;
- _context = new SCARDCONTEXT[1];
- auto res = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, _context);
- return res == SCARD_S_SUCCESS;
- }
-
- bool ScReader::freeContext()
- {
- if (!_context)
- return true;
- auto res = SCardReleaseContext(*_context);
- delete[] _context;
- _context = nullptr;
- return res == 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];
- auto res = SCardConnect(*_context, _name.c_str(), shareMode, protocols, _card, _proto);
- return res == SCARD_S_SUCCESS;
- }
-
- bool ScReader::disconnect(DWORD disposition)
- {
- if (!_card)
- return true;
- auto res = SCardDisconnect(*_card, disposition);
- delete[] _proto;
- _proto = nullptr;
- delete[] _card;
- _card = nullptr;
- return res == SCARD_S_SUCCESS;
- }
-
- std::shared_ptr<ScResult> ScReader::transmit(const ScCommand& command, DWORD size)
- {
- auto data = command.getData();
- auto resBuffer = new BYTE[size];
- auto res = SCardTransmit(*_card, _sendPci, data.getData(), data.getSize(), nullptr, resBuffer, &size);
- if (res == SCARD_S_SUCCESS)
- return std::make_shared<ScResult>(ScByteArray(resBuffer, size));
- return std::make_shared<ScResult>(ScByteArray());
- }
-
- std::vector<std::shared_ptr<ScReader>> ScReader::getReaders()
- {
- std::vector<std::shared_ptr<ScReader>> readers;
- DWORD readerCount = SCARD_AUTOALLOCATE;
- LPTSTR readersNames = nullptr;
- auto res = SCardListReaders(*_context, nullptr, (LPTSTR)&readersNames, &readerCount);
- if (res == 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;
- }
|