2014-02-23 37 views
1

我想與使用中斷傳輸進行通信的USB設備進行通信。 它是而不是一個查詢設備,任何一方都可以隨時發送。我發現的所有示例似乎都是輪詢響應,您首先發送數據,等待發送完成,然後等待響應,處理它,然後再返回到發送數據。Android USB主機中斷傳輸:如何在任何時間發送和接收

我的代碼,我發現這裏的計算器以下爲藍本(我展示了我原有的基於它,因爲我自己的代碼有很多事情,是不太緊湊)

boolean retval = request.queue(buffer, 1); 
    if (mConnection.requestWait() == request) { 
     // wait for confirmation (request was sent) 
     UsbRequest inRequest = new UsbRequest(); 
     // URB for the incoming data 
     inRequest.initialize(mConnection, mEndpointIn); 
     // the direction is dictated by this initialisation to the incoming endpoint. 
     if(inRequest.queue(buffer, bufferMaxLength) == true){ 
       mConnection.requestWait(); 
       // wait for this request to be completed 
       // at this point buffer contains the data received 
     } 
    } 

第二個requestWait()會阻塞,直到有東西到達,所以我不能做另一個TX操作,直到我收到一些東西!我錯過了什麼?

回答

3

你說:「第二個requestWait()將阻塞,直到到達的東西,所以直到我收到東西,我不能做一套TX操作」

有我自己寫的代碼也根據您展示的例子,我想我明白你在哪裏感到困惑:第二個requestWait()將返回任何 USB操作,而不僅僅是前面的操作。 (來自Android API文檔「請注意,這可能會返回在多個UsbEndpoints上排隊的請求」)

因此,即使您在等待時排隊發送請求,您的「接收waitRequest」將會返回,但發送端點。您應該始終檢查waitRequest結果的端點,或者將它與初始請求本身進行比較。如果它匹配inRequest,那麼它實際上是您阻止的接收操作。如果它不匹配,請將它與您的發送請求進行比較(或者在下面的示例代碼中,我簡單地假設它是發送響應並忽略它)

您需要排隊發送和接收來自不同方法的請求或但是不是在你提供的代碼所隱含的同一個循環中。

下面是我自己的項目代碼(注意,我的應用程序運行到堆損壞,所以下面的代碼也許不是完美的,但它確實讓我即使在接收操作掛起發送)

所以這是我收到循環,你會看到你的代碼相似:

while(mUsbDevice != null) { 

     if (inRequest.queue(buffer, BUFFER_SIZE) == true) { 
      // (mUsbConnection.requestWait() is blocking 
      if (mUsbConnection.requestWait() == inRequest){ 

       // this is an actual receive 
       // do receive processing here (send to conusmer) 

      } else{ 
       Log.d(TAG, "mConnection.requestWait() returned for a different request (likely a send operation)"); 
      } 
     } else { 
      Log.e(TAG, "failed to queue USB request"); 
     } 
     buffer.clear(); 
    } 

我做的發送形式,使用消息隊列傳入發送請求另一個線程:

 mHandler = new Handler() { 
      public void handleMessage(Message msg) {      
       if (msg.what == 1) { // 1 means send a 64 bytes array in msg.obj 
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); 
        final byte[] array = (byte[]) msg.obj;      
        buffer.clear(); 
        buffer.put(array); 
        UsbRequest outRequest = new UsbRequest(); 
        outRequest.initialize(mUsbConnection, mUsbEndpointOut); 
        outRequest.queue(buffer, BUFFER_SIZE); 
        Log.d(L.TAG, "Queueing request:"+outRequest); 
        // don't do a mConnection.requestWait() here, ReceiveThread is already listening 
       } else if (msg.what == 2) { // 2 means exit 
        Log.d(L.TAG, "SenderThread::handleMessage(): terminate"); 
        Looper.myLooper().quit(); 
       } else { 
        Log.e(L.TAG, "SenderThread::handleMessage(): unknow message type: " + msg.what); 
       } 
      } 
     }; 
相關問題