首页 文章

如何知道BLE设备何时订阅Android上的特性?

提问于
浏览
7

来自iOS开发背景,当使用蓝牙LE充当外围设备时,您可以在“中央”BLE设备订阅(启用通知)特征时注册回调 .

我_1147631_正在使用蓝牙LE作为中心,我可以看到你如何订阅: bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);

在iOS上与此相同: peripheralDevice.setNotifyValue(true, forCharacteristic characteristicToSubscribeTo)

现在,在iOS上调用上面的内容之后,在外围设备上你会得到一个回调,说中央已经订阅了一个类似于: peripheralManager(manager, central subscribedCentral didSubscribeToCharacteristic characteristic) 的方法,然后它会为你提供对订阅/启用通知的设备的引用以及它的特性 .

什么是Android上的等价物?

为了清楚起见,我将指出我不需要在Android上订阅特性,该设备充当外围设备,并且需要在其他设备订阅特性时得到通知 .

很抱歉,如果这很明显,但我无法在文档或其他地方找到它 .

2 回答

  • 7

    在设定赏金之后,我有了一个想法,哈哈应该等一下,让我的大脑有更多时间思考;)

    似乎iOS已经抽象了一些内部订阅的工作方式 . 在ios CoreBluetooth引擎盖下,中心编写了一个特征的“描述符”,表示中心想要订阅特征的值 .

    以下是您需要添加到 BluetoothGattServerCallback 子类的代码:

    @Override
        public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
            super.onDescriptorWriteRequest(device, requestId, descriptor, preparedWrite, responseNeeded, offset, value);
    
            Log.i(TAG, "onDescriptorWriteRequest, uuid: " + descriptor.getUuid());
    
            if (descriptor.getUuid().equals(Descriptor.CLIENT_CHARACTERISTIC_CONFIGURATION) && descriptor.getValue().equals(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE)) {
                Log.i(TAG, "its a subscription!!!!");
    
                for (int i = 0; i < 30; i++) {
                    descriptor.getCharacteristic().setValue(String.format("new value: %d", i));
                    mGattServer.notifyCharacteristicChanged(device, descriptor.getCharacteristic(), false);
                }
            }
        }
    

    最好使用https://github.com/movisens/SmartGattLib作为uuid( Descriptor.CLIENT_CHARACTERISTIC_CONFIGURATION ,但原始值是 00002902-0000-1000-8000-00805f9b34fb

  • 3

    同意@stefreak

    和,

    bluetoothGatt.setCharacteristicNotification(characteristicToSubscribeTo, true);
    

    没有为远程设备做任何事情,此API仅更改了本地蓝牙堆栈的通知位,即如果外围设备向本地,本地堆栈发送通知将判断应用程序是否已经注册此通知,如果是,则将其转移到应用程序,否则忽略它 .

    所以除了setCharacteristicNotification,你还应该为你的注册通知需要writeDescriptor(这是告诉远程需要发送通知的步骤) .

相关问题