date:2017/04/12 11:10
調用HIDAPI可實現讀數據功能,但是功能十分單一,無法滿足需求。
最簡單的調用如下:
1 void Widget::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 void Widget::on_readButton_clicked() 2 { 3 qDebug("read data."); 4 myhid_read(); 5 }
但是使用的時候發現,每次點擊read按鈕運行一次myhid_read(),輸出一個包的數據。hid設備產生了多少個數據包就要點多少次按鈕才能全部接收。因此需要對它進行改造。
1 void Widget::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. */
HIDAPI提供兩種讀設備的方式,阻塞和非阻塞。阻塞是指在進入讀設備函數后,直到有數據被讀取才退出,而非阻塞則不等待數據的到來,沒有數據則返回0
設置阻塞后,點擊read按鈕,開始循環接收數據。但是未設置終止標志,即啟動接收后軟件一直等待接收數據直到退出軟件。
現考慮:
1、提取報文數據總長度做判斷量,接收包數與總包數相等則退出;
2、設置數據結束符,接收到特定結束符則退出接收。