date:2017/04/12 11:10
调用HIDAPI可实现读数据功能,但是功能十分单一,无法满足需求。
最简单的调用如下:
1 voidWidget::myhid_read(){2 res = hid_read(handle,buf_IN,2);3 for(int i = 0;i < 2;i++){4 qDebug("buf[%d]:0x%02x",i,buf_IN[i]);5 }6 }
使用按钮click()操作调用该方法:
1 voidWidget::on_readButton_clicked()2 {3 qDebug("read data.");4 myhid_read();5 }
但是使用的时候发现,每次点击read按钮运行一次myhid_read(),输出一个包的数据。hid设备产生了多少个数据包就要点多少次按钮才能全部接收。因此需要对它进行改造。
1 voidWidget::myhid_read(){2 qDebug("hid read start");3 res = hid_set_nonblocking(handle, 0);4
5 while (1) {6 res = hid_read(handle,buf_IN,2);7 for(int i = 0;i < 2;i++){8 qDebug("buf[%d]:0x%02x",i,buf_IN[i]);9 }10 }11 }
这里第3行设置接收为阻塞式,HIDAPI文档说明如下:
/** @brief Set the device handle to be non-blocking.
In non-blocking mode calls to hid_read() will return
immediately with a value of 0 if there is no data to be
read. In blocking mode, hid_read() will wait (block) until
there is data to read before returning.
Nonblocking can be turned on and off at any time.
@ingroup API
@param device A device handle returned from hid_open().
@param nonblock enable or not the nonblocking reads
- 1 to enable nonblocking
- 0 to disable nonblocking.
@returns
This function returns 0 on success and -1 on error.*/
设置阻塞后,点击read按钮,开始循环接收数据。但是未设置终止标志,即启动接收后软件一直等待接收数据直到退出软件。
现考虑:
1、提取报文数据总长度做判断量,接收包数与总包数相等则退出;
2、设置数据结束符,接收到特定结束符则退出接收。