簡體   English   中英

如何知道 BLE 指示是否在 Android 中被確認

[英]How to know if BLE indicate was acknowledged in Android

我們正在研究兩個 Android 應用程序之間的藍牙低功耗通信。 一個是外圍/服務器,一個是中央/客戶端。 如果數據已更改,服務器將向客戶端發送一個指示。 但是,我們沒有找到一種方法來確保數據在客戶端得到實際確認。 我們如何確定客戶端是否收到並確認了數據,以便在服務器端做出相應的反應?

根據 Android 文檔,BleutoothGattServer 有回調 onNotificationSent。 https://developer.android.com/reference/android/bluetooth/BluetoothGattServerCallback#onNotificationSent(android.bluetooth.BluetoothDevice,%20int)

然而,通過調試和做一些測試,如果通知被發送,這個方法似乎真的被調用了。 無法保證實際收到或確認消息。

所以這里是我們如何設置 GattServer 的特性

BluetoothGattService service = new BluetoothGattService(SERVICE_LOGIN_UUID,
                BluetoothGattService.SERVICE_TYPE_PRIMARY);

        // Write characteristic
        BluetoothGattCharacteristic writeCharacteristic = new BluetoothGattCharacteristic(CHARACTERISTIC_LOGIN_UUID,
                BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ| BluetoothGattCharacteristic.PROPERTY_INDICATE,
                // Somehow this is not necessary, the client can still enable notifications
//                        | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
                BluetoothGattCharacteristic.PERMISSION_WRITE | BluetoothGattCharacteristic.PERMISSION_READ);

        service.addCharacteristic(writeCharacteristic);

        mGattServer.addService(service);

然后我們通過調用這個來通知客戶

mHandler.post(() -> {
            BluetoothGattService service = mGattServer.getService(SERVICE_LOGIN_UUID);
            BluetoothGattCharacteristic characteristic = service.getCharacteristic(uuid);
            log("Notifying characteristic " + characteristic.getUuid().toString()
                    + ", new value: " + StringUtils.byteArrayInHexFormat(value));

            characteristic.setValue(value);
            boolean confirm = BluetoothUtils.requiresConfirmation(characteristic);
            for(BluetoothDevice device : mDevices) {
                mGattServer.notifyCharacteristicChanged(device, characteristic, confirm);
            }
        });

*請暫時忽略這里的for循環

這將導致 onNotificationSent 被調用,但無助於了解它是否被確認。

如果您需要其他代碼部分,請告訴我。

已經謝謝大家了,多多問候

不幸的是,在 Android 上,確認是在幕后發送/接收的,即沒有可以在您的應用程序中使用它的機制。 請查看以下鏈接:-

在 Android BLE 中處理指示而不是通知

如果你真的想要一些應用層機制來證明數據被接收,你可以在你的服務器端實現另一個(額外的)特性。 當中心端收到數據時,它可以簡單地寫入該特征以證明它具有。 這樣做的缺點是使您的應用程序更復雜,但可以說更可靠。 這樣做的原因是您從應用層手動發送確認,確保一切都按預期工作,而從基帶層自動發送 ACK 並不能證明一切都 100% 成功(例如數據沒有) t 從基帶到應用程序,或者您的應用程序崩潰等)。

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM