Драйверы торгового оборудования v.9
inputexample.cpp
1 #include <memory>
2 #include <exception>
3 #include <QLibrary>
4 #include <QDebug>
5 #include <QDir>
6 #include <QThread>
7 
8 // Заголовочные файлы ДТО9
9 #include "ifptr.h"
10 #include "iinput.h"
11 #include "dto_errors.h"
12 #include "dto_const.h"
13 
14 static const bool SCANNER_ON_FPRINT11 = false;
15 static const bool USE_SHOW_PROPERTIES = false;
16 
17 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
18 # include <QTextCodec>
19 
20 static class TrInit
21 {
22 public:
23  TrInit()
24  {
25  QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
26  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
27  QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
28  }
29 } g_TrInit;
30 #endif
31 
32 class Exception : public std::exception {
33 public:
34  Exception(const QString &msg)
35  : m_message(msg)
36  {
37  }
38 
39  virtual ~Exception() throw()
40  {
41  }
42 
43  virtual const char* what() const throw()
44  {
45  static QByteArray rawMessage = m_message.toUtf8();
46  return rawMessage.data();
47  }
48 
49 private:
50  QString m_message;
51 };
52 
53 class Thread : public QThread
54 {
55  Q_OBJECT
56 public:
57  static void sleep(unsigned long secs)
58  {
59  QThread::sleep(secs);
60  }
61 };
62 
63 void checkError(TED::IDTOBase *iface)
64 {
65  if(!iface)
66  throw Exception("Invalid interface");
67 
68  int rc = EC_OK;
69  iface->get_ResultCode(&rc);
70  if(rc < 0)
71  {
72  QString resultDescription, badParamDescription;
73  QVector<wchar_t> v(256);
74  int size = iface->get_ResultDescription(&v[0], v.size());
75  if (size <= 0)
76  throw Exception("get_ResultDescription error");
77  if (size > v.size())
78  {
79  v.clear();
80  v.resize(size + 1);
81  iface->get_ResultDescription(&v[0], v.size());
82  }
83  resultDescription = QString::fromWCharArray(&v[0]);
84  if(rc == EC_INVALID_PARAM) {
85  QVector<wchar_t> v(256);
86  int size = iface->get_BadParamDescription(&v[0], v.size());
87  if (size <= 0)
88  throw Exception("get_BadParamDescription error");
89  if (size > v.size())
90  {
91  v.clear();
92  v.resize(size + 1);
93  iface->get_ResultDescription(&v[0], v.size());
94  }
95  badParamDescription = QString::fromWCharArray(&v[0]);
96  }
97 
98  if(badParamDescription.isEmpty())
99  throw Exception(QObject::trUtf8("[%1] %2")
100  .arg(rc)
101  .arg(resultDescription));
102  else
103  throw Exception(QObject::trUtf8("[%1] %2 (%3)")
104  .arg(rc)
105  .arg(resultDescription)
106  .arg(badParamDescription));
107  }
108 }
109 
110 class Handler : public TED::AbstractEventHandler
111 {
112 public:
113  virtual int on_data_event(void *p = 0)
114  {
116 
117  try
118  {
119  // Забираем данные
120  QVector<wchar_t> v(64);
121  int size = iface->get_ScanData(&v[0], v.size());
122  if (size <= 0)
123  throw Exception("get_ScanData error");
124  if (size > v.size())
125  {
126  v.clear();
127  v.resize(size + 1);
128  iface->get_DeviceSettings(&v[0], v.size());
129  }
130  QString scanData = QString::fromWCharArray(&v[0], v.size());
131  qDebug() << "Data = " << qPrintable(scanData);
132 
133  // Удаляем сообщение из буфера драйвера.
134  // Если удаляете сообщение не сразу, то нужно сохранить значение свойства EventNumber (get_EventNumber()), а потом удалить по нему.
135  iface->DeleteEvent();
136  }
137  catch(const std::exception &ex)
138  {
139  qDebug() << qPrintable(QString::fromUtf8(ex.what()));
140  }
141  return 0;
142  }
143 };
144 
145 int main()
146 {
147  std::auto_ptr<Handler> eventHandler(new Handler);
148 
149 #if defined(Q_OS_LINUX)
150  QLibrary libFptr("../bins/linux-x64/libfptr.so");
151  if(!libFptr.load())
152  {
153  libFptr.setFileName("../bins/linux-x86/libfptr.so");
154  libFptr.load();
155  }
156 #elif defined(Q_OS_WIN32)
157  QLibrary libFptr("../bins/nt-x86-mingw/fptr.dll");
158  libFptr.load();
159 #else
160 # error "Unknown OS"
161 #endif
162 
163  if(!libFptr.isLoaded())
164  {
165  qDebug() << qPrintable(QObject::trUtf8("Не удалось загрузить библиотеку fptr - [%1]")
166  .arg(libFptr.errorString()));
167  return 1;
168  }
169 
170 
171 #if defined(Q_OS_LINUX)
172  QLibrary libInput("../bins/linux-x64/libinput.so");
173  if(!libInput.load())
174  {
175  libInput.setFileName("../bins/linux-x86/libinput.so");
176  libInput.load();
177  }
178 #elif defined(Q_OS_WIN32)
179  QLibrary libInput("../bins/nt-x86-mingw/input.dll");
180  libInput.load();
181 #else
182 # error "Unknown OS"
183 #endif
184 
185  if(!libInput.isLoaded())
186  {
187  qDebug() << qPrintable(QObject::trUtf8("Не удалось загрузить библиотеку input - [%1]")
188  .arg(libInput.errorString()));
189  return 1;
190  }
191 
192  CreateFptrInterfacePtr createFptr = (CreateFptrInterfacePtr) libFptr.resolve("CreateFptrInterface");
193  ReleaseFptrInterfacePtr releaseFptr = (ReleaseFptrInterfacePtr) libFptr.resolve("ReleaseFptrInterface");
194  CreateInputInterfacePtr createInput = (CreateInputInterfacePtr) libInput.resolve("CreateInputInterface");
195  ReleaseInputInterfacePtr releaseInput = (ReleaseInputInterfacePtr) libInput.resolve("ReleaseInputInterface");
196 
197  TED::Fptr::IFptr *ifptr = createFptr(DTO_IFPTR_VER1);
198  if(!ifptr)
199  {
200  qDebug() << qPrintable("Cannot create Fptr object");
201  return 1;
202  }
203  TED::Input::IInput *iinput = createInput(DTO_IINPUT_VER1);
204  if(!iinput)
205  {
206  qDebug() << qPrintable("Cannot create Input object");
207  return 1;
208  }
209 
210  try
211  {
212  // Выставляем рабочий каталог. В нем дККМ и дУВ будут искать требуемые им библиотеки.
213  QFileInfo finfo(libFptr.fileName());
214  if(ifptr->put_DeviceSingleSetting(S_SEARCHDIR, finfo.absolutePath().toStdWString().c_str()) < 0)
215  checkError(ifptr);
216  if(ifptr->ApplySingleSettings() < 0)
217  checkError(ifptr);
218  if(iinput->put_DeviceSingleSetting(S_SEARCHDIR, finfo.absolutePath().toStdWString().c_str()) < 0)
219  checkError(iinput);
220  if(iinput->ApplySingleSettings() < 0)
221  checkError(iinput);
222 
223  // Для настройки драйвера можно вызвать графическое окно настроек
224  if(USE_SHOW_PROPERTIES)
225  {
226  if(ifptr->ShowProperties() < 0)
227  checkError(ifptr);
228  if(iinput->ShowProperties() < 0)
229  checkError(iinput);
230  }
231  // Или настроить без него
232  else
233  {
234  // COM17
235  //if(ifptr->put_DeviceSingleSetting(S_PORT, 17) < 0)
236  //checkError(ifptr);
237  // USB. Можно указать положение на шине (USB$1-1.3, например), но тогда не нужно указывать Vid и Pid
238  // Работа напрямую с USB - Linux Only!
240  checkError(ifptr);
241  if(ifptr->put_DeviceSingleSetting(S_VID, 0x2912) < 0)
242  checkError(ifptr);
243  if(ifptr->put_DeviceSingleSetting(S_PID, 0x0001) < 0)
244  checkError(ifptr);
246  checkError(ifptr);
248  checkError(ifptr);
249  if(ifptr->put_DeviceSingleSetting(S_BAUDRATE, 115200) < 0)
250  checkError(ifptr);
251  if(ifptr->ApplySingleSettings() < 0)
252  checkError(ifptr);
253 
254  // Для работы со стандратными УВ нужно настроить параметры связи с ними
255  if(!SCANNER_ON_FPRINT11)
256  {
257 #if defined(Q_OS_LINUX)
258  // Для работы с клавиатурными устройствами под Linux используется event-интерфейс.
259  // Укажите или eventX, или ссылку на него (например, из /dev/input/by-path).
260  if(iinput->put_DeviceSingleSetting(S_PORT, L"/dev/input/event6") < 0)
261  checkError(iinput);
262 #elif defined(Q_OS_WIN32)
263  // Для работы с клавиатурными устройствами под Windows нужно указать порт KBD
264  if(iinput->put_DeviceSingleSetting(S_PORT, SV_PORT_KBD) < 0)
265  checkError(iinput);
266 #endif
267  // Значение чувствительности. Чем меньше - тем быстрее будут приходить данные, но выше шанс часть потерять.
268  if(iinput->put_DeviceSingleSetting(S_SENS, 50) < 0)
269  checkError(iinput);
270  }
271  // Для работы со сканером, подключенным к FPrint11, нужно установить специальный порт
272  else
273  {
275  checkError(iinput);
276  }
277  // Параметры распознавания данных нужны в любом случае
279  checkError(iinput);
280  if(iinput->put_DeviceSingleSetting(S_PFX, L"") < 0)
281  checkError(iinput);
282  if(iinput->put_DeviceSingleSetting(S_SFX, L"0D") < 0)
283  checkError(iinput);
284  if(iinput->ApplySingleSettings() < 0)
285  checkError(iinput);
286 
287  // Для работы со сканером через FPrint11 необходимо связать дККМ и дУВ
288  if(SCANNER_ON_FPRINT11)
289  {
290  void *hndl;
291  ifptr->get_ScannerPortHandler(&hndl);
292  iinput->put_ScannerPortHandler(hndl);
293  iinput->get_ScannerEventHandler(&hndl);
295  }
296 
297  // Устанавливаем callback, куда будут приходить данные
298  if (iinput->put_EventHandler(eventHandler.get()) < 0)
299  checkError(iinput);
300 
301  // Активируем дККМ
302  if (ifptr->put_DeviceEnabled(1) < 0)
303  checkError(ifptr);
304  // Активируем дУВ
305  if (iinput->put_DeviceEnabled(1) < 0)
306  checkError(iinput);
307 
308  // Включаем выдачу данных
309  if (iinput->put_DataEventEnabled(1) < 0)
310  checkError(iinput);
311 
312  // Процедура сохранения актуальных настроек дУВ. Если пользуетесь ShowProperties(),
313  // то ей можно вытащить актуальные настройки, чтобы потом передать из в драйвер через put_DeviceSettings(),
314  // а не настраивать заново
315  if(true)
316  {
317  QVector<wchar_t> v(256);
318  int size = iinput->get_DeviceSettings(&v[0], v.size());
319  if (size <= 0)
320  throw Exception("get_DeviceSettings error");
321  if (size > v.size())
322  {
323  v.clear();
324  v.resize(size + 1);
325  iinput->get_DeviceSettings(&v[0], v.size());
326  }
327  QString settings = QString::fromWCharArray(&v[0], v.size());
328  // settings - строка с настройками
329  qDebug() << qPrintable(settings);
330  }
331 
332  // Для примера ждем 20 секунд, а потом выключаемся. Данные будет выводить Handler.
333  Thread::sleep(20);
334  }
335  }
336  catch(const std::exception &ex)
337  {
338  qDebug() << qPrintable(ex.what());
339  releaseFptr(&ifptr);
340  releaseInput(&iinput);
341  return 1;
342  }
343 
344  releaseFptr(&ifptr);
345  releaseInput(&iinput);
346  return 0;
347 }
virtual int DTOSHARED_CCA ShowProperties()=0
Выводит диалог настройки драйвера
virtual int DTOSHARED_CCA put_EventHandler(AbstractEventHandler *value)=0
Устанавливает обработчик событий устройства ввода.
Абстрактный обработчик событий
#define S_PID
Definition: dto_const.h:62
#define SV_PORT_USB
Definition: dto_const.h:78
virtual int DTOSHARED_CCA get_ResultCode(int *value)=0
Возвращает результат последней операции
virtual int DTOSHARED_CCA get_ScannerEventHandler(void **value)=0
Возвращает дескриптор для связи дУВ и дККТ.
TED::Input::IInput *(* CreateInputInterfacePtr)(int ver)
Тип функции CreateInputInterface().
Definition: iinput.h:56
#define S_SEARCHDIR
Definition: dto_const.h:36
Базовый интерфейс для работы с драйверами
Definition: idtobase.h:28
void(* ReleaseInputInterfacePtr)(TED::Input::IInput **iface)
Тип функции ReleaseInputInterface().
Definition: iinput.h:58
virtual int DTOSHARED_CCA put_DeviceSingleSetting(const wchar_t *name, const wchar_t *value)=0
Устанавливает значение настроки
TED::Fptr::IFptr *(* CreateFptrInterfacePtr)(int ver)
Тип функции CreateFptrInterface().
Definition: ifptr.h:545
virtual int DTOSHARED_CCA put_ScannerPortHandler(void *value)=0
Устанавливает дескриптор для управления портом ККТ из дУВ.
#define DTO_IINPUT_VER1
Версия интерфейса драйвера устройств ввода
Definition: iinput.h:18
virtual int DTOSHARED_CCA get_DeviceSettings(wchar_t *bfr, int bfrSize)=0
Возвращает строку с текущими настройками драйвера
#define SV_PORT_KBD
Definition: dto_const.h:71
virtual int DTOSHARED_CCA get_ResultDescription(wchar_t *bfr, int bfrSize)=0
Возвращает текстовое описание результата последней операции
#define SV_PORT_SOFT
Definition: dto_const.h:73
virtual int DTOSHARED_CCA DeleteEvent()=0
Удаляет сообщение из внутреннего буфера драйвера.
#define S_VID
Definition: dto_const.h:63
virtual int DTOSHARED_CCA put_DeviceEnabled(int value)=0
Устанавливает логическое состояние драйвера
#define S_PFX
Definition: dto_const.h:140
Интерфейс драйвера устройств ввода (дУВ)
Definition: iinput.h:68
virtual int DTOSHARED_CCA ApplySingleSettings()=0
Применяет установленные настройки
#define EC_OK
Нет ошибки
Definition: dto_errors.h:27
virtual int DTOSHARED_CCA put_ScannerEventHandler(AbstractScannerEventHandler *value)=0
Устанавливает дескриптор для получения данных от устройства ввода.
virtual int DTOSHARED_CCA get_ScanData(wchar_t *bfr, int bfrSize)=0
Возвращает считанные с устройства данные.
#define S_SFX
Definition: dto_const.h:141
#define S_PORT
Definition: dto_const.h:29
virtual int DTOSHARED_CCA get_BadParamDescription(wchar_t *bfr, int bfrSize)=0
Возвращает текстовое описание неверного параметра
#define S_BAUDRATE
Definition: dto_const.h:30
virtual int on_data_event(void *p=0)=0
Callback-функция обработки события
Обработчик событий сканера (для дККТ)
virtual int DTOSHARED_CCA get_ScannerPortHandler(void **value)=0
Возвращает дескриптор для управления портом ККТ из дУВ.
Сканер ШК
Definition: iinput.h:27
#define S_MODEL
Definition: dto_const.h:27
virtual int DTOSHARED_CCA put_DataEventEnabled(int value)=0
Устанавливает флаг обработки событий.
#define S_PROTOCOL
Definition: dto_const.h:28
Интерфейс драйвера контрольно кассовых машин (дККТ)
Definition: ifptr.h:557
#define S_SENS
Definition: dto_const.h:142
#define EC_INVALID_PARAM
Недопустимое значение
Definition: dto_errors.h:37
void(* ReleaseFptrInterfacePtr)(TED::Fptr::IFptr **iface)
Тип функции ReleaseFptrInterface().
Definition: ifptr.h:547