Keyple Plugin PC/SC C++ Library - 2.5.2
Component of the Keyple C++ middleware
TerminalFactory.cpp
Go to the documentation of this file.
1/******************************************************************************
2 * Copyright (c) 2025 Calypso Networks Association https://calypsonet.org/ *
3 * *
4 * See the NOTICE file(s) distributed with this work for additional *
5 * information regarding copyright ownership. *
6 * *
7 * This program and the accompanying materials are made available under the *
8 * terms of the Eclipse Public License 2.0 which is available at *
9 * http://www.eclipse.org/legal/epl-2.0 *
10 * *
11 * SPDX-License-Identifier: EPL-2.0 *
12 ******************************************************************************/
13
14#include "keyple/plugin/pcsc/cpp/TerminalFactory.hpp"
15
16#include <cstdint>
17#include <cstring>
18#include <vector>
19
20#include "PcscUtils.hpp"
21
22#include "keyple/plugin/pcsc/cpp/exception/CardTerminalException.hpp"
23
24namespace keyple {
25namespace plugin {
26namespace pcsc {
27namespace cpp {
28
29using keyple::plugin::pcsc::cpp::exception::CardTerminalException;
30
31std::shared_ptr<TerminalFactory> TerminalFactory::mInstance;
32
33std::shared_ptr<TerminalFactory>
34TerminalFactory::getDefault()
35{
36 if (mInstance == nullptr) {
37 mInstance = std::shared_ptr<TerminalFactory>(new TerminalFactory());
38
39 }
40
41 return mInstance;
42}
43
44const std::vector<std::string>
45TerminalFactory::listTerminals()
46{
47 ULONG ret;
48 char* readers = NULL;
49 char* ptr = NULL;
50 DWORD len = 0;
51 static std::vector<std::string> list;
52
53 /* Clear list */
54 list.clear();
55
56 ret = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &mContext);
57 if (ret != SCARD_S_SUCCESS) {
58 throw CardTerminalException(pcsc_stringify_error(ret));
59 }
60
61 ret = SCardListReaders(mContext, NULL, NULL, &len);
62 if (ret != SCARD_S_SUCCESS) {
63 throw CardTerminalException(pcsc_stringify_error(ret));
64 }
65
66 readers = static_cast<char*>(calloc(len, sizeof(char)));
67
68 if (readers == NULL) {
69 /* No readers to add to list */
70 return list;
71 }
72
73 ret = SCardListReaders(mContext, NULL, readers, &len);
74 if (ret != SCARD_S_SUCCESS) {
75 throw CardTerminalException(pcsc_stringify_error(ret));
76 }
77
78 ptr = readers;
79
80 if (!ptr) {
81 return list;
82 }
83
84 while (*ptr) {
85 std::string s(ptr);
86 list.push_back(s);
87 ptr += strlen(ptr) + 1;
88 }
89
90 SCardReleaseContext(mContext);
91 free(readers);
92
93 return list;
94}
95
96std::shared_ptr<CardTerminals>
97TerminalFactory::terminals()
98{
99 LONG ret = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &mContext);
100 if (ret != SCARD_S_SUCCESS) {
101 throw CardTerminalException(pcsc_stringify_error(ret));
102 }
103
104 return std::make_shared<CardTerminals>(mContext);
105}
106
107} /* namespace cpp */
108} /* namespace pcsc */
109} /* namespace plugin */
110} /* namespace keyple */
Definition: Card.cpp:20