#android #bluetooth #android-bluetooth #bluetooth-gatt
#Android #bluetooth #android-bluetooth #bluetooth-gatt
Вопрос:
Я написал приложение для Android для изучения изменений частоты сердечных сокращений. Написал службы Bluetooth, обратные вызовы и т. Д. С диапазоном Polar H10 все работало нормально.
Теперь, пытаясь с Polar OH1 , а также с другими часами, частота сердечных сокращений не достигала обратных вызовов. Я задавался вопросом, почему, и начал проверять результаты ошибок. Я обнаружил проблему при чтении характеристик, метода BluetoothGattCharactersitic#readCharacteristic()
, который возвращается false
для всех устройств (даже с Polar H10). Проблема в том, что я не знаю, как это решить, поскольку нет никаких указаний на то, что пошло не так.
Я предположил, что Polar OH1 должен работать, поскольку я предполагаю, что он соответствует стандарту HR.
Вот мой код для BleService.readCharacteristic()
. Это то, что не удается вернуть false
и показать в журналах недопустимую характеристику:
public void readCharacteristic(BluetoothGattCharacteristic characteristic)
{
if ( this.btDevice != null ) {
if ( this.adapter != null
amp;amp; this.gatt != null )
{
Log.i( LogTag, "Reading characteristic: " characteristic );
Log.d( LogTag, "Properties: " characteristic.getPermissions() );
if ( !this.gatt.readCharacteristic( characteristic ) ) {
Log.e( LogTag, "GATT Characteristic invalid: "
characteristic.getUuid().toString() );
}
} else {
Log.w( LogTag, "Connection is not ready for: " this.btDevice.getName() );
}
} else {
Log.e( LogTag, "BT Device is null!!!" );
}
return;
}
Код из BroadcastReceiver.onReceive()
:
return new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent)
{
final String ACTION = intent.getAction();
final HRListenerActivity LISTENER_ACTIVITY = (HRListenerActivity) context;
final BleService SERVICE = LISTENER_ACTIVITY.getService();
// ACTION_GATT_CONNECTED: connected to a GATT server.
if ( BleService.ACTION_GATT_CONNECTED.equals( ACTION ) ) {
LISTENER_ACTIVITY.showStatus( MSG_CONNECTED );
}
else
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
if ( BleService.ACTION_GATT_DISCONNECTED.equals( ACTION ) ) {
LISTENER_ACTIVITY.showStatus( MSG_DISCONNECTED );
}
else
if ( BleService.ACTION_GATT_SERVICES_DISCOVERED.equals( ACTION ) ) {
if ( this.hrGattCharacteristic == null ) {
this.hrGattCharacteristic =
BluetoothUtils.getHeartRateChar( SERVICE.getGatt() );
}
if ( this.hrGattCharacteristic != null ) {
SERVICE.readCharacteristic( this.hrGattCharacteristic );
Log.d( LogTag, "Reading hr..." );
} else {
Log.e( LogTag, "Won't read hr since was not found..." );
}
}
И, наконец, код, определяющий частоту сердечных сокращений для устройства:
public static BluetoothGattCharacteristic getHeartRateChar(BluetoothGatt gatt)
{
final String deviceName = gatt.getDevice().getName();
BluetoothGattCharacteristic toret = null;
BluetoothGattService hrService = gatt.getService( UUID_HR_MEASUREMENT_SRV );
if ( hrService != null ) {
toret = hrService.getCharacteristic( UUID_HR_MEASUREMENT_CHR );
if ( toret != null ) {
Log.d( LogTag, "Building HR characteristic ("
toret.getUuid().toString()
") in: " deviceName );
// Enabling notifications for HR
gatt.setCharacteristicNotification( toret, true );
Log.d( LogTag, "HR enabled notifications ("
toret.getUuid().toString() ") in: " deviceName );
final BluetoothGattDescriptor DESCRIPTOR = toret.getDescriptor( UUID_CLIENT_CHAR_CONFIG );
if ( !DESCRIPTOR.setValue( BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE ) )
{
Log.e( LogTag, " Cannot create descriptor for HR in: " deviceName );
}
if ( !gatt.writeDescriptor( DESCRIPTOR ) ) {
Log.e( LogTag, " Cannot enable notifications for HR in: " deviceName );
toret = null;
}
} else {
Log.d( LogTag, "No HR characteristic found in: " deviceName );
}
} else {
Log.d( LogTag, "No HR service in: " deviceName );
}
if ( toret != null ) {
Log.d( LogTag, " Returning built HR char: " toret.getUuid().toString() );
}
return toret;
}
При выполнении выходного журнала отображается следующее (для рабочей полосы Polar H10):
D/BluetoothUtils: Building HR characteristic (00002a37-0000-1000-8000-00805f9b34fb) in: Polar H10 4EDA232A
D/BluetoothGatt: setCharacteristicNotification() - uuid: 00002a37-0000-1000-8000-00805f9b34fb enable: true
D/BluetoothUtils: HR enabled notifications (00002a37-0000-1000-8000-00805f9b34fb) in: Polar H10 4EDA232A
D/BluetoothUtils: Returning built HR char: 00002a37-0000-1000-8000-00805f9b34fb
D/BleService: Properties: 0
E/BleService: GATT Characteristic invalid: 00002a37-0000-1000-8000-00805f9b34fb
D/BluetoothUtils: Reading hr...
D/Surface: Surface::disconnect(this=0x901e5800,api=1)
V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@50e7f8f, this = DecorView@13676f0[PerformExperimentActivity]
D/GattHeartRateCharAnalyzer: Heart rate format UINT8.
D/GattHeartRateCharAnalyzer: Received heart rate: 70
D/GattHeartRateCharAnalyzer: Received raw rr (1024-based): 972
D/GattHeartRateCharAnalyzer: Received rr: 949
Свойства встроенной характеристики HR равны нулю, и это заставляет меня думать, что что-то не так.
В чем может быть проблема?
Ответ №1:
Хорошо — проблема была в другом месте, и это было связано с тем, что модели отправляют только информацию о ЧСС, а не данные RR.
Однако этот вызов по-прежнему отвечает с помощью a false
. Я не могу себе представить, почему.