Драйверы торгового оборудования v.9
displayexample.cpp
1 #include <exception>
2 #include <QLibrary>
3 #include <QDebug>
4 #include <QDir>
5 #include <QThread>
6 
7 // Заголовочные файлы ДТО9
8 #include "idisplay.h"
9 #include "ifptr.h"
10 #include "dto_errors.h"
11 #include "dto_const.h"
12 
13 static const bool USE_SHOW_PROPERTIES = false;
14 static const bool DISPLAY_ON_FPTR = false;
15 
16 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
17 # include <QTextCodec>
18 
19 static class TrInit
20 {
21 public:
22  TrInit()
23  {
24  QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
25  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
26  QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
27  }
28 } g_TrInit;
29 #endif
30 
31 class Exception : public std::exception {
32 public:
33  Exception(const QString &msg)
34  : m_message(msg)
35  {
36  }
37 
38  virtual ~Exception() throw()
39  {
40  }
41 
42  virtual const char* what() const throw()
43  {
44  static QByteArray rawMessage = m_message.toUtf8();
45  return rawMessage.data();
46  }
47 
48 private:
49  QString m_message;
50 };
51 
52 class Thread : public QThread
53 {
54  Q_OBJECT
55 public:
56  static void sleep(unsigned long secs)
57  {
58  QThread::sleep(secs);
59  }
60 };
61 
62 void checkError(TED::IDTOBase *iface)
63 {
64  if(!iface)
65  throw Exception("Invalid interface");
66 
67  int rc = EC_OK;
68  iface->get_ResultCode(&rc);
69  if(rc < 0)
70  {
71  QString resultDescription, badParamDescription;
72  QVector<wchar_t> v(256);
73  int size = iface->get_ResultDescription(&v[0], v.size());
74  if (size <= 0)
75  throw Exception("get_ResultDescription error");
76  if (size > v.size())
77  {
78  v.clear();
79  v.resize(size + 1);
80  iface->get_ResultDescription(&v[0], v.size());
81  }
82  resultDescription = QString::fromWCharArray(&v[0]);
83  if(rc == EC_INVALID_PARAM) {
84  QVector<wchar_t> v(256);
85  int size = iface->get_BadParamDescription(&v[0], v.size());
86  if (size <= 0)
87  throw Exception("get_BadParamDescription error");
88  if (size > v.size())
89  {
90  v.clear();
91  v.resize(size + 1);
92  iface->get_ResultDescription(&v[0], v.size());
93  }
94  badParamDescription = QString::fromWCharArray(&v[0]);
95  }
96 
97  if(badParamDescription.isEmpty())
98  throw Exception(QObject::trUtf8("[%1] %2")
99  .arg(rc)
100  .arg(resultDescription));
101  else
102  throw Exception(QObject::trUtf8("[%1] %2 (%3)")
103  .arg(rc)
104  .arg(resultDescription)
105  .arg(badParamDescription));
106  }
107 }
108 
109 int main()
110 {
111 #if defined(Q_OS_LINUX)
112  QLibrary libFptr("../bins/linux-x64/libfptr.so");
113  if(!libFptr.load())
114  {
115  libFptr.setFileName("../bins/linux-x86/libfptr.so");
116  libFptr.load();
117  }
118 #elif defined(Q_OS_WIN32)
119  QLibrary libFptr("../bins/nt-x86-mingw/fptr.dll");
120  libFptr.load();
121 #else
122 # error "Unknown OS"
123 #endif
124 
125  if(!libFptr.isLoaded())
126  {
127  qDebug() << qPrintable(QObject::trUtf8("Не удалось загрузить библиотеку fptr - [%1]")
128  .arg(libFptr.errorString()));
129  return 1;
130  }
131 
132 
133 #if defined(Q_OS_LINUX)
134  QLibrary libDisplay("../bins/linux-x64/libdisplay.so");
135  if(!libDisplay.load())
136  {
137  libDisplay.setFileName("../bins/linux-x86/libdisplay.so");
138  libDisplay.load();
139  }
140 #elif defined(Q_OS_WIN32)
141  QLibrary libDisplay("../bins/nt-x86-mingw/display.dll");
142  libDisplay.load();
143 #else
144 # error "Unknown OS"
145 #endif
146 
147  if(!libDisplay.isLoaded())
148  {
149  qDebug() << qPrintable(QObject::trUtf8("Не удалось загрузить библиотеку display - [%1]")
150  .arg(libDisplay.errorString()));
151  return 1;
152  }
153 
154  CreateFptrInterfacePtr createFptr = (CreateFptrInterfacePtr) libFptr.resolve("CreateFptrInterface");
155  ReleaseFptrInterfacePtr releaseFptr = (ReleaseFptrInterfacePtr) libFptr.resolve("ReleaseFptrInterface");
156  CreateDisplayInterfacePtr createDisplay = (CreateDisplayInterfacePtr) libDisplay.resolve("CreateDisplayInterface");
157  ReleaseDisplayInterfacePtr releaseDisplay = (ReleaseDisplayInterfacePtr) libDisplay.resolve("ReleaseDisplayInterface");
158 
159  TED::Fptr::IFptr *ifptr = createFptr(DTO_IFPTR_VER1);
160  if(!ifptr)
161  {
162  qDebug() << qPrintable("Cannot create Fptr object");
163  return 1;
164  }
165  TED::Display::IDisplay *idisplay = createDisplay(DTO_IDISPLAY_VER1);
166  if(!idisplay)
167  {
168  qDebug() << qPrintable("Cannot create Display object");
169  return 1;
170  }
171 
172  try
173  {
174  // Выставляем рабочий каталог. В нем дККМ и дДП будут искать требуемые им библиотеки.
175  QFileInfo finfo(libFptr.fileName());
176  if(ifptr->put_DeviceSingleSetting(S_SEARCHDIR, finfo.absolutePath().toStdWString().c_str()) < 0)
177  checkError(ifptr);
178  if(ifptr->ApplySingleSettings() < 0)
179  checkError(ifptr);
180  if(idisplay->put_DeviceSingleSetting(S_SEARCHDIR, finfo.absolutePath().toStdWString().c_str()) < 0)
181  checkError(idisplay);
182  if(idisplay->ApplySingleSettings() < 0)
183  checkError(idisplay);
184 
185  // Для настройки драйвера можно вызвать графическое окно настроек
186  if(USE_SHOW_PROPERTIES)
187  {
188  if(ifptr->ShowProperties() < 0)
189  checkError(ifptr);
190  if(idisplay->ShowProperties() < 0)
191  checkError(idisplay);
192  }
193  // Или настроить без него
194  else
195  {
196  // COM17
197  //if(ifptr->put_DeviceSingleSetting(S_PORT, 17) < 0)
198  //checkError(ifptr);
199  // USB. Можно указать положение на шине (USB$1-1.3, например), но тогда не нужно указывать Vid и Pid
200  // Работа напрямую с USB - Linux Only!
202  checkError(ifptr);
203  if(ifptr->put_DeviceSingleSetting(S_VID, 0x2912) < 0)
204  checkError(ifptr);
205  if(ifptr->put_DeviceSingleSetting(S_PID, 0x0001) < 0)
206  checkError(ifptr);
208  checkError(ifptr);
210  checkError(ifptr);
211  if(ifptr->put_DeviceSingleSetting(S_BAUDRATE, 115200) < 0)
212  checkError(ifptr);
213  if(ifptr->ApplySingleSettings() < 0)
214  checkError(ifptr);
215 
216  // Для работы со стандратными ДП нужно настроить параметры связи с ними
217  if(!DISPLAY_ON_FPTR)
218  {
219  if(idisplay->put_DeviceSingleSetting(S_PORT, SV_PORT_TTY) < 0)
220  checkError(idisplay);
221  if(idisplay->put_DeviceSingleSetting(S_DEVICEFILE, L"ttyACM0") < 0)
222  checkError(idisplay);
223  if(idisplay->put_DeviceSingleSetting(S_BAUDRATE, 115200) < 0)
224  checkError(idisplay);
225  }
226  // Для работы с дисплеем, подключенным к ККМ, нужно установить специальный порт.
227  // Также согласуйте скорости портов в таблицах ККМ.
228  else
229  {
230  if(idisplay->put_DeviceSingleSetting(S_PORT, SV_PORT_SOFT) < 0)
231  checkError(idisplay);
232  }
234  checkError(idisplay);
235  if(idisplay->ApplySingleSettings() < 0)
236  checkError(idisplay);
237 
238  // Для работы через ККМ необходимо связать дККМ и дДП
239  if(DISPLAY_ON_FPTR)
240  {
241  void *hndl;
242  ifptr->get_ClsPtr(&hndl);
243  idisplay->put_ClsPtr(hndl);
244  }
245 
246  // Активируем дККМ
247  if (ifptr->put_DeviceEnabled(1) < 0)
248  checkError(ifptr);
249  // Активируем дДП
250  if (idisplay->put_DeviceEnabled(1) < 0)
251  checkError(idisplay);
252 
253  // Выводим текст
254  idisplay->DisplayText(L"ТЕКСТ", TED::Display::ScrollLeft, 1000, 100);
255 
256  Thread::sleep(10);
257  }
258  }
259  catch(const std::exception &ex)
260  {
261  qDebug() << qPrintable(ex.what());
262  releaseFptr(&ifptr);
263  releaseDisplay(&idisplay);
264  return 1;
265  }
266 
267  releaseFptr(&ifptr);
268  releaseDisplay(&idisplay);
269  return 0;
270 }
271 
virtual int DTOSHARED_CCA ShowProperties()=0
Выводит диалог настройки драйвера
#define S_DEVICEFILE
Definition: dto_const.h:35
#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
Возвращает результат последней операции
void(* ReleaseDisplayInterfacePtr)(TED::Display::IDisplay **iface)
Тип функции ReleaseDisplayInterface().
Definition: idisplay.h:72
#define S_SEARCHDIR
Definition: dto_const.h:36
Базовый интерфейс для работы с драйверами
Definition: idtobase.h:28
virtual int DTOSHARED_CCA put_DeviceSingleSetting(const wchar_t *name, const wchar_t *value)=0
Устанавливает значение настроки
TED::Display::IDisplay *(* CreateDisplayInterfacePtr)(int ver)
Тип функции CreateDisplayInterface().
Definition: idisplay.h:70
TED::Fptr::IFptr *(* CreateFptrInterfacePtr)(int ver)
Тип функции CreateFptrInterface().
Definition: ifptr.h:545
#define SV_PORT_TTY
Definition: dto_const.h:76
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 DisplayText(const wchar_t *text, int scrollType, int repeatTimeout, int unitTimeout)=0
Выводит на дисплей текст
#define S_VID
Definition: dto_const.h:63
virtual int DTOSHARED_CCA put_ClsPtr(void *value)=0
Устанавливает дескриптор устройства вывода (для подключения через ККТ).
virtual int DTOSHARED_CCA put_DeviceEnabled(int value)=0
Устанавливает логическое состояние драйвера
virtual int DTOSHARED_CCA ApplySingleSettings()=0
Применяет установленные настройки
#define EC_OK
Нет ошибки
Definition: dto_errors.h:27
Интерфейс драйвера дисплеев покупателя (дДП)
Definition: idisplay.h:81
#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
#define S_MODEL
Definition: dto_const.h:27
virtual int DTOSHARED_CCA get_ClsPtr(void **value)=0
Возвращает дескриптор устройства вывода (для подключения дисплея покупателя).
#define S_PROTOCOL
Definition: dto_const.h:28
Интерфейс драйвера контрольно кассовых машин (дККТ)
Definition: ifptr.h:557
#define EC_INVALID_PARAM
Недопустимое значение
Definition: dto_errors.h:37
void(* ReleaseFptrInterfacePtr)(TED::Fptr::IFptr **iface)
Тип функции ReleaseFptrInterface().
Definition: ifptr.h:547
#define DTO_IDISPLAY_VER1
Версия интерфейса драйвера дисплеев покупателя
Definition: idisplay.h:16