2012-12-17 29 views
1

根據https://github.com/signal11/hidapi/issues/72 HIDAPI應該在Linux機器上是線程安全的。但是,我根本無法工作。這就是我所做的:兩個線程中的HIDAPI

#ifdef WIN32 
#include <windows.h> 
#endif 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <pthread.h> 
#include <stdlib.h> 
#include <assert.h> 

#include "hidapi.h" 
hid_device *handle; 

static void *TaskCode(void *argument) 
{ 
    int res; 
    //hid_device *handle; 
    unsigned char buf[64]; 

//  res = hid_init(); 
//  if(res == -1) 
//  { 
//   return (void*)1; 
//  } 
// 
//  handle = hid_open(0x0911, 0x251c, NULL); 
//  if(handle == NULL) 
//  { 
//   return (void*)2; 
//  } 

    printf("while 2\n"); 

    while(1) 
    { 
     memset(buf, 64, 0); 
     res = hid_read(handle, buf, 0); 
     if(res == -1) 
     { 
      return (void*)3; 
     } 

     printf("received %d bytes\n", res); 

     for (int i = 0; i < res; i++) 
      printf("Byte %d: %02x ", i+1, buf[i]); 
     //printf("%02x ", buf[0]); 
     fflush(stdout); 
    } 

    return (void*)0; 
} 


int main(int argc, char* argv[]) 
{ 
    int res; 
    //hid_device *handle; 
    unsigned char buf[65]; 

    res = hid_init(); 
    if(res == -1) 
    { 
     return 1; 
    } 

    handle = hid_open(0x0911, 0x251c, NULL); 
    if(handle == NULL) 
    { 
     return 2; 
    } 

    hid_set_nonblocking(handle, 0); 

    pthread_t thread; 
    int rc = pthread_create(&thread, NULL, TaskCode, NULL); 

    printf("while 1\n"); 

    while(1) 
    { 
     int a = getchar(); 
     if(a == 'a') 
     { 
      // Get Device Type (cmd 0x82). The first byte is the report number (0x0). 
      buf[0] = 0x0; 
      buf[1] = 0x82; 
      res = hid_write(handle, buf, 65); 
      if(res != -1) 
       printf("write ok, transferred %d bytes\n", res); 
      else 
      { 
       printf("write error\n"); 
       char* str = hid_error(handle); 
       printf("error: %s\n", str); 
       return 1; 
      } 
     } 
     else if(a== 'b') 
      break; 
    } 

    void* trc; 
    rc = pthread_join(thread, &trc); 

    printf("rc code: %d\n", (int)trc); 

    // Finalize the hidapi library 
    res = hid_exit(); 

    return 0; 
} 

如果我不使用全局句柄,每次都會出現'寫入錯誤'。如果我這樣做,正如在這個例子中,正式的一切工作,但hid_read總是返回0字節......當然,如果我做了簡單的hid_write()後跟hid_read(),我會得到正確的回覆命令0x82的意圖。我真的迷失在這裏,我忽略了什麼?

編輯:澄清,零字節返回也爲一切,包括。鼠標等按鈕,所以它似乎工作,但數據緩衝區總是零字節。

回答

1

對我很恥辱,一個愚蠢的錯誤。代碼應該是:

memset(buf, 0, 64); 
res = hid_read(handle, buf, 64); 

然後它工作。應該睡得更多,寫得更少!