3.4 Commands for Gate Reader 50
3.4.1 SetGPIOWorkParam 50
3.4.2 GetGPIOWorkParam 51
3.4.3 SetGateWorkParam 51
3.4.4 GetGateWorkParam 51
3.4.5 GetGateStatus 52
3.4.6 SetEASMask 52
3.4.7 GetEASMask 53
3.5 Access control integrated reader related commands 53
3.5.1 GetAccessInfo【Get access control information】 53
3.5.2 BeginWhiteList【Notify the device to enter the whitelist data update or acquisition process】 54
3.5.3 GetWhiteList【Get whitelist】 54
3.5.4 SetWhiteList【Set whitelist】 55
3.5.5 EndWhiteList【End setting whitelist】 56
3.5.6 GetAccessOperateParam【Get access control operation parameters】 56
3.5.6 SetAccessOperateParam【Set access control operating parameters】 57
Appendix 1, Return value error code sheet 58
Appendix 2,ErrorCode sheet 59
1.Introduction
The SDK support C, C++ and other languages that can call C library interfaces, es delphi,C#,VB6.0,VB.NET etc.
At present,the SDK only can support Windwos Operation system (32 bits & 64 bits)
Upper computer application operate Prime Reader serials ISO18000-6C format reader through UHFPrimeReader.DLL, Support upper computer application open multiples reader under multiple communication port
2.Application Integration
The SDK include the file as below:
File name Application
UHFPrimeReader.dll DLL ,Include app API port
Language Description
C# UHF_RFID_API.cs copy to project contents, and join project,copy UHFPrimeReader.DLL to exe file output contents
Assistant
User
давай пошаговую что создать куда нажать , что скопировать
Assistant
User
system.pause(); добавь
Assistant
В Qt-приложении (особенно в кроссплатформенном) system("pause"); не очень рекомендуется, но если нужно именно в Windows, чтобы программа не закрывалась сразу после окончания, можно вставить в конце main:
#include <cstdlib> // для system
// в конце main перед return 0:
system("pause");
Т.е. полный конец функции main будет примерно так:
Если хочешь, могу вставить полный исправленный код с этой строкой — скажи.
User
при запуске FAiled to resole one or more functions
Assistant
User
if (!dll.load()) в какое место программы
Assistant
if (!dll.load()) нужно вызывать сразу после создания объекта QLibrary, чтобы проверить успешность загрузки DLL прежде, чем вызывать функции из неё.
В твоём случае в main.cpp это будет выглядеть так:
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1; // Завершаем программу, если DLL не загрузилась
}
qDebug() << "DLL loaded successfully from" << dll.fileName();
// Далее разрешаем функции
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
// ...
Конкретно — вот полный фрагмент с правильным местом:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM4";
BYTE baudrate = 0x04;
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
qDebug() << "DLL loaded successfully from" << dll.fileName();
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
auto GetTagInfo = (pfnGetTagInfo)dll.resolve("GetTagInfo");
auto InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
auto CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
if (!OpenDevice || !InventoryContinue || !GetTagInfo || !InventoryStop || !CloseDevice) {
qCritical() << "Failed to resolve one or more functions";
return -1;
}
// Остальной код...
}
User
так окно при запуске мигает и закрывается
Assistant
Это классическая ситуация для консольных приложений на Windows, когда окно открывается, программа выполняется и сразу завершается — окно консоли закрывается моментально, и вы не успеваете увидеть вывод.
Решение — сделать паузу перед завершением программы
Вариант 1: В конце main() вызвать system("pause") (только Windows)
#include <cstdlib> // Для system()
// ...
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// ... весь твой код ...
qDebug() << "Device closed";
system("pause"); // Ждем нажатия клавиши, консоль не закроется сразу
return 0;
}
Вариант 2: Запускать приложение из открытой консоли (cmd.exe)
Открой cmd.exe
Перейди в папку с исполняемым файлом (команда cd)
Запусти приложение вручную: UHFReaderDemo.exe
Так окно не закроется автоматически.
User
может библиотека не подключатеся, подклчи еще в pro файле
Assistant
Да, если у тебя DLL, обычно ты не подключаешь её напрямую в .pro, а загружаешь динамически через QLibrary (как в твоём коде).
Однако, если у тебя есть также UHFPrimeReader.lib (импортная библиотека), её можно подключить в .pro для компоновки.
-L — путь к папке с .lib (можно абсолютный или относительный)
-lUHFPrimeReader — имя либы без префикса и расширения
User
как узнать для какой версии dll
Assistant
Чтобы узнать для какой архитектуры (32-bit или 64-bit), а также для какой версии ОС или компилятора предназначена DLL, можно использовать несколько способов:
1. Проверка архитектуры DLL в Windows
а) Через свойства файла
Кликни правой кнопкой мыши на UHFPrimeReader.dll
Выбери Свойства
Перейди во вкладку Подробно — иногда есть информация о версии
Однако, это часто не даёт архитектуру.
Assistant
Если кратко, то для определения версии и архитектуры DLL используйте:
Dependency Walker — покажет 32/64 битность.
dumpbin (Visual Studio) dumpbin /headers UHFPrimeReader.dll | findstr machine — код 14C значит x86 (32-бит), 8664 — x64 (64-бит).
Свойства файла — вкладка Подробно (может быть версия).
PE-бира или другие PE-анализаторы.
После этого убедитесь, что архитектура DLL совпадает с архитектурой вашего Qt-приложения (32- или 64-бит). Если не совпадает — DLL не загрузится (QLibrary.load() вернёт ошибку).
Если нужна пошаговая помощь с конкретным файлом — обращайтесь.
User
проверь еще раз по документации там есть несколько режимов и мне надо по запросу
Assistant
User
замени cout на qdebug и после запуска пользователь ничего не вводит, запускается кода код который дает команду ридеру читать
Assistant
User
слушай а можно это сделать без dll
Assistant
User
как подругому в qt подключить .dll т.к функции не импортируются, может что-то не хватает
Assistant
User
Assistant
Да, этот заголовочный файл (header) выглядит довольно полным и правильным для доступа к вашим функциям из UHFPrimeReader.DLL.
Что здесь хорошо:
Все структуры, константы и перечисления определены.
User
давай полный пример и у меня COM6
Assistant
User
Assistant
User
готовый код давай
Assistant
User
добавь еще в код функцию AnswerMod
Assistant
User
qDebug() << buf << tag.code[i].hex()
Assistant
tag.code[i] — это quint8 (один байт), у него нет метода hex(). Чтобы вывести его в шестнадцатеричном виде через qDebug(), надо привести к числу и использовать форматирование.
Пример правильного вывода одного байта в hex с двумя цифрами:
Для отдельного байта — конвертируй через QString::arg()
Для массива байт — используй QByteArray::toHex()
Если надо вывести байт в шестнадцатеричном виде в цикле (по одному) например:
for (int i = 0; i < tag.codeLen; ++i) {
qDebug() << QString("%1").arg(tag.code[i], 2, 16, QLatin1Char('0')).toUpper();
}
User
Assistant
User
не у меня 32 бита и библиотека 32 бит, а исходный код пример есть только 64 бит, и документаци
Assistant
Если у тебя 32-битное приложение и 32-битная DLL, а документация и пример кода дают 64-битный дескриптор (int64_t), то для совместимости нужно:
Как сделать код под 32-бита с 64-битным дескриптором
User
длинна карты 12 а по символам 24 что там просиходит
Assistant
Когда у метки длина EPC указана как 12, а по символам (в выводе например в hex) получается 24 символа — это нормальное и ожидаемое поведение. Вот почему:
Объяснение
Длина EPC в tag.codeLen — это количество байт (octets), то есть число байтов в массиве tag.code.
Каждый байт отображается в hex как 2 символа (например, байт 0xAB — символы 'A' и 'B').
Значит, длина в символах при выводе hex-строкой будет примерно в 2 раза больше длины в байтах.
Пример
Длина в байтах: 12 байт
В hex-строке, например "AB 23 97 45 00 11 ..." будет: 12 байт * 2 символа = 24 символа
Именно поэтому при конвертации байтового массива метки в hex-представление длина строки в символах будет в два раза больше, чем .
И ты хочешь понять, как из данных (например, приведённых 24 байт из code) получить корректное EPC и почему длина может быть 12, а данные — 24 байта.
User
вообще в документации такая структура
ypedef struct
{
WORD reserve;
SHORT rssi;
BYTE antenna;
BYTE channel;
BYTE reserve;
BYTE reserve;
BYTE codeLen;
BYTE code[255];
}TagInfo;
Assistant
Спасибо за уточнение! В документации структура TagInfo выглядит так:
unsigned char – это целочисленный тип данных без знака, обычно занимающий 1 байт (8 бит).
В стандарте C/C++ размер char всегда равен 1 байту. Это определение размера байта зависит от платформы, но по факту 1 байт обычно 8 бит, что позволяет хранить значения в диапазоне от 0 до 255 для unsigned char.
Кратко:
unsigned char = 1 байт (8 бит)
Диапазон значений: от 0 до 255
Например:
unsigned char a = 255; // максимальное значение для unsigned char
Используется часто для хранения байтовых данных, например, в массивах, буферах и при работе с бинарными протоколами.
User
short int
Assistant
short int (обычно сокращённо short) — это целочисленный тип данных со знаком, который обычно занимает 2 байта (16 бит) на большинстве современных платформ.
Основные характеристики short int:
Размер: 2 байта (16 бит)
Диапазон значений:
От –32,768 до 32,767 (то есть от –2^15 до 2^15–1)
Знаковый тип (signed), то есть может хранить отрицательные и положительные числа
Пример:
short int x = 1000;
short int y = -500;
Важно:
В стандарте C++ размер short гарантированно не меньше 16 бит
На большинстве современных платформ он действительно 2 байта
Для гарантии размеров в кодах для обмена данными лучше использовать фиксированные по размеру типы из <cstdint>, например, int16_t
Аналогичный тип с точным размером:
#include <cstdint>
int16_t number; // точно 16-битный знаковый тип
Если нужна краткая резюме: short int — 2 байта, хранит целые числа в диапазоне от –32768 до 32767.
User
WORD в СИ unsigned int
Assistant
В языке C (и C++) тип WORD — это просто псевдоним (typedef) для какого-то целочисленного типа, обычно 16-битного беззнакового.
Часто в Windows или драйверах определено так:
typedef unsigned short WORD; // 16 бит, беззнаковое
Важно
unsigned int в Си обычно 32-битный (зависит от платформы и компилятора, но в современных системах так)
WORD обычно — 16 бит, то есть unsigned short, а не unsigned int
Итоги
Тип
Рекомендуемый размер
Обычно соответствует
WORD
16 бит
unsigned short
unsigned int
32 бит
зависит от платформы
Рекомендация
Если в документации определено — всегда используйте , а не .
3.API
3.1 Connect/Close Reader
3.1.1 OpenDevice
Definition Int OpenDevice(HANDLE *hComm,char *ComPort, byte Baudrate);
Description Open serial port connected to reader ,default baud rate is 115200,8 data bits,4 stop bit,no check
Parameter
Name Type Remarks
hComm HANDLE * Return the handle connected to reader, all API operation need use this handle
strComPort char * Input reader address, if don’t know real address, can input broadcast address 0xFF, After call library success, this parameter will return real address
Baudrate Byte Set communication baud rate 0x00:9600; 0x01:19200;0x02:38400;0x03:57600;0x04:115200(Default);
Return
(int) Success:0 ;Failure:NOT 0 ;(Check return value error code sheet)
Parameter
Code string[] ports = SerialPort.GetPortNames();
HANDLE m_handler = HANDLE.Zero;
int state = OpenDevice(out m_handler, port);
3.1.1 OpenNetConnection
Definition Int OpenNetConnection(HANDLE *hComm, char *ip, WORD port,DWORD timeoutMs)
Description Open network port connected to reader, the default IP address is 192.168.1.200, defaultport is 2022. use tcpclient way connect reader
Parameter
Nmae Type Remarks
hComm HANDLE * Return the handle connected to reader, all API operation need use this handle
ip char * Input reader IP address, the reader default IP address is 192.168.1.200
port WORD Input reader default port,0~65535;
timeoutMs DWORD The connection timeout period set,unit :ms。
Return
(int) Success:0 ;Failure:NOT 0 ;(Check return value error code sheet)
Parameter NO
3.1.2 CloseDevice
Definition int CloseDevice(HANDLE hComm);
Description Close serial port or network port connected to reader
Parameter
Nmae Type Remarks
hComm HANDLE A handle connected with reader, when open serial port returned handle
Return
(int) Success:0 ;Failure:NO 0 ;(Check return value error code sheet)
Parameter
Code int state = UHF_RFID_API. CloseDevice (m_handler);
3.1.3 OpenHidConnection
Definition Int OpenHidConnection (HANDLE *hComm, WORD index)
Illustration Open the device corresponding to the HID device serial number and return the handle.
Parameter Name Type Remark
hComm HANDLE * Returns the handle to the connection to the reader/writer, which is required for all API operations thereafter
index WORD Equipment serial number
Return (int) Success:0 ;Fail:Not 0 ;(View the return value error code table)
Reference Code None
3.1.4 CFHid_GetUsbCount
Definition Int CFHid_GetUsbCount(void);
Illustration Obtain the HID device with a vid of 0x0483 and a pid of 0x5750, and return the number of HID devices.
Parameter Name Type Remark
- - -
Return (int) Success:Not 0 ,This value is the number of HID devices;Fail:0 ;
Reference Code None
3.1.5 CFHid_GetUsbInfo
Definition Int CFHid_GetUsbInfo(WORD index, char * pucDeviceInfo);
Illustration Obtain the address of the specified device. The device address suffix is kbd, which is the keyboard. Unable to connect.
Parameter Name Type Remark
index WORD Specify the equipment serial number, which is determined by CFHide_ GetUsbCount Get;
pucDeviceInfo char * Device address.
Return (int) Success:0 ;Fail:Not 0 ;(View the return value error code table)
Reference Code None
3.2. 18000-6C (EPC G2)
3.2.1. InventoryContinue
Definition int InventoryContinue(HANDLE hComm, BYTE btInvCount, DWORD dwInvParam);
Description Check whether have tag comppliant with the protocol exists in the valid range
Parameter
Name Type Direction Remarks
hComm HANDLE [in] A handle connected with reader
invCount BYTE [in] Inventory type:0x00:
Inventory according time:0x03:
Custom inventory,select and query parameter use SelectOrSortSet and
QueryCfgSet command set
invParam DWORD [in] Inventory parameter:4 byte ,unit: S, value as 0 will continue inventory
When inventory type as custom inventory, max inventory 256S
Return
(int) Default no Return (Check return value error code sheet)
Parameter
Code Int state =0;
Int count =0;
Int invParam =0;
state =InventoryContinue(m_handler, count, invParam);// Set cycle inventory
3.2.2. GetTagInfo
Definition int GetTagInfo(HANDLE hComm, TagInfo* tag_info, WORD timeout);
Description Check whether have tag comppliant with the protocol exists in the valid range
Parameter
Nmae Type Direction Remarks
hComm HANDLE [in] The handle connected to reader,all API operation need use this handle
tag_info TagInfo [out] typedef struct
{
WORD reserve;
SHORT rssi;
BYTE antenna;
BYTE channel;
BYTE reserve;
BYTE reserve;
BYTE codeLen;
BYTE code[255];
}TagInfo;
timeout WORD [in] Waiting data time, Unit:ms
Return
(int) STAT_OK: Command operation success,at the same time return inventoried other tag data
STAT_CMD_INVENTORY_STOP: finish inventory or no tag around
Parameter
Code TagInfo info;
int state = UHF_RFID_API.GetTagUii(m_handler, out info,1000);
3.2.3. InventoryStop
Definition int InventoryStop(HANDLE hComm, WORD timeout);
Description Initialize the callback library
After initialize the API, inventory command and mix inventory command received tag can upload by callback way
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
timeout WORD [in] Waiting data time, Unit:ms
Return NO
Parameter Code Int state = UHF_RFID_API.InventoryStop(m_handler, 10000);
3.2.4. ReadTag
Definition int ReadTag(HANDLE hComm, byte option, BYTE* accPwd, byte memBank, WORD wordPtr, WORD wordCount);
Description This command read tag whole or part resersed area,EPC storager, TID storager or data in USER storeager,read start from indicated address, use word as unit
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
option BYTE [in] 0x00,Retain Byte 。
accPwd BYTE* [in] 4 bytes, access password, to allow tag enter safety state,default as 0x00000000。
memBank BYTE [in] 1 byte,select storage area need read
0x00 – Reserved area;
0x01 – EPC Storage area;
0x02 – TID Storage area;
0x03 –USER Storage area, other value reserve
If appear other value among command, will return parameter error message
WordPtr WORD [in] 1 byte, the start word address to read (word)
wordCount BYTE [in] 1 byte, the data length to read (word)
Return (int) 0: Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code BYTE* m_arrPwd = new BYTE* { 0, 0, 0, 0 };
byte memBank = 0;
byte wordPtr = 0;
byte wordcount = 2;
int state = ReadTag(m_handler, 0, accPwd,
• (byte)memBank, wordPtr, wordCount);//
Read the kill password
3.2.5. GetReadTagResp
Definition int GetReadTagResp(HANDLE hComm, TagResp* resp,byte wordCount, BYTE* readData, WORD timeout);
Description This command can write a few words to reserved memory,EPC storager, TID storager or USER storage by one time
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
resp TagResp [out] Return read data。
typedef struct
{
BYTE tagStatus;
BYTE antenna;
BYTE crc[2];
BYTE pc[2];
BYTE codeLen;
BYTE code[255];
}TagResp;
wordCount BYTE [out] 1 byte, return the number of tag data words that read
readData BYTE* [out] The tag data that read,length is WordCount×2 bytes
timeout WORD [in] Waiting tag return time, unit:ms
Return (int) 0:Success。Not 0: Failure,(check the return value error code sheet)
Parameter
Code No
3.2.6. WriteTag
Definition int WriteTag(HANDLE hComm, byte option, BYTE* accPwd, byte memBank, WORD wordPtr, byte wordCount, BYTE* writeData);
Description This command can write a few words to reserved memory,EPC storager, TID storager or USER storage by one time
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
option BYTE [in] 0x00,Retain byte。
accPwd BYTE* [in] 4 bytes, access password, to allow tag enter safety state,default as 0x00000000。
memBank BYTE [in] 1 byte,select storage area need read
0x00 – Reserved area;
0x01 – EPC Storage area;
0x02 – TID Storage area;
0x03 –USER Storage area, other value reserve
If appear other value among command, will return parameter error message
WordPtr WORD [in] 2 bytes, the start word adress to read
wordCount BYTE [in] 1 byte, the word length to read
Writedata BYTE* [in] wordcount*2 bytes,data need to be written
Return (int) 0:success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.7. GetTagResp
Definition int GetTagResp(HANDLE hComm, WORD cmd, out TagResp resp, WORD timeout);
Description
This command respond to command for obtaining write,kill and lock
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
cmd WORD [in] Command word,
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.8. LockTag
Definition int LockTag(HANDLE hComm, BYTE* accPwd, byte erea, byte action);
Description This command can set reserved area as readable/writable,always readable/writable, with password readable/writable; can separate set EPC storage, TID storage and USER storage as read/write.always writable, with password writable, always not-writable; EPC storeage, TID storage or USER storeage are always readable. And then, TID storage just reader only, can not write.
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
accPwd byte[4] [in] 4 bytes, access password, to allow tag enter safety state,default as 0x00000000
erea BYTE [in] 0x00:Kill password area;0x01:Access password area; 0x02:EPC; 0x03:TID; 0x04:User;
action BYTE [in] 1 Byte ,
When select as 0x00 or 0x01,SetProtect value represent the definition as below:
0x00 – Set as readable/writable
0x01 – Set as always readable/writable
0x02 – Set as with password readable/writable
0x03 – Set as non-readable/non-writable
When Select as 0x02、0x03、0x04,SetProtectvalue represent the definition as below:
0x00 – Set as writable
0x01 – Set as always writable
0x02 –Set as with passwrod writable
0x03 –Set as always non-writable
Return (int) 0:Success。NOT 0:Failure,(check the return value error code sheet)
Parameter Code NO
3.2.9. KillTag
Definition KillTag(HANDLE hComm, BYTE* accPwd);
Description This command use to destruct tag, after destructed, won’t process reader command never (need select tag before operate that command)
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
accPwd byte[4] [in] 4 bytes, access password, to allow tag enter safety state,default as 0x00000000
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.10. SetSelectMask
Definition int SetSelectMask(HANDLE hComm, WORD maskPtr, byte maskBits, BYTE* mask);
Description This command can select tag according rule
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
maskPtr WORD [in] 2 bytes, default as 0x0000。
maskBits byte [in] 1 byte, need match EPC number bit length,default as 0x00;if maskBits as 0,means didn’t indicated tag,multiple tags operation ( will operation for all tags at current area)
mask BYTE* [in] • Need matching data, effective data length as lengthbit, if length is odd, need add 0 to the lower part of the mask code
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
CF FF 00 07 0F 00 00 60 E2 80 68 94 00 00 40 0B 19 B6 16 01 CB D0
Select tag with EPC number as E2 80 68 94 00 00 40 0B 19 B6 16 01 。
3.2.11. SetCoilPRM
Definition int SetCoilPRM(HANDLE hComm, byte qVal, byte reserved);
Description
This command can set Q value size
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
qVal byte [in] 1 byte, Q value size have relation to tags quantity around, the number of tags is 2 to the Q
reserved byte [in] 1 byte, Rserved, default as 0
Return
(int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter
Code NO
3.2.12. GetCoilPRM
Definition GetCoilPRM(HANDLE hComm, out byte pqVal, out byte reserved);
Description This command use to obtain Q value
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
qVal byte [out] 1 byte, Q value size have relation to tags quantity around, the number of tags is 2 to the Q
reserved byte [in] 1 byte, Rserved, default as 0
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.13. SelectOrSortSet
Definition
int SelectOrSortSet(HANDLE hComm, byte prot, SelectSortParam param);
Description
Check whether exist tag that comply with protocol in the valid range
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
prot byte [in] Protocol No:Set as 0x00;
param SelectSortParam [in] typedef struct
{
BYTE target;
BYTE trucate;
BYTE action;
BYTE membank;
WORD m_ptr;
BYTE len;
BYTE mask[31];
}SelectSortParam;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.14. SelectOrSortGet
Definition int SelectOrSortGet(HANDLE hComm, byte proto, SelectSortParam param);
Description Check whether exist tag that comply with protocol in the valid range
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
prot byte [in] Protocol No:Set as 0x00;
param SelectSortParam [out] typedef struct
{
BYTE target;
BYTE trucate;
BYTE action;
BYTE membank;
WORD m_ptr;
BYTE len;
BYTE mask[31];
}SelectSortParam;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.15. QueryCfgSet
Definition int QueryCfgSet(HANDLE hComm, byte proto, QueryParam param);
Description Check whether exist tag that comply with protocol in the valid range
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
prot byte [in] Protocl No:Set as 0x00;
param QueryParam [in] typedef struct
{
BYTE condition;
BYTE session;
BYTE target;
}QueryParam;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.2.16. QueryCfgGet
Definition int QueryCfgGet(HANDLE hComm, byte proto, QueryParam param);
Description Check whether exist tag that comply with protocol in the valid range
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
prot byte [in] Protocl No:Set as 0x00;
param QueryParam [out] typedef struct
{
BYTE condition;
BYTE session;
BYTE target;
}QueryParam;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3. Reader Custom Comamand
3.3.1. GetInfo
Definition
int GetInfo (HANDLE hComm, DeviceInfo* devInfo);
Description Obtain reader information, reader software version and other informations
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
devInfo DeviceInfo [out] typedef struct
{
BYTE firmVersion[32];
BYTE hardVersion[32];
BYTE SN[12];
BYTE PARA[12];
}DeviceInfo;
struct PARA
{
BYTE RFIDPRO;
WORD STRATFREI;
WORD STRATFRED;
WORD STEPFRE;
BYTE CN;
BYTE POWER;
BYTE ANTENNA;
BYTE REGION;
BYTE RESERVED;
};
Return
(int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.2. GetDeviceInfo
Definition int GetDeviceInfo(HANDLE hComm, DeviceFullInfo* devInfo);
Description Obtain reader information, reader software version and other informations
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
devInfo DeviceFullInfo [out] typedef struct
Parameter Code No
3.3.3. GetDevicePara
Definition int GetDevicePara(HANDLE hComm, DevicePara* devInfo);
Description Obtain reader information, reader software version and other informations
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
devInfo DevicePara [in] typedef struct
{
BYTE DEVICEARRD;
BYTE RFIDPRO;
BYTE WORKMODE;
BYTE INTERFACE;
BYTE BAUDRATE;
BYTE WGSET;
BYTE ANT;
BYTE REGION;
BYTE STRATFREI[2];
BYTE STRATFRED[2];
BYTE STEPFRE[2];
BYTE CN;
BYTE RFIDPOWER;
BYTE INVENTORYAREA;
BYTE QVALUE;
BYTE SESSION;
BYTE ACSADDR;
BYTE ACSDATALEN;
BYTE FILTERTIME;
BYTE TRIGGLETIME;
BYTE BUZZERTIME;
BYTE INTENERLTIME;
}DevicePara;
Return
(int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
参考代码 无
3.3.4. SetDevicePara
Definition int SetDevicePara(HANDLE hComm, DevicePara devInfo);
Description Obtain reader information, reader software version and other informations
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
devInfo DevicePara [in] typedef struct
{
BYTE DEVICEARRD;
BYTE RFIDPRO;
BYTE WORKMODE;
BYTE INTERFACE;
BYTE BAUDRATE;
BYTE WGSET;
BYTE ANT;
BYTE REGION;
BYTE STRATFREI[2];
BYTE STRATFRED[2];
BYTE STEPFRE[2];
BYTE CN;
BYTE RFIDPOWER;
BYTE INVENTORYAREA;
BYTE QVALUE;
BYTE SESSION;
BYTE ACSADDR;
BYTE ACSDATALEN;
BYTE FILTERTIME;
BYTE TRIGGLETIME;
BYTE BUZZERTIME;
BYTE INTENERLTIME;
}DevicePara;
Return
(int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.5 SetDevicePara
illustrate Obtain the information of the reader, the software version of the reader and many other information
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
DEVICEARRD BYTE [in] 1 Byte
Communication address of the device
The default is 0x00 and cannot be 0xFF
RFIDPRO BYTE [in] 1 Byte
Device RF
0x00:ISO 18000-6c
0X01: GB/T29768
0x02:GJB7377.1
Currently only supports ISO18000-6C
WORKMODE BYTE [in] 1 Byte
The working mode of the device
0: answer mode
1: active mode
2: trigger mode
INTERFACE BYTE [in] 1 Byte
Device communication interface
Default 0x80
0x80: RS232
0x40: RS485
0x20: RJ45
0x10: WiFi
BAUDRATE BYTE [in] 1 Byte
Serial baud rate
default 4
0: 9600bps
1: 19200bps
2: 38400bps
3: 57600bps
4: 115200bps
WGSET BYTE [in] 1 Byte
Configuration parameters of the Wiegand data output interface
Default 0x00
ANT BYTE [in] 8 Bytes
The default is 0x01, which means antenna 1
All the antenna numbers of the device, which represent the selected antenna by bit, and the corresponding bit value is 1, which means that the antenna is used.
A value of 0 means that the antenna is not used; starting from the lower bit, the 0th bit means antenna 1, the 1st bit means antenna 2, and so on, up to 8 antennas can be represented; different modules support different antennas, depending on the specific depending on the situation;
REGION BYTE [in] 1 Byte
National frequency range:
0x00: User-defined according to requirements;
0x01: US[902.75927.25]
0x02: Korea[917.1923.5]
0x03: EU[865.1868.1]
0x04: JAPAN[952.2953.6]
0x05: MALAYSIA[919.5922.5]
0x06: EU3[865.7867,5]
0x07: CHINA_BAND1[840.125844.875]
0x08: CHINA_BAND2[920.125924.875]
STRATFREI1 BYTE [in] 1 Byte
High byte of the integer part of the megahertz start frequency
Such as 920.125MHz
STRATFREI=920=0x0398,
High byte=0x03, low byte=0x98;
STRATFREI2 BYTE [in] 1 Byte
Low byte of the integer part of the megahertz start frequency
STRATFRED1 BYTE [in] 1 Byte
The high byte of the fractional part of the megahertz start frequency
Such as 920.125MHz
STRATFREI= 125= 0x007D,
High byte = 0x00, low byte = 0x7D;
STRATFRED2 BYTE [in] 1 Byte
Low byte of the fractional part of the megahertz start frequency
STEPFRE1 BYTE [in] 1 Byte
High byte of frequency step (KHz)
Such as 125KHz,
STEPFRE=125=0x007D,
high byte = 0x00,
Low byte = 0x7D;
STEPFRE2 BYTE [in] 1 Byte
Low byte of frequency step (KHz)
CN BYTE [in] 1 Byte
number of channels
RFIDPOWER BYTE [in] 1 Byte
The RFID output power of the device, the unit is: dBm, the value range is: [0,30]dBm, others are invalid.
INVENTORYAREA BYTE [in] 1 Byte
The memory area of the device to access the tag
0x01 Default EPC
0x02 TID
0x03 USER
0x04 EPC+TID
0x05 EPC+USER
0x06 EPC+TID+USER
Other values are reserved
QVALUE BYTE [in] 1 Byte
The initial Q value used when querying EPC tags
The default value is 4
The value range is 0~15
SESSION BYTE [in] 1 Byte
Session value used when querying EPC tags
Default is 0
Value range [0, 3]
ACSADDR BYTE [in] 1 Byte
The starting address of the device to access the label storage area
Default value 0x00
ACSDATALEN BYTE [in] 1 Byte
The data length of the device to access the tag storage area
Default value 0x00
FILTERTIME BYTE [in] 1 Byte
filter time
default value 0
Value range [0, 255]
Unit second (s)
TRIGGLETIME BYTE [in] 1 Byte
The query duration after the device receives the trigger signal
default value 0
Value range [0, 255]
Unit second (s)
BUZZERTIME BYTE [in] 1 Byte
Buzzer beeping time
default value 1
When the value is 0, it means no tweet
Value range [0, 255]
Unit 10 milliseconds (10ms)
INTENERLTIME BYTE [in] 1 Byte
query interval
default value 1
Value range [0, 255]
Unit 10 milliseconds (10ms)
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.3.6 RebootDevice
Definition int RebootDevice(HANDLE hComm);
Description After operate command, reader restore factory default parameter, include frequency,power,antenna enable etc
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.7 SetRFPower
Definition int SetRFPower(HANDLE hComm, byte power, byte reserved);
Description Set reader output power
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
power BYTE [in] 1 byte, reader power ,range 0~33dBm。
reserved byte [in] Reserved
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.8. GetRFPower
Definition int GetRFPower(HANDLE hComm, out byte power, out byte reserved);
Description Obtain reader power
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle。
power BYTE [out] 1 byte, reader power ,range 0~33dBm。
reserved byte [out] Reserved
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.9. SetFreq
Definition int SetFreq(HANDLE hComm, ref FreqInfo frqInfo);
Description
This command sets the upper limit and lower limit of the reader working frequency. The upper frequency must be greater than or equal to the lower frequency.
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
frqInfo FreqInfo [in] typedef struct
{
BYTE region;
WORD StartFreq;
WORD StopFreq;
WORD StepFreq;
BYTE cnt;
}FreqInfo;
Return
(int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
Frequency set as below:
0x00: User define according demand ;
0x01:US [902.75927.25]
0x02:Korea [917.1923.5]
0x03:EU [865.1868.1]
0x04:JAPAN [952.2953.6]
0x05:MALAYSIA [919.5922.5]
0x06:EU3 [865.7867,5]
0x07:CHINA_BAND1 [840.125844.875]
0x08:CHINA_BAND2 [920.125924.875]
Each frequency band calculation formula:
Chinese band2: Fs = 920.125 + N * 0.25 (MHz) N∈[0, 19]。
US band: Fs = 902.75 + N * 0.5 (MHz) N∈[0,49]。
Korean band: Fs = 917.1 + N * 0.2 (MHz) N∈[0, 31]。
EU band: Fs = 865.1 + N0.2(MHz) N∈[0, 14]。
Ukraine band: Fs = 868.0 + N0.1(MHz) N∈[0, 6]。
Chinese band1: Fs = 840.125 + N * 0.25 (MHz) N∈[0, 19]。
US band3: Fs = 902 + N * 0.5 (MHz) N∈[0,52]。
3.3.10. GetFreq
Definition int SetBaudRate(BYTE * ComAddr, BYTE baud, int FrmHandle);
Description Set reader communication baud rate
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
frqInfo FreqInfo [in] typedef struct
{
BYTE region;
WORD StartFreq;
WORD StopFreq;
WORD StepFreq;
BYTE cnt;
}FreqInfo;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.11 SetAntenna
definition int SetAntenna(HANDLE hComm, BYTE* antenna);
illustrate This command is used to set the antenna.
parameter.
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
antenna byte [in] 1 byte, the corresponding Bit value is 1, which means that the antenna is used, and the value is 0, which means that the antenna is not used; starting from the low bit, the 0th bit indicates the 1st antenna, the 1st bit indicates the 2nd antenna, and so on , can represent up to 8 antennas, and different modules support different antennas, depending on the specific situation;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.3.12 GetAntenna
definition int GetAntenna(HANDLE hComm, BYTE* antenna);
illustrate This command is used for 4-port reader antenna configuration.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
antenna byte [out] 1 byte, the corresponding Bit value is 1, which means that the antenna is used, and the value is 0, which means that the antenna is not used; starting from the low bit, the 0th bit indicates the 1st antenna, the 1st bit indicates the 2nd antenna, and so on , can represent up to 8 antennas, and different modules support different antennas, depending on the specific situation;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.3.13. SetRFIDType
Definition int SetRFIDType(HANDLE hComm, byte type);
Description This command use to set module protocol type
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type byte [in] 1 byte,0x00:ISO 18000-6C; 0x01:GB/T 29768;0x02:GJB 7377.1;
At present only support ISO 18000-6C。
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.14. GetRFIDType
Definition int GetRFIDType(HANDLE hComm, out byte type);
Description This command use to obtain module protocol type
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type byte [out] 1 byte,0x00:ISO 18000-6C; 0x01:GB/T 29768;0x02:GJB 7377.1;
At present only support ISO 18000-6C。
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.15. GetTemperature
Definition int GetTemperature(HANDLE handler, out byte tempCur, out byte tempLimit);
Description This command use to obtain the current temperature and threshold
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
tempCur byte [out] 1 byte,current temperature unit as degrees Celsius 。
tempLimit byte [out] 1 byte, current temperature threshold, over this temperatuere ,module will stop work to wait temperature reduce
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.16. SetTemperature
Definition int SetTemperature(HANDLE handler, byte tempLimit, byte resv);
Description This command use to set temperature and threshold
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
tempLimit byte [in] 1 byte,current temperature threshold, over this temperatuere ,module will stop work to wait temperature reduce, generally set 50~90℃。
resv byte [in] 保留
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.17 GetNetInfo
Definition int GetNetInfo(HANDLE hComm, NetInfo *type);
Description This command use to obtain device network parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type NetInfo [out] typedef struct
3.3.18 SetNetInfo
Definition int SetNetInfo(HANDLE hComm, NetInfo type);
Description This command use to set device network parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type NetInfo [in] typedef struct
{
BYTE IP[4];
BYTE MAC[6];
BYTE PORT[2];
BYTE NetMask[4];
BYTE Gateway[4];
}NetInfo;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.19. GetRemoteNetInfo
Definition int GetRemoteNetInfo(HANDLE hComm, RemoteNetInfo *type);
Description This command use to obtain remote network parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type NetInfo [out] typedef struct
{
BYTE Enable;
BYTE IP[4];
BYTE PORT[2];
BYTE HeartTime;
}RemoteNetInfo;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.7.16. SetRemoteNetInfo
Definition Int SetRemoteNetInfo(HANDLE hComm, RemoteNetInfo type);
Description This command use to set remote network parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
type NetInfo [in] typedef struct
{
BYTE Enable;
BYTE IP[4];
BYTE PORT[2];
BYTE HeartTime;
}RemoteNetInfo;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.21. GetPermissonPara
Definition Int GetPermissonPara(HANDLE hComm, PermissonPara* PermissonPara);
Description This command use to obtain reading permission parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
PermissonPara PermissonPara [out] typedef struct
{
BYTE CodeEn;
BYTE Code[4];
BYTE MaskEn;
BYTE StartAdd;
BYTE MaskLen;
BYTE MaskData[12];
BYTE MaskCondition;
}PermissonPara;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.22. SetPermissonPara
Definition Int SetPermissonPara(HANDLE hComm, PermissonPara PermissonPara);
Description This command use to set reading permission parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
PermissonPara PermissonPara [in] typedef struct
{
BYTE CodeEn;
BYTE Code[4];
BYTE MaskEn;
BYTE StartAdd;
BYTE MaskLen;
BYTE MaskData[12];
BYTE MaskCondition;
}PermissonPara;;
Return (int) 0:Success。NOT 0: Failure,(check the return value error code sheet)
Parameter Code NO
3.3.23. GetGpioPara
Definition int GetGpioPara(HANDLE hComm, GpioPara* GpioPara);
Description This command use to obtain GPIO parameter
Parameter
Name Type Direction Remarks
hComm HANDLE [in] Connected reader handle, all API operation need use this handle
GpioPara NetInfo [out] typedef struct
3.3.25 GetLongPermissonPara
definition Int GetPermissonPara(HANDLE hComm, PermissonPara* PermissonPara);
illustrate This command is used to obtain read permission.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
PermissonPara LongPermissonPara * [out] typedef struct
{
BYTE CodeEn;
BYTE Code[4];
BYTE MaskEn;
BYTE StartAdd;
BYTE MaskLen;
BYTE MaskData[31];
BYTE MaskCondition;
}LongPermissonPara;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.3.26 SetLongPermissonPara
definition Int SetPermissonPara(HANDLE hComm, LongPermissonPara PermissonPara);
illustrate This command is used to set the card reading authority.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
PermissonPara LongPermissonPara [in] typedef struct
{
BYTE CodeEn;
BYTE Code[4];
BYTE MaskEn;
BYTE StartAdd;
BYTE MaskLen;
BYTE MaskData[31];
BYTE MaskCondition;
}LongPermissonPara;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.3.27 GetGPIOLevel
definition int GetGPIOLevel(HANDLE hComm, GPIOLevel* GPIO);
illustrate This command is used to get the GPIO level。
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection. This handle is required for all API operations thereafter.。
GPIO GPIOLevel [in] typedef struct {
BYTE GPILEVEL;
BYTE GPOLEVEL;
BYTE SYSTIME[4];
}GPIOLevel;
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.3.28 Close_Relay
definition int Close_Relay(HANDLE hComm, BYTE time);
illustrate This command closes the relay.
parameter name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
time Byte [out] Time represents the closing time, 0 means always closed, unit S.
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.3.29 Release_Relay
definition int Release_Relay(HANDLE hComm, BYTE time);
illustrate 该命令用于释放继电器。
parameter name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection. This handle is required for all API operations thereafter.。
time Byte [out] invalid
return
(int) 0:Indicates success. Not equal to 0: indicates failure, please check the return value error code table。
Reference Code none
3.3.30 Close_Relay2
definition int Close_Relay2(HANDLE hComm, BYTE time);
illustrate This command is used to close relay 2.
parameter name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection. This handle is required for all API operations thereafter.。
time Byte [out] Time represents the closing time, 0 means always closed, unit S.
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.3.31 Release_Relay2
definition int Release_Relay2(HANDLE hComm, BYTE time);
illustrate Set relay 2 release
parameter name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection. This handle is required for all API operations thereafter.。
time Byte [out] invalid
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.4 Commands for Gate Reader
3.4.1 SetGPIOWorkParam
definition int SetGPIOWorkParam(HANDLE hComm, GPIOWorkParam gpio);
illustrate This command is used to set GPIO working parameters.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
gpio GPIOWorkParam [in] typedef struct {
BYTE Mode;
BYTE GPIEnable;
BYTE InLevel;
BYTE GPOEnable;
BYTE PutLevel;
BYTE PutTime[8];
}GPIOWorkParam;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.2 GetGPIOWorkParam
definition int GetGPIOWorkParam(HANDLE hComm, GPIOWorkParam* gpio);
illustrate This command is used to obtain GPIO working parameters.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
gpio GPIOWorkParam [out] typedef struct {
BYTE Mode;
BYTE GPIEnable;
BYTE InLevel;
BYTE GPOEnable;
BYTE PutLevel;
BYTE PutTime[8];
}GPIOWorkParam;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.3 SetGateWorkParam
definition int SetGateWorkParam(HANDLE hComm, GateWorkParam gate);
illustrate This command is used to set the working parameters of the gate reader.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
gate GateWorkParam [in] typedef struct {
BYTE GateMode;
BYTE GateGPI1;
BYTE GateGPI2;
BYTE GatePower;
BYTE GateRead;
BYTE EASMode;
BYTE EASGPO;
}GateWorkParam;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.4 GetGateWorkParam
definition int GetGateWorkParam(HANDLE hComm, GateWorkParam gate);
illustrate This command is used to obtain the working parameters of the gate reader
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter. .
gate GateWorkParam [out] typedef struct {
BYTE GateMode;
BYTE GateGPI1;
BYTE GateGPI2;
BYTE GatePower;
BYTE GateRead;
BYTE EASMode;
BYTE EASGPO;
}GateWorkParam;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.5 GetGateStatus
definition int GetGateStatus(HANDLE hComm, GateParam* status, WORD timeout);
illustrate This command is used to get access gate reader.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
status GateParam [in] typedef struct {
BYTE DIR;
BYTE GPI;
BYTE SYSTIME[4];
}GateParam;
timeout WORD [in] Waiting time for command response, in ms.
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.6 SetEASMask
definition int SetEASMask(HANDLE hComm, EASMask* eas);
illustrate This command is used to set EAS data matching.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
eas EASMask [in] typedef struct {
BYTE Addr;
BYTE Len;
BYTE Data[32];
}EASMask;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.4.7 GetEASMask
definition int SetEASMask(HANDLE hComm, EASMask* eas);
illustrate This command is used to obtain EAS data matching.
parameter
name type direction Remark
hComm HANDLE [in] The handle to the reader/writer connection, which is required for all API operations thereafter.
eas EASMask [out] typedef struct {
BYTE Addr;
BYTE Len;
BYTE Data[32];
}EASMask;
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table.
Reference Code none
3.5 Access control integrated reader related commands
3.5.1 GetAccessInfo【Get access control information】
definition int GetAccessInfo(HANDLE hComm, AccessInfo* access);
illustrate This command is used to obtain access control information.
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection. This handle is required for all API operations thereafter.。
access AccessInfo [out] typedef struct {
BYTE STATE;
WORD CUSTOMERCOUNT;
}AccessInfo;
return(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.5.2 BeginWhiteList【Notify the device to enter the whitelist data update or acquisition process】
definition int BeginWhiteList(HANDLE hComm, BYTE Option, DWORD infoCount);
illustrate This command is used to notify the device to enter the whitelist data update or acquisition process.
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
Option BYTE [in] 0x01: Enter the status of the host computer transmitting whitelist data to the device;
0x02: Enter the state where the device transmits whitelist data to the host computer;
Other values: invalid.
infoCount DWORD [in] When Option=1, it indicates the total number of customer information CUSTOMERINFO that needs to be updated; when Option=2, INFOCOUNT = 0
return(int) 0: indicates success. Not equal to 0: indicates failure, please check the return value error code table。
Reference Code none
3.5.3 GetWhiteList【Get whitelist】
definition int GetWhiteList(HANDLE hComm, WhiteList* whiteList, WORD timeout)
illustrate This command is used to obtain the whitelist.
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
whiteList WhiteList [out] typedef struct {
BYTE STATUS;
WORD FRAMENUM;
BYTE INFOCOUNT;
BYTE WHITELIST[4096];
}WhiteList;
timeout WORD [in] Connection timeout setting, unit ms.
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
WhiteList Parameter Description:
Status:command response code
0x8Cupload data;
Other values: invalid;
FRAMENUM: Transmission packet number, counting from 0, length 2 bytes.
INFOCOUNT: The number of customer information CUSTOMERINFO in the uploaded data packet, length 1 byte, maximum 2048/32 = 64.
WHITELIST: Whitelist, N Bytes, N maximum 251, N = 32INFOCOUNT. It consists of multiple customer information CUSTOMERINFO.
3.5.4 SetWhiteList【Set whitelist】
definition int SetWhiteList(HANDLE hComm, WORD len, const BYTE pParam)
illustrate This command is used to set the whitelist.
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
len WORD [in] The length of the long pass whitelist
pParam BYTE [out] The number of whitelists returned by the device for the current update
return(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.5.5 EndWhiteList【End setting whitelist】
definition int EndWhiteList(HANDLE hComm, DWORD* infoCount);
illustrate This command is used to end setting the whitelist.
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
infoCount DWORD [out] The device returns the total number of whitelists for this update
return(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
3.5.6 GetAccessOperateParam【Get access control operation parameters】
definition int GetAccessOperateParam(HANDLE hComm, AccessOperateParam* aParam);
illustrate This command is used to obtain access control operation parameters。
parameter
name type direction Remark
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
aParam AccessOperateParam [out] typedef struct {
BYTE LISTENABLE;
BYTE GPI1;
BYTE GPI2;
BYTE GPI3;
BYTE GPI4;
BYTE RECVGPIEXEFUNC[4];
BYTE GPO1;
BYTE GPO2;
BYTE RECVGPOEXEFUNC[6];
}AccessOperateParam;
return(int) 0 indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
AccessOperateParam Parameter Description:
LISTENABLE: Whitelist enable parameter, 1Byte.
bit Definition
7 0
6 0
5 0
4 0
3 0
2 0
1 0
0 0: Turn off the whitelist; 1: Turn on the whitelist
GPI1: GPI1 input execution function parameter, length 1Byte, default 0x01 triggers card reading, can be configured for other action triggers。
bit Definition
7 0
6 0
5 0
4 0: Disable the trigger GPO1 output; 1: Enable the trigger GPO1 output.
3 0x00: No action;
0x01: read card;
0x02: Channel is open;
0x03: Channel closed;
Other values are invalid.
2
1
0
GPI2:GPI2Input execution function parameters, length 1Byte, default 0x01 to trigger card reading, can be configured for other action triggers.
bit Definition
7 0
6 0
5 0
4 0: Disable the trigger GPO1 output; 1: Enable the trigger GPO1 output.
3 0x00: No action;
0x01: read card;
0x02: Channel is open;
0x03: Channel closed;
Other values are invalid.
2
1
0
GPI3:GPI3 input execution function parameters, length 1Byte, default 0x03 trigger channel is closed, can be configured for other action triggers。
bit Definition
7 0
6 0
5 0
4 0: Disable to trigger GPO1 output; 1: Enable to trigger GPO1 output。
3 0x00: No action;
0x01: read card;
0x02: Channel is open;
0x03: Channel closed;
Other values are invalid.
2
1
0
GPI4: GPI4 input execution function parameter, length 1Byte, default 0x02 trigger channel is enabled, can be configured for other action triggers.
bit Definition
7 0
6 0
5 0
4 0: Disable to trigger GPO1 output; 1: Enable to trigger GPO1 output。
3 0x00: No action;
0x01: read card;
0x02: Channel is open;
0x03: Channel closed;
Other values are invalid.
2
1
0
RECVGPIEXEFUNC: reserved input execution function parameters, length 4Bytes, default all 0x00.
GPO1: The action is executed when the authorization tag is detected. The GPO parameter is the gate switch control GPO parameter. The length is 1Byte and the default is 0x80.
bit Definition
7 0: Do not select RELAY; 1: Select RELAY。
6 0
5 0
4 0
3 0
2 0
1 0
0 0: Do not select GPO1; 1: Select GPO1。
GPO2: When an unauthorized tag is detected, the action is executed as GPO parameters, that is, the warning switch controls the GPO parameters, length 1Byte, default 0x01.
bit Definition
7 0: Do not select RELAY; 1: Select RELAY。
6 0
5 0
4 0
3 0
2 0
1 0
0 0: Do not select GPO1; 1: Select GPO1.
RECVACTIONEXEFUNC:Reserved output execution function parameters, length 6Bytes, default all 0x00。
3.5.6 SetAccessOperateParam【Set access control operating parameters】
definition int SetAccessOperateParam(HANDLE hComm, AccessOperateParam aParam);
illustrate This command is used to set access control operation parameters.
parameter Name Type Direction Remarks
hComm HANDLE [in] The handle of the reader/writer connection, which is required for all API operations thereafter.
aParam AccessOperateParam [in] typedef struct {
BYTE LISTENABLE;
BYTE GPI1;
BYTE GPI2;
BYTE GPI3;
BYTE GPI4;
BYTE RECVGPIEXEFUNC[4];
BYTE GPO1;
BYTE GPO2;
BYTE RECVGPOEXEFUNC[6];
}AccessOperateParam;
return
(int) 0: indicates success. Not equal to 0: Indicates failure, please check the return value error code table.
Reference Code none
Appendix 1, Return value error code sheet
Definition Annotation
#define STAT_OK 0x00000000
#define STAT_PORT_HANDLE_ERR 0xFFFFFF01 Handle error, or input serial port parameter error
#define STAT_PORT_OPEN_FAILED 0xFFFFFF02 Open serial port failure
#define STAT_DLL_INNER_FAILED 0xFFFFFF03 Internal dynamic library error
#define STAT_CMD_PARAM_ERR 0xFFFFFF04 Parameter value incorrect or out of bounds,or module do not support that parameter value
#define STAT_CMD_SERIAL_NUM_EXIT 0xFFFFFF05 Serial number existed
#define STAT_CMD_INNER_ERR 0xFFFFFF06 •
The command execution failed due to an internal error in the module pocedure
•
#define STAT_CMD_INVENTORY_STOP 0xFFFFFF07 Didn’t inventoried tag or inventory finished
#define STAT_CMD_TAG_NO_RESP 0xFFFFFF08 Tag response timeout
#define STAT_CMD_DECODE_TAG_DATA_FAIL 0xFFFFFF09 Failed to call tag data
#define STAT_CMD_CODE_OVERFLOW 0xFFFFFF0A Tag data exceed the max transmission length of serial port
#define STAT_CMD_AUTH_FAIL 0xFFFFFF0B authentication failure
#define STAT_CMD_PWD_ERR 0xFFFFFF0C Command error
#define STAT_CMD_SAM_NO_RESP 0xFFFFFF0D SAM card no response
#define STAT_CMD_SAM_CMD_FAIL 0xFFFFFF0E PSAM card command execute failure
#define STAT_CMD_RESP_FORMAT_ERR 0xFFFFFF0F reader response format incorrect
#define STAT_CMD_HAS_MORE_DATA 0xFFFFFF10 Command executed successfully, but subrequent data didn’t finish transfer
#define STAT_CMD_BUF_OVERFLOW 0xFFFFFF11 Incoming cache too small, data overflows
#define STAT_CMD_COMM_TIMEOUT 0xFFFFFF12 Wait reader response overtime
#define STAT_CMD_COMM_WR_FAILED 0xFFFFFF13 Write data to serial port failure
#define STAT_CMD_COMM_RD_FAILED 0xFFFFFF14 Read serial port data failure
#define STAT_CMD_NOMORE_DATA 0xFFFFFF15 No more data
#define STAT_DLL_UNCONNECT 0xFFFFFF16 Network connect have not been established
#define STAT_DLL_DISCONNECT 0xFFFFFF17 Network already disconnect
#define STAT_CMD_RESP_CRC_ERR 0xFFFFFF18 Reader respond to crc check error
Tag power supply insufficient, and tag do not have enough power to completed the operation
#define STAT_GB_TAG_OPR_LIMIT
0xFFFFFF41 Insufficient tag operation permissions, unauthorized access
#define STAT_GB_TAG_MEM_OVF
0xFFFFFF42 Tag operation store overflows, or the target store does not exist
#define STAT_GB_TAG_MEM_LCK
0xFFFFFF43 The tag storage area locked, write operation or erase operation to locked unwritable storage area, to do read operation for locked unreadable storeage area
#define STAT_GB_TAG_PWD_ERR
0xFFFFFF44 Tag operation command error, access command error
#define STAT_GB_TAG_AUTH_FAIL
0xFFFFFF45 Tag failed to be authenticated
#define STAT_GB_TAG_UNKNW_ERR
0xFFFFFF46 Tag operation occurred unkonwn error
Привет! Судя по твоему описанию, тебе нужно консольное приложение на Qt, которое использует UHFPrimeReader.DLL для подключения, чтения меток и отключения ридера UHF.
Ниже предложу минимальный пример простого консольного Qt-приложения на C++, показывающего, как подключиться к устройству по COM-порту, считать EPC метки и закрыть соединение.
Основные моменты:
Работаем с DLL через QLibrary и загрузку функций по указателям (или подготавливаем заголовочный файл с декларациями).
Используем функции из документации:
OpenDevice
InventoryContinue
GetTagInfo (или GetTagUii)
InventoryStop
CloseDevice
Пример реализации
Шаг 1: Заголовок и определения типов из API (упрощенно)
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QThread>
// Тип HANDLE определим как void*
typedef void* HANDLE;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
// Структура TagInfo
struct TagInfo {
WORD reserve;
short rssi;
BYTE antenna;
BYTE channel;
BYTE reserve2;
BYTE reserve3;
BYTE codeLen;
BYTE code[255];
};
// Функции из DLL (подписи)
typedef int (*pfnOpenDevice)(HANDLE* hComm, char* ComPort, BYTE Baudrate);
typedef int (*pfnInventoryContinue)(HANDLE hComm, BYTE btInvCount, DWORD dwInvParam);
typedef int (*pfnGetTagInfo)(HANDLE hComm, TagInfo* tag_info, WORD timeout);
typedef int (*pfnInventoryStop)(HANDLE hComm, WORD timeout);
typedef int (*pfnCloseDevice)(HANDLE hComm);
Шаг 2: Основной код
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM4"; // Порт, поменяй под свое устройство
BYTE baudrate = 0x04; // 115200
// Загрузка DLL
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
// Получение функций
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
auto GetTagInfo = (pfnGetTagInfo)dll.resolve("GetTagInfo");
auto InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
auto CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
if (!OpenDevice || !InventoryContinue || !GetTagInfo || !InventoryStop || !CloseDevice) {
qCritical() << "Failed to resolve one or more functions";
return -1;
}
HANDLE hComm = nullptr;
QByteArray portArray = comPort.toLocal8Bit();
char* portStr = portArray.data();
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
qCritical() << "OpenDevice failed with code:" << hex << ret;
return -1;
}
qDebug() << "Device opened";
// Запускаем непрерывное сканирование с инвентаризацией
ret = InventoryContinue(hComm, 0x00, 0); // 0 инвентаризация для 0 - непрерывное
if (ret != 0) {
qCritical() << "InventoryContinue failed with code:" << hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "Inventory started, scanning tags...";
// Через цикл попробуем получить метки
for (int i = 0; i < 10; ++i) {
TagInfo tagInfo;
ret = GetTagInfo(hComm, &tagInfo, 1000); // Таймаут 1000ms
if (ret == 0) {
// Есть метка - выведем EPC
QByteArray epcData((char*)tagInfo.code, tagInfo.codeLen);
qDebug() << "Tag found:" << epcData.toHex(':');
} else {
qDebug() << "No tag or timeout, code:" << hex << ret;
}
QThread::msleep(500);
// Можно добавить выход по условию, если нужно
}
// Останавливаем инвентаризацию
InventoryStop(hComm, 1000);
qDebug() << "Inventory stopped";
// Закрываем устройство
ret = CloseDevice(hComm);
if (ret != 0) {
qCritical() << "CloseDevice failed:" << hex << ret;
} else {
qDebug() << "Device closed";
}
return 0;
}
Пояснения:
OpenDevice принимает имя COM-порта, для USB/HID используйте OpenHidConnection или OpenNetConnection (если сетевое подключение).
В этом примере подставлен COM4 и байт кода 0x04 для 115200 бод, подставляй актуальные параметры.
InventoryContinue запускает сканирование меток.
GetTagInfo считывает метку в течении таймаута.
Для HID или сетевого варианта в коде надо вызывать соответствующие функции (OpenHidConnection или OpenNetConnection).
Обработка ошибок - по значению функции, если не 0 - ошибка.
Пример очень базовый, можно добавить логику с циклом, обработку нескольких меток, асинхронность и пр.
Где UHFPrimeReader_Dir - путь к dll и lib (если есть), или убери, если подключаешь dll через QLibrary.
Что дальше
Если нужен пример с другим типом подключения (сеть, HID) - скажи.
Можно обернуть всё в класс для удобной работы.
Можно реализовать асинхронное чтение с обработкой сигналов/слотов.
В реальном проекте надо внимательно читать статусные коды и обрабатывать ошибки более подробно.
Если нужно — могу помочь с доработкой.
Хорошо! Давай сделаю пошаговую инструкцию для создания консольного Qt-приложения, которое подключается к UHF Prime Reader по COM-порту, считывает метки и закрывается.
Выбери версию Qt (например Qt 6.x или 5.x, желательно 5.x если у тебя не Qt 6)
Нажми Next и потом Finish
Шаг 3. Подключить DLL к проекту
Предполагаю, что у тебя есть файл UHFPrimeReader.dll
Скопируй UHFPrimeReader.dll в каталог с исполняемым файлом проекта. Обычно это папка UHFReaderDemo/build-UHFReaderDemo-Desktop_Qt_XX_MinGW_XYZ-Release (после первого компиля) или рядом с .pro файлом для простоты.
Шаг 4. Отредактировать .pro файл проекта
Открой файл UHFReaderDemo.pro и добавь (если уже не добавлено) следующие строки, чтобы приложение было консольным и использовало C++11:
CONFIG += console c++11
QT -= gui
Шаг 5. Написать код
Открой файл main.cpp, очисти его, и вставь следующий код:
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QThread>
typedef void* HANDLE;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
struct TagInfo {
WORD reserve;
short rssi;
BYTE antenna;
BYTE channel;
BYTE reserve2;
BYTE reserve3;
BYTE codeLen;
BYTE code[255];
};
typedef int (*pfnOpenDevice)(HANDLE* hComm, char* ComPort, BYTE Baudrate);
typedef int (*pfnInventoryContinue)(HANDLE hComm, BYTE btInvCount, DWORD dwInvParam);
typedef int (*pfnGetTagInfo)(HANDLE hComm, TagInfo* tag_info, WORD timeout);
typedef int (*pfnInventoryStop)(HANDLE hComm, WORD timeout);
typedef int (*pfnCloseDevice)(HANDLE hComm);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM4"; // **Замените на ваш порт**
BYTE baudrate = 0x04; // 115200
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
auto GetTagInfo = (pfnGetTagInfo)dll.resolve("GetTagInfo");
auto InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
auto CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
if (!OpenDevice || !InventoryContinue || !GetTagInfo || !InventoryStop || !CloseDevice) {
qCritical() << "Failed to resolve one or more functions";
return -1;
}
HANDLE hComm = nullptr;
QByteArray portArray = comPort.toLocal8Bit();
char* portStr = portArray.data();
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
qCritical() << "OpenDevice failed with code:" << hex << ret;
return -1;
}
qDebug() << "Device opened";
ret = InventoryContinue(hComm, 0x00, 0);
if (ret != 0) {
qCritical() << "InventoryContinue failed with code:" << hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "Inventory started, scanning tags...";
for (int i = 0; i < 10; ++i) {
TagInfo tagInfo;
ret = GetTagInfo(hComm, &tagInfo, 1000);
if (ret == 0) {
QByteArray epcData((char*)tagInfo.code, tagInfo.codeLen);
qDebug() << "Tag found:" << epcData.toHex(':');
} else {
qDebug() << "No tag or timeout, code:" << hex << ret;
}
QThread::msleep(500);
}
InventoryStop(hComm, 1000);
qDebug() << "Inventory stopped";
ret = CloseDevice(hComm);
if (ret != 0) {
qCritical() << "CloseDevice failed:" << hex << ret;
} else {
qDebug() << "Device closed";
}
return 0;
}
Шаг 6. Настроить COM-порт
Замените в коде строку QString comPort = "COM4"; на номер COM-порта вашего ридера.
Проверьте диспетчер устройств Windows или с помощью терминала (например, mode в cmd), какой COM-порт используется.
Шаг 7. Скомпилировать и запустить
В QtCreator нажми Build -> Build All
Внизу в Compile Output проверь ошибки. Если всё успешно:
Нажми Run (зелёная стрелка запуска)
В консоли должно появится что-то вроде:
Device opened
Inventory started, scanning tags...
Tag found: xx:xx:xx:xx:xx:...
...
Inventory stopped
Device closed
Если меток нет, будет сообщение об ошибке или таймауте.
Важные замечания
Если DLL не грузится, скопируйте её рядом с исполняемым файлом EXE (обычно build-...-release/).
Если нужна работа с HID или по сети — команды OpenHidConnection и OpenNetConnection должны быть вызваны вместо OpenDevice.
Это базовый пример, без полного трёхуровневого контроля ошибок.
В реальном проекте удобно создавать обёртку вокруг DLL для повторного использования.
Если нужна помощь с отладкой или отдельными шагами — пиши, помогу!
Ошибка "Failed to resolve one or more functions" означает, что не удалось получить адрес хотя бы одной функции из DLL.
Если DLL не грузится — значит путь к DLL неизвестен или DLL не подходит (ошибка архитектуры, отсутствует зависимость).
2. Проверь, что имена функций совпадают
В твоём UHFPrimeReader.dll функция OpenDevice может экспортироваться под другим именем (например, с подчеркиваниями или в ANSI/Unicode вариантах).
Чтобы проверить экспортированные функции:
Используй утилиту Dependency Walker (depends.exe)
Или PowerShell:
dumpbin /exports UHFPrimeReader.dll
Посмотри, есть ли среди экспортов OpenDevice, InventoryContinue, GetTagInfo и т.п.
Если в экспортах нет этих имен — значит либо функции экспортируются через "C++ name mangling" (нужно использовать extern "C"), либо имена отличаются.
3. Используй корректные имена функций
Если имена с префиксом или суффиксом, попробуй их в resolve, например:
auto OpenDevice = (pfnOpenDevice)dll.resolve("?OpenDevice@@YAHPEAPEAXPEADE@Z"); // пример mangled name для C++
Лучше уточнить в документации, есть ли предоставленный заголовочный файл .h или LIB-файл.
4. Можно обернуть вызовы через QLibrary::resolve с выводом имён:
Добавь отладку:
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
qDebug() << "OpenDevice func ptr:" << OpenDevice;
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
qDebug() << "InventoryContinue func ptr:" << InventoryContinue;
// И так далее для остальных
Проверь, какие функции nullptr, какие нет.
5. Вариант с использованием extern "C" и собственного DLL-импортера
Если есть .lib от производителя, лучше подключить .lib к проекту и подключать функции через обычное объявление:
extern "C" int __stdcall OpenDevice(HANDLE* hComm, char* ComPort, BYTE Baudrate);
6. Пример исправления для Windows с cdecl/stdcall
Возможно, нужно указать соглашение вызова:
typedef int (__stdcall *pfnOpenDevice)(HANDLE* hComm, char* ComPort, BYTE Baudrate);
Т.к. иногда DLL экспортируют функции с __stdcall.
Попробуй это и заново делать dll.resolve с именами.
Итог
Для начала советую:
Проверить, успешно ли загружается DLL
Проверить экспортируемые имена функций в DLL (Dependency Walker)
Поправить имена функций/соглашения вызова
Добавить дополнительный вывод на экран, какие фунции всё-таки нашлись
Если пришлёшь список экспортируемых имен из твоей DLL, помогу подобрать правильные строки.
Если нужна помощь с этим, напиши — помогу подробнее.
Если DLL не грузится — программа сразу сообщает об этом и завершится, что позволит понять проблему.
Вариант 3: Использовать Qt функционал ожидания
Если надо, можно заставить программу ждать ввода пользователя:
#include <iostream>
std::cout << "Press Enter to exit...";
std::cin.get();
Совет
Для простоты сделай в конце main:
#include <cstdlib>
int main(...) {
// ... твой код ...
qDebug() << "Device closed";
system("pause");
return 0;
}
Это самый простой способ.
Если хочешь, могу показать полный обновлённый main.cpp с этим правкой.
lib
.lib
Например, если .lib в папке libs рядом с проектом:
LIBS += -L$$PWD/libs -lUHFPrimeReader
2. Если есть только DLL без .lib — не надо добавлять в .pro
Тогда используй QLibrary (как у тебя) и динамическую загрузку.
3. Убедись что DLL есть в папке запуска
При запуске .exe, вместе с ним в одной папке должна лежать UHFPrimeReader.dll
Если запускаешь из Qt Creator — скопируй DLL в папку build-yourproject-Desktop_Qt_...-release/ (папка где лежит exe)
4. Проверка архитектуры
Очень важно, чтобы разрядность:
DLL совпадала с разрядностью сборки проекта (32 или 64 бит)
Если Qt собран 64-битным — и DLL должна быть 64-битной, иначе QLibrary::load() будет падать
Итог: Пример минимального подключения .pro если есть lib
Открываешь DLL и бачишь всю структуру, включая архитектуру.
2. Проверка версии DLL
Если разработчик правильно вписал версию, можно:
Через свойства файла — вкладка "Подробно" или "Версия"
С помощью API-функций или специализированных утилит посмотреть ресурсную версию
3. Проверка связки с Qt
Если Qt собран 64-битным, нужна 64-битная DLL
Если Qt 32-битный — DLL должна быть 32-битной
4. Общие рекомендации
Узнай у поставщика DLL для каких платформ она предназначена
Если скомпилирован пример — убедись что архитектуры совпадают
Если DLL не загружается (ошибка в QLibrary.load()), скорее всего архитектуру надо уточнить
Если нужна помощь — можешь приложить сам DLL (если можно), и я помогу проанализировать архитектуру.
Понял, ты хочешь реализовать консольное приложение на Qt, использующее UHFPrimeReader.DLL, которое будет подключаться к ридеру, считывать метки по запросу (т.е. не постоянно, а по команде пользователя), и затем отключаться.
Согласно документации в твоём запросе — для подключения используется OpenDevice, для запроса меток — InventoryContinue + GetTagInfo, для остановки — InventoryStop и CloseDevice.
Подход с "по запросу"
Т.е. логика будет:
Открываем порт командой OpenDevice
Каждый раз по команде пользователя делаем одноразовый вызов InventoryContinue с параметром, чтобы считать один или несколько тэгов за предел таймаута
Вызываем GetTagInfo для получения данных одного тэга по таймауту
Останавливаем инвентаризацию InventoryStop (можно вызывать один раз в конце)
Закрываем порт CloseDevice
Пример кода: чтение метки по запросу (собираем из твоей документации, Qt, DLL)
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QTextStream>
typedef void* HANDLE;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
struct TagInfo {
WORD reserve;
short rssi;
BYTE antenna;
BYTE channel;
BYTE reserve2;
BYTE reserve3;
BYTE codeLen;
BYTE code[255];
};
typedef int (*pfnOpenDevice)(HANDLE* hComm, char* ComPort, BYTE Baudrate);
typedef int (*pfnInventoryContinue)(HANDLE hComm, BYTE btInvCount, DWORD dwInvParam);
typedef int (*pfnGetTagInfo)(HANDLE hComm, TagInfo* tag_info, WORD timeout);
typedef int (*pfnInventoryStop)(HANDLE hComm, WORD timeout);
typedef int (*pfnCloseDevice)(HANDLE hComm);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream cin(stdin);
QTextStream cout(stdout);
QString comPort = "COM4"; // Укажи свой порт
BYTE baudrate = 0x04; // 115200
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
cout << "Failed to load DLL: " << dll.errorString() << endl;
return -1;
}
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
auto GetTagInfo = (pfnGetTagInfo)dll.resolve("GetTagInfo");
auto InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
auto CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
if (!OpenDevice || !InventoryContinue || !GetTagInfo || !InventoryStop || !CloseDevice) {
cout << "Failed to resolve one or more functions" << endl;
return -1;
}
HANDLE hComm = nullptr;
QByteArray portArray = comPort.toLocal8Bit();
char* portStr = portArray.data();
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
cout << "OpenDevice failed with code:" << hex << ret << endl;
return -1;
}
cout << "Device opened on port " << comPort << endl;
cout << "Type 'r' to read tag, 'q' to quit:" << endl;
while (true) {
cout << "> ";
cout.flush();
QString input = cin.readLine().trimmed();
if (input == "q") {
break;
}
if (input == "r") {
// Для одиночного сканирования делаем InventoryContinue с btInvCount=1 и dwInvParam=0
ret = InventoryContinue(hComm, 1, 0);
if (ret != 0) {
cout << "InventoryContinue failed with code:" << hex << ret << endl;
continue;
}
TagInfo tagInfo;
ret = GetTagInfo(hComm, &tagInfo, 1000); // Таймаут 1000 ms
if (ret == 0) {
QByteArray epcData((char*)tagInfo.code, tagInfo.codeLen);
cout << "Tag found EPC: " << epcData.toHex(':') << endl;
} else {
cout << "No tag found or timeout, code: " << hex << ret << endl;
}
} else {
cout << "Unknown command. Use 'r' or 'q'." << endl;
}
}
ret = InventoryStop(hComm, 1000);
if (ret != 0) {
cout << "InventoryStop failed with code:" << hex << ret << endl;
}
ret = CloseDevice(hComm);
if (ret != 0) {
cout << "CloseDevice failed with code:" << hex << ret << endl;
} else {
cout << "Device closed." << endl;
}
#ifdef Q_OS_WIN
system("pause");
#endif
return 0;
}
Что делает этот пример
Загружает DLL и её функции
Открывает порт
В цикле ожидает команды от пользователя:
r — читает одну метку, запуская одиночную инвентаризацию (по запросу)
q — выходит из программы
По запросу запускает InventoryContinue с btInvCount=1 — чтобы начать одиночный опрос тэгов
Вызывает GetTagInfo, чтобы получить первый найденный тег (если есть)
По завершении закрывает сканирование и девайс
Важное
Порт и параметры выставь свои актуальные
Таймауты для GetTagInfo можно регулировать (например, до 2000 или по необходимости)
Такой способ не будет постоянно читать и заполнять очередь тэгов — только по явной команде r
Обработка ошибок сделана базовая — можно добавить логику
Если нужно, могу помочь и с версией с сетью / HID / другим режимом.
Если хочешь — могу объяснить подробнее каждый шаг.
Понял. Сделаем так:
Заменим все cout на qDebug().
Уберём ввод пользователя.
Запускаем однократное чтение метки сразу при запуске, т.е. программа автоматически вызывает команду чтения, ждёт тег и выводит EPC.
В конце останавливаем и закрываем устройство.
Добавим system("pause") для Windows, чтобы окно не закрывалось сразу.
Вот полный пример main.cpp с твоими пожеланиями:
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QThread>
typedef void* HANDLE;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef unsigned int DWORD;
struct TagInfo {
WORD reserve;
short rssi;
BYTE antenna;
BYTE channel;
BYTE reserve2;
BYTE reserve3;
BYTE codeLen;
BYTE code[255];
};
typedef int (*pfnOpenDevice)(HANDLE* hComm, char* ComPort, BYTE Baudrate);
typedef int (*pfnInventoryContinue)(HANDLE hComm, BYTE btInvCount, DWORD dwInvParam);
typedef int (*pfnGetTagInfo)(HANDLE hComm, TagInfo* tag_info, WORD timeout);
typedef int (*pfnInventoryStop)(HANDLE hComm, WORD timeout);
typedef int (*pfnCloseDevice)(HANDLE hComm);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString comPort = "COM4"; // Настрой под свой порт
BYTE baudrate = 0x04; // 115200
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
qDebug() << "DLL loaded successfully from" << dll.fileName();
auto OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
auto InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
auto GetTagInfo = (pfnGetTagInfo)dll.resolve("GetTagInfo");
auto InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
auto CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
if (!OpenDevice || !InventoryContinue || !GetTagInfo || !InventoryStop || !CloseDevice) {
qCritical() << "Failed to resolve one or more functions";
return -1;
}
HANDLE hComm = nullptr;
QByteArray portArray = comPort.toLocal8Bit();
char* portStr = portArray.data();
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
qCritical() << "OpenDevice failed with code:" << hex << ret;
return -1;
}
qDebug() << "Device opened on port" << comPort;
// Запускаем одиночную инвентаризацию, чтобы прочитать тег
ret = InventoryContinue(hComm, 1, 0);
if (ret != 0) {
qCritical() << "InventoryContinue failed with code:" << hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "InventoryContinue command sent";
TagInfo tagInfo;
ret = GetTagInfo(hComm, &tagInfo, 2000); // Таймаут 2000ms
if (ret == 0) {
QByteArray epcData((char*)tagInfo.code, tagInfo.codeLen);
qDebug() << "Tag found EPC:" << epcData.toHex(':');
} else {
qDebug() << "No tag found or timeout, code:" << hex << ret;
}
InventoryStop(hComm, 1000);
qDebug() << "Inventory stopped";
ret = CloseDevice(hComm);
if (ret != 0) {
qCritical() << "CloseDevice failed with code:" << hex << ret;
} else {
qDebug() << "Device closed";
}
#ifdef Q_OS_WIN
system("pause"); // Чтобы окно не закрылось сразу
#endif
return 0;
}
Что это делает
Загружает DLL и необходимые функции.
Подключается к ридеру по COM4 (поменяй под свой порт).
Запускает однократный запрос на чтение метки.
Ждёт до 2 секунд метку.
Если метка найдена — выводит EPC в qDebug().
Останавливает инвентаризацию, закрывает ридер.
В Windows ждёт нажатия клавиши перед закрытием окна.
Если хочешь, могу помочь с другими режимами — например, циклическое чтение или с вводом пользователя.
Для работы с UHF Prime Reader напрямую без DLL нужно понимать, как именно протокол общения с устройством устроен. Обычно такие RFID-ричдеры используют один из следующих вариантов:
Собственный протокол поверх COM-порта (RS232) или USB-to-Serial:
Тогда ты можешь использовать стандартный доступ к последовательному порту (например, через QSerialPort в Qt), и самостоятельно формировать и парсить команды согласно протоколу устройства.
Сетевой протокол (TCP/IP):
Если устройство может работать по сети, тогда нужно знать, какие команды отправлять и получать.
Но вообще:
DLL обычно содержит готовые функции и логику для работы с устройством, инкапсулирует сложность протокола.
Если ты хочешь работать без DLL — нужно знать протокол передачи, формат команд и ответов.
Можно ли без DLL?
Да, можно, но только если есть документация протокола взаимодействия (формат запросов/ответов).
В твоём случае SDK предоставляет только DLL + описание API, но не "сырые" протоколы.
Если у тебя есть описание последовательности байт для каждой команды (например, команды InventoryContinue, как они выглядят в "сыром" виде) — можно реализовать клиента на QSerialPort.
Что делать?
Узнать документацию протокола USB/COM устройства (например, байтовые последовательности команд и ответов).
Использовать QSerialPort (или нативные WinAPI) для открытия порта и отправки байтов.
Читать с порта ответы устройства.
Реализовать парсинг ответов — для получения EPC и статуса.
Примерный код для открытия COM-порта и отправки данных без DLL (на Qt):
#include <QCoreApplication>
#include <QSerialPort>
#include <QDebug>
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QSerialPort serial;
serial.setPortName("COM4"); // Поменять на свой порт
serial.setBaudRate(QSerialPort::Baud115200);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
if (!serial.open(QIODevice::ReadWrite)) {
qCritical() << "Failed to open port";
return -1;
}
// Пример: отправляем команду (нужно заменить на настоящие байты по протоколу)
QByteArray command = QByteArray::fromHex("AA5504..."); // Тут реальные байты команды
qint64 written = serial.write(command);
if (written == -1) {
qCritical() << "Failed to write data";
return -1;
}
serial.flush();
if (!serial.waitForReadyRead(2000)) {
qCritical() << "Timeout waiting for response";
return -1;
}
QByteArray response = serial.readAll();
while (serial.waitForReadyRead(100))
response += serial.readAll();
qDebug() << "Response:" << response.toHex();
serial.close();
return 0;
}
Важное: Без документации протокола работать сложно!
Даже если SDK дал DLL, но не дал описания байтовых команд — нужно либо запросить у производителя, либо снимать сниффером USB/COM и анализировать команды.
DLL обычно нужна именно для удобства.
Итог
Если есть документация протокола — реализуй через QSerialPort.
Если нет — проще работать через DLL, как мы делали.
Если хочешь, могу помочь написать код для низкоуровневой работы по последовательному порту — при наличии протокола команд.
Если расскажешь, как именно устройство подключено (USB, COM, Ethernet) и есть ли протокол — дам рекомендации по реализации без DLL.
В Qt есть несколько способов подключать и использовать DLL. Если через QLibrary::resolve() не удается получить функции — возможно, проблема в экспорте функций, соглашении вызова, или в отсутствии импорта.
Варианты подключения DLL в Qt
1. Использовать QLibrary и resolve() как в твоем примере
Причины ошибок:
Неверное имя функции (учти регистр, возможен C++ name mangling)
Неправильное соглашение вызова (__stdcall vs __cdecl) — может менять имя функции
DLL не экспортирует функции в "C" стиле. Нужно, чтобы экспорты были с extern "C"
Решение:
Проверь экспортируемые имена утилитой Dependency Walker (depends.exe)
Попробуй распечатать dll.resolve() для разных вариантов имени, например:
"OpenDevice"
"_OpenDevice@12" (stdcall)
"?OpenDevice@@..." (mangled C++ имя)
Если DLL от производителя, спроси у них заголовочный файл .h или .lib с точными объявлениями.
2. Использовать заголовочный файл + *.lib (импортная библиотека)
Функции экспортированы с extern "C", что отключает C++ name mangling и позволит корректно их найти в DLL.
Функции объявлены с типом параметра int64_t hComm (вместо void* HANDLE), что соответствует описанию.
Используются базовые типы (unsigned char, unsigned short, unsigned long) совместимые с DLL.
Что нужно проверить и/или добавить
Соглашение о вызове (calling convention)
В Windows для DLL чаще используется __stdcall. В заголовке его не видно, возможно, стоит добавить:
#ifdef _WIN32
#define API_CALL __stdcall
#else
#define API_CALL
#endif
// И в объявлениях функций:
int API_CALL OpenDevice(int64_t* hComm, char* pcCom, int iBaudRate);
// и т.п.
Это важно, иначе возможна проблема при GetProcAddress или линковке.
Подключение этого заголовочного файла и .lib
Если есть импортная библиотека .lib, её можно подключить, и тогда можно вызывать функции напрямую без QLibrary.
Использование typedef для удобства
Можно в коде typedef-ить HANDLE как int64_t чтобы не писать так громоздко.
typedef int64_t HANDLE;
Проверка импорта и использования DLL
Если нет .lib, используйте QLibrary и resolve(), например:
Сохрани этот файл рядом с проектом. Здесь API_CALL — макрос для __stdcall:
#ifndef UHFPRIMEAPI_H
#define UHFPRIMEAPI_H
#include <cstdint>
#ifdef _WIN32
#define API_CALL __stdcall
#else
#define API_CALL
#endif
typedef int64_t HANDLE;
struct TagInfo {
uint16_t NO;
short rssi;
uint8_t antenna;
uint8_t channel;
uint8_t crc[2];
uint8_t pc[2];
uint8_t codeLen;
uint8_t code[255];
};
extern "C" {
// Открытие устройства по COM-порту
int API_CALL OpenDevice(HANDLE* hComm, char* pcCom, int iBaudRate);
// Закрытие устройства
int API_CALL CloseDevice(HANDLE hComm);
// Начать считывание тегов (однократно или циклом)
int API_CALL InventoryContinue(HANDLE hComm, uint8_t btInvCount, uint32_t dwInvParam);
// Получить информацию о метке
int API_CALL GetTagUii(HANDLE hComm, TagInfo* tag_info, uint16_t timeout);
// Остановить инвентаризацию
int API_CALL InventoryStop(HANDLE hComm, uint16_t timeout);
}
#endif // UHFPRIMEAPI_H
Шаг 2. main.cpp
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QThread>
#include <conio.h> // _getch для Windows — задержка
#include "uhfprimeapi.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// Название DLL без расширения
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
qDebug() << "DLL loaded from" << dll.fileName();
// Сигнатуры функций
typedef int (API_CALL *pOpenDevice)(HANDLE*, char*, int);
typedef int (API_CALL *pCloseDevice)(HANDLE);
typedef int (API_CALL *pInventoryContinue)(HANDLE, uint8_t, uint32_t);
typedef int (API_CALL *pGetTagUii)(HANDLE, TagInfo*, uint16_t);
typedef int (API_CALL *pInventoryStop)(HANDLE, uint16_t);
// Разрешаем функции
pOpenDevice OpenDevice = (pOpenDevice)dll.resolve("OpenDevice");
pCloseDevice CloseDevice = (pCloseDevice)dll.resolve("CloseDevice");
pInventoryContinue InventoryContinue = (pInventoryContinue)dll.resolve("InventoryContinue");
pGetTagUii GetTagUii = (pGetTagUii)dll.resolve("GetTagUii");
pInventoryStop InventoryStop = (pInventoryStop)dll.resolve("InventoryStop");
if (!OpenDevice || !CloseDevice || !InventoryContinue || !GetTagUii || !InventoryStop) {
qCritical() << "Failed to resolve one or more functions.";
return -1;
}
HANDLE hComm = 0;
QByteArray portName = "COM6"; // <-- Твой COM порт
char* portStr = portName.data();
int baudrate = 115200; // Часто 115200, проверь для устройства
// Открываем устройство
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
qCritical() << "OpenDevice failed with error code:" << hex << ret;
return -1;
}
qDebug() << "Device opened on" << portStr;
// Запускаем однократную инвентаризацию (1 скан)
ret = InventoryContinue(hComm, 1, 0);
if (ret != 0) {
qWarning() << "InventoryContinue failed:" << hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "InventoryContinue command sent, scanning tags...";
TagInfo tagInfo;
ret = GetTagUii(hComm, &tagInfo, 2000); // Ожидаем до 2 секунд
if (ret == 0) {
QByteArray epc((char*)tagInfo.code, tagInfo.codeLen);
qDebug() << "Tag found EPC:" << epc.toHex(':');
qDebug() << "RSSI:" << tagInfo.rssi << "Antenna:" << (int)tagInfo.antenna;
} else {
qDebug() << "No tag found or timeout, code:" << hex << ret;
}
// Останавливаем инвентаризацию
ret = InventoryStop(hComm, 1000);
if (ret != 0) {
qWarning() << "InventoryStop failed:" << hex << ret;
}
// Закрываем устройство
ret = CloseDevice(hComm);
if (ret != 0) {
qWarning() << "CloseDevice failed:" << hex << ret;
} else {
qDebug() << "Device closed.";
}
qDebug() << "Press any key to exit...";
_getch(); // Для Windows: ждем нажатия клавиши прежде чем завершить
return 0;
}
Шаг 3. Файл .pro
QT += core
QT -= gui
CONFIG += console c++11
SOURCES += main.cpp
# Добавь путь, если dll в нестандартной папке
# DLL будет загружаться динамически через QLibrary, .lib не требуется
Важные моменты и рекомендации:
DLL (UHFPrimeReader.dll) должен лежать в каталоге запуска приложения — рядом с .exe (например, в папке сборки Release/Debug).
Порт COM6 должен существовать и быть доступен.
Архитектура DLL (x86 vs x64) должна совпадать с архитектурой билда Qt.
Параметр скорости в OpenDevice — это обычно 115200, если не уверен проверь в документации.
Если будут ошибки вида "не найдена функция" — проверь экспорт функций через Dependency Walker. Если имена отличаются, поправь в dll.resolve().
Если нужно, могу помочь с расширением, циклическим сканированием, или сетевым подключением. Просто скажи!
вот код на СИ проверь его там запускается Inventory.. в втоем варианте - ошибка наверное
#include
#include <dlfcn.h>
#include <unistd.h>
#include
#include <string.h>
#include
#include
#include
#include <stdio.h>
Спасибо за предоставленный код на C. Давайте разберёмся, как он работает и почему может возникать ошибка в вашем Qt-примере, а также что нужно поправить.
Ключевые моменты из вашего C-кода:
Вы вызываете InventoryContinue(hComm, 0, 0) для запуска непрерывного чтения. Это значит инвентаризация без ограничения по количеству, пока не вызовете InventoryStop.
Функция GetTagUii вызывается для чтения одной метки с таймаутом.
Используете int64_t hComm как тип для дескриптора устройства — важно, чтобы Qt код использовал тоже int64_t (а не void* или HANDLE), иначе разные типы могут привести к ошибкам.
В вашем Qt-примере для однократного опроса вы использовали вызов InventoryContinue(hComm, 1, 0); — тогда как в Си коде для постоянного чтения вызывается с 0 (что значит бесконечно).
При цикле чтения в Си коде вызывается Read(), который вызывает GetTagUii десятки раз с маленькой задержкой.
Главные отличия и рекомендации для Qt-кода
Параметры InventoryContinue:
В доках и коде: btInvCount = 0 — бесконечное (непрерывное) чтение, btInvCount > 0 — количество событий (меток).
Поэтому если хотите поведение как в Си-версии — используйте InventoryContinue(hComm, 0, 0), а не 1.
Тип дескриптора hComm:
В вашем хедере и функции все операции используют int64_t hComm. В Qt коде используйте именно этот тип (например qint64).
Цикл чтения меток:
В C коде вы запускаете InventoryContinue(hComm, 0, 0); и в цикле вызываете GetTagUii многократно с маленьким интервалом (~10 мс). Подобное нужно делать и в Qt:
InventoryContinue(hComm, 0, 0); // Запускаем непрерывную инвентаризацию
for (int i = 0; i < 100; ++i) {
TagInfo tag;
int ret = GetTagUii(hComm, &tag, 1000);
if (ret == 0) {
// обработать тег
}
QThread::msleep(10);
}
InventoryStop(hComm, 10000);
Проверяйте возвращаемые коды функций!
В документации 0x00 — успешное выполнение.
Соглашение вызова:
Убедитесь, что функции подключены с __stdcall (через макрос API_CALL или typedef).
Исправленный пример Qt (фрагмент с корректным чтением):
// Предполагается, что typedef HANDLE = qint64 (int64_t)
// и функция InventoryContinue, GetTagUii, InventoryStop, CloseDevice загружены через QLibrary
qint64 hComm = 0;
// Открытие устройства
int ret = OpenDevice(&hComm, portStr, 115200);
if (ret != 0) {
qCritical() << "OpenDevice failed" << Qt::hex << ret;
return -1;
}
// Запускаем непрерывное считывание
ret = InventoryContinue(hComm, 0, 0);
if (ret != 0) {
qCritical() << "InventoryContinue failed" << Qt::hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "Reading tags...";
for (int i = 0; i < 100; ++i) {
TagInfo tag;
ret = GetTagUii(hComm, &tag, 1000);
if (ret == 0) {
QByteArray epc((char*)tag.code, tag.codeLen);
qDebug() << "Tag EPC:" << epc.toHex(':');
} else if (ret == 0xFFFFFF07) {
// STAT_CMD_INVENTORY_STOP - нет тегов
qDebug() << "No tag in inventory";
} else {
qWarning() << "GetTagUii error" << Qt::hex << ret;
}
QThread::msleep(10);
}
// Останавливаем считывание
ret = InventoryStop(hComm, 10000);
if (ret != 0)
qWarning() << "InventoryStop error" << Qt::hex << ret;
// Закрываем устройство
CloseDevice(hComm);
Итог
Используйте InventoryContinue(hComm, 0, 0) для запуска бесконечной инвентаризации.
В цикле опрашивайте GetTagUii с небольшими задержками.
Не вызывайте InventoryContinue на каждый тег отдельно (иначе ошибка).
Убедитесь, что тип hComm в вашем Qt-коде — qint64 или int64_t.
Проверяйте коды возврата и соответствуйте документации.
Если хотите, могу помочь адаптировать полный Qt пример под такой алгоритм с циклом.
Если есть вопросы — пишите!
Ниже полный пример Qt-консольного приложения на C++, адаптированный под твой Си-код. В нем:
Используется InventoryContinue(hComm, 0, 0) — бесконечная инвентаризация,
В цикле 100 раз вызывается GetTagUii с задержкой 10 мс,
Правильный тип qint64 для hComm,
Функции загружаются из DLL c __stdcall через QLibrary,
Вывод происходит через qDebug(),
После завершения сканирования вызывается InventoryStop и CloseDevice,
В конце — ждем нажатием клавиши (_getch) чтобы окно не закрывалось.
#include <QCoreApplication>
#include <QLibrary>
#include <QDebug>
#include <QThread>
#include <conio.h> // _getch для Windows
// Заголовочные определения (можно оформить в отдельный файл .h и подключить)
typedef qint64 HANDLE; // int64_t
struct TagInfo {
quint16 NO; // 2 bytes
short rssi; // 2 bytes
quint8 antenna;
quint8 channel;
quint8 crc[2];
quint8 pc[2];
quint8 codeLen;
quint8 code[255];
};
#ifdef _WIN32
#define API_CALL __stdcall
#else
#define API_CALL
#endif
typedef int (API_CALL *pfnOpenDevice)(HANDLE* hComm, char* pcCom, int iBaudRate);
typedef int (API_CALL *pfnCloseDevice)(HANDLE hComm);
typedef int (API_CALL *pfnInventoryContinue)(HANDLE hComm, quint8 btInvCount, quint32 dwInvParam);
typedef int (API_CALL *pfnGetTagUii)(HANDLE hComm, TagInfo* tag_info, quint16 timeout);
typedef int (API_CALL *pfnInventoryStop)(HANDLE hComm, quint16 timeout);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QLibrary dll("UHFPrimeReader");
if (!dll.load()) {
qCritical() << "Failed to load DLL:" << dll.errorString();
return -1;
}
pfnOpenDevice OpenDevice = (pfnOpenDevice)dll.resolve("OpenDevice");
pfnCloseDevice CloseDevice = (pfnCloseDevice)dll.resolve("CloseDevice");
pfnInventoryContinue InventoryContinue = (pfnInventoryContinue)dll.resolve("InventoryContinue");
pfnGetTagUii GetTagUii = (pfnGetTagUii)dll.resolve("GetTagUii");
pfnInventoryStop InventoryStop = (pfnInventoryStop)dll.resolve("InventoryStop");
if (!OpenDevice || !CloseDevice || !InventoryContinue || !GetTagUii || !InventoryStop) {
qCritical() << "Failed to resolve one or more functions.";
return -1;
}
HANDLE hComm = 0;
QByteArray portName = "COM6"; // ваш COM-порт
char* portStr = portName.data();
int baudrate = 115200;
int ret = OpenDevice(&hComm, portStr, baudrate);
if (ret != 0) {
qCritical() << "OpenDevice failed with code:" << Qt::hex << ret;
return -1;
}
qDebug() << "Device opened on" << portStr;
ret = InventoryContinue(hComm, 0, 0); // бесконечное чтение
if (ret != 0) {
qCritical() << "InventoryContinue failed with code:" << Qt::hex << ret;
CloseDevice(hComm);
return -1;
}
qDebug() << "Inventory started, reading tags...";
for (int i = 0; i < 100; ++i) {
TagInfo tag;
ret = GetTagUii(hComm, &tag, 1000); // таймаут 1000ms на метку
if (ret == 0) {
QByteArray epc((char*)tag.code, tag.codeLen);
qDebug() << "Tag EPC:" << epc.toHex(':')
<< " RSSI:" << tag.rssi/10
<< " Antenna:" << (int)tag.antenna;
} else if (ret == 0xFFFFFF07) {
qDebug() << "No tags or inventory stopped";
} else {
qWarning() << "GetTagUii failed with code:" << Qt::hex << ret;
}
QThread::msleep(10);
}
ret = InventoryStop(hComm, 10000);
if (ret != 0) qWarning() << "InventoryStop failed:" << Qt::hex << ret;
ret = CloseDevice(hComm);
if (ret != 0)
qWarning() << "CloseDevice failed:" << Qt::hex << ret;
else
qDebug() << "Device closed.";
qDebug() << "Press any key to exit...";
_getch();
return 0;
}
Что сделать:
Помести этот код в main.cpp.
Собери под нужную архитектуру (x86 или x64), совпадающую с DLL.
Помести рядом с exe файл UHFPrimeReader.dll.
Используй Qt Creator с .pro файлом, содержащим как минимум:
Скорость в OpenDevice должна соответствовать настройкам вашего устройства (часто 115200).
Если хотите, чтобы цикл был бесконечным — делай while (true) вместо цикла на 100 итераций с подходящими выходными условиями.
Проверяйте возвращаемые коды функций и обрабатывайте ошибки согласно документации.
Если нужна помощь с расширениями или асинхронным чтением — обращайтесь!
Добавлю функцию AnswerMod, которая, предположу, что из твоей документации — это установка рабочего режима (Answer Mode). В твоем C-коде WORKMODE — это из структуры DevicePara, а установка значения выполняется через SetDevicePara.
В данном контексте AnswerMod — будет простая функция, которая:
Считывает текущие параметры устройства (GetDevicePara),
Меняет WORKMODE на 0 (Answer Mode),
Записывает параметры обратно (SetDevicePara),
Выводит результат.
1. Объявим типы функций в main.cpp и подгрузим
typedef int (API_CALL *pfnGetDevicePara)(HANDLE hComm, void* param);
typedef int (API_CALL *pfnSetDevicePara)(HANDLE hComm, const void* param);
Если у тебя структура DevicePara уже есть в заголовочном файле — включи ее. Для примера объявлю здесь минимальный вид:
В целом код на Qt выглядит в порядке, но есть несколько важных замечаний по твоему вопросу о 32-битности и 64-битности. Разберёмся:
1. Тип HANDLE = qint32 (32-битный)
typedef qint32 HANDLE; // int64_t в комментарии — лучше убрать int64_t, чтобы не путать
Если DLL явно ожидает 64-битный дескриптор (int64_t, qint64), а ты передаёшь 32-битный тип, это будет ошибка!
Опасность: 32-битный HANDLE не соответствует тому, что ожидает DLL — вызовы будут ломаться.
Вывод:
Если в документации и исходных заголовках DLL дескриптор — int64_t (64-бит), то нужно в Qt писать именно:
typedef qint64 HANDLE;
2. Твой текущий код с typedef qint32 HANDLE; — скорее всего причина проблем.
3. Проверь архитектуру сборки
Собирай приложение под 64-бит (x64), чтобы совпадала с DLL (обычно Производитель предоставляет 64-битную DLL).
Если DLL 32-битная — нужно билдить и тестировать Qt-приложение в 32-битном режиме и HANDLE = qint32.
4. Пример проверки типа и размеров (оставь этот код в main.cpp для отладки):
qDebug() << "Size of HANDLE:" << sizeof(HANDLE) << "bytes";
qDebug() << "Size of void*:" << sizeof(void*) << "bytes";
5. Ваш код можно поправить так:
В начале main.cpp:
typedef qint64 HANDLE; // uint64, чтобы соответствовать int64_t дескриптору
Также вся работа с hComm идет как с 64-битным числом.
6. Исправленный фрагмент по участку объявления типов функций:
typedef int (API_CALL *pfnOpenDevice)(HANDLE* hComm, char* pcCom, int iBaudRate);
typedef int (API_CALL *pfnCloseDevice)(HANDLE hComm);
typedef int (API_CALL *pfnInventoryContinue)(HANDLE hComm, quint8 btInvCount, quint32 dwInvParam);
typedef int (API_CALL *pfnGetTagUii)(HANDLE hComm, TagInfo* tag_info, quint16 timeout);
typedef int (API_CALL *pfnInventoryStop)(HANDLE hComm, quint16 timeout);
typedef int (API_CALL *pfnGetDevicePara)(HANDLE hComm, void* param);
typedef int (API_CALL *pfnSetDevicePara)(HANDLE hComm, const void* param);
7. Проверка кодов возврата и вывод тегов — твой код сделан хорошо.
Единственное отложи временно блок
/*
if (ret == 0) {
...
}
*/
Заменив на твой вывод — это ок.
8. Итог: для работы с вашей DLL в Qt:
HANDLE должен быть 64-битным целым, т.е. typedef qint64 HANDLE;
Скомпилируй приложение под 64-бит (в Qt Creator выбери Qt Kit x64)
Проверь, что DLL именно 64-битная (Dependency Walker или dumpbin)
Передавай HANDLE как 64-битное число во все функции
Если хочешь, могу подготовить полный исправленный вариант кода с qint64 HANDLE и советами по сборке. Хотел бы?
int64_t
int64_t (64-битное целое) в 32-битном приложении отлично поддерживается (типа __int64), но указатель на него нельзя приводить к 32-битному int.
В оригинальном коде используется тип int64_t hComm (64-битное целое) как дескриптор, и это просто число (не указатель!).
Что важно
В 32-битном приложении int64_t занимает 8 байт (64 бита) — просто число/идентификатор дескриптора, значит нужно в Qt именно использовать qint64 или long long.
НЕ стоит использовать qint32 для hComm, даже в 32-бит приложении — потому что DLL ждет 64-битный идентификатор.
В функциях OpenDevice параметр int64_t* hComm — это указатель на 64-битный идентификатор, чтобы функция записала туда дескриптор.
Вывод
В 32-битном Qt-приложении:
Используйте typedef qint64 HANDLE (или typedef long long HANDLE).
При вызове OpenDevice передавай указатель на qint64:
qint64 hComm = 0;
ret = OpenDevice(&hComm, portStr, baudrate);
Все остальные функции получают qint64 hComm (64-битное число).
Пример из твоего кода — всё правильно:
typedef qint64 HANDLE;
int ret = OpenDevice(&hComm, portStr, 115200);
// hComm — 64-битное число в 32-битном приложении
ret = InventoryContinue(hComm, 0, 0);
ret = GetTagUii(hComm, &tag, 1000);
Резюме
Код с typedef qint64 HANDLE; подходит и для 32-битной программы.
Скомпилируй проект под 32-битную сборку Qt (в Qt Creator выбери Kit с 32-бит компилятором).
Тут toHex() создаст строку из tag.codeLen * 2 символов
Разделитель ':' добавляет двоеточия между байтами
Вывод
tag.codeLen = 12 — это байты
24 символа — hex-представление этих байт
Это нормально, не означает ошибку.
Если хочешь вывести длину именно в байтах, используй tag.codeLen. Для hex-представления — всегда в 2 раза символов.
Если нужно — могу помочь с примером конвертации и вывода!
Похоже, ты столкнулся с тем, что длинна массива кода 24, но значения элементов в массиве выглядят не как ожидаемые байты EPC (пример: "E2 80 68 94 ..."), а как числа вроде 0, 68, 80, 64 и т.д., не совпадающие с этим форматом.
Разберёмся, что может происходить.
1. Как данные EPC хранятся и передаются?
EPC — это последовательность байтов, обычно длиной от 12 до 24 байт. Именно байтов, а не символов.
В структуре TagInfo поле codeLen — это длина в байтах, а code — массив байтов.
2. Почему у тебя в выводе элементы — такие числа, а карта другая?
Правильная EPC обычно выводится как последовательность байтов, например: E2 80 68 94 00 00 50 2C 14 76 52 45
Если у тебя выводятся числа типа:
0
0
0
0
0
68
80
64
0
124
27
217
0
47
92
232
...
возможно:
Ты выводишь числовые значения элементов массива как целые, а не как hex байты.
Массив code может содержать данные в разном формате или смещённые.
3. Важно — как ты считываешь и выводишь?
Рассмотрим пример:
for (int i = 0; i < tag.codeLen; ++i) {
// Если так:
qDebug() << tag.code[i];
}
Это выведет десятичные числовые значения байтов.
Если хочешь вывести именно в hex, нужно использовать:
Потому, что ты выводишь байты как числа — в десятичном формате. В момент вывода 68 — это 0x44, 80 — 0x50, 64 — 0x40 и т.д.
Если хочешь видеть их вшестнадцатеричном виде, надо либо:
Использовать QByteArray::toHex(), либо
Форматировать каждый байт в hex строку, например так:
QString epcStr;
for (int i = 0; i < tag.codeLen; ++i) {
epcStr += QString("%1 ").arg(tag.code[i], 2, 16, QLatin1Char('0')).toUpper();
}
qDebug() << "EPC:" << epcStr.trimmed();
5. Что делать, если хочешь "сложить" в строку?
QString epcStr;
for (int i = 0; i < tag.codeLen; ++i) {
epcStr += QString("%1").arg(tag.code[i], 2, 16, QLatin1Char('0')).toUpper();
}
// теперь epcStr содержит EPC в виде, например, "E28068940000502C14765245"
6. Пример — как получить корректный EPC из твоих байт
Если у тебя есть весь массив code с длиной в codeLen, например:
Если нужно, помогу с примером на Qt, который прочитает структуру и выведет EPC корректно.
Как работает структура и хранит данные
NO — 2 байта (2 + 4 = 6 байт сверху бывают служебными)
rssi — 2 байта
antenna — 1 байт
channel — 1 байт
crc — 2 байта
pc — 2 байта
codeLen — 1 байт (длина EPC в байтах)
code — массив байтов EPC, максимум 255 байт
Что с codeLen и массивом code?
codeLen — это длина EPC (кол-во байт в code), например 12.
code — содержит raw байты EPC, длиной codeLen.
Почему 12 байт EPC и 24 символа?
1 байт = 2 символа в hex-представлении.
Если EPC длиной 12 байт, то в hex будет 24 символа.
Пример правильного получения EPC из TagInfo
TagInfo tag;
// ... получили данные в tag ...
QByteArray epc((char*)tag.code, tag.codeLen);
QString epcStr = epc.toHex(' ').toUpper();
qDebug() << "EPC:" << epcStr;
qDebug() << "EPC len (bytes):" << tag.codeLen;
Эти данные — tag.code длиной tag.codeLen — и есть твоя карта.
Что делать если у тебя "странные" числа?
Когда печатаешь tag.code[i] просто через qDebug() << tag.code[i]; — это десятичные значения байт.
Например, чтобы вывести этот байт в hex-формате:
for (int i = 0; i < tag.codeLen; ++i) {
qDebug() << QString("%1").arg(tag.code[i], 2, 16, QLatin1Char('0')).toUpper();
}
Итог:
Просто используй tag.codeLen для длины EPC.
Берёшь первые codeLen байт в code.
Выводи через toHex() или форматируй каждый байт в hex.
Если хочешь — могу помочь написать функцию, которая из TagInfo сразу возвращает красивую строку с EPC.
BYTE reserve2;
BYTE reserve3; — 1 байт, резерв
BYTE codeLen; — 1 байт, длина EPC
BYTE code[255]; — массив байт, содержащий EPC-код
Общий размер заголовка перед самим EPC: 2 + 2 +1 +1 +1 +1 +1 = 9 байт
Работа с EPC
EPC — это первые codeLen байт из массива code
Чтобы вывести EPC в hex-формате (обычно в Qt):
TagInfo tag;
// ... получили заполнение tag ...
QByteArray epc((char*)tag.code, tag.codeLen);
qDebug() << "EPC:" << epc.toHex(':').toUpper();
Почему длина EPC в символах в два раза больше длины codeLen в байтах?
Каждый байт — 2 hex-символа
Если EPC длина 12 байт — при выводе hex будет 24 символа
Как правильно выводить по байтам в цикле (Qt):
for (int i = 0; i < tag.codeLen; ++i) {
qDebug() << QString("%1").arg(tag.code[i], 2, 16, QLatin1Char('0')).toUpper();
}
Итог:
Используй именно эту структуру
Берёшь tag.codeLen для длины EPC
Выводи первые codeLen байт из tag.code как hex
Не обращай внимания, что tag.codeLen больше или меньше 12 — вывод зависит от реальной длины EPC в теге
Если нужно, могу помочь оформить структуру и пример использования в Qt с твоей документацией.
Несколько важных моментов:
Используй Qt типы (quint8, quint16, qint16) — для гарантии размера и переносимости.
Важно, чтобы структура имела ровно тот же размер и выравнивание, что и в исходной DLL. По умолчанию struct в C++ может иметь разное выравнивание, попробуй добавить #pragma pack(push,1) / #pragma pack(pop) если возникнут проблемы: