Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit e14fcef8 authored by Kyunglyul Hyun's avatar Kyunglyul Hyun
Browse files

BAS: Write CCCD to get notified battery level

Tag: #feature
Bug: 233692672
Test: Manually connect to LE device and wait to
see the battey level drops.

Change-Id: Ib610bddcb69d01710dfcc1d5c375dc4ba4d3b912
parent 134c14bf
Loading
Loading
Loading
Loading
+22 −2
Original line number Diff line number Diff line
@@ -24,6 +24,7 @@ import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.os.Looper;
@@ -51,9 +52,10 @@ public class BatteryStateMachine extends StateMachine {

    static final UUID GATT_BATTERY_SERVICE_UUID =
            UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb");

    static final UUID GATT_BATTERY_LEVEL_CHARACTERISTIC_UUID =
            UUID.fromString("00002a19-0000-1000-8000-00805f9b34fb");
    static final UUID CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID =
            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");

    static final int CONNECT = 1;
    static final int DISCONNECT = 2;
@@ -553,7 +555,8 @@ public class BatteryStateMachine extends StateMachine {
                return;
            }

            gatt.setCharacteristicNotification(batteryLevel, /*enable=*/true);
            // This may not trigger onCharacteristicRead if CCCD is already set but then
            // onCharacteristicChanged will be triggered soon.
            gatt.readCharacteristic(batteryLevel);
        }

@@ -575,6 +578,23 @@ public class BatteryStateMachine extends StateMachine {

            if (GATT_BATTERY_LEVEL_CHARACTERISTIC_UUID.equals(characteristic.getUuid())) {
                updateBatteryLevel(value);
                BluetoothGattDescriptor cccd =
                        characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_DESCRIPTOR_UUID);
                if (cccd != null) {
                    gatt.setCharacteristicNotification(characteristic, /*enable=*/true);
                    gatt.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                } else {
                    Log.w(TAG, "No CCCD for battery level characteristic, "
                            + "it won't be notified");
                }
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor,
                int status) {
            if (status != BluetoothGatt.GATT_SUCCESS) {
                Log.w(TAG, "Failed to write descriptor " + descriptor.getUuid());
            }
        }