我正在尝试通过BLE获取传感器值。我可以连接到传感器并调用onCharacteristicRead,但是调用BluetoothGattCharacteristc.value或.getStringValue(0)等。总是返回传感器设备名称而不是特征值。
我可以通过手机上的BLE应用访问传感器值,因此我知道传感器发送的是正确的值。
BluetoothGattCallback:
private val gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
bluetoothGatt?.discoverServices()
}
}
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (service: BluetoothGattService in bluetoothGatt!!.services) {
Log.i(TAG, service.uuid.toString())
Log.i(TAG, service.characteristics.size.toString())
for (characteristic: BluetoothGattCharacteristic in service.characteristics) {
//Read
bluetoothGatt?.readCharacteristic(characteristic)
if(characteristic.uuid == CHARACTERISTIC_UUID){
//Notify
Log.i(TAG, characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID).uuid.toString())
bluetoothGatt?.setCharacteristicNotification(characteristic, true)
val descriptor = characteristic
.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID).apply {
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
}
bluetoothGatt?.writeDescriptor(descriptor)
}
}
}
}
}
override fun onCharacteristicRead(
gatt: BluetoothGatt?,
characteristic: BluetoothGattCharacteristic?,
status: Int
) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.i(TAG, characteristic!!.getStringValue(0)) // Returns device name
Log.i(TAG, String(characteristic.value)) // Returns device name
} else {
Log.w(TAG, "GATT failure")
}
}
override fun onCharacteristicChanged(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic?) {
Log.i(TAG, String(characteristic!!.value))
}
}
onCharacteristicRead被调用,但是返回了不正确的值。即使传感器值不断更新,也不会调用onCharacteristicChanged。我做错了什么?
答案 0 :(得分:0)
此更改解决了问题:
override fun onServicesDiscovered(gatt: BluetoothGatt?, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS) {
for (service: BluetoothGattService in bluetoothGatt!!.services) {
for (characteristic: BluetoothGattCharacteristic in service.characteristics) {
if(characteristic.uuid == CHARACTERISTIC_UUID){
//Read
bluetoothGatt?.readCharacteristic(characteristic)
//Notify
Log.i(TAG, characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID).uuid.toString())
bluetoothGatt?.setCharacteristicNotification(characteristic, true)
val descriptor = characteristic
.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID).apply {
value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
}
bluetoothGatt?.writeDescriptor(descriptor)
}
}
}
}
}