Драйверы торгового оборудования v.9
rcpprnexample.cpp
1 #include <exception>
2 #include <QLibrary>
3 #include <QDebug>
4 #include <QDir>
5 
6 // Заголовочные файлы ДТО9
7 #include "ircpprn.h"
8 #include "dto_errors.h"
9 #include "dto_const.h"
10 
11 static const bool USE_SHOW_PROPERTIES = false;
12 
13 #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
14 # include <QTextCodec>
15 
16 static class TrInit
17 {
18 public:
19  TrInit()
20  {
21  QTextCodec::setCodecForTr(QTextCodec::codecForName("utf-8"));
22  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("utf-8"));
23  QTextCodec::setCodecForLocale(QTextCodec::codecForName("utf-8"));
24  }
25 } g_TrInit;
26 #endif
27 
28 class Exception : public std::exception {
29 public:
30  Exception(const QString &msg)
31  : m_message(msg)
32  {
33  }
34 
35  virtual ~Exception() throw()
36  {
37  }
38 
39  virtual const char* what() const throw()
40  {
41  static QByteArray rawMessage = m_message.toUtf8();
42  return rawMessage.data();
43  }
44 
45 private:
46  QString m_message;
47 };
48 
49 void checkError(TED::IDTOBase *iface)
50 {
51  if(!iface)
52  throw Exception("Invalid interface");
53 
54  int rc = EC_OK;
55  iface->get_ResultCode(&rc);
56  if(rc < 0)
57  {
58  QString resultDescription, badParamDescription;
59  QVector<wchar_t> v(256);
60  int size = iface->get_ResultDescription(&v[0], v.size());
61  if (size <= 0)
62  throw Exception("get_ResultDescription error");
63  if (size > v.size())
64  {
65  v.clear();
66  v.resize(size + 1);
67  iface->get_ResultDescription(&v[0], v.size());
68  }
69  resultDescription = QString::fromWCharArray(&v[0]);
70  if(rc == EC_INVALID_PARAM) {
71  QVector<wchar_t> v(256);
72  int size = iface->get_BadParamDescription(&v[0], v.size());
73  if (size <= 0)
74  throw Exception("get_BadParamDescription error");
75  if (size > v.size())
76  {
77  v.clear();
78  v.resize(size + 1);
79  iface->get_ResultDescription(&v[0], v.size());
80  }
81  badParamDescription = QString::fromWCharArray(&v[0]);
82  }
83 
84  if(badParamDescription.isEmpty())
85  throw Exception(QObject::trUtf8("[%1] %2")
86  .arg(rc)
87  .arg(resultDescription));
88  else
89  throw Exception(QObject::trUtf8("[%1] %2 (%3)")
90  .arg(rc)
91  .arg(resultDescription)
92  .arg(badParamDescription));
93  }
94 }
95 
96 int main()
97 {
98 #if defined(Q_OS_LINUX)
99  QLibrary lib("../bins/linux-x64/librcpprn.so");
100  if(!lib.load())
101  {
102  lib.setFileName("../bins/linux-x86/librcpprn.so");
103  lib.load();
104  }
105 #elif defined(Q_OS_WIN32)
106  QLibrary lib("../bins/nt-x86-mingw/rcpprn.dll");
107  lib.load();
108 #else
109 # error "Unknown OS"
110 #endif
111 
112  if(!lib.isLoaded())
113  {
114  qDebug() << qPrintable(QObject::trUtf8("Не удалось загрузить библиотеку rcpprn - [%1]")
115  .arg(lib.errorString()));
116  return 1;
117  }
118 
119  CreateRcpPrnInterfacePtr create = (CreateRcpPrnInterfacePtr) lib.resolve("CreateRcpPrnInterface");
120  ReleaseRcpPrnInterfacePtr release = (ReleaseRcpPrnInterfacePtr) lib.resolve("ReleaseRcpPrnInterface");
121 
122  TED::RcpPrn::IRcpPrn *ircpprn = create(DTO_IRCPPRN_VER1);
123  if(!ircpprn)
124  {
125  qDebug() << qPrintable("Cannot create RcpPrn object");
126  return 1;
127  }
128 
129  try
130  {
131  // Выставляем рабочий каталог. В нем дПЧ будет искать требуемые ему библиотеки.
132  QFileInfo finfo(lib.fileName());
133  if(ircpprn->put_DeviceSingleSetting(S_SEARCHDIR, finfo.absolutePath().toStdWString().c_str()) < 0)
134  checkError(ircpprn);
135  if(ircpprn->ApplySingleSettings() < 0)
136  checkError(ircpprn);
137 
138  // Для настройки драйвера можно вызвать графическое окно настроек
139  if(USE_SHOW_PROPERTIES)
140  {
141  if(ircpprn->ShowProperties() < 0)
142  checkError(ircpprn);
143  }
144  // Или настроить без него
145  else
146  {
147  // COM17
148  //if(ircpprn->put_DeviceSingleSetting(S_PORT, 17) < 0)
149  //checkError(ircpprn);
150  if(ircpprn->put_DeviceSingleSetting(S_PORT, SV_PORT_TTY) < 0)
151  checkError(ircpprn);
152  if(ircpprn->put_DeviceSingleSetting(S_DEVICEFILE, L"ttyACM0") < 0)
153  checkError(ircpprn);
154  if(ircpprn->put_DeviceSingleSetting(S_BAUDRATE, 115200) < 0)
155  checkError(ircpprn);
156  if(ircpprn->put_DeviceSingleSetting(S_MODEL, TED::RcpPrn::ModelPP7000) < 0)
157  checkError(ircpprn);
158  if(ircpprn->ApplySingleSettings() < 0)
159  checkError(ircpprn);
160  }
161 
162  // Активируем дПЧ
163  if (ircpprn->put_DeviceEnabled(1) < 0)
164  checkError(ircpprn);
165 
166  // Добавляем строки в буфер заданий
167  if(ircpprn->put_Caption(L"Строка1") < 0)
168  checkError(ircpprn);
169  if(ircpprn->put_Alignment(TED::RcpPrn::AlignmentLeft) < 0)
170  checkError(ircpprn);
171  if(ircpprn->AddText() < 0)
172  checkError(ircpprn);
173 
174  if(ircpprn->put_Caption(L"Строка2") < 0)
175  checkError(ircpprn);
177  checkError(ircpprn);
178  if(ircpprn->AddText() < 0)
179  checkError(ircpprn);
180 
181  if(ircpprn->put_Caption(L"Строка3") < 0)
182  checkError(ircpprn);
184  checkError(ircpprn);
185  if(ircpprn->AddText() < 0)
186  checkError(ircpprn);
187 
188  // Добавляем ШК в буфер заданий
190  checkError(ircpprn);
191  if(ircpprn->put_BarcodeText(L"123456789012") < 0)
192  checkError(ircpprn);
193  if(ircpprn->put_BarcodePrintText(1) < 0)
194  checkError(ircpprn);
195  if(ircpprn->put_BarcodeControlCode(0) < 0)
196  checkError(ircpprn);
198  checkError(ircpprn);
199  if(ircpprn->AddBarCode() < 0)
200  checkError(ircpprn);
201 
202  // Печатаем буфер
203  if(ircpprn->PrintAllTasks() < 0)
204  checkError(ircpprn);
205  }
206  catch(const std::exception &ex)
207  {
208  qDebug() << qPrintable(ex.what());
209  release(&ircpprn);
210  return 1;
211  }
212 
213  release(&ircpprn);
214  return 0;
215 }
216 
virtual int DTOSHARED_CCA AddBarCode()=0
Добавляет задачу печати штрихкода в очередь задач.
virtual int DTOSHARED_CCA ShowProperties()=0
Выводит диалог настройки драйвера
#define S_DEVICEFILE
Definition: dto_const.h:35
virtual int DTOSHARED_CCA put_BarcodeControlCode(int value)=0
Определяет, используется ли контрольный символ ШК
virtual int DTOSHARED_CCA put_BarcodePrintText(int value)=0
Устанавливает флаг печати символьного эквивалента ШК
virtual int DTOSHARED_CCA get_ResultCode(int *value)=0
Возвращает результат последней операции
#define S_SEARCHDIR
Definition: dto_const.h:36
TED::RcpPrn::IRcpPrn *(* CreateRcpPrnInterfacePtr)(int ver)
Тип функции CreateFptrInterface().
Definition: ircpprn.h:144
Базовый интерфейс для работы с драйверами
Definition: idtobase.h:28
virtual int DTOSHARED_CCA put_DeviceSingleSetting(const wchar_t *name, const wchar_t *value)=0
Устанавливает значение настроки
virtual int DTOSHARED_CCA put_BarcodeText(const wchar_t *bfr)=0
Устанавливает текст для формирования штрихкода
#define SV_PORT_TTY
Definition: dto_const.h:76
virtual int DTOSHARED_CCA AddText()=0
Добавляет задачу печати текста в очередь задач.
virtual int DTOSHARED_CCA put_BarcodeType(int value)=0
Устанавливает тип ШК
virtual int DTOSHARED_CCA get_ResultDescription(wchar_t *bfr, int bfrSize)=0
Возвращает текстовое описание результата последней операции
virtual int DTOSHARED_CCA PrintAllTasks()=0
Запускает печать заданий из очереди
virtual int DTOSHARED_CCA put_DeviceEnabled(int value)=0
Устанавливает логическое состояние драйвера
virtual int DTOSHARED_CCA ApplySingleSettings()=0
Применяет установленные настройки
#define EC_OK
Нет ошибки
Definition: dto_errors.h:27
virtual int DTOSHARED_CCA put_Alignment(int value)=0
Устанавливает тип печатаемых данных
#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
void(* ReleaseRcpPrnInterfacePtr)(TED::RcpPrn::IRcpPrn **iface)
Тип функции ReleaseFptrInterface().
Definition: ircpprn.h:146
virtual int DTOSHARED_CCA put_Caption(const wchar_t *value)=0
Устанавливает строковое значение
#define S_MODEL
Definition: dto_const.h:27
#define EC_INVALID_PARAM
Недопустимое значение
Definition: dto_errors.h:37
Интерфейс драйвера принтеров чеков (дПЧ)
Definition: ircpprn.h:155