You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ScReader.cpp 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //
  2. // Created by robin on 6/28/15.
  3. //
  4. #include <winscard.h>
  5. #include <vector>
  6. #include "ScReader.h"
  7. LPSCARDCONTEXT ScReader::_context = nullptr;
  8. ScReader::~ScReader()
  9. {
  10. disconnect();
  11. }
  12. bool ScReader::establishContext()
  13. {
  14. if (!freeContext())
  15. return false;
  16. _context = new SCARDCONTEXT[1];
  17. auto res = SCardEstablishContext(SCARD_SCOPE_SYSTEM, nullptr, nullptr, _context);
  18. return res == SCARD_S_SUCCESS;
  19. }
  20. bool ScReader::freeContext()
  21. {
  22. if (!_context)
  23. return true;
  24. auto res = SCardReleaseContext(*_context);
  25. delete[] _context;
  26. _context = nullptr;
  27. return res == SCARD_S_SUCCESS;
  28. }
  29. bool ScReader::connect(DWORD shareMode, DWORD protocols, DWORD disposition)
  30. {
  31. if (!disconnect(disposition))
  32. return false;
  33. _card = new SCARDCONTEXT[1];
  34. _proto = new DWORD[1];
  35. auto res = SCardConnect(*_context, _name.c_str(), shareMode, protocols, _card, _proto);
  36. return res == SCARD_S_SUCCESS;
  37. }
  38. bool ScReader::disconnect(DWORD disposition)
  39. {
  40. if (!_card)
  41. return true;
  42. auto res = SCardDisconnect(*_card, disposition);
  43. delete[] _proto;
  44. _proto = nullptr;
  45. delete[] _card;
  46. _card = nullptr;
  47. return res == SCARD_S_SUCCESS;
  48. }
  49. std::shared_ptr<ScResult> ScReader::transmit(const ScCommand& command, DWORD size)
  50. {
  51. auto data = command.getData();
  52. auto resBuffer = new BYTE[size];
  53. auto res = SCardTransmit(*_card, _sendPci, data.getData(), data.getSize(), nullptr, resBuffer, &size);
  54. if (res == SCARD_S_SUCCESS)
  55. return std::make_shared<ScResult>(ScByteArray(resBuffer, size));
  56. return std::make_shared<ScResult>(ScByteArray());
  57. }
  58. std::vector<std::shared_ptr<ScReader>> ScReader::getReaders()
  59. {
  60. std::vector<std::shared_ptr<ScReader>> readers;
  61. DWORD readerCount = SCARD_AUTOALLOCATE;
  62. LPTSTR readersNames = nullptr;
  63. auto res = SCardListReaders(*_context, nullptr, (LPTSTR)&readersNames, &readerCount);
  64. if (res == SCARD_S_SUCCESS)
  65. {
  66. LPTSTR reader = readersNames;
  67. while (*reader)
  68. {
  69. readers.push_back(std::make_shared<ScReader>(reader));
  70. reader += strlen(reader) + 1;
  71. }
  72. }
  73. SCardFreeMemory(*_context, readersNames);
  74. return readers;
  75. }