藍牙學習筆記二(Android連接問題)


可以通過以下兩點加速藍牙連接:
1、更新連接參數
interval:連接間隔(connection intervals ),范圍在 7.5 毫秒 到 4 秒。
latency:連接延遲
。。。 還有一些其它參數.
 
Android API不提供具體的參數值, 只提供了三個常量:
CONNECTION_PRIORITY_HIGH
CONNECTION_PRIORITY_BALANCED
CONNECTION_PRIORITY_LOW_POWER
從Android的源碼找到對應的參數:
在發起連接請求時,通過BluetoothGatt實例發起更新:
mBluetoothGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
 
2、在請求連接時,設置自動連接標識為 false。
自動連接標識為true 時,雖然能提高連接成功的概率,但是會導致連接時間加長.
具體解釋如下:
 
連接失敗的問題
由於Android的藍牙協議棧bluedroid 在低版本存在一些bug,如當連接的時候,callback 返回 status=133 的情況. 出現這種情況的原因應該手機APP頻繁的操作連接以及斷開。解決的方式可以參考以下幾種:
1、當斷開連接時,調用mBluetoothGatt.disconnect(); 該方式只是斷開連接,並沒有真正釋放資源,可以在 disconnect 的回調里調用 mBluetoothGatt.close()
2、當連接同一台設備時,可通過判斷地址是否一樣,使用mBluetoothGatt.connect(); 但這方式似乎會導致連接放慢.
3、出現這種情況,delay 一會兒,然后再重連. 只能通過多次重連方式。
4、從google 回來的一些資料顯示,當手機斷開連接 mBluetoothGatt.disconnect(); 甚至是mBluetoothGatt.close()。 app藍牙只是給藍牙服務發送了一個斷開連接,藍牙服務是以隊列的形式去處理它. 要徹底斷開該連接,可以通過讓對方設備(從設備)也主動斷開。我嘗試過這種方式,確實解決了我當前的問題.
 
connection fail 資料:
 
status=133, 對於狀態的錯誤:GATT_ERROR
 
connections fail :
1)If your connections fail to happen, the BLE peripheral may be sending packets too slowly, or their signal level may be too low. This can be an issue with output power, range between the devices, interference, or other issues.
 
2)The BLE connection settings are some of the most critical parameters to understand in BLE. Connection interval, slave latency and other settings are sent upon during a connection, and they can tell you a lot about what the devices agree to. If you’re having connection problems, it can be that the two devices don’t agree on the parameters (and the central device disconnects).
 
 
另外可以查看一下Android源碼 packages\apps\Bluetooth 目錄下 bluetooth APP 的源碼,看處理的方式.
 
 
BLE 連接過程:
 
 
注:圖中M代表手機,S代表設備B,M->S表示手機將數據包發給設備B,即手機開啟Tx窗口,設備B開啟Rx窗口;S->M正好相反,表示設備B將數據包發給手機,即設備B開啟Tx窗口,手機開啟Rx窗口。
如圖所示,手機在收到A1廣播包ADV_IND后,以此為初始錨點(這個錨點不是連接的錨點),T_IFS后給Advertiser發送一個connection request命令,即A2數據包,告訴advertiser我將要過來連你,請做好准備。Advertiser根據connect_req命令信息做好接收准備,connect_req包含如下關鍵信息:
  • Transmit window offset,發送窗口偏移
  • Transmit window size, 發送窗口大小
  •  connection interval  連接間隔
  •  latency 從設備延遲
  • timeout 監控超時
.......
這些參數可以由主設備確定,也可以讓從設備確定. 我們取了最優(也是最耗電的配置)
connection interval = 7.5ms
latency = 0
timeout = 4000ms
當主設備發起一個連接請求后(意思告訴從設備,我要連你, 要你做好准備), 在一個1.25ms時間單位, 加上發送窗口大小,發送窗口偏移時間后,發送一個空白給 從設備,並准備接收從設備的包,當接收到從設備的空包后,表示連接正式確立。我們可以理想大概這樣計算連接時間:
 
time = 1.25ms + Transmit window offset + Transmit window size +  connection interval
 
連接成功后,master和slave在每一個connection interval開始的時候,都必須交互一次,即master給slave發一個包,slave再給master發一個包,整個交互過程稱為一個connection event。
 
參考資料:BLE連接建立過程 http://www.mamicode.com/info-detail-2275982.html
 
 
其它資料:
Android BLE Issues:
開源框架 SweetBlue 對藍牙問題的總結:
 
google bluetooth的問題列表:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM