diff options
437 files changed, 5809 insertions, 8154 deletions
diff --git a/Android.bp b/Android.bp index 3ea90eb91b..93d31a7b63 100644 --- a/Android.bp +++ b/Android.bp @@ -121,6 +121,7 @@ java_defaults { javacflags: [ "-Xep:AlmostJavadoc:ERROR", "-Xep:AlreadyChecked:ERROR", + "-Xep:ArrayRecordComponent:ERROR", "-Xep:BadImport:ERROR", "-Xep:CatchAndPrintStackTrace:ERROR", "-Xep:CatchFail:ERROR", @@ -137,6 +138,7 @@ java_defaults { "-Xep:EqualsIncompatibleType:ERROR", "-Xep:FallThrough:ERROR", "-Xep:Finalize:ERROR", + "-Xep:ForEachIterable:ERROR", "-Xep:FutureReturnValueIgnored:ERROR", "-Xep:GuardedBy:ERROR", "-Xep:HidingField:ERROR", @@ -151,6 +153,7 @@ java_defaults { "-Xep:LockOnNonEnclosingClassLiteral:ERROR", "-Xep:LongFloatConversion:ERROR", "-Xep:LoopOverCharArray:ERROR", + "-Xep:MethodCanBeStatic:ERROR", "-Xep:MissingCasesInEnumSwitch:ERROR", "-Xep:MixedMutabilityReturnType:ERROR", "-Xep:MockNotUsedInProduction:ERROR", diff --git a/TEST_MAPPING b/TEST_MAPPING index 15894058b7..34772b59b0 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -21,9 +21,6 @@ // "name": "bluetooth-test-audio-hal-interface" //}, { - "name": "net_test_audio_hearing_aid_hw" - }, - { "name": "net_test_bluetooth" }, { @@ -259,9 +256,6 @@ // "name": "bluetooth-test-audio-hal-interface" //}, { - "name": "net_test_audio_hearing_aid_hw" - }, - { "name": "net_test_bluetooth" }, { @@ -493,9 +487,6 @@ // "name": "bluetooth-test-audio-hal-interface" //}, { - "name": "net_test_audio_hearing_aid_hw" - }, - { "name": "net_test_bluetooth" }, { diff --git a/android/ChannelSoundingTestApp/app/src/main/java/com/android/bluetooth/channelsoundingtestapp/BleConnectionViewModel.java b/android/ChannelSoundingTestApp/app/src/main/java/com/android/bluetooth/channelsoundingtestapp/BleConnectionViewModel.java index c5f25cff1f..6751ec208e 100644 --- a/android/ChannelSoundingTestApp/app/src/main/java/com/android/bluetooth/channelsoundingtestapp/BleConnectionViewModel.java +++ b/android/ChannelSoundingTestApp/app/src/main/java/com/android/bluetooth/channelsoundingtestapp/BleConnectionViewModel.java @@ -16,6 +16,9 @@ package com.android.bluetooth.channelsoundingtestapp; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.annotation.SuppressLint; import android.app.Application; import android.bluetooth.BluetoothAdapter; @@ -25,7 +28,6 @@ import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattServer; import android.bluetooth.BluetoothGattServerCallback; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.bluetooth.le.AdvertiseData; import android.bluetooth.le.AdvertisingSet; import android.bluetooth.le.AdvertisingSetCallback; @@ -156,10 +158,10 @@ public class BleConnectionViewModel extends AndroidViewModel { public void onConnectionStateChange( BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { printLog("Device connected: " + device.getName()); mTargetDevice.postValue(device); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { printLog("Device disconnected: " + device.getName()); mTargetDevice.postValue(null); } @@ -218,13 +220,13 @@ public class BleConnectionViewModel extends AndroidViewModel { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { printLog("onConnectionStateChange status:" + status + ", newState:" + newState); - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { printLog(gatt.getDevice().getName() + " is connected"); gatt.requestMtu(GATT_MTU_SIZE); mBluetoothGatt = gatt; mGattState.postValue(mExpectedGattState); mTargetDevice.postValue(gatt.getDevice()); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { printLog("disconnected from " + gatt.getDevice().getName()); mExpectedGattState = GattState.DISCONNECTED; mGattState.postValue(mExpectedGattState); diff --git a/android/app/Android.bp b/android/app/Android.bp index 7a30c2242a..b7e4929cbb 100644 --- a/android/app/Android.bp +++ b/android/app/Android.bp @@ -223,7 +223,7 @@ android_library { "bluetooth_flags_java_lib", "error_prone_annotations", "framework-annotations-lib", - "framework-bluetooth-pre-jarjar", + "framework-bluetooth.impl", "framework-configinfrastructure.stubs.module_lib", "framework-connectivity-t.stubs.module_lib", "framework-connectivity.stubs.module_lib", @@ -343,7 +343,7 @@ android_app { enabled: true, shrink: true, optimize: false, - // ignore_warnings: false, // TODO: b/191783947 -- re-activate error + ignore_warnings: false, proguard_flags_files: ["proguard.flags"], }, diff --git a/android/app/aidl/android/bluetooth/IBluetooth.aidl b/android/app/aidl/android/bluetooth/IBluetooth.aidl index 9ab583b042..b9cf6bca14 100644 --- a/android/app/aidl/android/bluetooth/IBluetooth.aidl +++ b/android/app/aidl/android/bluetooth/IBluetooth.aidl @@ -350,4 +350,7 @@ interface IBluetooth @JavaPassthrough(annotation="@android.annotation.RequiresNoPermission") IBinder getDistanceMeasurement(); + + @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)") + int getKeyMissingCount(in BluetoothDevice device, in AttributionSource source); } diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp index 3a3d8ceed6..a003f5b579 100644 --- a/android/app/jni/com_android_bluetooth_le_audio.cpp +++ b/android/app/jni/com_android_bluetooth_le_audio.cpp @@ -130,6 +130,8 @@ static std::shared_timed_mutex interface_mutex; static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; +static jclass class_LeAudioNativeInterface; + jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig) { log::info( "ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, " @@ -174,7 +176,7 @@ public: if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInitialized); + sCallbackEnv->CallStaticVoidMethod(class_LeAudioNativeInterface, method_onInitialized); } void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { @@ -233,8 +235,10 @@ public: (jint)group_id, (jint)node_status); } - void OnAudioConf(uint8_t direction, int group_id, uint32_t sink_audio_location, - uint32_t source_audio_location, uint16_t avail_cont) override { + void OnAudioConf(uint8_t direction, int group_id, + std::optional<std::bitset<32>> sink_audio_location, + std::optional<std::bitset<32>> source_audio_location, + uint16_t avail_cont) override { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); @@ -243,13 +247,15 @@ public: return; } + jint jni_sink_audio_location = sink_audio_location ? sink_audio_location->to_ulong() : -1; + jint jni_source_audio_location = source_audio_location ? source_audio_location->to_ulong() : -1; sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConf, (jint)direction, (jint)group_id, - (jint)sink_audio_location, (jint)source_audio_location, + jni_sink_audio_location, jni_source_audio_location, (jint)avail_cont); } void OnSinkAudioLocationAvailable(const RawAddress& bd_addr, - uint32_t sink_audio_location) override { + std::optional<std::bitset<32>> sink_audio_location) override { log::info(""); std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex); @@ -266,8 +272,9 @@ public: } sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr); + jint jni_sink_audio_location = sink_audio_location ? sink_audio_location->to_ulong() : -1; sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSinkAudioLocationAvailable, addr.get(), - (jint)sink_audio_location); + jni_sink_audio_location); } void OnAudioLocalCodecCapabilities( @@ -430,6 +437,10 @@ static void initNative(JNIEnv* env, jobject object, jobjectArray codecOffloading return; } + jclass tmpControllerInterface = + env->FindClass("com/android/bluetooth/le_audio/LeAudioNativeInterface"); + class_LeAudioNativeInterface = (jclass)env->NewGlobalRef(tmpControllerInterface); + if (mCallbacksObj != nullptr) { log::info("Cleaning up LeAudio callback object"); env->DeleteGlobalRef(mCallbacksObj); @@ -1573,7 +1584,7 @@ int register_com_android_bluetooth_le_audio(JNIEnv* env) { {"onGroupNodeStatus", "([BII)V", &method_onGroupNodeStatus}, {"onAudioConf", "(IIIII)V", &method_onAudioConf}, {"onSinkAudioLocationAvailable", "([BI)V", &method_onSinkAudioLocationAvailable}, - {"onInitialized", "()V", &method_onInitialized}, + {"onInitialized", "()V", &method_onInitialized, true}, {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, {"onAudioLocalCodecCapabilities", "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;" diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java index 6c7d53c8e6..31549ea3fd 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java @@ -168,7 +168,7 @@ class A2dpCodecConfig { } // Get the codec type of the highest priority of selectableCodecs and codecConfig. - private int getPrioitizedCodecType( + private static int getPrioitizedCodecType( BluetoothCodecConfig codecConfig, List<BluetoothCodecConfig> selectableCodecs) { BluetoothCodecConfig prioritizedCodecConfig = codecConfig; for (BluetoothCodecConfig config : selectableCodecs) { diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java index 89174b84ec..e739c24c99 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java @@ -18,8 +18,13 @@ package com.android.bluetooth.a2dp; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static com.android.bluetooth.Utils.checkCallerTargetSdk; @@ -219,7 +224,7 @@ public class A2dpService extends ProfileService { public boolean connect(BluetoothDevice device) { Log.d(TAG, "connect(): " + device); - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN"); return false; } @@ -235,9 +240,7 @@ public class A2dpService extends ProfileService { List<BluetoothDevice> sinks = getDevicesMatchingConnectionStates( new int[] { - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTING + STATE_CONNECTED, STATE_CONNECTING, STATE_DISCONNECTING }); for (BluetoothDevice sink : sinks) { if (sink.equals(device)) { @@ -306,8 +309,8 @@ public class A2dpService extends ProfileService { synchronized (mStateMachines) { for (A2dpStateMachine sm : mStateMachines.values()) { switch (sm.getConnectionState()) { - case BluetoothProfile.STATE_CONNECTING: - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTING: + case STATE_CONNECTED: if (Objects.equals(device, sm.getDevice())) { return true; // Already connected or accounted for } @@ -356,8 +359,8 @@ public class A2dpService extends ProfileService { return false; } } - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { if (!isOutgoingRequest) { HeadsetService headsetService = HeadsetService.getHeadsetService(); if (headsetService != null && headsetService.okToAcceptConnection(device, true)) { @@ -391,7 +394,7 @@ public class A2dpService extends ProfileService { mAdapterService.getRemoteUuids(device), BluetoothUuid.A2DP_SINK)) { continue; } - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; A2dpStateMachine sm = mStateMachines.get(device); if (sm != null) { connectionState = sm.getConnectionState(); @@ -427,7 +430,7 @@ public class A2dpService extends ProfileService { synchronized (mStateMachines) { A2dpStateMachine sm = mStateMachines.get(device); if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -532,7 +535,7 @@ public class A2dpService extends ProfileService { + "no state machine"); return false; } - if (sm.getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (sm.getConnectionState() != STATE_CONNECTED) { Log.e( TAG, "setActiveDevice(" @@ -629,9 +632,9 @@ public class A2dpService extends ProfileService { device, BluetoothProfile.A2DP, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -1166,9 +1169,14 @@ public class A2dpService extends ProfileService { if (bondState != BluetoothDevice.BOND_NONE) { return; } + if (mFactory.getAvrcpTargetService() != null) { + Log.d(TAG, "bondStateChanged: going for removeStoredVolumeForDevice"); + mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device); + } synchronized (mStateMachines) { A2dpStateMachine sm = mStateMachines.get(device); if (sm == null) { + Log.d(TAG, "bondStateChanged: SM is null, return "); return; } @@ -1176,13 +1184,11 @@ public class A2dpService extends ProfileService { // If pseudo address is not same as the identity address, all further events from the // native stack would get ignored. So the state machine must be removed right away. if (!Flags.a2dpCleanupOnRemoveDevice() - && sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + && sm.getConnectionState() != STATE_DISCONNECTED) { + Log.d(TAG, "bondStateChanged: not in STATE_DISCONNECTED, return "); return; } } - if (mFactory.getAvrcpTargetService() != null) { - mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device); - } removeStateMachine(device); } @@ -1300,17 +1306,17 @@ public class A2dpService extends ProfileService { if ((device == null) || (fromState == toState)) { return; } - if (toState == BluetoothProfile.STATE_CONNECTED) { + if (toState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.A2DP); } // Set the active device if only one connected device is supported and it was connected - if (toState == BluetoothProfile.STATE_CONNECTED && (mMaxConnectedAudioDevices == 1)) { + if (toState == STATE_CONNECTED && (mMaxConnectedAudioDevices == 1)) { setActiveDevice(device); } // When disconnected, ActiveDeviceManager will call setActiveDevice(null) // Check if the device is disconnected - if unbond, remove the state machine - if (toState == BluetoothProfile.STATE_DISCONNECTED) { + if (toState == STATE_DISCONNECTED) { if (mAdapterService.getBondState(device) == BluetoothDevice.BOND_NONE) { if (mFactory.getAvrcpTargetService() != null) { mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device); @@ -1434,7 +1440,7 @@ public class A2dpService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { A2dpService service = getServiceAndEnforceConnect(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -1481,7 +1487,7 @@ public class A2dpService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { A2dpService service = getServiceAndEnforceConnect(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java index 75350f949b..e26624b614 100644 --- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java +++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java @@ -138,7 +138,7 @@ public class A2dpSinkNativeInterface { } /** Send a stack event up to the A2DP Sink Service */ - private void sendMessageToService(StackEvent event) { + private static void sendMessageToService(StackEvent event) { A2dpSinkService service = A2dpSinkService.getA2dpSinkService(); if (service != null) { service.messageFromNative(event); diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java index 7ad03639a7..10b9249bad 100644 --- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java +++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java @@ -17,6 +17,11 @@ package com.android.bluetooth.a2dpsink; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -249,7 +254,7 @@ public class A2dpSinkService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { A2dpSinkService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); } @@ -271,7 +276,7 @@ public class A2dpSinkService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { A2dpSinkService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); @@ -314,7 +319,7 @@ public class A2dpSinkService extends ProfileService { if (device == null) { throw new IllegalArgumentException("Null device"); } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.w(TAG, "Connection not allowed: <" + device + "> is CONNECTION_POLICY_FORBIDDEN"); return false; } @@ -354,8 +359,7 @@ public class A2dpSinkService extends ProfileService { return false; } int connectionState = stateMachine.getState(); - if (connectionState == BluetoothProfile.STATE_DISCONNECTED - || connectionState == BluetoothProfile.STATE_DISCONNECTING) { + if (connectionState == STATE_DISCONNECTED || connectionState == STATE_DISCONNECTING) { return false; } // upon completion of disconnect, the state machine will remove itself from the available @@ -437,14 +441,12 @@ public class A2dpSinkService extends ProfileService { * BluetoothProfile#STATE_DISCONNECTING} if this profile is being disconnected */ public int getConnectionState(BluetoothDevice device) { - if (device == null) return BluetoothProfile.STATE_DISCONNECTED; + if (device == null) return STATE_DISCONNECTED; A2dpSinkStateMachine stateMachine; synchronized (mDeviceStateMap) { stateMachine = mDeviceStateMap.get(device); } - return (stateMachine == null) - ? BluetoothProfile.STATE_DISCONNECTED - : stateMachine.getState(); + return (stateMachine == null) ? STATE_DISCONNECTED : stateMachine.getState(); } /** @@ -468,9 +470,9 @@ public class A2dpSinkService extends ProfileService { device, BluetoothProfile.A2DP_SINK, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java index 9e76df75c3..3ab495fdb0 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java @@ -178,7 +178,7 @@ public class AvrcpBipObexServer extends ServerRequestHandler { * * @return True if the image handle is valid, false otherwise. */ - private boolean isImageHandleValid(String handle) { + private static boolean isImageHandleValid(String handle) { if (handle == null || handle.length() != 7) return false; for (int i = 0; i < 7; i++) { char c = handle.charAt(i); @@ -305,7 +305,7 @@ public class AvrcpBipObexServer extends ServerRequestHandler { } /** Send a response to the given operation using the given headers and bytes. */ - private int sendResponse(Operation op, HeaderSet replyHeaders, byte[] bytes) { + private static int sendResponse(Operation op, HeaderSet replyHeaders, byte[] bytes) { if (op != null && bytes != null && replyHeaders != null) { OutputStream outStream = null; int maxChunkSize = 0; @@ -344,11 +344,11 @@ public class AvrcpBipObexServer extends ServerRequestHandler { return ResponseCodes.OBEX_HTTP_NOT_FOUND; } - private void warn(String msg) { + private static void warn(String msg) { Log.w(TAG, msg); } - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java index 46805f404c..232bdfa56a 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java @@ -273,12 +273,12 @@ public class AvrcpCoverArtService { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java index 1ad024ab80..cd97e9970c 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java @@ -182,12 +182,12 @@ final class AvrcpCoverArtStorage { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java index 2436bc6bb4..82f4fa4b7b 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java @@ -16,11 +16,12 @@ package com.android.bluetooth.avrcp; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static java.util.Objects.requireNonNull; import android.annotation.NonNull; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothUtils; import android.content.BroadcastReceiver; import android.content.Context; @@ -294,7 +295,7 @@ public class AvrcpTargetService extends ProfileService { * <p>This will be called by the native stack when a play event is received from a remote * device. See packages/modules/Bluetooth/system/profile/avrcp/device.cc. */ - private void setA2dpActiveDevice(@NonNull BluetoothDevice device) { + private static void setA2dpActiveDevice(@NonNull BluetoothDevice device) { A2dpService service = A2dpService.getA2dpService(); if (service == null) { Log.d(TAG, "setA2dpActiveDevice: A2dp service not found"); @@ -341,7 +342,7 @@ public class AvrcpTargetService extends ProfileService { */ public void handleA2dpConnectionStateChanged(BluetoothDevice device, int newState) { if (device == null) return; - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { // If there is no connection, disconnectDevice() will do nothing if (mNativeInterface.disconnectDevice(device)) { Log.d(TAG, "request to disconnect device " + device); diff --git a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java index dd720077a0..d2e34c64ac 100644 --- a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java +++ b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java @@ -77,7 +77,7 @@ public class CoverArt { } /** Covert a Bitmap to a byte array with an image format without lossy compression */ - private byte[] toByteArray(Bitmap bitmap) { + private static byte[] toByteArray(Bitmap bitmap) { if (bitmap == null) return null; ByteArrayOutputStream buffer = new ByteArrayOutputStream(bitmap.getWidth() * bitmap.getHeight()); @@ -131,7 +131,7 @@ public class CoverArt { } /** Determine if a given image descriptor is valid */ - private boolean isDescriptorValid(BipImageDescriptor descriptor) { + private static boolean isDescriptorValid(BipImageDescriptor descriptor) { debug("isDescriptorValid(descriptor=" + descriptor + ")"); if (descriptor == null) return false; @@ -196,12 +196,12 @@ public class CoverArt { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java index 1407b9292f..dd5f3bb067 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java @@ -16,9 +16,14 @@ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; +import static android.bluetooth.BluetoothProfile.getConnectionStateName; + import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.HandlerThread; @@ -79,7 +84,7 @@ public class AvrcpBipClient { private final BluetoothDevice mDevice; private final int mPsm; - private int mState = BluetoothProfile.STATE_DISCONNECTED; + private int mState = STATE_DISCONNECTED; private BluetoothSocket mSocket; private BluetoothObexTransport mTransport; @@ -185,7 +190,7 @@ public class AvrcpBipClient { * @return True if connected, False otherwise */ public boolean isConnected() { - return getState() == BluetoothProfile.STATE_CONNECTED; + return getState() == STATE_CONNECTED; } /** @@ -247,7 +252,7 @@ public class AvrcpBipClient { } try { - setConnectionState(BluetoothProfile.STATE_CONNECTING); + setConnectionState(STATE_CONNECTING); mSocket = mDevice.createL2capSocket(mPsm); mSocket.connect(); @@ -261,7 +266,7 @@ public class AvrcpBipClient { headerSet = mSession.connect(headerSet); int responseCode = headerSet.getResponseCode(); if (responseCode == ResponseCodes.OBEX_HTTP_OK) { - setConnectionState(BluetoothProfile.STATE_CONNECTED); + setConnectionState(STATE_CONNECTED); debug("Connection established"); } else { error("Error connecting, code: " + responseCode); @@ -278,7 +283,7 @@ public class AvrcpBipClient { if (mSession == null) return; try { - setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + setConnectionState(STATE_DISCONNECTING); mSession.disconnect(null); debug("Disconnected from OBEX session"); } catch (IOException e) { @@ -288,7 +293,7 @@ public class AvrcpBipClient { } try { - setConnectionState(BluetoothProfile.STATE_CONNECTING); + setConnectionState(STATE_CONNECTING); HeaderSet headerSet = new HeaderSet(); headerSet.setHeader(HeaderSet.TARGET, BLUETOOTH_UUID_AVRCP_COVER_ART); @@ -296,7 +301,7 @@ public class AvrcpBipClient { headerSet = mSession.connect(headerSet); int responseCode = headerSet.getResponseCode(); if (responseCode == ResponseCodes.OBEX_HTTP_OK) { - setConnectionState(BluetoothProfile.STATE_CONNECTED); + setConnectionState(STATE_CONNECTED); debug("Reconnection established"); } else { error("Error reconnecting, code: " + responseCode); @@ -319,7 +324,7 @@ public class AvrcpBipClient { */ private synchronized void disconnect() { if (mSession != null) { - setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + setConnectionState(STATE_DISCONNECTING); try { mSession.disconnect(null); @@ -341,7 +346,7 @@ public class AvrcpBipClient { mTransport = null; mSocket = null; } - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); } private void executeRequest(BipRequest request) { @@ -423,28 +428,12 @@ public class AvrcpBipClient { } } - @VisibleForTesting - String getStateName() { - int state = getState(); - switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: - return "Disconnected"; - case BluetoothProfile.STATE_CONNECTING: - return "Connecting"; - case BluetoothProfile.STATE_CONNECTED: - return "Connected"; - case BluetoothProfile.STATE_DISCONNECTING: - return "Disconnecting"; - } - return "Unknown"; - } - @Override public String toString() { return "<AvrcpBipClient" + (" device=" + mDevice) + (" psm=" + mPsm) - + (" state=" + getStateName()) + + (" state=" + getConnectionStateName(getState())) + ">"; } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java index 318ce4ba4c..12344bd56d 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java @@ -17,6 +17,9 @@ package com.android.bluetooth.avrcpcontroller; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -24,7 +27,6 @@ import android.annotation.RequiresPermission; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAvrcpPlayerSettings; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothAvrcpController; import android.content.AttributionSource; import android.content.Intent; @@ -422,7 +424,7 @@ public class AvrcpControllerService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { AvrcpControllerService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); } @@ -705,8 +707,7 @@ public class AvrcpControllerService extends ProfileService { return false; } int connectionState = stateMachine.getState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } stateMachine.disconnect(); @@ -790,9 +791,7 @@ public class AvrcpControllerService extends ProfileService { synchronized int getConnectionState(BluetoothDevice device) { AvrcpControllerStateMachine stateMachine = mDeviceStateMap.get(device); - return (stateMachine == null) - ? BluetoothProfile.STATE_DISCONNECTED - : stateMachine.getState(); + return (stateMachine == null) ? STATE_DISCONNECTED : stateMachine.getState(); } @Override diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java index 5679c916d7..93e5f8c369 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java @@ -17,6 +17,10 @@ package com.android.bluetooth.avrcpcontroller; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -126,7 +130,7 @@ class AvrcpControllerStateMachine extends StateMachine { protected final Disconnecting mDisconnecting; protected int mCoverArtPsm; - protected int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED; + protected int mMostRecentState = STATE_DISCONNECTED; private boolean mShouldSendPlayOnFocusRecovery = false; private boolean mRemoteControlConnected = false; @@ -256,9 +260,7 @@ class AvrcpControllerStateMachine extends StateMachine { ProfileService.println(sb, "Control: " + mRemoteControlConnected); ProfileService.println(sb, "Browsing: " + mBrowsingConnected); ProfileService.println( - sb, - "Cover Art: " - + (mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED)); + sb, "Cover Art: " + (mCoverArtManager.getState(mDevice) == STATE_CONNECTED)); ProfileService.println(sb, "Addressed Player ID: " + mAddressedPlayerId); ProfileService.println(sb, "Browsed Player ID: " + mBrowseTree.getCurrentBrowsedPlayer()); @@ -321,7 +323,7 @@ class AvrcpControllerStateMachine extends StateMachine { // Called from "connected" state, which assumes either control or browse is connected if (mCoverArtManager != null && mCoverArtPsm != 0 - && mCoverArtManager.getState(mDevice) != BluetoothProfile.STATE_CONNECTED) { + && mCoverArtManager.getState(mDevice) != STATE_CONNECTED) { debug("Attempting to connect to AVRCP BIP, psm: " + mCoverArtPsm); mCoverArtManager.connect(mDevice, /* psm */ mCoverArtPsm); } @@ -330,7 +332,7 @@ class AvrcpControllerStateMachine extends StateMachine { synchronized void refreshCoverArt() { if (mCoverArtManager != null && mCoverArtPsm != 0 - && mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED) { + && mCoverArtManager.getState(mDevice) == STATE_CONNECTED) { debug("Attempting to refresh AVRCP BIP OBEX session, psm: " + mCoverArtPsm); mCoverArtManager.refreshSession(mDevice); } @@ -415,10 +417,10 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { debug("Disconnected: Entered"); - if (mMostRecentState != BluetoothProfile.STATE_DISCONNECTED) { + if (mMostRecentState != STATE_DISCONNECTED) { sendMessage(CLEANUP); } - broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionStateChanged(STATE_DISCONNECTED); } @Override @@ -448,7 +450,7 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { debug("Connecting: Enter Connecting"); - broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTING); + broadcastConnectionStateChanged(STATE_CONNECTING); transitionTo(mConnected); } } @@ -458,8 +460,8 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { - if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { - broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); + if (mMostRecentState == STATE_CONNECTING) { + broadcastConnectionStateChanged(STATE_CONNECTED); mService.getBrowseTree().mRootNode.addChild(mBrowseTree.mRootNode); BluetoothMediaBrowserService.onBrowseNodeChanged( mService.getBrowseTree().mRootNode); @@ -802,7 +804,7 @@ class AvrcpControllerStateMachine extends StateMachine { } } - private boolean isHoldableKey(int cmd) { + private static boolean isHoldableKey(int cmd) { return (cmd == AvrcpControllerService.PASS_THRU_CMD_ID_REWIND) || (cmd == AvrcpControllerService.PASS_THRU_CMD_ID_FF); } @@ -1051,7 +1053,7 @@ class AvrcpControllerStateMachine extends StateMachine { * @return true: a new folder in the same scope a new player while fetching contents of a * folder false: other cases, specifically Now Playing while fetching a folder */ - private boolean shouldAbort(int currentScope, int fetchScope) { + private static boolean shouldAbort(int currentScope, int fetchScope) { if ((currentScope == fetchScope) || (currentScope == AvrcpControllerService.BROWSE_SCOPE_VFS && fetchScope == AvrcpControllerService.BROWSE_SCOPE_PLAYER_LIST)) { @@ -1192,7 +1194,7 @@ class AvrcpControllerStateMachine extends StateMachine { onBrowsingDisconnected(); mService.getBrowseTree().mRootNode.removeChild(mBrowseTree.mRootNode); BluetoothMediaBrowserService.onBrowseNodeChanged(mService.getBrowseTree().mRootNode); - broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING); + broadcastConnectionStateChanged(STATE_DISCONNECTING); transitionTo(mDisconnected); } } @@ -1276,7 +1278,7 @@ class AvrcpControllerStateMachine extends StateMachine { } } - private int getFocusState() { + private static int getFocusState() { int focusState = AudioManager.ERROR; A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService(); if (a2dpSinkService != null) { @@ -1403,7 +1405,7 @@ class AvrcpControllerStateMachine extends StateMachine { if (mMostRecentState == currentState) { return; } - if (currentState == BluetoothProfile.STATE_CONNECTED) { + if (currentState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent( BluetoothMetricsProto.ProfileId.AVRCP_CONTROLLER); } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java index a48b2d5ea2..826361a36b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java @@ -16,8 +16,10 @@ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.graphics.Bitmap; import android.net.Uri; import android.os.SystemProperties; @@ -215,11 +217,11 @@ public class AvrcpCoverArtManager { * Get the client connection state for a particular device's BIP Client * * @param device The Bluetooth device you want connection status for - * @return Connection status, based on BluetoothProfile.STATE_* constants + * @return Connection status, based on STATE_* constants */ public int getState(BluetoothDevice device) { AvrcpBipClient client = getClient(device); - if (client == null) return BluetoothProfile.STATE_DISCONNECTED; + if (client == null) return STATE_DISCONNECTED; return client.getState(); } @@ -403,14 +405,14 @@ public class AvrcpCoverArtManager { @Override public void onConnectionStateChanged(int oldState, int newState) { debug(mDevice + ": " + oldState + " -> " + newState); - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { // Ensure the handle map is cleared since old ones are invalid on a new connection clearHandleUuids(mDevice); // Once we're connected fetch the current metadata again in case the target has an // image handle they can now give us. Only do this if we don't already have one. mService.getCurrentMetadataIfNoCoverArt(mDevice); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { AvrcpBipClient client = getClient(mDevice); boolean shouldReconnect = (client != null); disconnect(mDevice); @@ -501,17 +503,17 @@ public class AvrcpCoverArtManager { } /** Print to debug if debug is enabled for this class */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print to warn */ - private void warn(String msg) { + private static void warn(String msg) { Log.w(TAG, msg); } /** Print to error */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java index 71728e29db..d3c97b8cb1 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java @@ -74,7 +74,7 @@ public class AvrcpCoverArtProvider extends ContentProvider { return uri; } - private Bitmap getImage(BluetoothDevice device, String imageUuid) { + private static Bitmap getImage(BluetoothDevice device, String imageUuid) { AvrcpControllerService service = AvrcpControllerService.getAvrcpControllerService(); if (service == null) { debug("Failed to get service, cover art not available"); @@ -89,7 +89,7 @@ public class AvrcpCoverArtProvider extends ContentProvider { return manager.getImage(device, imageUuid); } - private ParcelFileDescriptor getImageDescriptor(BluetoothDevice device, String imageUuid) + private static ParcelFileDescriptor getImageDescriptor(BluetoothDevice device, String imageUuid) throws FileNotFoundException, IOException { debug("getImageDescriptor(" + device + ", " + imageUuid + ")"); Bitmap image = getImage(device, imageUuid); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java index ff9e69cc4d..a188eb5494 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java @@ -157,7 +157,7 @@ public class AvrcpCoverArtStorage { return sb.toString(); } - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java index 5fa4852246..8c498f6a7b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java @@ -262,7 +262,7 @@ public class BluetoothMediaBrowserService extends MediaBrowserServiceCompat { mSession.setPlaybackState(errorState); } - private Bundle getDefaultStyle() { + private static Bundle getDefaultStyle() { Bundle style = new Bundle(); style.putBoolean(CONTENT_STYLE_SUPPORTED, true); style.putInt(CONTENT_STYLE_BROWSABLE_HINT, CONTENT_STYLE_GRID_ITEM_HINT_VALUE); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java index 801dcc99d8..7e389ff45f 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java @@ -278,7 +278,7 @@ public class BipImageProperties { } } - private boolean isThumbnailFormat(BipImageFormat format) { + private static boolean isThumbnailFormat(BipImageFormat format) { if (format == null) return false; BipEncoding encoding = format.getEncoding(); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java index 44cae25780..2e2818d97b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java @@ -122,7 +122,7 @@ public class BipTransformation { * BipTransformation.* constants, but doesn't *have* to be * @return True if the transformation constant is valid, False otherwise */ - private boolean isValid(int transformation) { + private static boolean isValid(int transformation) { return transformation >= STRETCH && transformation <= CROP; } diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java index 23cda4bd5c..ac5eaab2f9 100644 --- a/android/app/src/com/android/bluetooth/bas/BatteryService.java +++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java @@ -16,6 +16,11 @@ package com.android.bluetooth.bas; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static java.util.Objects.requireNonNull; import android.bluetooth.BluetoothDevice; @@ -136,7 +141,7 @@ public class BatteryService extends ProfileService { return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.w(TAG, "Cannot connect to " + device + " : policy forbidden"); return false; } @@ -164,7 +169,7 @@ public class BatteryService extends ProfileService { */ public boolean connectIfPossible(BluetoothDevice device) { if (device == null - || getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN + || getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN || !Utils.arrayContains( mAdapterService.getRemoteUuids(device), BluetoothUuid.BATTERY)) { return false; @@ -215,8 +220,8 @@ public class BatteryService extends ProfileService { if (bondState != BluetoothDevice.BOND_BONDED) { Log.w(TAG, "canConnect: return false, bondState=" + bondState); return false; - } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "canConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -239,7 +244,7 @@ public class BatteryService extends ProfileService { } // Check if the device is disconnected - if unbonded, remove the state machine - if (toState == BluetoothProfile.STATE_DISCONNECTED) { + if (toState == STATE_DISCONNECTED) { int bondState = mAdapterService.getBondState(device); if (bondState == BluetoothDevice.BOND_NONE) { Log.d(TAG, device + " is unbonded. Remove state machine"); @@ -259,7 +264,7 @@ public class BatteryService extends ProfileService { } synchronized (mStateMachines) { for (BluetoothDevice device : bondedDevices) { - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; BatteryStateMachine sm = mStateMachines.get(device); if (sm != null) { connectionState = sm.getConnectionState(); @@ -296,7 +301,7 @@ public class BatteryService extends ProfileService { synchronized (mStateMachines) { BatteryStateMachine sm = mStateMachines.get(device); if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -320,9 +325,9 @@ public class BatteryService extends ProfileService { Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy); mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.BATTERY, connectionPolicy); - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -370,7 +375,7 @@ public class BatteryService extends ProfileService { if (sm == null) { return; } - if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (sm.getConnectionState() != STATE_DISCONNECTED) { return; } removeStateMachine(device); diff --git a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java index 3b1fa511e1..abd223648d 100644 --- a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java +++ b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java @@ -20,6 +20,10 @@ import static android.bluetooth.BluetoothDevice.BATTERY_LEVEL_UNKNOWN; import static android.bluetooth.BluetoothDevice.PHY_LE_1M_MASK; import static android.bluetooth.BluetoothDevice.PHY_LE_2M_MASK; import static android.bluetooth.BluetoothDevice.TRANSPORT_LE; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.bluetooth.BluetoothProfile.getConnectionStateName; import static java.util.Objects.requireNonNull; @@ -71,7 +75,7 @@ public class BatteryStateMachine extends StateMachine { private Connecting mConnecting; private Connected mConnected; private Disconnecting mDisconnecting; - private int mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + private int mLastConnectionState = STATE_DISCONNECTED; private final BatteryService mService; @@ -119,7 +123,7 @@ public class BatteryStateMachine extends StateMachine { } synchronized boolean isConnected() { - return mLastConnectionState == BluetoothProfile.STATE_CONNECTED; + return mLastConnectionState == STATE_CONNECTED; } private static String messageWhatToString(int what) { @@ -236,11 +240,11 @@ public class BatteryStateMachine extends StateMachine { mBluetoothGatt = null; } - if (mLastConnectionState != BluetoothProfile.STATE_DISCONNECTED) { + if (mLastConnectionState != STATE_DISCONNECTED) { // Don't broadcast during startup - dispatchConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED); + dispatchConnectionStateChanged(STATE_DISCONNECTED); } - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -286,8 +290,8 @@ public class BatteryStateMachine extends StateMachine { @Override public void enter() { log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - dispatchConnectionStateChanged(BluetoothProfile.STATE_CONNECTING); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + dispatchConnectionStateChanged(STATE_CONNECTING); + mLastConnectionState = STATE_CONNECTING; } @Override @@ -318,11 +322,11 @@ public class BatteryStateMachine extends StateMachine { // in Connecting state private void processConnectionEvent(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED -> { + case STATE_DISCONNECTED -> { Log.w(TAG, "Device disconnected: " + mDevice); transitionTo(mDisconnected); } - case BluetoothProfile.STATE_CONNECTED -> transitionTo(mConnected); + case STATE_CONNECTED -> transitionTo(mConnected); default -> Log.e(TAG, "Incorrect state: " + state); } } @@ -337,8 +341,8 @@ public class BatteryStateMachine extends StateMachine { public void enter() { log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(MESSAGE_CONNECT_TIMEOUT, CONNECT_TIMEOUT.toMillis()); - dispatchConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING; + dispatchConnectionStateChanged(STATE_DISCONNECTING); + mLastConnectionState = STATE_DISCONNECTING; } @Override @@ -370,11 +374,11 @@ public class BatteryStateMachine extends StateMachine { // in Disconnecting state private void processConnectionEvent(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED -> { + case STATE_DISCONNECTED -> { Log.i(TAG, "Disconnected: " + mDevice); transitionTo(mDisconnected); } - case BluetoothProfile.STATE_CONNECTED -> { + case STATE_CONNECTED -> { // TODO: Check if connect while disconnecting is okay. It is related to // MESSAGE_CONNECT_TIMEOUT as well. @@ -397,8 +401,8 @@ public class BatteryStateMachine extends StateMachine { @Override public void enter() { log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - dispatchConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + dispatchConnectionStateChanged(STATE_CONNECTED); + mLastConnectionState = STATE_CONNECTED; discoverServicesGatt(); } @@ -434,7 +438,7 @@ public class BatteryStateMachine extends StateMachine { // in Connected state private void processConnectionEvent(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED -> { + case STATE_DISCONNECTED -> { Log.i(TAG, "Disconnected from " + mDevice); transitionTo(mDisconnected); } diff --git a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java index aacd344a78..3368059b90 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java @@ -19,7 +19,11 @@ package com.android.bluetooth.bass_client; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID; import static com.android.bluetooth.flags.Flags.leaudioBassScanWithInternalScanController; @@ -490,7 +494,7 @@ public class BassClientService extends ProfileService { } @SuppressLint("NewApi") // Api is protected by flag check and the lint is wrong - private boolean hasAnyMessagesOrCallbacks(Handler handler) { + private static boolean hasAnyMessagesOrCallbacks(Handler handler) { if (android.os.Flags.mainlineVcnPlatformApi()) { return handler.hasMessagesOrCallbacks(); } else { @@ -881,7 +885,7 @@ public class BassClientService extends ProfileService { }); } - private boolean isSuccess(int status) { + private static boolean isSuccess(int status) { boolean ret = false; switch (status) { case BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST: @@ -975,13 +979,13 @@ public class BassClientService extends ProfileService { } } - private boolean removeMatchingOperation( + private static boolean removeMatchingOperation( List<Pair<Integer, Object>> operations, int reqMsg, Object obj) { return operations.removeIf( m -> m.first.equals(reqMsg) && isMatchingOperation(m.second, obj)); } - private boolean isMatchingOperation(Object operationData, Object obj) { + private static boolean isMatchingOperation(Object operationData, Object obj) { if (obj instanceof BluetoothLeBroadcastReceiveState) { return ((BluetoothLeBroadcastMetadata) operationData).getBroadcastId() == ((BluetoothLeBroadcastReceiveState) obj).getBroadcastId(); @@ -1004,7 +1008,7 @@ public class BassClientService extends ProfileService { && (leAudioService.getActiveDevices().contains(device)); } - private boolean isEmptyBluetoothDevice(BluetoothDevice device) { + private static boolean isEmptyBluetoothDevice(BluetoothDevice device) { if (device == null) { Log.e(TAG, "Device is null!"); return true; @@ -1614,7 +1618,7 @@ public class BassClientService extends ProfileService { + BluetoothProfile.getConnectionStateName(toState)); // Check if the device is disconnected - if unbond, remove the state machine - if (toState == BluetoothProfile.STATE_DISCONNECTED) { + if (toState == STATE_DISCONNECTED) { mPendingGroupOp.remove(device); mPausedBroadcastSinks.remove(device); synchronized (mSinksWaitingForPast) { @@ -1674,7 +1678,7 @@ public class BassClientService extends ProfileService { if (sm == null) { return; } - if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (sm.getConnectionState() != STATE_DISCONNECTED) { Log.i(TAG, "Disconnecting device because it was unbonded."); disconnect(device); return; @@ -1695,7 +1699,7 @@ public class BassClientService extends ProfileService { Log.e(TAG, "connect: device is null"); return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.e(TAG, "connect: connection policy set to forbidden"); return false; } @@ -1757,8 +1761,8 @@ public class BassClientService extends ProfileService { if (bondState != BluetoothDevice.BOND_BONDED) { Log.w(TAG, "okToConnect: return false, bondState=" + bondState); return false; - } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -1777,7 +1781,7 @@ public class BassClientService extends ProfileService { BassClientStateMachine sm = getOrCreateStateMachine(sink); if (sm == null) { log("getConnectionState returns STATE_DISC"); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -1804,7 +1808,7 @@ public class BassClientService extends ProfileService { if (!Utils.arrayContains(featureUuids, BluetoothUuid.BASS)) { continue; } - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; BassClientStateMachine sm = getOrCreateStateMachine(device); if (sm != null) { connectionState = sm.getConnectionState(); @@ -1854,10 +1858,9 @@ public class BassClientService extends ProfileService { boolean setSuccessfully = mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT, connectionPolicy); - if (setSuccessfully && connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (setSuccessfully && connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (setSuccessfully - && connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (setSuccessfully && connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return setSuccessfully; @@ -4332,7 +4335,7 @@ public class BassClientService extends ProfileService { return false; } - private boolean isReceiverActive(BluetoothLeBroadcastReceiveState receiveState) { + private static boolean isReceiverActive(BluetoothLeBroadcastReceiveState receiveState) { if (receiveState.getPaSyncState() == BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_SYNCHRONIZED) { return true; @@ -4388,7 +4391,9 @@ public class BassClientService extends ProfileService { .anyMatch( receiveState -> (receiveState.getBisSyncState().stream() - .anyMatch(this::isSyncedToBroadcastStream)))) { + .anyMatch( + BassClientService + ::isSyncedToBroadcastStream)))) { activeSinks.add(device); } } @@ -4406,7 +4411,7 @@ public class BassClientService extends ProfileService { .collect(Collectors.toUnmodifiableList()); } - private boolean isSyncedToBroadcastStream(Long syncState) { + private static boolean isSyncedToBroadcastStream(Long syncState) { return syncState != BassConstants.BCAST_RCVR_STATE_BIS_SYNC_NOT_SYNC_TO_BIS && syncState != BassConstants.BCAST_RCVR_STATE_BIS_SYNC_FAILED_SYNC_TO_BIG; } @@ -4518,7 +4523,7 @@ public class BassClientService extends ProfileService { } } - private void checkForPendingGroupOpRequest(Message msg) { + private static void checkForPendingGroupOpRequest(Message msg) { if (sService == null) { Log.e(TAG, "Service is null"); return; @@ -4549,7 +4554,7 @@ public class BassClientService extends ProfileService { } } - private boolean handleServiceInternalMessage(Message msg) { + private static boolean handleServiceInternalMessage(Message msg) { boolean isMsgHandled = false; if (sService == null) { Log.e(TAG, "Service is null"); @@ -4608,7 +4613,8 @@ public class BassClientService extends ProfileService { } } - private void invokeCallback(IBluetoothLeBroadcastAssistantCallback callback, Message msg) + private static void invokeCallback( + IBluetoothLeBroadcastAssistantCallback callback, Message msg) throws RemoteException { final int reason = msg.arg1; final int sourceId = msg.arg2; @@ -4861,7 +4867,7 @@ public class BassClientService extends ProfileService { /* Dump first connected state machines */ for (Map.Entry<BluetoothDevice, BassClientStateMachine> entry : mStateMachines.entrySet()) { BassClientStateMachine sm = entry.getValue(); - if (sm.getConnectionState() == BluetoothProfile.STATE_CONNECTED) { + if (sm.getConnectionState() == STATE_CONNECTED) { sm.dump(sb); sb.append("\n\n"); } @@ -4870,7 +4876,7 @@ public class BassClientService extends ProfileService { /* Dump at least all other than connected state machines */ for (Map.Entry<BluetoothDevice, BassClientStateMachine> entry : mStateMachines.entrySet()) { BassClientStateMachine sm = entry.getValue(); - if (sm.getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (sm.getConnectionState() != STATE_CONNECTED) { sm.dump(sb); } } @@ -4940,7 +4946,7 @@ public class BassClientService extends ProfileService { BassClientService service = getServiceAndEnforceConnect(source); if (service == null) { Log.e(TAG, "Service is null"); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(sink); } @@ -4982,7 +4988,7 @@ public class BassClientService extends ProfileService { BassClientService service = getServiceAndEnforceConnect(source); if (service == null) { Log.e(TAG, "Service is null"); - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } return service.getConnectionPolicy(device); } diff --git a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java index 67f8b6afc2..a77b098c51 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java @@ -18,6 +18,9 @@ package com.android.bluetooth.bass_client; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.flags.Flags.leaudioBigDependsOnAudioState; import static com.android.bluetooth.flags.Flags.leaudioBroadcastReceiveStateProcessingRefactor; @@ -610,13 +613,13 @@ class BassClientStateMachine extends StateMachine { mBroadcastSyncStats.clear(); } - private boolean isSourceAbsent(BluetoothLeBroadcastReceiveState recvState) { + private static boolean isSourceAbsent(BluetoothLeBroadcastReceiveState recvState) { return recvState == null || recvState.getSourceDevice() == null || recvState.getSourceDevice().getAddress().equals("00:00:00:00:00:00"); } - private boolean isSourcePresent(BluetoothLeBroadcastReceiveState recvState) { + private static boolean isSourcePresent(BluetoothLeBroadcastReceiveState recvState) { return !isSourceAbsent(recvState); } @@ -1113,8 +1116,7 @@ class BassClientStateMachine extends StateMachine { public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { boolean isStateChanged = false; log("onConnectionStateChange : Status=" + status + ", newState=" + newState); - if (newState == BluetoothProfile.STATE_CONNECTED - && getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED && getConnectionState() != STATE_CONNECTED) { isStateChanged = true; Log.w(TAG, "Bassclient Connected from Disconnected state: " + mDevice); if (mService.okToConnect(mDevice)) { @@ -1132,10 +1134,10 @@ class BassClientStateMachine extends StateMachine { mBluetoothGatt.close(); mBluetoothGatt = null; // force move to disconnected - newState = BluetoothProfile.STATE_DISCONNECTED; + newState = STATE_DISCONNECTED; } - } else if (newState == BluetoothProfile.STATE_DISCONNECTED - && getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED + && getConnectionState() != STATE_DISCONNECTED) { isStateChanged = true; log("Disconnected from Bass GATT server."); } @@ -1389,9 +1391,8 @@ class BassClientStateMachine extends StateMachine { if (mLastConnectionState == -1) { log("no Broadcast of initial profile state "); } else { - broadcastConnectionState( - mDevice, mLastConnectionState, BluetoothProfile.STATE_DISCONNECTED); - if (mLastConnectionState != BluetoothProfile.STATE_DISCONNECTED) { + broadcastConnectionState(mDevice, mLastConnectionState, STATE_DISCONNECTED); + if (mLastConnectionState != STATE_DISCONNECTED) { // Reconnect in background if not disallowed by the service if (mService.okToConnect(mDevice) && mAllowReconnect) { connectGatt(/*autoConnect*/ true); @@ -1407,7 +1408,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -1448,7 +1449,7 @@ class BassClientStateMachine extends StateMachine { case CONNECTION_STATE_CHANGED: int state = (int) message.obj; Log.w(TAG, "connection state changed:" + state); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { log("remote/wl connection"); transitionTo(mConnected); } else { @@ -1473,8 +1474,7 @@ class BassClientStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, mDevice, mConnectTimeoutMs); - broadcastConnectionState( - mDevice, mLastConnectionState, BluetoothProfile.STATE_CONNECTING); + broadcastConnectionState(mDevice, mLastConnectionState, STATE_CONNECTING); } @Override @@ -1484,7 +1484,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -1511,7 +1511,7 @@ class BassClientStateMachine extends StateMachine { case CONNECTION_STATE_CHANGED: int state = (int) message.obj; Log.w(TAG, "Connecting: connection state changed:" + state); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { transitionTo(mConnected); } else { Log.w(TAG, "Connection failed to " + mDevice); @@ -1765,9 +1765,8 @@ class BassClientStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); removeDeferredMessages(CONNECT); - if (mLastConnectionState != BluetoothProfile.STATE_CONNECTED) { - broadcastConnectionState( - mDevice, mLastConnectionState, BluetoothProfile.STATE_CONNECTED); + if (mLastConnectionState != STATE_CONNECTED) { + broadcastConnectionState(mDevice, mLastConnectionState, STATE_CONNECTED); } } @@ -1778,7 +1777,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } private void writeBassControlPoint(byte[] value) { @@ -1818,7 +1817,7 @@ class BassClientStateMachine extends StateMachine { case CONNECTION_STATE_CHANGED: int state = (int) message.obj; Log.w(TAG, "Connected:connection state changed:" + state); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { Log.w(TAG, "device is already connected to Bass" + mDevice); } else { Log.w(TAG, "unexpected disconnected from " + mDevice); @@ -2050,7 +2049,7 @@ class BassClientStateMachine extends StateMachine { } } - private boolean isSuccess(int status) { + private static boolean isSuccess(int status) { boolean ret = false; switch (status) { case BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST: @@ -2167,7 +2166,7 @@ class BassClientStateMachine extends StateMachine { case CONNECTION_STATE_CHANGED: int state = (int) message.obj; Log.w(TAG, "ConnectedProcessing: connection state changed:" + state); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { Log.w(TAG, "should never happen from this state"); } else { Log.w(TAG, "Unexpected disconnection " + mDevice); @@ -2226,8 +2225,7 @@ class BassClientStateMachine extends StateMachine { void broadcastConnectionState(BluetoothDevice device, int fromState, int toState) { log("broadcastConnectionState " + device + ": " + fromState + "->" + toState); - if (fromState == BluetoothProfile.STATE_CONNECTED - && toState == BluetoothProfile.STATE_CONNECTED) { + if (fromState == STATE_CONNECTED && toState == STATE_CONNECTED) { log("CONNECTED->CONNECTED: Ignore"); return; } @@ -2254,15 +2252,15 @@ class BassClientStateMachine extends StateMachine { } switch (currentState) { case "Disconnected": - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case "Connecting": - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; case "Connected": case "ConnectedProcessing": - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; default: Log.e(TAG, "Bad currentState: " + currentState); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java index bdf0db4d47..0669bc4ac2 100644 --- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java +++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java @@ -16,6 +16,9 @@ package com.android.bluetooth.btservice; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import android.annotation.NonNull; import android.annotation.Nullable; import android.bluetooth.BluetoothAdapter; @@ -180,7 +183,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac */ public void profileConnectionStateChanged( int profile, BluetoothDevice device, int fromState, int toState) { - if (toState == BluetoothProfile.STATE_CONNECTED) { + if (toState == STATE_CONNECTED) { switch (profile) { case BluetoothProfile.A2DP: mHandler.post(() -> handleA2dpConnected(device)); @@ -198,7 +201,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac mHandler.post(() -> handleHapConnected(device)); break; } - } else if (fromState == BluetoothProfile.STATE_CONNECTED) { + } else if (fromState == STATE_CONNECTED) { switch (profile) { case BluetoothProfile.A2DP: mHandler.post(() -> handleA2dpDisconnected(device)); @@ -291,7 +294,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac } // Activate A2DP if audio mode is normal or HFP is not supported or enabled. if (mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET) - != BluetoothProfile.CONNECTION_POLICY_ALLOWED + != CONNECTION_POLICY_ALLOWED || mAudioManager.getMode() == AudioManager.MODE_NORMAL) { boolean a2dpMadeActive = setA2dpActiveDevice(device); if (a2dpMadeActive && !Utils.isDualModeAudioEnabled()) { @@ -361,7 +364,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac } // Activate HFP if audio mode is not normal or A2DP is not supported or enabled. if (mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP) - != BluetoothProfile.CONNECTION_POLICY_ALLOWED + != CONNECTION_POLICY_ALLOWED || mAudioManager.getMode() != AudioManager.MODE_NORMAL) { if (Utils.isWatch(mAdapterService, device)) { Log.i(TAG, "Do not set hfp active for watch device " + device); @@ -682,7 +685,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac if (!Objects.equals(mHfpActiveDevice, device) && mHfpConnectedDevices.contains(device) && mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + == CONNECTION_POLICY_ALLOWED) { mClassicDeviceToBeActivated = device; setHfpActiveDevice(device); mHandler.postDelayed( @@ -753,7 +756,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac if (!Objects.equals(mA2dpActiveDevice, device) && mA2dpConnectedDevices.contains(device) && mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + == CONNECTION_POLICY_ALLOWED) { mClassicDeviceToBeActivated = device; setA2dpActiveDevice(device); mHandler.postDelayed( diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java index b99debdede..f195eec079 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java @@ -19,6 +19,10 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.annotation.NonNull; import android.app.BroadcastOptions; @@ -597,7 +601,7 @@ class AdapterProperties { if (p != null) { return p.first; } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } @@ -667,24 +671,22 @@ class AdapterProperties { } } - - - private boolean validateProfileConnectionState(int state) { - return (state == BluetoothProfile.STATE_DISCONNECTED - || state == BluetoothProfile.STATE_CONNECTING - || state == BluetoothProfile.STATE_CONNECTED - || state == BluetoothProfile.STATE_DISCONNECTING); + private static boolean validateProfileConnectionState(int state) { + return (state == STATE_DISCONNECTED + || state == STATE_CONNECTING + || state == STATE_CONNECTED + || state == STATE_DISCONNECTING); } private static int convertToAdapterState(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return BluetoothAdapter.STATE_DISCONNECTED; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: return BluetoothAdapter.STATE_DISCONNECTING; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: return BluetoothAdapter.STATE_CONNECTED; - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: return BluetoothAdapter.STATE_CONNECTING; } Log.e(TAG, "convertToAdapterState, unknow state " + state); @@ -693,14 +695,13 @@ class AdapterProperties { private static boolean isNormalStateTransition(int prevState, int nextState) { switch (prevState) { - case BluetoothProfile.STATE_DISCONNECTED: - return nextState == BluetoothProfile.STATE_CONNECTING; - case BluetoothProfile.STATE_CONNECTED: - return nextState == BluetoothProfile.STATE_DISCONNECTING; - case BluetoothProfile.STATE_DISCONNECTING: - case BluetoothProfile.STATE_CONNECTING: - return (nextState == BluetoothProfile.STATE_DISCONNECTED) - || (nextState == BluetoothProfile.STATE_CONNECTED); + case STATE_DISCONNECTED: + return nextState == STATE_CONNECTING; + case STATE_CONNECTED: + return nextState == STATE_DISCONNECTING; + case STATE_DISCONNECTING: + case STATE_CONNECTING: + return (nextState == STATE_DISCONNECTED) || (nextState == STATE_CONNECTED); default: return false; } @@ -708,7 +709,7 @@ class AdapterProperties { private boolean updateCountersAndCheckForConnectionStateChange(int state, int prevState) { switch (prevState) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: if (mProfilesConnecting > 0) { mProfilesConnecting--; } else { @@ -718,7 +719,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: if (mProfilesConnected > 0) { mProfilesConnected--; } else { @@ -728,7 +729,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: if (mProfilesDisconnecting > 0) { mProfilesDisconnecting--; } else { @@ -740,19 +741,19 @@ class AdapterProperties { } switch (state) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: mProfilesConnecting++; return (mProfilesConnected == 0 && mProfilesConnecting == 1); - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: mProfilesConnected++; return (mProfilesConnected == 1); - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: mProfilesDisconnecting++; return (mProfilesConnected == 0 && mProfilesDisconnecting == 1); - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return (mProfilesConnected == 0 && mProfilesConnecting == 0); default: @@ -787,17 +788,15 @@ class AdapterProperties { if (newState == currHashState) { numDev++; - } else if (newState == BluetoothProfile.STATE_CONNECTED - || (newState == BluetoothProfile.STATE_CONNECTING - && currHashState != BluetoothProfile.STATE_CONNECTED)) { + } else if (newState == STATE_CONNECTED + || (newState == STATE_CONNECTING && currHashState != STATE_CONNECTED)) { numDev = 1; } else if (numDev == 1 && oldState == currHashState) { update = true; } else if (numDev > 1 && oldState == currHashState) { numDev--; - if (currHashState == BluetoothProfile.STATE_CONNECTED - || currHashState == BluetoothProfile.STATE_CONNECTING) { + if (currHashState == STATE_CONNECTED || currHashState == STATE_CONNECTING) { newHashState = currHashState; } } else { @@ -1159,7 +1158,7 @@ class AdapterProperties { writer.println(sb.toString()); } - private String dumpDeviceType(int deviceType) { + private static String dumpDeviceType(int deviceType) { switch (deviceType) { case BluetoothDevice.DEVICE_TYPE_UNKNOWN: return " ???? "; @@ -1174,7 +1173,7 @@ class AdapterProperties { } } - private String dumpConnectionState(int state) { + private static String dumpConnectionState(int state) { switch (state) { case BluetoothAdapter.STATE_DISCONNECTED: return "STATE_DISCONNECTED"; diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java index 075b2aee3b..8184c78c1e 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java @@ -28,6 +28,12 @@ import static android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERA import static android.bluetooth.BluetoothAdapter.SCAN_MODE_NONE; import static android.bluetooth.BluetoothDevice.BATTERY_LEVEL_UNKNOWN; import static android.bluetooth.BluetoothDevice.TRANSPORT_AUTO; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothProfile.getProfileName; import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID; import static android.text.format.DateUtils.MINUTE_IN_MILLIS; @@ -1125,7 +1131,7 @@ public class AdapterService extends Service { } } - private void invalidateBluetoothGetStateCache() { + private static void invalidateBluetoothGetStateCache() { if (Flags.getStateFromSystemServer()) { // State is managed by the system server return; @@ -1509,7 +1515,7 @@ public class AdapterService extends Service { mMetadataListeners.values().forEach(v -> v.kill()); } - private void invalidateBluetoothCaches() { + private static void invalidateBluetoothCaches() { BluetoothAdapter.invalidateGetProfileConnectionStateCache(); BluetoothAdapter.invalidateIsOffloadedFilteringSupportedCache(); BluetoothDevice.invalidateBluetoothGetBondStateCache(); @@ -1729,17 +1735,16 @@ public class AdapterService extends Service { remoteDeviceUuids, HidHostService.ANDROID_HEADTRACKER_UUID); } if (profile == BluetoothProfile.HID_DEVICE) { - return mHidDeviceService.getConnectionState(device) - == BluetoothProfile.STATE_DISCONNECTED; + return mHidDeviceService.getConnectionState(device) == STATE_DISCONNECTED; } if (profile == BluetoothProfile.PAN) { return Utils.arrayContains(remoteDeviceUuids, BluetoothUuid.NAP); } if (profile == BluetoothProfile.MAP) { - return mMapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED; + return mMapService.getConnectionState(device) == STATE_CONNECTED; } if (profile == BluetoothProfile.PBAP) { - return mPbapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED; + return mPbapService.getConnectionState(device) == STATE_CONNECTED; } if (profile == BluetoothProfile.MAP_CLIENT) { return Utils.arrayContains(localDeviceUuids, BluetoothUuid.MNS) @@ -1787,73 +1792,60 @@ public class AdapterService extends Service { */ boolean isAllProfilesUnknown(BluetoothDevice device) { if (mA2dpService != null - && mA2dpService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mA2dpService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mA2dpSinkService != null - && mA2dpSinkService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mA2dpSinkService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mHeadsetService != null - && mHeadsetService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mHeadsetService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mHeadsetClientService != null - && mHeadsetClientService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mHeadsetClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mMapClientService != null - && mMapClientService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mMapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mHidHostService != null - && mHidHostService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mHidHostService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mPanService != null - && mPanService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mPanService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mPbapClientService != null - && mPbapClientService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mPbapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mHearingAidService != null - && mHearingAidService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mHearingAidService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mHapClientService != null - && mHapClientService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mHapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mVolumeControlService != null - && mVolumeControlService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mVolumeControlService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mCsipSetCoordinatorService != null && mCsipSetCoordinatorService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + != CONNECTION_POLICY_UNKNOWN) { return false; } if (mLeAudioService != null - && mLeAudioService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mLeAudioService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } if (mBassClientService != null - && mBassClientService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + && mBassClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) { return false; } return true; @@ -1870,105 +1862,93 @@ public class AdapterService extends Service { if (mCsipSetCoordinatorService != null && isProfileSupported(device, BluetoothProfile.CSIP_SET_COORDINATOR) && mCsipSetCoordinatorService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Coordinated Set Profile"); mCsipSetCoordinatorService.connect(device); } if (mA2dpService != null && isProfileSupported(device, BluetoothProfile.A2DP) - && mA2dpService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mA2dpService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting A2dp"); mA2dpService.connect(device); } if (mA2dpSinkService != null && isProfileSupported(device, BluetoothProfile.A2DP_SINK) - && mA2dpSinkService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mA2dpSinkService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting A2dp Sink"); mA2dpSinkService.connect(device); } if (mHeadsetService != null && isProfileSupported(device, BluetoothProfile.HEADSET) - && mHeadsetService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mHeadsetService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Headset Profile"); mHeadsetService.connect(device); } if (mHeadsetClientService != null && isProfileSupported(device, BluetoothProfile.HEADSET_CLIENT) && mHeadsetClientService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting HFP"); mHeadsetClientService.connect(device); } if (mMapClientService != null && isProfileSupported(device, BluetoothProfile.MAP_CLIENT) - && mMapClientService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mMapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting MAP"); mMapClientService.connect(device); } if (mHidHostService != null && isProfileSupported(device, BluetoothProfile.HID_HOST) - && mHidHostService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mHidHostService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Hid Host Profile"); mHidHostService.connect(device); } if (mPanService != null && isProfileSupported(device, BluetoothProfile.PAN) - && mPanService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mPanService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Pan Profile"); mPanService.connect(device); } if (mPbapClientService != null && isProfileSupported(device, BluetoothProfile.PBAP_CLIENT) - && mPbapClientService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mPbapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Pbap"); mPbapClientService.connect(device); } if (mHearingAidService != null && isProfileSupported(device, BluetoothProfile.HEARING_AID) - && mHearingAidService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mHearingAidService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Hearing Aid Profile"); mHearingAidService.connect(device); } if (mHapClientService != null && isProfileSupported(device, BluetoothProfile.HAP_CLIENT) - && mHapClientService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mHapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting HAS Profile"); mHapClientService.connect(device); } if (mVolumeControlService != null && isProfileSupported(device, BluetoothProfile.VOLUME_CONTROL) && mVolumeControlService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Volume Control Profile"); mVolumeControlService.connect(device); } if (mLeAudioService != null && isProfileSupported(device, BluetoothProfile.LE_AUDIO) - && mLeAudioService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mLeAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting LeAudio profile (BAP)"); mLeAudioService.connect(device); } if (mBassClientService != null && isProfileSupported(device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT) - && mBassClientService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mBassClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting LE Broadcast Assistant Profile"); mBassClientService.connect(device); } if (mBatteryService != null && isProfileSupported(device, BluetoothProfile.BATTERY) - && mBatteryService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + && mBatteryService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.i(TAG, "connectEnabledProfiles: Connecting Battery Service"); mBatteryService.connect(device); } @@ -2139,7 +2119,7 @@ public class AdapterService extends Service { } } - private void pendingSocketTimeoutRunnable( + private static void pendingSocketTimeoutRunnable( RfcommListenerData listenerData, BluetoothSocket socket) { boolean socketFound = listenerData.mPendingSockets.remove(socket); if (socketFound) { @@ -2646,7 +2626,7 @@ public class AdapterService extends Service { || (checkConnect && !Utils.checkConnectPermissionForDataDelivery( service, source, "AdapterService getProfileConnectionState"))) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.mAdapterProperties.getProfileConnectionState(profile); @@ -4438,6 +4418,27 @@ public class AdapterService extends Service { AdapterService service = getService(); return service == null ? null : service.getDistanceMeasurement(); } + + @Override + public int getKeyMissingCount(BluetoothDevice device, AttributionSource source) { + AdapterService service = getService(); + if (service == null) { + return -1; + } + if (!callerIsSystemOrActiveOrManagedUser(service, TAG, "getKeyMissingCount")) { + throw new IllegalStateException( + "Caller is not the system or part of the active/managed user"); + } + if (!BluetoothAdapter.checkBluetoothAddress(device.getAddress())) { + throw new IllegalArgumentException("device cannot have an invalid address"); + } + if (!Utils.checkConnectPermissionForDataDelivery( + service, source, "AdapterService getKeyMissingCount")) { + return -1; + } + + return service.mDatabaseManager.getKeyMissingCount(device); + } } /** @@ -5206,8 +5207,7 @@ public class AdapterService extends Service { return; } - if (mLeAudioService.getConnectionPolicy(device) - != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (mLeAudioService.getConnectionPolicy(device) != CONNECTION_POLICY_ALLOWED) { Log.d( TAG, "addGattClientToControlAutoActiveMode: " @@ -5479,17 +5479,17 @@ public class AdapterService extends Service { mA2dpService != null && (device == null || mA2dpService.getConnectionPolicy(device) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED); + == CONNECTION_POLICY_ALLOWED); boolean hfpSupported = mHeadsetService != null && (device == null || mHeadsetService.getConnectionPolicy(device) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED); + == CONNECTION_POLICY_ALLOWED); boolean leAudioSupported = mLeAudioService != null && (device == null || mLeAudioService.getConnectionPolicy(device) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED); + == CONNECTION_POLICY_ALLOWED); if (leAudioSupported) { Log.i(TAG, "setActiveDevice: Setting active Le Audio device " + device); @@ -5529,7 +5529,7 @@ public class AdapterService extends Service { if (mHearingAidService != null && (device == null || mHearingAidService.getConnectionPolicy(device) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + == CONNECTION_POLICY_ALLOWED)) { Log.i(TAG, "setActiveDevice: Setting active Hearing Aid " + device); if (device == null) { mHearingAidService.removeActiveDevice(false); @@ -5676,48 +5676,44 @@ public class AdapterService extends Service { if (mA2dpService != null && isProfileSupported(device, BluetoothProfile.A2DP)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting A2dp"); // Set connection policy also connects the profile with CONNECTION_POLICY_ALLOWED - mA2dpService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mA2dpService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mA2dpSinkService != null && isProfileSupported(device, BluetoothProfile.A2DP_SINK)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting A2dp Sink"); - mA2dpSinkService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mA2dpSinkService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mHeadsetService != null && isProfileSupported(device, BluetoothProfile.HEADSET)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Headset Profile"); - mHeadsetService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mHeadsetService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mHeadsetClientService != null && isProfileSupported(device, BluetoothProfile.HEADSET_CLIENT)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting HFP"); - mHeadsetClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mHeadsetClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mMapClientService != null && isProfileSupported(device, BluetoothProfile.MAP_CLIENT)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting MAP"); - mMapClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mMapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mHidHostService != null && isProfileSupported(device, BluetoothProfile.HID_HOST)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Hid Host Profile"); - mHidHostService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mHidHostService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mPanService != null && isProfileSupported(device, BluetoothProfile.PAN)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Pan Profile"); - mPanService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mPanService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mPbapClientService != null && isProfileSupported(device, BluetoothProfile.PBAP_CLIENT)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Pbap"); - mPbapClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mPbapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mHearingAidService != null @@ -5731,46 +5727,41 @@ public class AdapterService extends Service { + " Profile"); } else { Log.i(TAG, "connectAllSupportedProfiles: Connecting Hearing Aid Profile"); - mHearingAidService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mHearingAidService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } } if (mHapClientService != null && isProfileSupported(device, BluetoothProfile.HAP_CLIENT)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Hearing Access Client Profile"); - mHapClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mHapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mVolumeControlService != null && isProfileSupported(device, BluetoothProfile.VOLUME_CONTROL)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Volume Control Profile"); - mVolumeControlService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mVolumeControlService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mCsipSetCoordinatorService != null && isProfileSupported(device, BluetoothProfile.CSIP_SET_COORDINATOR)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Coordinated Set Profile"); - mCsipSetCoordinatorService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mCsipSetCoordinatorService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mLeAudioService != null && isProfileSupported(device, BluetoothProfile.LE_AUDIO)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting LeAudio profile (BAP)"); - mLeAudioService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mLeAudioService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mBassClientService != null && isProfileSupported(device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting LE Broadcast Assistant Profile"); - mBassClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mBassClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } if (mBatteryService != null && isProfileSupported(device, BluetoothProfile.BATTERY)) { Log.i(TAG, "connectAllSupportedProfiles: Connecting Battery Service"); - mBatteryService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mBatteryService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); numProfilesConnected++; } @@ -5793,134 +5784,111 @@ public class AdapterService extends Service { } if (mA2dpService != null - && (mA2dpService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mA2dpService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mA2dpService.getConnectionState(device) == STATE_CONNECTED + || mA2dpService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting A2dp"); mA2dpService.disconnect(device); } if (mA2dpSinkService != null - && (mA2dpSinkService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mA2dpSinkService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mA2dpSinkService.getConnectionState(device) == STATE_CONNECTED + || mA2dpSinkService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting A2dp Sink"); mA2dpSinkService.disconnect(device); } if (mHeadsetService != null - && (mHeadsetService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mHeadsetService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHeadsetService.getConnectionState(device) == STATE_CONNECTED + || mHeadsetService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Headset Profile"); mHeadsetService.disconnect(device); } if (mHeadsetClientService != null - && (mHeadsetClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED - || mHeadsetClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHeadsetClientService.getConnectionState(device) == STATE_CONNECTED + || mHeadsetClientService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting HFP"); mHeadsetClientService.disconnect(device); } if (mMapClientService != null - && (mMapClientService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mMapClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mMapClientService.getConnectionState(device) == STATE_CONNECTED + || mMapClientService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting MAP Client"); mMapClientService.disconnect(device); } if (mMapService != null - && (mMapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mMapService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mMapService.getConnectionState(device) == STATE_CONNECTED + || mMapService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting MAP"); mMapService.disconnect(device); } if (mHidDeviceService != null - && (mHidDeviceService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mHidDeviceService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHidDeviceService.getConnectionState(device) == STATE_CONNECTED + || mHidDeviceService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hid Device Profile"); mHidDeviceService.disconnect(device); } if (mHidHostService != null - && (mHidHostService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mHidHostService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHidHostService.getConnectionState(device) == STATE_CONNECTED + || mHidHostService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hid Host Profile"); mHidHostService.disconnect(device); } if (mPanService != null - && (mPanService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mPanService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mPanService.getConnectionState(device) == STATE_CONNECTED + || mPanService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pan Profile"); mPanService.disconnect(device); } if (mPbapClientService != null - && (mPbapClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED - || mPbapClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mPbapClientService.getConnectionState(device) == STATE_CONNECTED + || mPbapClientService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pbap Client"); mPbapClientService.disconnect(device); } if (mPbapService != null - && (mPbapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mPbapService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mPbapService.getConnectionState(device) == STATE_CONNECTED + || mPbapService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pbap Server"); mPbapService.disconnect(device); } if (mHearingAidService != null - && (mHearingAidService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED - || mHearingAidService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHearingAidService.getConnectionState(device) == STATE_CONNECTED + || mHearingAidService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hearing Aid Profile"); mHearingAidService.disconnect(device); } if (mHapClientService != null - && (mHapClientService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mHapClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mHapClientService.getConnectionState(device) == STATE_CONNECTED + || mHapClientService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hearing Access Profile Client"); mHapClientService.disconnect(device); } if (mVolumeControlService != null - && (mVolumeControlService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED - || mVolumeControlService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mVolumeControlService.getConnectionState(device) == STATE_CONNECTED + || mVolumeControlService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Volume Control Profile"); mVolumeControlService.disconnect(device); } if (mSapService != null - && (mSapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mSapService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mSapService.getConnectionState(device) == STATE_CONNECTED + || mSapService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Sap Profile"); mSapService.disconnect(device); } if (mCsipSetCoordinatorService != null - && (mCsipSetCoordinatorService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED + && (mCsipSetCoordinatorService.getConnectionState(device) == STATE_CONNECTED || mCsipSetCoordinatorService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Coordinator Set Profile"); mCsipSetCoordinatorService.disconnect(device); } if (mLeAudioService != null - && (mLeAudioService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mLeAudioService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mLeAudioService.getConnectionState(device) == STATE_CONNECTED + || mLeAudioService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting LeAudio profile (BAP)"); mLeAudioService.disconnect(device); } if (mBassClientService != null - && (mBassClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTED - || mBassClientService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mBassClientService.getConnectionState(device) == STATE_CONNECTED + || mBassClientService.getConnectionState(device) == STATE_CONNECTING)) { Log.i( TAG, "disconnectAllEnabledProfiles: Disconnecting " @@ -5928,9 +5896,8 @@ public class AdapterService extends Service { mBassClientService.disconnect(device); } if (mBatteryService != null - && (mBatteryService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED - || mBatteryService.getConnectionState(device) - == BluetoothProfile.STATE_CONNECTING)) { + && (mBatteryService.getConnectionState(device) == STATE_CONNECTED + || mBatteryService.getConnectionState(device) == STATE_CONNECTING)) { Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting " + "Battery Service"); mBatteryService.disconnect(device); } @@ -6707,19 +6674,19 @@ public class AdapterService extends Service { list.finishBroadcast(); } - private int getIdleCurrentMa() { + private static int getIdleCurrentMa() { return BluetoothProperties.getHardwareIdleCurrentMa().orElse(0); } - private int getTxCurrentMa() { + private static int getTxCurrentMa() { return BluetoothProperties.getHardwareTxCurrentMa().orElse(0); } - private int getRxCurrentMa() { + private static int getRxCurrentMa() { return BluetoothProperties.getHardwareRxCurrentMa().orElse(0); } - private double getOperatingVolt() { + private static double getOperatingVolt() { return BluetoothProperties.getHardwareOperatingVoltageMv().orElse(0) / 1000.0; } @@ -6727,7 +6694,7 @@ public class AdapterService extends Service { return mRemoteDevices; } - private String dumpScanMode(int scanMode) { + private static String dumpScanMode(int scanMode) { switch (scanMode) { case SCAN_MODE_NONE: return "SCAN_MODE_NONE"; @@ -7391,7 +7358,7 @@ public class AdapterService extends Service { deleteDirectoryContents("/data/misc/bluetooth/"); } - private void deleteDirectoryContents(String dirPath) { + private static void deleteDirectoryContents(String dirPath) { Path directoryPath = Paths.get(dirPath); try { Files.walkFileTree( diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterState.java b/android/app/src/com/android/bluetooth/btservice/AdapterState.java index d6f0646aef..b5ff730b5a 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterState.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterState.java @@ -17,12 +17,12 @@ package com.android.bluetooth.btservice; import android.bluetooth.BluetoothAdapter; -import com.android.bluetooth.flags.Flags; import android.os.Looper; import android.os.Message; import android.os.SystemProperties; import android.util.Log; +import com.android.bluetooth.flags.Flags; import com.android.internal.util.State; import com.android.internal.util.StateMachine; @@ -91,7 +91,7 @@ final class AdapterState extends StateMachine { start(); } - private String messageString(int message) { + private static String messageString(int message) { switch (message) { case BLE_TURN_ON: return "BLE_TURN_ON"; diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java b/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java index efda7a5385..2f4c03c17c 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java @@ -16,6 +16,8 @@ package com.android.bluetooth.btservice; +import static java.util.Objects.requireNonNull; + import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; @@ -36,7 +38,11 @@ public class BluetoothQualityReportNativeInterface { private static final Object INSTANCE_LOCK = new Object(); - private BluetoothQualityReportNativeInterface() {} + private final AdapterService mAdapterService; + + private BluetoothQualityReportNativeInterface() { + mAdapterService = requireNonNull(AdapterService.getAdapterService()); + } /** Get singleton instance. */ public static BluetoothQualityReportNativeInterface getInstance() { @@ -84,14 +90,9 @@ public class BluetoothQualityReportNativeInterface { Log.e(TAG, "bqrDeliver failed: adapter is null"); return; } - AdapterService adapterService = AdapterService.getAdapterService(); - if (adapterService == null) { - Log.e(TAG, "bqrDeliver failed: adapterService is null"); - return; - } BluetoothDevice device = adapter.getRemoteDevice(remoteAddress); - BluetoothClass remoteClass = new BluetoothClass(adapterService.getRemoteClass(device)); + BluetoothClass remoteClass = new BluetoothClass(mAdapterService.getRemoteClass(device)); BluetoothQualityReport bqr; try { bqr = @@ -100,7 +101,7 @@ public class BluetoothQualityReportNativeInterface { .setLmpVersion(lmpVer) .setLmpSubVersion(lmpSubVer) .setManufacturerId(manufacturerId) - .setRemoteName(adapterService.getRemoteName(device)) + .setRemoteName(mAdapterService.getRemoteName(device)) .setBluetoothClass(remoteClass) .build(); Log.i(TAG, bqr.toString()); @@ -110,7 +111,7 @@ public class BluetoothQualityReportNativeInterface { } try { - int status = adapterService.bluetoothQualityReportReadyCallback(device, bqr); + int status = mAdapterService.bluetoothQualityReportReadyCallback(device, bqr); if (status != BluetoothStatusCodes.SUCCESS) { Log.e(TAG, "bluetoothQualityReportReadyCallback failed, status: " + status); } diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java index d2813b827b..30be010ae4 100644 --- a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java +++ b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java @@ -17,6 +17,7 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND_RETRY; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__FAIL; @@ -27,7 +28,6 @@ import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothProtoEnums; import android.bluetooth.OobData; import android.content.Intent; @@ -765,7 +765,7 @@ final class BondStateMachine extends StateMachine { removeMessages(what); } - private void clearProfilePriority(BluetoothDevice device) { + private static void clearProfilePriority(BluetoothDevice device) { HidHostService hidService = HidHostService.getHidHostService(); A2dpService a2dpService = A2dpService.getA2dpService(); HeadsetService headsetService = HeadsetService.getHeadsetService(); @@ -779,39 +779,34 @@ final class BondStateMachine extends StateMachine { HapClientService hapClientService = HapClientService.getHapClientService(); if (hidService != null) { - hidService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + hidService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (a2dpService != null) { - a2dpService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + a2dpService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (headsetService != null) { - headsetService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + headsetService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (headsetClientService != null) { - headsetClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + headsetClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (a2dpSinkService != null) { - a2dpSinkService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + a2dpSinkService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (pbapClientService != null) { - pbapClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + pbapClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (leAudioService != null) { - leAudioService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + leAudioService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (csipSetCoordinatorService != null) { - csipSetCoordinatorService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + csipSetCoordinatorService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (volumeControlService != null) { - volumeControlService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + volumeControlService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } if (hapClientService != null) { - hapClientService.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + hapClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN); } } @@ -825,19 +820,19 @@ final class BondStateMachine extends StateMachine { } else return "UNKNOWN(" + state + ")"; } - private void infoLog(String msg) { + private static void infoLog(String msg) { Log.i(TAG, msg); } - private void errorLog(String msg) { + private static void errorLog(String msg) { Log.e(TAG, msg); } - private void warnLog(String msg) { + private static void warnLog(String msg) { Log.w(TAG, msg); } - private int getUnbondReasonFromHALCode(int reason) { + private static int getUnbondReasonFromHALCode(int reason) { if (reason == AbstractionLayer.BT_STATUS_SUCCESS) { return BluetoothDevice.BOND_SUCCESS; } else if (reason == AbstractionLayer.BT_STATUS_RMT_DEV_DOWN) { diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java index fb925b7e00..10a853c59d 100644 --- a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java +++ b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java @@ -15,6 +15,8 @@ */ package com.android.bluetooth.btservice; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; + import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION; import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP; @@ -344,7 +346,7 @@ public class MetricsLogger { BluetoothDevice device = connIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int state = connIntent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); int metricId = mAdapterService.getMetricId(device); - if (state == BluetoothProfile.STATE_CONNECTING) { + if (state == STATE_CONNECTING) { String deviceName = mRemoteDevices.getName(device); BluetoothStatsLog.write( BluetoothStatsLog.BLUETOOTH_DEVICE_NAME_REPORTED, metricId, deviceName); @@ -472,7 +474,7 @@ public class MetricsLogger { mAlarmManager.cancel(mOnAlarmListener); } - private void writeFieldIfNotNull( + private static void writeFieldIfNotNull( ProtoOutputStream proto, long fieldType, long fieldCount, @@ -594,7 +596,7 @@ public class MetricsLogger { } } - private int getOui(BluetoothDevice device) { + private static int getOui(BluetoothDevice device) { return Integer.parseInt(device.getAddress().replace(":", "").substring(0, 6), 16); } @@ -807,7 +809,7 @@ public class MetricsLogger { return digest.digest(name.getBytes(StandardCharsets.UTF_8)); } - private int getProfileEnumFromProfileId(int profile) { + private static int getProfileEnumFromProfileId(int profile) { return switch (profile) { case BluetoothProfile.A2DP -> BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP; diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java index fd18a104ee..048602338f 100644 --- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java +++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java @@ -1008,9 +1008,8 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { List<BluetoothDevice> connectedDevices = hapClientService.getConnectedDevices(); if (!connectedDevices.contains(device) && (hapClientService.getConnectionPolicy(device) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) - && (hapClientService.getConnectionState(device) - == BluetoothProfile.STATE_DISCONNECTED)) { + == CONNECTION_POLICY_ALLOWED) + && (hapClientService.getConnectionState(device) == STATE_DISCONNECTED)) { Log.d(TAG, log + "Retrying HAP connection"); hapClientService.connect(device); } @@ -1057,11 +1056,10 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { profileId < BluetoothProfile.MAX_PROFILE_ID; profileId++) { if (mAdapterService.getDatabase().getProfileConnectionPolicy(device, profileId) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + == CONNECTION_POLICY_ALLOWED) { mAdapterService .getDatabase() - .setProfileConnectionPolicy( - device, profileId, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .setProfileConnectionPolicy(device, profileId, CONNECTION_POLICY_FORBIDDEN); } } } diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java index f4aaf5715b..a4cb97f295 100644 --- a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java +++ b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java @@ -19,6 +19,8 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.modules.utils.build.SdkLevel.isAtLeastV; @@ -1405,8 +1407,7 @@ public class RemoteDevices { if (mAdapterService.getConnectionState(device) == 0) { BatteryService batteryService = BatteryService.getBatteryService(); if (batteryService != null - && batteryService.getConnectionState(device) - != BluetoothProfile.STATE_DISCONNECTED + && batteryService.getConnectionState(device) != STATE_DISCONNECTED && transportLinkType == BluetoothDevice.TRANSPORT_LE) { batteryService.disconnect(device); } @@ -1556,6 +1557,10 @@ public class RemoteDevices { .addFlags( Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); + + // Bond loss detected, add to the count. + mAdapterService.getDatabase().updateKeyMissingCount(bluetoothDevice, true); + if (Flags.keyMissingPublic()) { mAdapterService.sendOrderedBroadcast( intent, @@ -1629,6 +1634,9 @@ public class RemoteDevices { /* Classic link using non-secure connections mode */ algorithm = BluetoothDevice.ENCRYPTION_ALGORITHM_E0; } + + // Successful bond detected, reset the count. + mAdapterService.getDatabase().updateKeyMissingCount(bluetoothDevice, false); } Intent intent = @@ -1708,7 +1716,7 @@ public class RemoteDevices { Log.e(TAG, "onHeadsetConnectionStateChanged() remote device is null"); return; } - if (toState == BluetoothProfile.STATE_DISCONNECTED && !hasBatteryService(device)) { + if (toState == STATE_DISCONNECTED && !hasBatteryService(device)) { resetBatteryLevel(device, /* isBas= */ false); } } @@ -1923,7 +1931,7 @@ public class RemoteDevices { boolean hasBatteryService(BluetoothDevice device) { BatteryService batteryService = BatteryService.getBatteryService(); return batteryService != null - && batteryService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED; + && batteryService.getConnectionState(device) == STATE_CONNECTED; } /** Handles headset client connection state change event. */ @@ -1938,7 +1946,7 @@ public class RemoteDevices { Log.e(TAG, "onHeadsetClientConnectionStateChanged() remote device is null"); return; } - if (toState == BluetoothProfile.STATE_DISCONNECTED && !hasBatteryService(device)) { + if (toState == STATE_DISCONNECTED && !hasBatteryService(device)) { resetBatteryLevel(device, /* isBas= */ false); } } diff --git a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java index bbc8dfc521..4d6c706e06 100644 --- a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java +++ b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java @@ -17,6 +17,7 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; @@ -135,13 +136,13 @@ public class SilenceDeviceManager { int prevState = msg.arg1; int nextState = msg.arg2; - if (nextState == BluetoothProfile.STATE_CONNECTED) { + if (nextState == STATE_CONNECTED) { // enter connected state addConnectedDevice(device, BluetoothProfile.A2DP); if (!mSilenceDevices.containsKey(device)) { mSilenceDevices.put(device, false); } - } else if (prevState == BluetoothProfile.STATE_CONNECTED) { + } else if (prevState == STATE_CONNECTED) { // exiting from connected state removeConnectedDevice(device, BluetoothProfile.A2DP); if (!isBluetoothAudioConnected(device)) { @@ -156,13 +157,13 @@ public class SilenceDeviceManager { int prev = msg.arg1; int next = msg.arg2; - if (next == BluetoothProfile.STATE_CONNECTED) { + if (next == STATE_CONNECTED) { // enter connected state addConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET); if (!mSilenceDevices.containsKey(bluetoothDevice)) { mSilenceDevices.put(bluetoothDevice, false); } - } else if (prev == BluetoothProfile.STATE_CONNECTED) { + } else if (prev == STATE_CONNECTED) { // exiting from connected state removeConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET); if (!isBluetoothAudioConnected(bluetoothDevice)) { diff --git a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java index 6c7d69a723..9812509ea0 100644 --- a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java +++ b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java @@ -246,7 +246,7 @@ public class BluetoothKeystoreService { } } - private boolean isFactoryReset() { + private static boolean isFactoryReset() { return SystemProperties.getBoolean("persist.bluetooth.factoryreset", false); } @@ -310,7 +310,7 @@ public class BluetoothKeystoreService { cleanupMemory(); } - private void cleanupFile() throws IOException { + private static void cleanupFile() throws IOException { Files.deleteIfExists(Paths.get(CONFIG_CHECKSUM_ENCRYPTION_PATH)); Files.deleteIfExists(Paths.get(CONFIG_FILE_ENCRYPTION_PATH)); } @@ -676,7 +676,7 @@ public class BluetoothKeystoreService { return output; } - private KeyStore getKeyStore() { + private static KeyStore getKeyStore() { KeyStore keyStore = null; int counter = 0; diff --git a/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java index b790e92c73..76ba89e0a4 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java @@ -50,7 +50,7 @@ class AudioPolicyEntity { return builder.toString(); } - private String metadataToString(int metadata) { + private static String metadataToString(int metadata) { return String.valueOf(metadata); } } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java index d9fdf936e5..c083c04e01 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java @@ -16,6 +16,10 @@ package com.android.bluetooth.btservice.storage; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; @@ -187,9 +191,9 @@ public final class BluetoothDatabaseMigration { final List<Integer> allowedValue = new ArrayList<>( Arrays.asList( - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)); + CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_FORBIDDEN, + CONNECTION_POLICY_ALLOWED)); for (Pair<Integer, String> p : CONNECTION_POLICIES) { final int policy = cursor.getInt(cursor.getColumnIndexOrThrow(p.second)); if (allowedValue.contains(policy)) { diff --git a/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java index c100a45495..4b224c24d0 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java @@ -117,7 +117,7 @@ class CustomizedMetadataEntity { return builder.toString(); } - private String metadataToString(byte[] metadata) { + private static String metadataToString(byte[] metadata) { if (metadata == null) { return null; } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java index 7874b066c2..d6490110f7 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java @@ -16,6 +16,10 @@ package com.android.bluetooth.btservice.storage; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import static java.util.Objects.requireNonNull; import android.bluetooth.BluetoothA2dp; @@ -363,9 +367,8 @@ public class DatabaseManager { * BluetoothProfile#VOLUME_CONTROL}, {@link BluetoothProfile#CSIP_SET_COORDINATOR}, {@link * BluetoothProfile#LE_AUDIO_BROADCAST_ASSISTANT}, * @param newConnectionPolicy the connectionPolicy to set; one of {@link - * BluetoothProfile.CONNECTION_POLICY_UNKNOWN}, {@link - * BluetoothProfile.CONNECTION_POLICY_FORBIDDEN}, {@link - * BluetoothProfile.CONNECTION_POLICY_ALLOWED} + * CONNECTION_POLICY_UNKNOWN}, {@link CONNECTION_POLICY_FORBIDDEN}, {@link + * CONNECTION_POLICY_ALLOWED} */ public boolean setProfileConnectionPolicy( BluetoothDevice device, int profile, int newConnectionPolicy) { @@ -374,9 +377,9 @@ public class DatabaseManager { return false; } - if (newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (newConnectionPolicy != CONNECTION_POLICY_UNKNOWN + && newConnectionPolicy != CONNECTION_POLICY_FORBIDDEN + && newConnectionPolicy != CONNECTION_POLICY_ALLOWED) { Log.e( TAG, "setProfileConnectionPolicy: invalid connection policy " + newConnectionPolicy); @@ -387,7 +390,7 @@ public class DatabaseManager { synchronized (mMetadataCache) { if (!mMetadataCache.containsKey(address)) { - if (newConnectionPolicy == BluetoothProfile.CONNECTION_POLICY_UNKNOWN) { + if (newConnectionPolicy == CONNECTION_POLICY_UNKNOWN) { return true; } createMetadata(address, false); @@ -434,14 +437,13 @@ public class DatabaseManager { * BluetoothProfile#VOLUME_CONTROL}, {@link BluetoothProfile#CSIP_SET_COORDINATOR}, {@link * BluetoothProfile#LE_AUDIO_BROADCAST_ASSISTANT}, * @return the profile connection policy of the device; one of {@link - * BluetoothProfile.CONNECTION_POLICY_UNKNOWN}, {@link - * BluetoothProfile.CONNECTION_POLICY_FORBIDDEN}, {@link - * BluetoothProfile.CONNECTION_POLICY_ALLOWED} + * CONNECTION_POLICY_UNKNOWN}, {@link CONNECTION_POLICY_FORBIDDEN}, {@link + * CONNECTION_POLICY_ALLOWED} */ public int getProfileConnectionPolicy(BluetoothDevice device, int profile) { if (device == null) { Log.e(TAG, "getProfileConnectionPolicy: device is null"); - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } String address = device.getAddress(); @@ -449,7 +451,7 @@ public class DatabaseManager { synchronized (mMetadataCache) { if (!mMetadataCache.containsKey(address)) { Log.d(TAG, "getProfileConnectionPolicy: device=" + device + " is not in cache"); - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } Metadata data = mMetadataCache.get(address); @@ -1319,62 +1321,62 @@ public class DatabaseManager { Settings.Global.getInt( contentResolver, getLegacyA2dpSinkPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int a2dpSinkConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyA2dpSrcPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int hearingaidConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyHearingAidPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int headsetConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyHeadsetPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int headsetClientConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyHeadsetPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int hidHostConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyHidHostPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int mapConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyMapPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int mapClientConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyMapClientPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int panConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyPanPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int pbapConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyPbapClientPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int pbapClientConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacyPbapClientPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int sapConnectionPolicy = Settings.Global.getInt( contentResolver, getLegacySapPriorityKey(device.getAddress()), - BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + CONNECTION_POLICY_UNKNOWN); int a2dpSupportsOptionalCodec = Settings.Global.getInt( contentResolver, @@ -1403,8 +1405,7 @@ public class DatabaseManager { data.setProfileConnectionPolicy(BluetoothProfile.SAP, sapConnectionPolicy); data.setProfileConnectionPolicy( BluetoothProfile.HEARING_AID, hearingaidConnectionPolicy); - data.setProfileConnectionPolicy( - BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + data.setProfileConnectionPolicy(BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_UNKNOWN); data.a2dpSupportsOptionalCodecs = a2dpSupportsOptionalCodec; data.a2dpOptionalCodecsEnabled = a2dpOptionalCodecEnabled; mMetadataCache.put(address, data); @@ -1588,4 +1589,48 @@ public class DatabaseManager { writer.println(" " + entry.getValue()); } } + + /** + * Update Key missing count. + * + * <p> It is used to update the key missing count when a bond loss is detected (increment the + * count) or a successful bond is detected (reset the count) + * + * @param isKeyMissingDetected true if the bond loss is detected, false if the bond is + * successfully established. + */ + public void updateKeyMissingCount(BluetoothDevice device, boolean isKeyMissingDetected) { + synchronized (mMetadataCache) { + String address = device.getAddress(); + + if (!mMetadataCache.containsKey(address)) { + Log.e(TAG, "device is not bonded"); + return; + } + + Metadata metadata = mMetadataCache.get(address); + if (isKeyMissingDetected) { + metadata.key_missing_count++; + Log.i(TAG, "Bond loss detected, count: " + metadata.key_missing_count); + } else { + metadata.key_missing_count = 0; + Log.i(TAG, "Successful bond detected, reset key missing count"); + } + updateDatabase(metadata); + } + } + + public int getKeyMissingCount(BluetoothDevice device) { + synchronized (mMetadataCache) { + String address = device.getAddress(); + + if (!mMetadataCache.containsKey(address)) { + Log.e(TAG, "device is not bonded"); + return -1; + } + + Metadata metadata = mMetadataCache.get(address); + return metadata.key_missing_count; + } + } } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java index 43bd50afb1..2e8aaa625e 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java @@ -16,6 +16,9 @@ package com.android.bluetooth.btservice.storage; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothA2dp.OptionalCodecsPreferenceStatus; import android.bluetooth.BluetoothA2dp.OptionalCodecsSupportStatus; @@ -32,7 +35,6 @@ import java.util.ArrayList; import java.util.List; @Entity(tableName = "metadata") - public class Metadata { @PrimaryKey @NonNull private String address; @@ -74,6 +76,9 @@ public class Metadata { /** This is used to indicate whether device's microphone prefer to use during calls */ public boolean is_preferred_microphone_for_calls; + /** This is used to indicate the number of times the bond has been lost */ + public int key_missing_count; + Metadata(String address) { this(address, false, false); } @@ -93,6 +98,7 @@ public class Metadata { preferred_duplex_profile = 0; active_audio_device_policy = BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT; is_preferred_microphone_for_calls = true; + key_missing_count = 0; } static final class Builder { @@ -138,9 +144,9 @@ public class Metadata { void setProfileConnectionPolicy(int profile, int connectionPolicy) { // We no longer support BluetoothProfile.PRIORITY_AUTO_CONNECT and are merging it into - // BluetoothProfile.CONNECTION_POLICY_ALLOWED - if (connectionPolicy > BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + // CONNECTION_POLICY_ALLOWED + if (connectionPolicy > CONNECTION_POLICY_ALLOWED) { + connectionPolicy = CONNECTION_POLICY_ALLOWED; } switch (profile) { @@ -247,7 +253,7 @@ public class Metadata { case BluetoothProfile.BATTERY: return profileConnectionPolicies.battery_connection_policy; } - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } void setCustomizedMeta(int key, byte[] value) { diff --git a/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java b/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java index 0a9df7f70d..00c52734a8 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java @@ -33,7 +33,7 @@ import java.util.List; /** MetadataDatabase is a Room database stores Bluetooth persistence data */ @Database( entities = {Metadata.class}, - version = 121) + version = 122) public abstract class MetadataDatabase extends RoomDatabase { /** The metadata database file name */ public static final String DATABASE_NAME = "bluetooth_db"; @@ -71,6 +71,7 @@ public abstract class MetadataDatabase extends RoomDatabase { .addMigrations(MIGRATION_118_119) .addMigrations(MIGRATION_119_120) .addMigrations(MIGRATION_120_121) + .addMigrations(MIGRATION_121_122) .allowMainThreadQueries() .build(); } @@ -694,4 +695,25 @@ public abstract class MetadataDatabase extends RoomDatabase { } } }; + + @VisibleForTesting + static final Migration MIGRATION_121_122 = + new Migration(121, 122) { + @Override + public void migrate(SupportSQLiteDatabase database) { + try { + database.execSQL( + "ALTER TABLE metadata ADD COLUMN" + + " `key_missing_count` INTEGER NOT NULL" + + " DEFAULT 0"); + } catch (SQLException ex) { + // Check if user has new schema, but is just missing the version update + Cursor cursor = database.query("SELECT * FROM metadata"); + if (cursor == null + || cursor.getColumnIndex("key_missing_count") == -1) { + throw ex; + } + } + } + }; } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java index 85ec34544b..5fb23b9267 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java @@ -16,7 +16,7 @@ package com.android.bluetooth.btservice.storage; -import android.bluetooth.BluetoothProfile; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import androidx.room.Entity; @@ -44,25 +44,25 @@ class ProfilePrioritiesEntity { public int battery_connection_policy; ProfilePrioritiesEntity() { - a2dp_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - a2dp_sink_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - hfp_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - hfp_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - hid_host_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - pan_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - pbap_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - pbap_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - map_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - sap_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - hearing_aid_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - hap_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - map_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - le_audio_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - volume_control_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - csip_set_coordinator_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - le_call_control_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - bass_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; - battery_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + a2dp_connection_policy = CONNECTION_POLICY_UNKNOWN; + a2dp_sink_connection_policy = CONNECTION_POLICY_UNKNOWN; + hfp_connection_policy = CONNECTION_POLICY_UNKNOWN; + hfp_client_connection_policy = CONNECTION_POLICY_UNKNOWN; + hid_host_connection_policy = CONNECTION_POLICY_UNKNOWN; + pan_connection_policy = CONNECTION_POLICY_UNKNOWN; + pbap_connection_policy = CONNECTION_POLICY_UNKNOWN; + pbap_client_connection_policy = CONNECTION_POLICY_UNKNOWN; + map_connection_policy = CONNECTION_POLICY_UNKNOWN; + sap_connection_policy = CONNECTION_POLICY_UNKNOWN; + hearing_aid_connection_policy = CONNECTION_POLICY_UNKNOWN; + hap_client_connection_policy = CONNECTION_POLICY_UNKNOWN; + map_client_connection_policy = CONNECTION_POLICY_UNKNOWN; + le_audio_connection_policy = CONNECTION_POLICY_UNKNOWN; + volume_control_connection_policy = CONNECTION_POLICY_UNKNOWN; + csip_set_coordinator_connection_policy = CONNECTION_POLICY_UNKNOWN; + le_call_control_connection_policy = CONNECTION_POLICY_UNKNOWN; + bass_client_connection_policy = CONNECTION_POLICY_UNKNOWN; + battery_connection_policy = CONNECTION_POLICY_UNKNOWN; } public String toString() { diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java index a4ebffcb74..5480a61463 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java @@ -58,14 +58,14 @@ public class CsipSetCoordinatorNativeInterface { return mAdapter.getRemoteDevice(address); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } return Utils.getBytesFromAddress(device.getAddress()); } - private void sendMessageToService(CsipSetCoordinatorStackEvent event) { + private static void sendMessageToService(CsipSetCoordinatorStackEvent event) { CsipSetCoordinatorService service = CsipSetCoordinatorService.getCsipSetCoordinatorService(); if (service != null) { diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java index 0e06d831b7..2b49f467a8 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java @@ -19,6 +19,11 @@ package com.android.bluetooth.csip; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -231,7 +236,7 @@ public class CsipSetCoordinatorService extends ProfileService { return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { return false; } final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device); @@ -306,8 +311,8 @@ public class CsipSetCoordinatorService extends ProfileService { if (bondState != BluetoothDevice.BOND_BONDED) { Log.w(TAG, "okToConnect: return false, bondState=" + bondState); return false; - } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -330,7 +335,7 @@ public class CsipSetCoordinatorService extends ProfileService { if (!Utils.arrayContains(featureUuids, BluetoothUuid.COORDINATED_SET)) { continue; } - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; CsipSetCoordinatorStateMachine sm = mStateMachines.get(device); if (sm != null) { connectionState = sm.getConnectionState(); @@ -401,7 +406,7 @@ public class CsipSetCoordinatorService extends ProfileService { synchronized (mStateMachines) { CsipSetCoordinatorStateMachine sm = mStateMachines.get(device); if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -425,9 +430,9 @@ public class CsipSetCoordinatorService extends ProfileService { Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy); mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.CSIP_SET_COORDINATOR, connectionPolicy); - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -674,14 +679,14 @@ public class CsipSetCoordinatorService extends ProfileService { } for (BluetoothDevice groupDevice : mGroupIdToConnectedDevices.get(groupId)) { if (mLeAudioService.getConnectionPolicy(groupDevice) - == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + == CONNECTION_POLICY_FORBIDDEN) { Log.i( TAG, "Setting CSIP connection policy to FORBIDDEN for device " + groupDevice + " after all group devices bonded because LEA " + "connection policy is FORBIDDEN"); - setConnectionPolicy(groupDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + setConnectionPolicy(groupDevice, CONNECTION_POLICY_FORBIDDEN); } } } else { @@ -689,7 +694,7 @@ public class CsipSetCoordinatorService extends ProfileService { } } - private void executeCallback( + private static void executeCallback( Executor exec, IBluetoothCsipSetCoordinatorCallback callback, BluetoothDevice device, @@ -914,7 +919,7 @@ public class CsipSetCoordinatorService extends ProfileService { if (sm == null) { return; } - if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (sm.getConnectionState() != STATE_DISCONNECTED) { Log.i(TAG, "Disconnecting device because it was unbonded."); disconnect(device); return; @@ -963,13 +968,13 @@ public class CsipSetCoordinatorService extends ProfileService { } // Check if the device is disconnected - if unbond, remove the state machine - if (toState == BluetoothProfile.STATE_DISCONNECTED) { + if (toState == STATE_DISCONNECTED) { int bondState = mAdapterService.getBondState(device); if (bondState == BluetoothDevice.BOND_NONE) { Log.d(TAG, device + " is unbond. Remove state machine"); removeStateMachine(device); } - } else if (toState == BluetoothProfile.STATE_CONNECTED) { + } else if (toState == STATE_CONNECTED) { int groupId = getGroupId(device, BluetoothUuid.CAP); if (!mGroupIdToConnectedDevices.containsKey(groupId)) { mGroupIdToConnectedDevices.put(groupId, new HashSet<>()); @@ -1053,7 +1058,7 @@ public class CsipSetCoordinatorService extends ProfileService { CsipSetCoordinatorService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -1080,7 +1085,7 @@ public class CsipSetCoordinatorService extends ProfileService { CsipSetCoordinatorService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } return service.getConnectionPolicy(device); diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java index 1e72275324..8a9953dbb7 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java @@ -18,6 +18,11 @@ package com.android.bluetooth.csip; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; +import static android.bluetooth.BluetoothProfile.getConnectionStateName; import android.bluetooth.BluetoothCsipSetCoordinator; import android.bluetooth.BluetoothDevice; @@ -125,7 +130,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { removeDeferredMessages(DISCONNECT); if (mLastConnectionState != -1) { - csipConnectionState(BluetoothProfile.STATE_DISCONNECTED, mLastConnectionState); + csipConnectionState(STATE_DISCONNECTED, mLastConnectionState); } } @@ -136,7 +141,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -248,7 +253,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - csipConnectionState(BluetoothProfile.STATE_CONNECTING, mLastConnectionState); + csipConnectionState(STATE_CONNECTING, mLastConnectionState); } @Override @@ -258,7 +263,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -346,7 +351,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - csipConnectionState(BluetoothProfile.STATE_DISCONNECTING, mLastConnectionState); + csipConnectionState(STATE_DISCONNECTING, mLastConnectionState); } @Override @@ -356,7 +361,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING; + mLastConnectionState = STATE_DISCONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -463,7 +468,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); removeDeferredMessages(CONNECT); - csipConnectionState(BluetoothProfile.STATE_CONNECTED, mLastConnectionState); + csipConnectionState(STATE_CONNECTED, mLastConnectionState); } @Override @@ -473,7 +478,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } @Override @@ -545,16 +550,16 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { String currentState = getCurrentState().getName(); switch (currentState) { case "Disconnected": - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case "Connecting": - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; case "Connected": - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; case "Disconnecting": - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; default: Log.e(TAG, "Bad currentState: " + currentState); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } @@ -564,9 +569,9 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { "Connection state " + mDevice + ": " - + profileStateToString(prevState) + + getConnectionStateName(prevState) + "->" - + profileStateToString(newState)); + + getConnectionStateName(newState)); mService.handleConnectionStateChanged(mDevice, prevState, newState); Intent intent = @@ -596,22 +601,6 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { return Integer.toString(what); } - private static String profileStateToString(int state) { - switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: - return "DISCONNECTED"; - case BluetoothProfile.STATE_CONNECTING: - return "CONNECTING"; - case BluetoothProfile.STATE_CONNECTED: - return "CONNECTED"; - case BluetoothProfile.STATE_DISCONNECTING: - return "DISCONNECTING"; - default: - break; - } - return Integer.toString(state); - } - /** Dump the state machine logs */ public void dump(StringBuilder sb) { ProfileService.println(sb, "mDevice: " + mDevice); diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java index 4a1ec59a2a..0f28f6742c 100644 --- a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java +++ b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java @@ -671,7 +671,7 @@ public class AdvertiseManager { } } - private void sendToCallback(int advertiserId, CallbackWrapper wrapper) { + private static void sendToCallback(int advertiserId, CallbackWrapper wrapper) { try { wrapper.call(); } catch (RemoteException e) { diff --git a/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java b/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java index 1746194f17..4656976850 100644 --- a/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java +++ b/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java @@ -224,7 +224,7 @@ class AppAdvertiseStats { MetricsLogger.getInstance().cacheCount(BluetoothProtoEnums.LE_ADV_ERROR_ON_START_COUNT, 1); } - private int convertStatusCode(int status) { + private static int convertStatusCode(int status) { switch (status) { case AdvertisingSetCallback.ADVERTISE_SUCCESS: return BluetoothStatsLog.LE_ADV_ERROR_REPORTED__STATUS_CODE__ADV_STATUS_SUCCESS; @@ -444,7 +444,7 @@ class AppAdvertiseStats { } } - private int convertAdvInterval(int interval) { + private static int convertAdvInterval(int interval) { switch (interval) { case AdvertisingSetParameters.INTERVAL_HIGH: return BluetoothStatsLog.LE_ADV_STATE_CHANGED__ADV_INTERVAL__INTERVAL_HIGH; @@ -457,7 +457,7 @@ class AppAdvertiseStats { } } - private int convertTxPowerLevel(int level) { + private static int convertTxPowerLevel(int level) { switch (level) { case AdvertisingSetParameters.TX_POWER_ULTRA_LOW: return BluetoothStatsLog.LE_ADV_STATE_CHANGED__ADV_TX_POWER__TX_POWER_ULTRA_LOW; diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java index abadff3ad7..04c6f7fff8 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java @@ -337,7 +337,7 @@ public class DistanceMeasurementManager { return BluetoothStatusCodes.SUCCESS; } - private void invokeStartFail( + private static void invokeStartFail( IDistanceMeasurementCallback callback, BluetoothDevice device, int reason) { try { callback.onStartFail(device, reason); @@ -346,7 +346,7 @@ public class DistanceMeasurementManager { } } - private void invokeOnStopped( + private static void invokeOnStopped( IDistanceMeasurementCallback callback, BluetoothDevice device, int reason) { try { callback.onStopped(device, reason); @@ -356,7 +356,7 @@ public class DistanceMeasurementManager { } /** Convert frequency into interval in ms */ - private int getIntervalValue(int frequency, int method) { + private static int getIntervalValue(int frequency, int method) { switch (method) { case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_AUTO: case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI: diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java index ad8a7f9bd4..5992a7b9ce 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java @@ -127,7 +127,7 @@ public class DistanceMeasurementNativeInterface { method); } - private int convertErrorCode(int errorCode) { + private static int convertErrorCode(int errorCode) { switch (errorCode) { case REASON_FEATURE_NOT_SUPPORTED_LOCAL: return BluetoothStatusCodes.FEATURE_NOT_SUPPORTED; diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java index fe7aaecfdb..02099f9b8e 100644 --- a/android/app/src/com/android/bluetooth/gatt/GattService.java +++ b/android/app/src/com/android/bluetooth/gatt/GattService.java @@ -19,6 +19,8 @@ package com.android.bluetooth.gatt; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.Utils.callerIsSystemOrActiveOrManagedUser; import static com.android.bluetooth.Utils.checkCallerTargetSdk; @@ -1472,7 +1474,7 @@ public class GattService extends ProfileService { BluetoothDevice[] bondedDevices = mAdapterService.getBondedDevices(); for (BluetoothDevice device : bondedDevices) { if (getDeviceType(device) != AbstractionLayer.BT_DEVICE_TYPE_BREDR) { - deviceStates.put(device, BluetoothProfile.STATE_DISCONNECTED); + deviceStates.put(device, STATE_DISCONNECTED); } } @@ -1485,7 +1487,7 @@ public class GattService extends ProfileService { for (String address : connectedDevices) { BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address); if (device != null) { - deviceStates.put(device, BluetoothProfile.STATE_CONNECTED); + deviceStates.put(device, STATE_CONNECTED); } } @@ -2982,11 +2984,11 @@ public class GattService extends ProfileService { * Private functions *************************************************************************/ - private boolean isHidSrvcUuid(final UUID uuid) { + private static boolean isHidSrvcUuid(final UUID uuid) { return HID_SERVICE_UUID.equals(uuid); } - private boolean isHidCharUuid(final UUID uuid) { + private static boolean isHidCharUuid(final UUID uuid) { for (UUID hidUuid : HID_UUIDS) { if (hidUuid.equals(uuid)) { return true; @@ -2995,15 +2997,15 @@ public class GattService extends ProfileService { return false; } - private boolean isAndroidTvRemoteSrvcUuid(final UUID uuid) { + private static boolean isAndroidTvRemoteSrvcUuid(final UUID uuid) { return ANDROID_TV_REMOTE_SERVICE_UUID.equals(uuid); } - private boolean isFidoSrvcUuid(final UUID uuid) { + private static boolean isFidoSrvcUuid(final UUID uuid) { return FIDO_SERVICE_UUID.equals(uuid); } - private boolean isLeAudioSrvcUuid(final UUID uuid) { + private static boolean isLeAudioSrvcUuid(final UUID uuid) { for (UUID leAudioUuid : LE_AUDIO_SERVICE_UUIDS) { if (leAudioUuid.equals(uuid)) { return true; @@ -3012,11 +3014,11 @@ public class GattService extends ProfileService { return false; } - private boolean isAndroidHeadtrackerSrvcUuid(final UUID uuid) { + private static boolean isAndroidHeadtrackerSrvcUuid(final UUID uuid) { return HidHostService.ANDROID_HEADTRACKER_UUID.getUuid().equals(uuid); } - private boolean isRestrictedSrvcUuid(final UUID uuid) { + private static boolean isRestrictedSrvcUuid(final UUID uuid) { return isFidoSrvcUuid(uuid) || isAndroidTvRemoteSrvcUuid(uuid) || isLeAudioSrvcUuid(uuid) diff --git a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java index 5c1dca5464..97bd4e9f9e 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java @@ -18,6 +18,10 @@ package com.android.bluetooth.hap; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -26,7 +30,6 @@ import android.bluetooth.BluetoothCsipSetCoordinator; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHapClient; import android.bluetooth.BluetoothHapPresetInfo; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothHapClient; import android.bluetooth.IBluetoothHapClientCallback; import android.content.AttributionSource; @@ -102,7 +105,7 @@ class HapClientBinder extends IBluetoothHapClient.Stub public int getConnectionState(BluetoothDevice device, AttributionSource source) { HapClientService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } requireNonNull(device); @@ -119,8 +122,8 @@ class HapClientBinder extends IBluetoothHapClient.Stub } requireNonNull(device); - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connectionPolicy != CONNECTION_POLICY_ALLOWED + && connectionPolicy != CONNECTION_POLICY_FORBIDDEN) { throw new IllegalArgumentException( "Invalid connectionPolicy value: " + connectionPolicy); } @@ -132,7 +135,7 @@ class HapClientBinder extends IBluetoothHapClient.Stub public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { HapClientService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } requireNonNull(device); diff --git a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java index 6160e4efa9..42d234c346 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java @@ -43,7 +43,7 @@ public class HapClientNativeInterface { return disconnectHapClientNative(getByteAddress(device)); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java index e4c020f61b..ae8d4b6dec 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientService.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java @@ -19,8 +19,12 @@ package com.android.bluetooth.hap; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -225,7 +229,7 @@ public class HapClientService extends ProfileService { if (sm == null) { return; } - if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (sm.getConnectionState() != STATE_DISCONNECTED) { Log.i(TAG, "Disconnecting device because it was unbonded."); disconnect(device); return; @@ -264,7 +268,7 @@ public class HapClientService extends ProfileService { if (!Utils.arrayContains(featureUuids, BluetoothUuid.HAS)) { continue; } - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; HapClientStateMachine sm = mStateMachines.get(device); if (sm != null) { connectionState = sm.getConnectionState(); @@ -308,7 +312,7 @@ public class HapClientService extends ProfileService { synchronized (mStateMachines) { HapClientStateMachine sm = mStateMachines.get(device); if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -332,9 +336,9 @@ public class HapClientService extends ProfileService { Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy); mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.HAP_CLIENT, connectionPolicy); - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -369,8 +373,8 @@ public class HapClientService extends ProfileService { if (bondState != BluetoothDevice.BOND_BONDED) { Log.w(TAG, "okToConnect: return false, bondState=" + bondState); return false; - } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -392,7 +396,7 @@ public class HapClientService extends ProfileService { } // Check if the device is disconnected - if unbond, remove the state machine - if (toState == BluetoothProfile.STATE_DISCONNECTED) { + if (toState == STATE_DISCONNECTED) { int bondState = mAdapterService.getBondState(device); if (bondState == BluetoothDevice.BOND_NONE) { Log.d(TAG, device + " is unbond. Remove state machine"); @@ -418,7 +422,7 @@ public class HapClientService extends ProfileService { return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { return false; } final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device); @@ -620,7 +624,7 @@ public class HapClientService extends ProfileService { return 0x00; } - private int stackEventPresetInfoReasonToProfileStatus(int statusCode) { + private static int stackEventPresetInfoReasonToProfileStatus(int statusCode) { return switch (statusCode) { case HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO -> BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST; @@ -648,7 +652,7 @@ public class HapClientService extends ProfileService { stackEventPresetInfoReasonToProfileStatus(infoReason))); } - private int stackEventStatusToProfileStatus(int statusCode) { + private static int stackEventStatusToProfileStatus(int statusCode) { return switch (statusCode) { case HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED -> BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED; diff --git a/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java b/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java index a0e978ef1d..02e03f88c9 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java @@ -101,7 +101,7 @@ public class HapClientStackEvent { return result.toString(); } - private String eventTypeValueListToString(int type, List value) { + private static String eventTypeValueListToString(int type, List value) { switch (type) { case EVENT_TYPE_ON_PRESET_INFO: return "{presets count: " + (value == null ? 0 : value.size()) + "}"; @@ -110,7 +110,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt1ToString(int type, int value) { + private static String eventTypeValueInt1ToString(int type, int value) { switch (type) { case EVENT_TYPE_CONNECTION_STATE_CHANGED: return "{state: " + getConnectionStateName(value) + "}"; @@ -132,7 +132,7 @@ public class HapClientStackEvent { } } - private String infoReasonToString(int value) { + private static String infoReasonToString(int value) { switch (value) { case PRESET_INFO_REASON_ALL_PRESET_INFO: return "PRESET_INFO_REASON_ALL_PRESET_INFO"; @@ -149,7 +149,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt2ToString(int type, int value) { + private static String eventTypeValueInt2ToString(int type, int value) { switch (type) { case EVENT_TYPE_ON_PRESET_NAME_SET_ERROR: return "{presetIndex: " + value + "}"; @@ -166,7 +166,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt3ToString(int type, int value) { + private static String eventTypeValueInt3ToString(int type, int value) { switch (type) { case EVENT_TYPE_ON_PRESET_INFO: case EVENT_TYPE_ON_PRESET_INFO_ERROR: @@ -177,7 +177,7 @@ public class HapClientStackEvent { } } - private String statusCodeValueToString(int value) { + private static String statusCodeValueToString(int value) { switch (value) { case STATUS_NO_ERROR: return "STATUS_NO_ERROR"; @@ -200,7 +200,7 @@ public class HapClientStackEvent { } } - private String featuresToString(int value) { + private static String featuresToString(int value) { StringBuilder features_sb = new StringBuilder(); if (BigInteger.valueOf(value).testBit(FEATURE_BIT_NUM_TYPE_MONAURAL)) { features_sb.append("TYPE_MONAURAL"); diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java index a57557c1b5..a69c265c78 100644 --- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java +++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java @@ -18,6 +18,9 @@ package com.android.bluetooth.hearingaid; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -206,7 +209,7 @@ public class HearingAidService extends ProfileService { return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { return false; } final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device); @@ -346,8 +349,8 @@ public class HearingAidService extends ProfileService { return false; } } - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -452,9 +455,9 @@ public class HearingAidService extends ProfileService { device, BluetoothProfile.HEARING_AID, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -989,7 +992,7 @@ public class HearingAidService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { HearingAidService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); diff --git a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java index 1d58cdb3a2..8e2d0bd09f 100644 --- a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java +++ b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java @@ -506,7 +506,7 @@ public class AtPhonebook { return roundUpToPowerOfTwo(maxSize); } - private int roundUpToPowerOfTwo(int x) { + private static int roundUpToPowerOfTwo(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java index cde10203fd..9dbcd6d4e8 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java @@ -71,12 +71,12 @@ public class HeadsetNativeInterface { } } - private void sendMessageToService(HeadsetStackEvent event) { + private static void sendMessageToService(HeadsetStackEvent event) { HeadsetService service = HeadsetService.getHeadsetService(); if (service != null) { service.messageFromNative(event); } else { - // Service must call cleanup() when quiting and native stack shouldn't send any event + // Service must call cleanup() when quitting and native stack shouldn't send any event // after cleanup() -> cleanupNative() is called. Log.w(TAG, "Stack sent event while service is not available: " + event); } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java index 5155efbbcf..7825d64426 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java @@ -19,6 +19,12 @@ package com.android.bluetooth.hfp; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.MODIFY_PHONE_STATE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.media.audio.Flags.deprecateStreamBtSco; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -120,9 +126,7 @@ public class HeadsetService extends ProfileService { private static final String REJECT_SCO_IF_HFPC_CONNECTED_PROPERTY = "bluetooth.hfp.reject_sco_if_hfpc_connected"; private static final ParcelUuid[] HEADSET_UUIDS = {BluetoothUuid.HSP, BluetoothUuid.HFP}; - private static final int[] CONNECTING_CONNECTED_STATES = { - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED - }; + private static final int[] CONNECTING_CONNECTED_STATES = {STATE_CONNECTING, STATE_CONNECTED}; private static final int DIALING_OUT_TIMEOUT_MS = 10000; private static final int CLCC_END_MARK_INDEX = 0; @@ -505,7 +509,7 @@ public class HeadsetService extends ProfileService { if (stateMachine == null) { return; } - if (stateMachine.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (stateMachine.getConnectionState() != STATE_DISCONNECTED) { return; } removeStateMachine(device); @@ -590,7 +594,7 @@ public class HeadsetService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { HeadsetService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -613,7 +617,7 @@ public class HeadsetService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { HeadsetService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); @@ -846,7 +850,7 @@ public class HeadsetService extends ProfileService { } public boolean connect(BluetoothDevice device) { - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.w( TAG, "connect: CONNECTION_POLICY_FORBIDDEN, device=" @@ -881,8 +885,7 @@ public class HeadsetService extends ProfileService { mStateMachines.put(device, stateMachine); } int connectionState = stateMachine.getConnectionState(); - if (connectionState == BluetoothProfile.STATE_CONNECTED - || connectionState == BluetoothProfile.STATE_CONNECTING) { + if (connectionState == STATE_CONNECTED || connectionState == STATE_CONNECTING) { Log.w( TAG, "connect: device " @@ -929,8 +932,7 @@ public class HeadsetService extends ProfileService { return false; } int connectionState = stateMachine.getConnectionState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { Log.w( TAG, "disconnect: device " @@ -948,7 +950,7 @@ public class HeadsetService extends ProfileService { ArrayList<BluetoothDevice> devices = new ArrayList<>(); synchronized (mStateMachines) { for (HeadsetStateMachine stateMachine : mStateMachines.values()) { - if (stateMachine.getConnectionState() == BluetoothProfile.STATE_CONNECTED) { + if (stateMachine.getConnectionState() == STATE_CONNECTED) { devices.add(stateMachine.getDevice()); } } @@ -994,7 +996,7 @@ public class HeadsetService extends ProfileService { synchronized (mStateMachines) { final HeadsetStateMachine stateMachine = mStateMachines.get(device); if (stateMachine == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return stateMachine.getConnectionState(); } @@ -1028,9 +1030,9 @@ public class HeadsetService extends ProfileService { device, BluetoothProfile.HEADSET, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -1129,8 +1131,7 @@ public class HeadsetService extends ProfileService { return false; } int connectionState = stateMachine.getConnectionState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { Log.w(TAG, "startVoiceRecognition: " + device + " is not connected or connecting"); return false; } @@ -1203,8 +1204,7 @@ public class HeadsetService extends ProfileService { return false; } int connectionState = stateMachine.getConnectionState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { Log.w(TAG, "stopVoiceRecognition: " + device + " is not connected or connecting"); return false; } @@ -1357,7 +1357,7 @@ public class HeadsetService extends ProfileService { BluetoothDevice fallbackDevice = getFallbackDevice(); if (fallbackDevice != null && mActiveDevice != null - && getConnectionState(mActiveDevice) != BluetoothProfile.STATE_CONNECTED) { + && getConnectionState(mActiveDevice) != STATE_CONNECTED) { setActiveDevice(fallbackDevice); return; } @@ -1428,7 +1428,7 @@ public class HeadsetService extends ProfileService { Log.i(TAG, "setActiveDevice: device " + device + " is already active"); return true; } - if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState(device) != STATE_CONNECTED) { Log.e( TAG, "setActiveDevice: Cannot set " @@ -1563,7 +1563,7 @@ public class HeadsetService extends ProfileService { Log.w(TAG, "connectAudio, rejected SCO request to " + device); return scoConnectionAllowedState; } - if (stateMachine.getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (stateMachine.getConnectionState() != STATE_CONNECTED) { Log.w(TAG, "connectAudio: profile not connected"); return BluetoothStatusCodes.ERROR_PROFILE_NOT_CONNECTED; } @@ -2053,8 +2053,7 @@ public class HeadsetService extends ProfileService { BluetoothDevice fallbackDevice = getFallbackDevice(); if (fallbackDevice != null - && getConnectionState(fallbackDevice) - == BluetoothProfile.STATE_CONNECTED) { + && getConnectionState(fallbackDevice) == STATE_CONNECTED) { Log.d( TAG, "BluetoothSinkAudioPolicy set fallbackDevice=" @@ -2094,7 +2093,7 @@ public class HeadsetService extends ProfileService { return false; } int connectionState = stateMachine.getConnectionState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } // Currently we support only "+ANDROID". @@ -2140,7 +2139,7 @@ public class HeadsetService extends ProfileService { && !isHeadsetClientConnected(); } - private boolean isHeadsetClientConnected() { + private static boolean isHeadsetClientConnected() { HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); if (headsetClientService == null) { return false; @@ -2159,13 +2158,11 @@ public class HeadsetService extends ProfileService { @VisibleForTesting public void onConnectionStateChangedFromStateMachine( BluetoothDevice device, int fromState, int toState) { - if (fromState != BluetoothProfile.STATE_CONNECTED - && toState == BluetoothProfile.STATE_CONNECTED) { + if (fromState != STATE_CONNECTED && toState == STATE_CONNECTED) { updateInbandRinging(device, true); MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HEADSET); } - if (fromState != BluetoothProfile.STATE_DISCONNECTED - && toState == BluetoothProfile.STATE_DISCONNECTED) { + if (fromState != STATE_DISCONNECTED && toState == STATE_DISCONNECTED) { updateInbandRinging(device, false); if (device.equals(mActiveDevice)) { setActiveDevice(null); @@ -2270,10 +2267,10 @@ public class HeadsetService extends ProfileService { mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO); int ashaPolicy = mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.HEARING_AID); - return hfpPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED - && a2dpPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED - && leAudioPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED - && ashaPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED; + return hfpPolicy == CONNECTION_POLICY_ALLOWED + && a2dpPolicy != CONNECTION_POLICY_ALLOWED + && leAudioPolicy != CONNECTION_POLICY_ALLOWED + && ashaPolicy != CONNECTION_POLICY_ALLOWED; } private boolean shouldCallAudioBeActive() { @@ -2503,8 +2500,8 @@ public class HeadsetService extends ProfileService { return false; } } - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connection policy is not valid. if (!isOutgoingRequest) { A2dpService a2dpService = A2dpService.getA2dpService(); diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java index bc2feb9c55..d8391f68c0 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java @@ -19,6 +19,10 @@ package com.android.bluetooth.hfp; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.bluetooth.BluetoothDevice.ACCESS_ALLOWED; import static android.bluetooth.BluetoothDevice.ACCESS_REJECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.media.audio.Flags.deprecateStreamBtSco; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -545,7 +549,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnected extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @Override @@ -573,6 +577,13 @@ class HeadsetStateMachine extends StateMachine { && mAdapterService.getBondState(mDevice) == BluetoothDevice.BOND_NONE) { getHandler().post(() -> mHeadsetService.removeStateMachine(mDevice)); } + + if (mPrevState == mConnecting) { + logHfpSessionMetric( + mDevice, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECT_FAIL); + } } @Override @@ -581,6 +592,10 @@ class HeadsetStateMachine extends StateMachine { case CONNECT: BluetoothDevice device = (BluetoothDevice) message.obj; stateLogD("Connecting to " + device); + logHfpSessionMetric( + device, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__START_LOCAL_INITIATED); if (!mDevice.equals(device)) { stateLogE( "CONNECT failed, device=" + device + ", currentDevice=" + mDevice); @@ -589,16 +604,17 @@ class HeadsetStateMachine extends StateMachine { if (!mNativeInterface.connectHfp(device)) { stateLogE("CONNECT failed for connectHfp(" + device + ")"); // No state transition is involved, fire broadcast immediately - broadcastConnectionState( + logHfpSessionMetric( device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECT_FAIL); + broadcastConnectionState(device, STATE_DISCONNECTED, STATE_DISCONNECTED); BluetoothStatsLog.write( BluetoothStatsLog.BLUETOOTH_PROFILE_CONNECTION_ATTEMPTED, BluetoothProfile.HEADSET, BluetoothProtoEnums.RESULT_FAILURE, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, + STATE_DISCONNECTED, BluetoothProtoEnums.REASON_NATIVE_LAYER_REJECTED, MetricsLogger.getInstance().getRemoteDeviceInfoProto(mDevice)); break; @@ -653,6 +669,10 @@ class HeadsetStateMachine extends StateMachine { case HeadsetHalConstants.CONNECTION_STATE_CONNECTING: if (mHeadsetService.okToAcceptConnection(mDevice, false)) { stateLogI("accept incoming connection"); + logHfpSessionMetric( + mDevice, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__START_REMOTE_INITIATED); transitionTo(mConnecting); } else { stateLogI( @@ -665,18 +685,19 @@ class HeadsetStateMachine extends StateMachine { stateLogE("failed to disconnect"); } // Indicate rejection to other components. - broadcastConnectionState( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionState(mDevice, STATE_DISCONNECTED, STATE_DISCONNECTED); BluetoothStatsLog.write( BluetoothStatsLog.BLUETOOTH_PROFILE_CONNECTION_ATTEMPTED, BluetoothProfile.HEADSET, BluetoothProtoEnums.RESULT_FAILURE, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, + STATE_DISCONNECTED, BluetoothProtoEnums.REASON_INCOMING_CONN_REJECTED, MetricsLogger.getInstance().getRemoteDeviceInfoProto(mDevice)); + logHfpSessionMetric( + mDevice, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECT_REJECT_FAIL); } break; case HeadsetHalConstants.CONNECTION_STATE_DISCONNECTING: @@ -702,7 +723,7 @@ class HeadsetStateMachine extends StateMachine { BluetoothProfile.HEADSET, result, mPrevState.getConnectionStateInt(), - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, BluetoothProtoEnums.REASON_UNEXPECTED_STATE, MetricsLogger.getInstance().getRemoteDeviceInfoProto(mDevice)); } @@ -716,7 +737,7 @@ class HeadsetStateMachine extends StateMachine { class Connecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } @Override @@ -749,6 +770,10 @@ class HeadsetStateMachine extends StateMachine { break; } stateLogW("CONNECT_TIMEOUT"); + logHfpSessionMetric( + device, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__CONNECTION_TIMEOUT); transitionTo(mDisconnected); break; } @@ -898,7 +923,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; } @Override @@ -989,7 +1014,7 @@ class HeadsetStateMachine extends StateMachine { private abstract class ConnectedBase extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } /** @@ -1285,6 +1310,9 @@ class HeadsetStateMachine extends StateMachine { broadcastStateTransitions(); logSuccessIfNeeded(); + logHfpSessionMetric( + mDevice, + BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECTED); } @Override @@ -1308,10 +1336,7 @@ class HeadsetStateMachine extends StateMachine { if (!mNativeInterface.disconnectHfp(device)) { // broadcast immediately as no state transition is involved stateLogE("DISCONNECT from " + device + " failed"); - broadcastConnectionState( - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTED); + broadcastConnectionState(device, STATE_CONNECTED, STATE_CONNECTED); break; } transitionTo(mDisconnecting); @@ -1421,7 +1446,7 @@ class HeadsetStateMachine extends StateMachine { BluetoothProfile.HEADSET, BluetoothProtoEnums.RESULT_SUCCESS, mPrevState.getConnectionStateInt(), - BluetoothProfile.STATE_CONNECTED, + STATE_CONNECTED, BluetoothProtoEnums.REASON_SUCCESS, MetricsLogger.getInstance().getRemoteDeviceInfoProto(mDevice)); } @@ -2843,4 +2868,14 @@ class HeadsetStateMachine extends StateMachine { return "UNKNOWN(" + what + ")"; } } + + private static void logHfpSessionMetric(BluetoothDevice device, int state) { + MetricsLogger.getInstance() + .logBluetoothEvent( + device, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__HFP_SESSION, + state, + 0); + } } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java index 6bbb32d105..78e350fc37 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java @@ -68,7 +68,7 @@ class HeadsetSystemInterface { mTelecomManager = mHeadsetService.getSystemService(TelecomManager.class); } - private BluetoothInCallService getBluetoothInCallServiceInstance() { + private static BluetoothInCallService getBluetoothInCallServiceInstance() { return BluetoothInCallService.getInstance(); } diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java index 83c0d90f7a..022351faef 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java @@ -18,6 +18,12 @@ package com.android.bluetooth.hfpclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.content.pm.PackageManager.FEATURE_WATCH; import static java.util.Objects.requireNonNull; @@ -366,7 +372,7 @@ public class HeadsetClientService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { HeadsetClientService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } service.enforceCallingPermission(BLUETOOTH_PRIVILEGED, null); @@ -391,7 +397,7 @@ public class HeadsetClientService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { HeadsetClientService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingPermission(BLUETOOTH_PRIVILEGED, null); @@ -640,7 +646,7 @@ public class HeadsetClientService extends ProfileService { public boolean connect(BluetoothDevice device) { Log.d(TAG, "connect " + device); - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.w( TAG, "Connection not allowed: <" @@ -672,8 +678,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } @@ -689,7 +694,7 @@ public class HeadsetClientService extends ProfileService { synchronized (mStateMachineMap) { for (BluetoothDevice bd : mStateMachineMap.keySet()) { HeadsetClientStateMachine sm = mStateMachineMap.get(bd); - if (sm != null && sm.getConnectionState(bd) == BluetoothProfile.STATE_CONNECTED) { + if (sm != null && sm.getConnectionState(bd) == STATE_CONNECTED) { connectedDevices.add(bd); } } @@ -727,7 +732,7 @@ public class HeadsetClientService extends ProfileService { return sm.getConnectionState(device); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -751,9 +756,9 @@ public class HeadsetClientService extends ProfileService { device, BluetoothProfile.HEADSET_CLIENT, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -780,7 +785,7 @@ public class HeadsetClientService extends ProfileService { return false; } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } sm.sendMessage(HeadsetClientStateMachine.VOICE_RECOGNITION_START); @@ -794,7 +799,7 @@ public class HeadsetClientService extends ProfileService { return false; } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } sm.sendMessage(HeadsetClientStateMachine.VOICE_RECOGNITION_STOP); @@ -934,8 +939,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } Message msg = sm.obtainMessage(HeadsetClientStateMachine.HOLD_CALL); @@ -958,7 +962,7 @@ public class HeadsetClientService extends ProfileService { + device + ". Possibly disconnecting on " + entry.getValue()); - if (connectionState == BluetoothProfile.STATE_CONNECTED) { + if (connectionState == STATE_CONNECTED) { entry.getValue() .obtainMessage(HeadsetClientStateMachine.TERMINATE_CALL) .sendToTarget(); @@ -972,7 +976,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } Message msg = sm.obtainMessage(HeadsetClientStateMachine.ACCEPT_CALL); @@ -989,8 +993,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } @@ -1007,8 +1010,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } @@ -1026,8 +1028,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } @@ -1045,8 +1046,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return null; } @@ -1082,8 +1082,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } Message msg = sm.obtainMessage(HeadsetClientStateMachine.SEND_DTMF); @@ -1104,7 +1103,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return null; } return sm.getCurrentCalls(); @@ -1118,8 +1117,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } Message msg = sm.obtainMessage(HeadsetClientStateMachine.EXPLICIT_CALL_TRANSFER); @@ -1136,7 +1134,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } @@ -1155,7 +1153,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return null; } return sm.getCurrentAgEvents(); @@ -1168,7 +1166,7 @@ public class HeadsetClientService extends ProfileService { return null; } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return null; } return sm.getCurrentAgFeaturesBundle(); @@ -1181,7 +1179,7 @@ public class HeadsetClientService extends ProfileService { return null; } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return null; } return sm.getCurrentAgFeatures(); @@ -1200,7 +1198,7 @@ public class HeadsetClientService extends ProfileService { sm.sendMessage(StackEvent.STACK_EVENT, stackEvent); } - private boolean isConnectionEvent(StackEvent stackEvent) { + private static boolean isConnectionEvent(StackEvent stackEvent) { if (stackEvent.type == StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED) { if ((stackEvent.valueInt == HeadsetClientHalConstants.CONNECTION_STATE_CONNECTING) || (stackEvent.valueInt diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java index 553628da1e..9cf8237e09 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java @@ -38,7 +38,7 @@ public class HeadsetClientServiceInterface { public HeadsetClientServiceInterface() {} - private boolean isServiceAvailable(HeadsetClientService service) { + private static boolean isServiceAvailable(HeadsetClientService service) { if (service == null) { Log.w(TAG, "HeadsetClientService is not available"); return false; diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java index 123cf5eb7a..5ded2f9bb7 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java @@ -33,6 +33,12 @@ package com.android.bluetooth.hfpclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.content.pm.PackageManager.FEATURE_WATCH; import static java.util.Objects.requireNonNull; @@ -881,7 +887,7 @@ public class HeadsetClientStateMachine extends StateMachine { return features; } - private boolean isSupported(int bitfield, int mask) { + private static boolean isSupported(int bitfield, int mask) { return (bitfield & mask) == mask; } @@ -1053,21 +1059,13 @@ public class HeadsetClientStateMachine extends StateMachine { removeMessages(QUERY_CURRENT_CALLS); if (mPrevState == mConnecting) { - broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); } else if (mPrevState == mConnected || mPrevState == mAudioOn) { - broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED); } else if (Flags.hfpClientDisconnectingState()) { if (mPrevState == mDisconnecting) { broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_DISCONNECTING); } } else if (mPrevState != null) { // null is the default state before Disconnected @@ -1097,10 +1095,7 @@ public class HeadsetClientStateMachine extends StateMachine { BluetoothDevice device = (BluetoothDevice) message.obj; if (!mNativeInterface.connect(device)) { // No state transition is involved, fire broadcast immediately - broadcastConnectionState( - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionState(device, STATE_DISCONNECTED, STATE_DISCONNECTED); break; } mCurrentDevice = device; @@ -1152,10 +1147,7 @@ public class HeadsetClientStateMachine extends StateMachine { mNativeInterface.disconnect(device); // the other profile connection should be initiated // No state transition is involved, fire broadcast immediately - broadcastConnectionState( - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionState(device, STATE_DISCONNECTED, STATE_DISCONNECTED); } break; case HeadsetClientHalConstants.CONNECTION_STATE_CONNECTING: @@ -1183,10 +1175,7 @@ public class HeadsetClientStateMachine extends StateMachine { // the only transition is when connection attempt is initiated. sendMessageDelayed(CONNECTING_TIMEOUT, CONNECTING_TIMEOUT_MS); if (mPrevState == mDisconnected) { - broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionState(mCurrentDevice, STATE_CONNECTING, STATE_DISCONNECTED); } else { String prevStateName = mPrevState == null ? "null" : mPrevState.getName(); error( @@ -1357,13 +1346,8 @@ public class HeadsetClientStateMachine extends StateMachine { warn("incoming connection event, device: " + device); // No state transition is involved, fire broadcast immediately broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); - broadcastConnectionState( - device, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); + broadcastConnectionState(device, STATE_CONNECTING, STATE_DISCONNECTED); mCurrentDevice = device; } @@ -1398,10 +1382,7 @@ public class HeadsetClientStateMachine extends StateMachine { mCommandedSpeakerVolume = -1; if (mPrevState == mConnecting) { - broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING); + broadcastConnectionState(mCurrentDevice, STATE_CONNECTED, STATE_CONNECTING); if (mHeadsetService != null) { mHeadsetService.updateInbandRinging(mCurrentDevice, true); } @@ -1970,10 +1951,7 @@ public class HeadsetClientStateMachine extends StateMachine { + ", message=" + getMessageName(getCurrentMessage().what)); if (mPrevState == mConnected || mPrevState == mAudioOn) { - broadcastConnectionState( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED); + broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTING, STATE_CONNECTED); } else { String prevStateName = mPrevState == null ? "null" : mPrevState.getName(); error( @@ -2194,24 +2172,24 @@ public class HeadsetClientStateMachine extends StateMachine { public synchronized int getConnectionState(BluetoothDevice device) { if (device == null || !device.equals(mCurrentDevice)) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } IState currentState = getCurrentState(); if (currentState == mConnecting) { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } if (currentState == mConnected || currentState == mAudioOn) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } if (Flags.hfpClientDisconnectingState()) { if (currentState == mDisconnecting) { - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @VisibleForTesting @@ -2308,7 +2286,7 @@ public class HeadsetClientStateMachine extends StateMachine { intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); // add feature extras when connected - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { if ((mPeerFeatures & HeadsetClientHalConstants.PEER_FEAT_3WAY) == HeadsetClientHalConstants.PEER_FEAT_3WAY) { intent.putExtra(BluetoothHeadsetClient.EXTRA_AG_FEATURE_3WAY_CALLING, true); @@ -2396,8 +2374,8 @@ public class HeadsetClientStateMachine extends StateMachine { // it is likely that our SDP has not completed and peer is initiating // the // connection. Allow this connection, provided the device is bonded - if ((BluetoothProfile.CONNECTION_POLICY_FORBIDDEN < connectionPolicy) - || ((BluetoothProfile.CONNECTION_POLICY_UNKNOWN == connectionPolicy) + if ((CONNECTION_POLICY_FORBIDDEN < connectionPolicy) + || ((CONNECTION_POLICY_UNKNOWN == connectionPolicy) && (mAdapterService.getBondState(device) != BluetoothDevice.BOND_NONE))) { ret = true; } @@ -2517,7 +2495,7 @@ public class HeadsetClientStateMachine extends StateMachine { return mAudioRouteAllowed; } - private String createMaskString(BluetoothSinkAudioPolicy policies) { + private static String createMaskString(BluetoothSinkAudioPolicy policies) { StringBuilder mask = new StringBuilder(); mask.append(BluetoothSinkAudioPolicy.HFP_SET_SINK_AUDIO_POLICY_ID); mask.append(",").append(policies.getCallEstablishPolicy()); @@ -2582,7 +2560,7 @@ public class HeadsetClientStateMachine extends StateMachine { } /** handles the value of {@link BluetoothSinkAudioPolicy} from system property */ - private int getAudioPolicySystemProp(String propKey) { + private static int getAudioPolicySystemProp(String propKey) { int mProp = SystemProperties.getInt(propKey, BluetoothSinkAudioPolicy.POLICY_UNCONFIGURED); if (mProp < BluetoothSinkAudioPolicy.POLICY_UNCONFIGURED || mProp > BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) { diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java index 4b2dae00b0..792953a634 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java @@ -15,6 +15,9 @@ */ package com.android.bluetooth.hfpclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; @@ -59,7 +62,7 @@ public class HfpClientConnectionService extends ConnectionService { private static final Object INSTANCE_LOCK = new Object(); private static HfpClientConnectionService sHfpClientConnectionService; - private void setInstance(HfpClientConnectionService instance) { + private static void setInstance(HfpClientConnectionService instance) { synchronized (INSTANCE_LOCK) { sHfpClientConnectionService = instance; } @@ -120,14 +123,14 @@ public class HfpClientConnectionService extends ConnectionService { private void onConnectionStateChangedInternal( BluetoothDevice device, int newState, int oldState) { - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { Log.d(TAG, "Established connection with " + device); HfpClientDeviceBlock block = createBlockForDevice(device); if (block == null) { Log.w(TAG, "Block already exists for device= " + device + ", ignoring."); } - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { Log.d(TAG, "Disconnecting from " + device); // Disconnect any inflight calls from the connection service. diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java index aa259bebb3..f33acb586d 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java @@ -320,7 +320,7 @@ public class HfpClientDeviceBlock { } } - private Bundle getScoStateFromDevice(BluetoothDevice device) { + private static Bundle getScoStateFromDevice(BluetoothDevice device) { Bundle bundle = new Bundle(); HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); diff --git a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java index 31703caeec..603beae96b 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java +++ b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java @@ -113,7 +113,7 @@ class VendorCommandResponseProcessor { return true; } - private String getVendorIdFromAtCommand(String atString) { + private static String getVendorIdFromAtCommand(String atString) { // Get event code int indexOfEqual = atString.indexOf('='); int indexOfColon = atString.indexOf(':'); diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java index 9068d666a8..67e9349a28 100644 --- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java +++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java @@ -18,6 +18,11 @@ package com.android.bluetooth.hid; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -493,8 +498,7 @@ public class HidDeviceService extends ProfileService { public List<BluetoothDevice> getConnectedDevices(AttributionSource source) { Log.d(TAG, "getConnectedDevices()"); - return getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED}, source); + return getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}, source); } @Override @@ -683,7 +687,7 @@ public class HidDeviceService extends ProfileService { device, BluetoothProfile.HID_DEVICE, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -884,7 +888,7 @@ public class HidDeviceService extends ProfileService { mAdapterService.updateProfileConnectionAdapterProperties( device, BluetoothProfile.HID_DEVICE, newState, prevState); - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HID_DEVICE); } @@ -899,15 +903,15 @@ public class HidDeviceService extends ProfileService { private static int convertHalState(int halState) { switch (halState) { case HAL_CONN_STATE_CONNECTED: - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; case HAL_CONN_STATE_CONNECTING: - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; case HAL_CONN_STATE_DISCONNECTED: - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case HAL_CONN_STATE_DISCONNECTING: - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; default: - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java index 39a2d398ee..1d0294cd52 100644 --- a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java @@ -16,6 +16,11 @@ package com.android.bluetooth.hid; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import android.util.Log; import com.android.internal.annotations.GuardedBy; @@ -109,18 +114,18 @@ public class HidHostNativeInterface { private static int convertHalState(int halState) { switch (halState) { case CONN_STATE_CONNECTED: - return HidHostService.STATE_CONNECTED; + return STATE_CONNECTED; case CONN_STATE_CONNECTING: - return HidHostService.STATE_CONNECTING; + return STATE_CONNECTING; case CONN_STATE_DISCONNECTED: - return HidHostService.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case CONN_STATE_DISCONNECTING: - return HidHostService.STATE_DISCONNECTING; + return STATE_DISCONNECTING; case CONN_STATE_ACCEPTING: return HidHostService.STATE_ACCEPTING; default: Log.e(TAG, "bad hid connection state: " + halState); - return HidHostService.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/hid/HidHostService.java b/android/app/src/com/android/bluetooth/hid/HidHostService.java index 0e3df36b69..2712db71ad 100644 --- a/android/app/src/com/android/bluetooth/hid/HidHostService.java +++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java @@ -18,6 +18,12 @@ package com.android.bluetooth.hid; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -68,8 +74,8 @@ public class HidHostService extends ProfileService { private static class InputDevice { int mSelectedTransport = BluetoothDevice.TRANSPORT_AUTO; - private int mHidState = BluetoothProfile.STATE_DISCONNECTED; - private int mHogpState = BluetoothProfile.STATE_DISCONNECTED; + private int mHidState = STATE_DISCONNECTED; + private int mHogpState = STATE_DISCONNECTED; int getState(int transport) { return (transport == BluetoothDevice.TRANSPORT_LE) ? mHogpState : mHidState; @@ -122,11 +128,7 @@ public class HidHostService extends ProfileService { private static final int MESSAGE_SET_PREFERRED_TRANSPORT = 17; private static final int MESSAGE_SEND_DATA = 18; - public static final int STATE_DISCONNECTED = BluetoothProfile.STATE_DISCONNECTED; - public static final int STATE_CONNECTING = BluetoothProfile.STATE_CONNECTING; - public static final int STATE_CONNECTED = BluetoothProfile.STATE_CONNECTED; - public static final int STATE_DISCONNECTING = BluetoothProfile.STATE_DISCONNECTING; - public static final int STATE_ACCEPTING = BluetoothProfile.STATE_DISCONNECTING + 1; + public static final int STATE_ACCEPTING = STATE_DISCONNECTING + 1; public HidHostService(AdapterService adapterService) { super(adapterService); @@ -157,12 +159,8 @@ public class HidHostService extends ProfileService { if (mInputDevices != null) { for (BluetoothDevice device : mInputDevices.keySet()) { // Set both HID and HOGP connection states to disconnected - updateConnectionState( - device, BluetoothDevice.TRANSPORT_LE, BluetoothProfile.STATE_DISCONNECTED); - updateConnectionState( - device, - BluetoothDevice.TRANSPORT_BREDR, - BluetoothProfile.STATE_DISCONNECTED); + updateConnectionState(device, BluetoothDevice.TRANSPORT_LE, STATE_DISCONNECTED); + updateConnectionState(device, BluetoothDevice.TRANSPORT_BREDR, STATE_DISCONNECTED); } mInputDevices.clear(); } @@ -210,7 +208,7 @@ public class HidHostService extends ProfileService { * @param device remote device * @return address type */ - private int getAddressType(BluetoothDevice device) { + private static int getAddressType(BluetoothDevice device) { return device.getAddressType(); } @@ -265,7 +263,7 @@ public class HidHostService extends ProfileService { return inputDevice.getState(transport); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } public static synchronized HidHostService getHidHostService() { @@ -423,7 +421,7 @@ public class HidHostService extends ProfileService { /* If connections are allowed, ensure that the previous transport is disconnected and the new transport is connected */ - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_ALLOWED) { if (prevTransport != transport) { Log.i( TAG, @@ -435,8 +433,7 @@ public class HidHostService extends ProfileService { if (Flags.ignoreUnselectedHidTransportStates()) { // Immediately update the connection state to disconnected. From now on, // the connection state will be updated only for the selected transport. - updateConnectionState( - device, prevTransport, BluetoothProfile.STATE_DISCONNECTED); + updateConnectionState(device, prevTransport, STATE_DISCONNECTED); } // Request to connect the preferred transport nativeConnect(device, transport); @@ -482,7 +479,7 @@ public class HidHostService extends ProfileService { private void handleMessageOnVirtualUnplug(Message msg) { BluetoothDevice device = mAdapterService.getDeviceFromByte((byte[]) msg.obj); - updateConnectionState(device, getTransport(device), BluetoothProfile.STATE_DISCONNECTED); + updateConnectionState(device, getTransport(device), STATE_DISCONNECTED); mInputDevices.remove(device); int status = msg.arg2; @@ -637,15 +634,14 @@ public class HidHostService extends ProfileService { + (" prevState=" + prevState)); // Process connection - if (prevState == BluetoothProfile.STATE_DISCONNECTED - && state == BluetoothProfile.STATE_CONNECTED) { + if (prevState == STATE_DISCONNECTED && state == STATE_CONNECTED) { processConnection(device, transport); } // ACCEPTING state has to be treated as DISCONNECTED state int reportedState = state; if (state == STATE_ACCEPTING) { - reportedState = BluetoothProfile.STATE_DISCONNECTED; + reportedState = STATE_DISCONNECTED; } updateConnectionState(device, transport, reportedState); } @@ -655,7 +651,7 @@ public class HidHostService extends ProfileService { int connectionPolicy = msg.arg1; boolean reconnectAllowed = true; - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_ALLOWED) { reconnectAllowed = false; } nativeDisconnect(device, getTransport(device), reconnectAllowed); @@ -666,7 +662,7 @@ public class HidHostService extends ProfileService { InputDevice inputDevice = getOrCreateInputDevice(device); int connectionPolicy = getConnectionPolicy(device); - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_ALLOWED) { Log.e( TAG, "handleMessageConnect: Connection not allowed." @@ -775,15 +771,14 @@ public class HidHostService extends ProfileService { public int getConnectionState(BluetoothDevice device, AttributionSource source) { HidHostService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); } @Override public List<BluetoothDevice> getConnectedDevices(AttributionSource source) { - return getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED}, source); + return getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}, source); } @Override @@ -811,7 +806,7 @@ public class HidHostService extends ProfileService { public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { HidHostService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); return service.getConnectionPolicy(device); @@ -932,11 +927,11 @@ public class HidHostService extends ProfileService { public boolean connect(BluetoothDevice device) { Log.d(TAG, "connect: device=" + device); int state = getConnectionState(device); - if (state != BluetoothProfile.STATE_DISCONNECTED) { + if (state != STATE_DISCONNECTED) { Log.e(TAG, "Device " + device + " not disconnected. state=" + state); return false; } - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.e(TAG, "Device " + device + " CONNECTION_POLICY_FORBIDDEN"); return false; } @@ -986,7 +981,7 @@ public class HidHostService extends ProfileService { if (inputDevice != null) { return inputDevice.getState(); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @VisibleForTesting @@ -1020,10 +1015,10 @@ public class HidHostService extends ProfileService { return false; } Log.d(TAG, "Saved connectionPolicy=" + connectionPolicy + " for device=" + device); - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { - disconnect(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { + disconnect(device, CONNECTION_POLICY_FORBIDDEN); MetricsLogger.getInstance() .count(BluetoothProtoEnums.HIDH_COUNT_CONNECTION_POLICY_DISABLED, 1); } @@ -1093,7 +1088,7 @@ public class HidHostService extends ProfileService { boolean getProtocolMode(BluetoothDevice device) { Log.d(TAG, "getProtocolMode: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_GET_PROTOCOL_MODE, device); @@ -1105,7 +1100,7 @@ public class HidHostService extends ProfileService { boolean virtualUnplug(BluetoothDevice device) { Log.d(TAG, "virtualUnplug: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_VIRTUAL_UNPLUG, device); @@ -1117,7 +1112,7 @@ public class HidHostService extends ProfileService { boolean setProtocolMode(BluetoothDevice device, int protocolMode) { Log.d(TAG, "setProtocolMode: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_SET_PROTOCOL_MODE); @@ -1131,7 +1126,7 @@ public class HidHostService extends ProfileService { boolean getReport(BluetoothDevice device, byte reportType, byte reportId, int bufferSize) { Log.d(TAG, "getReport: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_GET_REPORT); @@ -1149,7 +1144,7 @@ public class HidHostService extends ProfileService { boolean setReport(BluetoothDevice device, byte reportType, String report) { Log.d(TAG, "setReport: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_SET_REPORT); @@ -1166,7 +1161,7 @@ public class HidHostService extends ProfileService { boolean sendData(BluetoothDevice device, String report) { Log.d(TAG, "sendData: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } @@ -1181,7 +1176,7 @@ public class HidHostService extends ProfileService { boolean getIdleTime(BluetoothDevice device) { Log.d(TAG, "getIdleTime: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_GET_IDLE_TIME, device); @@ -1192,7 +1187,7 @@ public class HidHostService extends ProfileService { boolean setIdleTime(BluetoothDevice device, byte idleTime) { Log.d(TAG, "setIdleTime: device=" + device); int state = this.getConnectionState(device); - if (state != BluetoothProfile.STATE_CONNECTED) { + if (state != STATE_CONNECTED) { return false; } Message msg = mHandler.obtainMessage(MESSAGE_SET_IDLE_TIME); @@ -1302,7 +1297,7 @@ public class HidHostService extends ProfileService { return; } - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HID_HOST); } @@ -1409,8 +1404,8 @@ public class HidHostService extends ProfileService { return false; } } - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w( TAG, diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java index a2cefdd648..b34f2a989d 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java @@ -67,7 +67,7 @@ public class LeAudioBroadcasterNativeInterface { } } - private void sendMessageToService(LeAudioStackEvent event) { + private static void sendMessageToService(LeAudioStackEvent event) { LeAudioService service = LeAudioService.getLeAudioService(); if (service != null) { service.messageFromNative(event); diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java index a501c6d8a7..e2d1490c9f 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java @@ -69,14 +69,14 @@ public class LeAudioNativeInterface { } } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } return Utils.getBytesFromAddress(device.getAddress()); } - private void sendMessageToService(LeAudioStackEvent event) { + private static void sendMessageToService(LeAudioStackEvent event) { LeAudioService service = LeAudioService.getLeAudioService(); if (service != null) { service.messageFromNative(event); @@ -92,7 +92,7 @@ public class LeAudioNativeInterface { // Callbacks from the native stack back into the Java framework. // All callbacks are routed via the Service which will disambiguate which // state machine the message should be routed to. - private void onInitialized() { + private static void onInitialized() { LeAudioStackEvent event = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java index 62b8918bef..19be391158 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java @@ -19,6 +19,11 @@ package com.android.bluetooth.le_audio; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID; import static com.android.bluetooth.bass_client.BassConstants.INVALID_BROADCAST_ID; @@ -78,6 +83,7 @@ import android.sysprop.BluetoothProperties; import android.util.Log; import android.util.Pair; +import com.android.bluetooth.BluetoothEventLogger; import com.android.bluetooth.BluetoothStatsLog; import com.android.bluetooth.Utils; import com.android.bluetooth.a2dp.A2dpService; @@ -210,6 +216,10 @@ public class LeAudioService extends ProfileService { boolean mIsSinkStreamMonitorModeEnabled = false; boolean mIsBroadcastPausedFromOutside = false; + private static final int LOG_NB_EVENTS = 150; + private final BluetoothEventLogger mEventLogger = + new BluetoothEventLogger(LOG_NB_EVENTS, TAG + " event log"); + @VisibleForTesting TbsService mTbsService; @VisibleForTesting McpService mMcpService; @@ -292,7 +302,7 @@ public class LeAudioService extends ProfileService { } } - private static class LeAudioGroupDescriptor { + private class LeAudioGroupDescriptor { LeAudioGroupDescriptor(int groupId, boolean isInbandRingtonEnabled) { mGroupId = groupId; mIsConnected = false; @@ -331,6 +341,15 @@ public class LeAudioService extends ProfileService { private Integer mAllowedSinkContexts; private Integer mAllowedSourceContexts; + private static String getStateString(int state) { + return switch (state) { + case ACTIVE_STATE_ACTIVE -> "active"; + case ACTIVE_STATE_INACTIVE -> "inactive"; + case ACTIVE_STATE_GETTING_ACTIVE -> "getting_active"; + default -> "unknownState [" + state + "]"; + }; + } + boolean isActive() { return mActiveState == ACTIVE_STATE_ACTIVE; } @@ -347,17 +366,17 @@ public class LeAudioService extends ProfileService { if ((state != ACTIVE_STATE_ACTIVE) && (state != ACTIVE_STATE_INACTIVE) && (state != ACTIVE_STATE_GETTING_ACTIVE)) { - Log.e( + mEventLogger.loge( TAG, ("LeAudioGroupDescriptor.setActiveState (groupId: " + mGroupId + "):") - + ("Invalid state set: " + state)); + + ("Invalid state set: " + getStateString(state))); return; } - Log.d( + mEventLogger.logd( TAG, ("LeAudioGroupDescriptor.setActiveState (groupId: " + mGroupId + "): ") - + (mActiveState + " -> " + state)); + + (getStateString(mActiveState) + " -> " + getStateString(state))); mActiveState = state; } @@ -528,7 +547,7 @@ public class LeAudioService extends ProfileService { mSessionStatus); } - private int convertToStatsAudioQuality(int audioQuality) { + private static int convertToStatsAudioQuality(int audioQuality) { switch (audioQuality) { case BluetoothLeBroadcastSubgroupSettings.QUALITY_STANDARD: return BluetoothStatsLog @@ -869,7 +888,7 @@ public class LeAudioService extends ProfileService { public boolean connect(BluetoothDevice device) { Log.d(TAG, "connect(): " + device); - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN"); return false; } @@ -980,7 +999,7 @@ public class LeAudioService extends ProfileService { if (!Utils.arrayContains(featureUuids, BluetoothUuid.LE_AUDIO)) { continue; } - int connectionState = BluetoothProfile.STATE_DISCONNECTED; + int connectionState = STATE_DISCONNECTED; LeAudioDeviceDescriptor descriptor = getDeviceDescriptor(device); if (descriptor == null) { Log.e( @@ -1042,12 +1061,12 @@ public class LeAudioService extends ProfileService { try { LeAudioDeviceDescriptor descriptor = getDeviceDescriptor(device); if (descriptor == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } LeAudioStateMachine sm = descriptor.mStateMachine; if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } finally { @@ -1728,8 +1747,7 @@ public class LeAudioService extends ProfileService { } if (groupDescriptor.mCurrentLeadDevice != null - && getConnectionState(groupDescriptor.mCurrentLeadDevice) - == BluetoothProfile.STATE_CONNECTED) { + && getConnectionState(groupDescriptor.mCurrentLeadDevice) == STATE_CONNECTED) { return groupDescriptor.mCurrentLeadDevice; } @@ -1739,7 +1757,7 @@ public class LeAudioService extends ProfileService { } LeAudioStateMachine sm = descriptor.mStateMachine; - if (sm == null || sm.getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (sm == null || sm.getConnectionState() != STATE_CONNECTED) { continue; } groupDescriptor.mCurrentLeadDevice = sm.getDevice(); @@ -1786,6 +1804,12 @@ public class LeAudioService extends ProfileService { device = mActiveAudioInDevice; } } else if (deviceDescriptor.mGroupId != LE_AUDIO_GROUP_ID_INVALID) { + mEventLogger.logd( + TAG, + "Switching(input) active group from " + + deviceDescriptor.mGroupId + + " to " + + groupId); /* Mark old group as no active */ LeAudioGroupDescriptor descriptor = getGroupDescriptor(deviceDescriptor.mGroupId); if (descriptor != null) { @@ -1805,14 +1829,6 @@ public class LeAudioService extends ProfileService { if (!Objects.equals(device, previousInDevice) || (oldSupportedByDeviceInput != newSupportedByDeviceInput)) { mActiveAudioInDevice = newSupportedByDeviceInput ? device : null; - Log.d( - TAG, - " handleBluetoothActiveDeviceChanged previousInDevice: " - + previousInDevice - + ", mActiveAudioInDevice: " - + mActiveAudioInDevice - + " isLeOutput: false"); - return true; } Log.d(TAG, "updateActiveInDevice: Nothing to do."); @@ -1855,9 +1871,9 @@ public class LeAudioService extends ProfileService { device = mActiveAudioOutDevice; } } else if (deviceDescriptor.mGroupId != LE_AUDIO_GROUP_ID_INVALID) { - Log.i( + mEventLogger.logd( TAG, - " Switching active group from " + "Switching(output) active group from " + deviceDescriptor.mGroupId + " to " + groupId); @@ -1880,13 +1896,6 @@ public class LeAudioService extends ProfileService { if (!Objects.equals(device, previousOutDevice) || (oldSupportedByDeviceOutput != newSupportedByDeviceOutput)) { mActiveAudioOutDevice = newSupportedByDeviceOutput ? device : null; - Log.d( - TAG, - " handleBluetoothActiveDeviceChanged previousOutDevice: " - + previousOutDevice - + ", mActiveAudioOutDevice: " - + mActiveAudioOutDevice - + " isLeOutput: true"); return true; } Log.d(TAG, "updateActiveOutDevice: Nothing to do."); @@ -1933,7 +1942,7 @@ public class LeAudioService extends ProfileService { Utils.getTempBroadcastOptions().toBundle()); } - void sentActiveDeviceChangeIntent(BluetoothDevice device) { + void sendActiveDeviceChangeIntent(BluetoothDevice device) { Intent intent = new Intent(BluetoothLeAudio.ACTION_LE_AUDIO_ACTIVE_DEVICE_CHANGED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); intent.addFlags( @@ -1942,6 +1951,9 @@ public class LeAudioService extends ProfileService { createContextAsUser(UserHandle.ALL, /* flags= */ 0) .sendBroadcastWithMultiplePermissions( intent, new String[] {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}); + mEventLogger.logd( + TAG, "[Intent] Active Device Changed:" + mExposedActiveDevice + " -> " + device); + mExposedActiveDevice = device; } void notifyVolumeControlServiceAboutActiveGroup(BluetoothDevice device) { @@ -1970,12 +1982,13 @@ public class LeAudioService extends ProfileService { "Notify Active device changed." + device + ". Currently active device is " - + mActiveAudioOutDevice); + + mActiveAudioOutDevice + + " Currently exposed device " + + mExposedActiveDevice); mAdapterService.handleActiveDeviceChange(BluetoothProfile.LE_AUDIO, device); - sentActiveDeviceChangeIntent(device); notifyVolumeControlServiceAboutActiveGroup(device); - mExposedActiveDevice = device; + sendActiveDeviceChangeIntent(device); } boolean isAnyGroupDisabledFromAutoActiveMode() { @@ -2143,12 +2156,13 @@ public class LeAudioService extends ProfileService { @VisibleForTesting boolean handleAudioDeviceAdded( BluetoothDevice device, int type, boolean isSink, boolean isSource) { - Log.d( + mEventLogger.logd( TAG, - (" handleAudioDeviceAdded: " + device) + ("[From AudioManager]: handleAudioDeviceAdded: " + device) + (", device type: " + type) + (", isSink: " + isSink) - + (" isSource: " + isSource)); + + (" isSource: " + isSource) + + (" exposed: " + mExposedActiveDevice)); /* Don't expose already exposed active device */ if (device.equals(mExposedActiveDevice)) { @@ -2158,9 +2172,9 @@ public class LeAudioService extends ProfileService { if ((isSink && !device.equals(mActiveAudioOutDevice)) || (isSource && !device.equals(mActiveAudioInDevice))) { - Log.e( + mEventLogger.loge( TAG, - "Added device does not match to the one activated here. (" + "[From AudioManager]: Added device does not match to the one activated here. (" + (device + " != " + mActiveAudioOutDevice @@ -2177,9 +2191,9 @@ public class LeAudioService extends ProfileService { @VisibleForTesting void handleAudioDeviceRemoved( BluetoothDevice device, int type, boolean isSink, boolean isSource) { - Log.d( + mEventLogger.logd( TAG, - (" handleAudioDeviceRemoved: " + device) + ("[From AudioManager]: handleAudioDeviceRemoved: " + device) + (" device type: " + type) + (" isSink: " + isSink) + (" isSource: " + isSource) @@ -2193,7 +2207,6 @@ public class LeAudioService extends ProfileService { if ((isSource && mActiveAudioInDevice == null) || (isSink && mActiveAudioOutDevice == null)) { - Log.d(TAG, "Expecting device removal"); if (mActiveAudioInDevice == null && mActiveAudioOutDevice == null) { mExposedActiveDevice = null; } @@ -2201,13 +2214,16 @@ public class LeAudioService extends ProfileService { } if (device.equals(mActiveAudioInDevice) || device.equals(mActiveAudioOutDevice)) { - Log.i(TAG, "Audio manager disactivate LeAudio device " + mExposedActiveDevice); + mEventLogger.loge( + TAG, + "[From AudioManager]: Audio manager autonomusly disactivated LeAudio device " + + mExposedActiveDevice); mExposedActiveDevice = null; setActiveDevice(null); return; } - Log.i( + mEventLogger.logd( TAG, ("LeAudio active device switch: " + mExposedActiveDevice @@ -2285,9 +2301,9 @@ public class LeAudioService extends ProfileService { BluetoothDevice previousDevice, boolean suppressNoisyIntent) { mActiveBroadcastAudioDevice = newDevice; - Log.d( + mEventLogger.logd( TAG, - "updateBroadcastActiveDevice: newDevice: " + "[To AudioManager]: updateBroadcastActiveDevice: newDevice: " + newDevice + ", previousDevice: " + previousDevice); @@ -2373,12 +2389,15 @@ public class LeAudioService extends ProfileService { final boolean suppressNoisyIntent = hasFallbackDevice || mActiveAudioOutDevice != null; - Log.d( + mEventLogger.logd( TAG, - "suppressNoisyIntent: " - + suppressNoisyIntent - + ", hasFallbackDevice: " - + hasFallbackDevice); + "[To AudioManager]: handleBluetoothActiveDeviceChanged previousOutDevice: " + + previousActiveOutDevice + + (", mActiveAudioOutDevice: " + mActiveAudioOutDevice) + + " isLeOutput: true" + + (", suppressNoisyIntent: " + suppressNoisyIntent) + + (", hasFallbackDevice: " + hasFallbackDevice)); + final BluetoothProfileConnectionInfo connectionInfo; if (isAtLeastU()) { connectionInfo = @@ -2393,6 +2412,12 @@ public class LeAudioService extends ProfileService { } if (isNewActiveInDevice) { + mEventLogger.logd( + TAG, + "[To AudioManager]: handleBluetoothActiveDeviceChanged previousActiveInDevice: " + + previousActiveInDevice + + (", mActiveAudioInDevice: " + mActiveAudioInDevice) + + " isLeOutput: false"); mAudioManager.handleBluetoothActiveDeviceChanged( mActiveAudioInDevice, previousActiveInDevice, @@ -2547,7 +2572,7 @@ public class LeAudioService extends ProfileService { + groupId + ", exposedDevice: " + mExposedActiveDevice); - sentActiveDeviceChangeIntent(mExposedActiveDevice); + sendActiveDeviceChangeIntent(mExposedActiveDevice); } return true; } @@ -2605,20 +2630,18 @@ public class LeAudioService extends ProfileService { * @return true on success, otherwise false */ public boolean setActiveDevice(BluetoothDevice device) { - Log.i( + mEventLogger.logd( TAG, - "setActiveDevice: device=" - + device - + ", current out=" - + mActiveAudioOutDevice - + ", current in=" - + mActiveAudioInDevice); + ("[API call] setActiveDevice: device=" + device) + + (", current out=" + mActiveAudioOutDevice) + + (", current in=" + mActiveAudioInDevice) + + (", exposed= " + mExposedActiveDevice)); /* Clear active group */ if (device == null) { Log.e(TAG, "device should not be null!"); return removeActiveDevice(false); } - if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState(device) != STATE_CONNECTED) { Log.e( TAG, "setActiveDevice(" @@ -2806,25 +2829,22 @@ public class LeAudioService extends ProfileService { Log.d(TAG, "Disable LE_AUDIO for the device: " + activeGroupDevice); final ParcelUuid[] uuids = mAdapterService.getRemoteUuids(activeGroupDevice); - setConnectionPolicy(activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_FORBIDDEN); if (hsService != null && !isDualMode && Utils.arrayContains(uuids, BluetoothUuid.HFP)) { Log.d(TAG, "Enable HFP for the device: " + activeGroupDevice); - hsService.setConnectionPolicy( - activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + hsService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED); } if (a2dpService != null && !isDualMode && (Utils.arrayContains(uuids, BluetoothUuid.A2DP_SINK) || Utils.arrayContains(uuids, BluetoothUuid.ADV_AUDIO_DIST))) { Log.d(TAG, "Enable A2DP for the device: " + activeGroupDevice); - a2dpService.setConnectionPolicy( - activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + a2dpService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED); } if (hearingAidService != null && Utils.arrayContains(uuids, BluetoothUuid.HEARING_AID)) { Log.d(TAG, "Enable ASHA for the device: " + activeGroupDevice); - hearingAidService.setConnectionPolicy( - activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + hearingAidService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED); } } } @@ -3683,6 +3703,14 @@ public class LeAudioService extends ProfileService { } else if (stackEvent.type == LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED) { int groupId = stackEvent.valueInt1; int groupStatus = stackEvent.valueInt2; + mEventLogger.logd( + TAG, + "[From Native]: groupId: " + + groupId + + ", status: " + + (groupStatus == LeAudioStackEvent.GROUP_STATUS_ACTIVE + ? "Active" + : "Inactive")); switch (groupStatus) { case LeAudioStackEvent.GROUP_STATUS_ACTIVE: @@ -4119,7 +4147,7 @@ public class LeAudioService extends ProfileService { if (sm == null) { return; } - if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (sm.getConnectionState() != STATE_DISCONNECTED) { Log.w(TAG, "Device is not disconnected yet."); disconnect(device); return; @@ -4327,8 +4355,8 @@ public class LeAudioService extends ProfileService { if (bondState != BluetoothDevice.BOND_BONDED) { Log.w(TAG, "okToConnect: return false, bondState=" + bondState); return false; - } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Otherwise, reject the connection if connectionPolicy is not valid. Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy); return false; @@ -4478,7 +4506,7 @@ public class LeAudioService extends ProfileService { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { setEnabledState(device, /* enabled= */ true); // Authorizes LEA GATT server services if already assigned to a group int groupId = getGroupId(device); @@ -4486,7 +4514,7 @@ public class LeAudioService extends ProfileService { setAuthorizationForRelatedProfiles(device, true); } connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { setEnabledState(device, /* enabled= */ false); // Remove authorization for LEA GATT server services setAuthorizationForRelatedProfiles(device, false); @@ -4731,11 +4759,6 @@ public class LeAudioService extends ProfileService { List<BluetoothDevice> activeBroadcastSinks = new ArrayList<>(); if (currentlyActiveGroupId == LE_AUDIO_GROUP_ID_INVALID) { - if (!Flags.leaudioBroadcastVolumeControlWithSetVolume()) { - Log.e(TAG, "There is no active group "); - return; - } - BassClientService bassClientService = getBassClientService(); if (bassClientService != null) { activeBroadcastSinks = bassClientService.getSyncedBroadcastSinks(); @@ -4748,24 +4771,23 @@ public class LeAudioService extends ProfileService { } VolumeControlService volumeControlService = getVolumeControlService(); - if (volumeControlService != null) { - if (Flags.leaudioBroadcastVolumeControlWithSetVolume() - && currentlyActiveGroupId == LE_AUDIO_GROUP_ID_INVALID - && !activeBroadcastSinks.isEmpty()) { - if (activeBroadcastSinks.stream() - .anyMatch(dev -> isPrimaryGroup(getGroupId(dev)))) { - Log.d( - TAG, - "Setting volume for broadcast sink primary group: " - + mUnicastGroupIdDeactivatedForBroadcastTransition); - volumeControlService.setGroupVolume( - mUnicastGroupIdDeactivatedForBroadcastTransition, volume); - } else { - Log.w(TAG, "Setting volume when no active or broadcast primary group"); - } + if (volumeControlService == null) { + return; + } + if (currentlyActiveGroupId == LE_AUDIO_GROUP_ID_INVALID + && !activeBroadcastSinks.isEmpty()) { + if (activeBroadcastSinks.stream().anyMatch(dev -> isPrimaryGroup(getGroupId(dev)))) { + Log.d( + TAG, + "Setting volume for broadcast sink primary group: " + + mUnicastGroupIdDeactivatedForBroadcastTransition); + volumeControlService.setGroupVolume( + mUnicastGroupIdDeactivatedForBroadcastTransition, volume); } else { - volumeControlService.setGroupVolume(currentlyActiveGroupId, volume); + Log.w(TAG, "Setting volume when no active or broadcast primary group"); } + } else { + volumeControlService.setGroupVolume(currentlyActiveGroupId, volume); } } @@ -4858,11 +4880,10 @@ public class LeAudioService extends ProfileService { } for (BluetoothDevice device : mDeviceDescriptors.keySet()) { int connection_policy = getConnectionPolicy(device); - if (connection_policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connection_policy != CONNECTION_POLICY_FORBIDDEN) { setAuthorizationForRelatedProfiles(device, true); } - setEnabledState( - device, connection_policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + setEnabledState(device, connection_policy != CONNECTION_POLICY_FORBIDDEN); } } finally { mGroupReadLock.unlock(); @@ -4875,7 +4896,9 @@ public class LeAudioService extends ProfileService { @VisibleForTesting void handleAudioModeChange(int mode) { - Log.d(TAG, "Audio mode changed: " + mCurrentAudioMode + " -> " + mode); + mEventLogger.logd( + TAG, + "[From AudioManager]: Audio mode changed: " + mCurrentAudioMode + " -> " + mode); int previousAudioMode = mCurrentAudioMode; mCurrentAudioMode = mode; @@ -5271,7 +5294,8 @@ public class LeAudioService extends ProfileService { } } - private boolean isAudioModeChangedFromCommunicationToNormal(int previousMode, int currentMode) { + private static boolean isAudioModeChangedFromCommunicationToNormal( + int previousMode, int currentMode) { switch (previousMode) { case AudioManager.MODE_RINGTONE: case AudioManager.MODE_IN_CALL: @@ -5747,7 +5771,7 @@ public class LeAudioService extends ProfileService { LeAudioService service = getServiceAndEnforceConnect(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -5830,7 +5854,7 @@ public class LeAudioService extends ProfileService { LeAudioService service = getServiceAndEnforceConnect(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null); @@ -6230,6 +6254,11 @@ public class LeAudioService extends ProfileService { mGroupReadLock.unlock(); } + if (mEventLogger != null) { + sb.append("\n\n"); + mEventLogger.dump(sb); + } + if (numberOfUngroupedDevs > 0) { ProfileService.println(sb, "UnGroup devices:"); for (Map.Entry<BluetoothDevice, LeAudioDeviceDescriptor> entry : diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java index 54e68641e0..fc5c54bbf5 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java @@ -43,8 +43,13 @@ package com.android.bluetooth.le_audio; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; +import static android.bluetooth.BluetoothProfile.getConnectionStateName; + import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.os.Looper; import android.os.Message; import android.util.Log; @@ -74,7 +79,7 @@ final class LeAudioStateMachine extends StateMachine { private Connecting mConnecting; private Disconnecting mDisconnecting; private Connected mConnected; - private int mConnectionState = BluetoothProfile.STATE_DISCONNECTED; + private int mConnectionState = STATE_DISCONNECTED; private int mLastConnectionState = -1; @@ -137,13 +142,13 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mConnectionState = STATE_DISCONNECTED; removeDeferredMessages(DISCONNECT); if (mLastConnectionState != -1) { // Don't broadcast during startup - broadcastConnectionState(BluetoothProfile.STATE_DISCONNECTED, mLastConnectionState); + broadcastConnectionState(STATE_DISCONNECTED, mLastConnectionState); } } @@ -154,7 +159,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -252,8 +257,8 @@ final class LeAudioStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - mConnectionState = BluetoothProfile.STATE_CONNECTING; - broadcastConnectionState(BluetoothProfile.STATE_CONNECTING, mLastConnectionState); + mConnectionState = STATE_CONNECTING; + broadcastConnectionState(STATE_CONNECTING, mLastConnectionState); } @Override @@ -263,7 +268,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -354,8 +359,8 @@ final class LeAudioStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - mConnectionState = BluetoothProfile.STATE_DISCONNECTING; - broadcastConnectionState(BluetoothProfile.STATE_DISCONNECTING, mLastConnectionState); + mConnectionState = STATE_DISCONNECTING; + broadcastConnectionState(STATE_DISCONNECTING, mLastConnectionState); } @Override @@ -365,7 +370,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING; + mLastConnectionState = STATE_DISCONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -463,9 +468,9 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mConnectionState = BluetoothProfile.STATE_CONNECTED; + mConnectionState = STATE_CONNECTED; removeDeferredMessages(CONNECT); - broadcastConnectionState(BluetoothProfile.STATE_CONNECTED, mLastConnectionState); + broadcastConnectionState(STATE_CONNECTED, mLastConnectionState); } @Override @@ -475,7 +480,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } @Override @@ -544,7 +549,7 @@ final class LeAudioStateMachine extends StateMachine { } synchronized boolean isConnected() { - return (getConnectionState() == BluetoothProfile.STATE_CONNECTED); + return (getConnectionState() == STATE_CONNECTED); } // This method does not check for error condition (newState == prevState) @@ -553,9 +558,9 @@ final class LeAudioStateMachine extends StateMachine { "Connection state " + mDevice + ": " - + profileStateToString(prevState) + + getConnectionStateName(prevState) + "->" - + profileStateToString(newState)); + + getConnectionStateName(newState)); mService.notifyConnectionStateChanged(mDevice, newState, prevState); } @@ -575,22 +580,6 @@ final class LeAudioStateMachine extends StateMachine { return Integer.toString(what); } - private static String profileStateToString(int state) { - switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: - return "DISCONNECTED"; - case BluetoothProfile.STATE_CONNECTING: - return "CONNECTING"; - case BluetoothProfile.STATE_CONNECTED: - return "CONNECTED"; - case BluetoothProfile.STATE_DISCONNECTING: - return "DISCONNECTING"; - default: - break; - } - return Integer.toString(state); - } - public void dump(StringBuilder sb) { ProfileService.println(sb, "mDevice: " + mDevice); ProfileService.println(sb, " StateMachine: " + this); diff --git a/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java b/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java index 9f4c910432..6d38a07d93 100644 --- a/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java +++ b/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java @@ -16,119 +16,29 @@ package com.android.bluetooth.le_scan; -import android.annotation.Nullable; import android.bluetooth.BluetoothDevice; -class AdvtFilterOnFoundOnLostInfo { - private int mClientIf; - - private int mAdvPktLen; - @Nullable private byte[] mAdvPkt; - - private int mScanRspLen; - - @Nullable private byte[] mScanRsp; - - private int mFiltIndex; - private int mAdvState; - private int mAdvInfoPresent; - private String mAddress; - - private int mAddrType; - private int mTxPower; - private int mRssiValue; - private int mTimeStamp; - - AdvtFilterOnFoundOnLostInfo( - int clientIf, - int advPktLen, - byte[] advPkt, - int scanRspLen, - byte[] scanRsp, - int filtIndex, - int advState, - int advInfoPresent, - String address, - int addrType, - int txPower, - int rssiValue, - int timeStamp) { - - mClientIf = clientIf; - mAdvPktLen = advPktLen; - mAdvPkt = advPkt; - mScanRspLen = scanRspLen; - mScanRsp = scanRsp; - mFiltIndex = filtIndex; - mAdvState = advState; - mAdvInfoPresent = advInfoPresent; - mAddress = address; - mAddrType = addrType; - mTxPower = txPower; - mRssiValue = rssiValue; - mTimeStamp = timeStamp; - } - - public int getClientIf() { - return mClientIf; - } - - public int getFiltIndex() { - return mFiltIndex; - } - - public int getAdvState() { - return mAdvState; - } - - public int getTxPower() { - return mTxPower; - } - - public int getTimeStamp() { - return mTimeStamp; - } - - public int getRSSIValue() { - return mRssiValue; - } - - public int getAdvInfoPresent() { - return mAdvInfoPresent; - } - - public String getAddress() { - return mAddress; - } - - @BluetoothDevice.AddressType - public int getAddressType() { - return mAddrType; - } - - public byte[] getAdvPacketData() { - return mAdvPkt; - } - - public int getAdvPacketLen() { - return mAdvPktLen; - } - - public byte[] getScanRspData() { - return mScanRsp; - } - - public int getScanRspLen() { - return mScanRspLen; - } +import com.google.protobuf.ByteString; + +record AdvtFilterOnFoundOnLostInfo( + int clientIf, + int advPacketLen, + ByteString advPacket, + int scanResponseLen, + ByteString scanResponse, + int filtIndex, + int advState, + int advInfoPresent, + String address, + @BluetoothDevice.AddressType int addressType, + int txPower, + int rssiValue, + int timeStamp) { public byte[] getResult() { - int resultLength = mAdvPkt.length + ((mScanRsp != null) ? mScanRsp.length : 0); - byte[] result = new byte[resultLength]; - System.arraycopy(mAdvPkt, 0, result, 0, mAdvPkt.length); - if (mScanRsp != null) { - System.arraycopy(mScanRsp, 0, result, mAdvPkt.length, mScanRsp.length); + if (scanResponse == null) { + return advPacket.toByteArray(); } - return result; + return advPacket.concat(scanResponse).toByteArray(); } } diff --git a/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java b/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java index 4d3bcc8a74..420a808e6d 100644 --- a/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java +++ b/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java @@ -17,6 +17,7 @@ package com.android.bluetooth.le_scan; import static java.util.Objects.requireNonNull; +import static java.util.Objects.requireNonNullElseGet; import android.annotation.Nullable; import android.bluetooth.BluetoothProtoEnums; @@ -43,15 +44,13 @@ import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; /** ScanStats class helps keep track of information about scans on a per application basis. */ class AppScanStats { private static final String TAG = AppScanStats.class.getSimpleName(); - private static final ThreadLocal<DateFormat> DATE_FORMAT = - ThreadLocal.withInitial(() -> new SimpleDateFormat("MM-dd HH:mm:ss")); - // Weight is the duty cycle of the scan mode static final int OPPORTUNISTIC_WEIGHT = 0; static final int SCREEN_OFF_LOW_POWER_WEIGHT = 5; @@ -62,22 +61,8 @@ class AppScanStats { static final int LARGE_SCAN_TIME_GAP_MS = 24000; - // ScannerMap here is needed to grab Apps - ScannerMap mScannerMap; - - // ScanController is needed to add scan event protos to be dumped later - final ScanController mScanController; - - // Battery stats is used to keep track of scans and result stats - BatteryStatsManager mBatteryStatsManager; - - private final AdapterService mAdapterService; - private final TimeProvider mTimeProvider; - - private static Object sLock = new Object(); - - @GuardedBy("sLock") - static long sRadioStartTime = 0; + private static final ThreadLocal<DateFormat> DATE_FORMAT = + ThreadLocal.withInitial(() -> new SimpleDateFormat("MM-dd HH:mm:ss")); static WorkSourceUtil sRadioScanWorkSourceUtil; static int sRadioScanType; @@ -87,27 +72,32 @@ class AppScanStats { static boolean sIsRadioStarted = false; static boolean sIsScreenOn = false; + @GuardedBy("sLock") + static long sRadioStartTime = 0; + + private static Object sLock = new Object(); + private static class LastScan { public long duration; public long suspendDuration; public long suspendStartTime; public boolean isSuspended; - public long timestamp; - public long reportDelayMillis; + public final long timestamp; + public final long reportDelayMillis; public boolean isOpportunisticScan; public boolean isTimeout; public boolean isDowngraded; public boolean isBackgroundScan; - public boolean isFilterScan; - public boolean isCallbackScan; + public final boolean isFilterScan; + public final boolean isCallbackScan; public boolean isBatchScan; public boolean isAutoBatchScan; public int results; - public int scannerId; - public int scanMode; - public int scanCallbackType; - public StringBuilder filterString; - @Nullable public String attributionTag; + public final int scannerId; + public final int scanMode; + public final int scanCallbackType; + public final StringBuilder filterString; + @Nullable public final String attributionTag; LastScan( long timestamp, @@ -141,12 +131,23 @@ class AppScanStats { } } - String mAppName; - private WorkSource mWorkSource; // Used for BatteryStatsManager + private final List<LastScan> mLastScans = new ArrayList<>(); + private final Map<Integer, LastScan> mOngoingScans = new HashMap<>(); + + final String mAppName; + final ScannerMap mScannerMap; // Used to grab Apps + final BatteryStatsManager mBatteryStatsManager; // Used to keep track of scans and result stats + final ScanController mScanController; // Used to add scan event protos to be dumped later + + private final WorkSource mWorkSource; // Used for BatteryStatsManager private final WorkSourceUtil mWorkSourceUtil; // Used for BluetoothStatsLog + private final AdapterService mAdapterService; + private final TimeProvider mTimeProvider; + + public boolean isAppDead = false; + public boolean isRegistered = false; private int mScansStarted = 0; private int mScansStopped = 0; - public boolean isRegistered = false; private long mScanStartTime = 0; private long mTotalActiveTime = 0; private long mTotalSuspendTime = 0; @@ -161,12 +162,9 @@ class AppScanStats { private int mBalancedScan = 0; private int mLowLatencyScan = 0; private int mAmbientDiscoveryScan = 0; - private List<LastScan> mLastScans = new ArrayList<LastScan>(); - private HashMap<Integer, LastScan> mOngoingScans = new HashMap<Integer, LastScan>(); private long startTime = 0; private long stopTime = 0; private int results = 0; - public boolean isAppDead = false; AppScanStats( String name, @@ -175,19 +173,31 @@ class AppScanStats { AdapterService adapterService, ScanController scanController, TimeProvider timeProvider) { - mAdapterService = requireNonNull(adapterService); - mTimeProvider = requireNonNull(timeProvider); mAppName = name; + mWorkSource = + requireNonNullElseGet( + // Bill the caller if the work source isn't passed through + source, () -> new WorkSource(Binder.getCallingUid(), mAppName)); + mWorkSourceUtil = new WorkSourceUtil(mWorkSource); mScannerMap = map; - mScanController = scanController; + mAdapterService = requireNonNull(adapterService); mBatteryStatsManager = adapterService.getSystemService(BatteryStatsManager.class); + mScanController = scanController; + mTimeProvider = requireNonNull(timeProvider); + } - if (source == null) { - // Bill the caller if the work source isn't passed through - source = new WorkSource(Binder.getCallingUid(), mAppName); - } - mWorkSource = source; - mWorkSourceUtil = new WorkSourceUtil(source); + private synchronized LastScan getScanFromScannerId(int scannerId) { + return mOngoingScans.get(scannerId); + } + + private BluetoothMetricsProto.ScanEvent.Builder createBaseScanEvent( + BluetoothMetricsProto.ScanEvent.ScanEventType type) { + return BluetoothMetricsProto.ScanEvent.newBuilder() + .setScanEventType(type) + .setScanTechnologyType( + BluetoothMetricsProto.ScanEvent.ScanTechnologyType.SCAN_TECH_TYPE_LE) + .setEventTimeMillis(System.currentTimeMillis()) + .setInitiator(truncateAppName(mAppName)); } synchronized void addResult(int scannerId) { @@ -214,10 +224,6 @@ class AppScanStats { return !mOngoingScans.isEmpty(); } - synchronized LastScan getScanFromScannerId(int scannerId) { - return mOngoingScans.get(scannerId); - } - synchronized boolean isScanTimeout(int scannerId) { LastScan scan = getScanFromScannerId(scannerId); if (scan == null) { @@ -301,14 +307,7 @@ class AppScanStats { } BluetoothMetricsProto.ScanEvent scanEvent = - BluetoothMetricsProto.ScanEvent.newBuilder() - .setScanEventType( - BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_START) - .setScanTechnologyType( - BluetoothMetricsProto.ScanEvent.ScanTechnologyType - .SCAN_TECH_TYPE_LE) - .setEventTimeMillis(System.currentTimeMillis()) - .setInitiator(truncateAppName(mAppName)) + createBaseScanEvent(BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_START) .build(); mScanController.addScanEvent(scanEvent); @@ -352,14 +351,7 @@ class AppScanStats { mLastScans.add(scan); BluetoothMetricsProto.ScanEvent scanEvent = - BluetoothMetricsProto.ScanEvent.newBuilder() - .setScanEventType( - BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_STOP) - .setScanTechnologyType( - BluetoothMetricsProto.ScanEvent.ScanTechnologyType - .SCAN_TECH_TYPE_LE) - .setEventTimeMillis(System.currentTimeMillis()) - .setInitiator(truncateAppName(mAppName)) + createBaseScanEvent(BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_STOP) .setNumberResults(scan.results) .build(); mScanController.addScanEvent(scanEvent); @@ -470,7 +462,7 @@ class AppScanStats { } } - private int convertScanCallbackType(int type) { + private static int convertScanCallbackType(int type) { switch (type) { case ScanSettings.CALLBACK_TYPE_ALL_MATCHES: return BluetoothStatsLog @@ -851,7 +843,7 @@ class AppScanStats { // or less package names names are untouched. // Examples: one.two.three.four => one.two.three // one.two.three => one.two - private String truncateAppName(String name) { + private static String truncateAppName(String name) { String initiator = name; String[] nameSplit = initiator.split("\\."); if (nameSplit.length > 3) { @@ -974,39 +966,37 @@ class AppScanStats { int lowLatencyScan = mLowLatencyScan; long ambientDiscoveryScan = mAmbientDiscoveryScan; - if (!mOngoingScans.isEmpty()) { - for (Integer key : mOngoingScans.keySet()) { - LastScan scan = mOngoingScans.get(key); - scanDuration = currTime - scan.timestamp; - - if (scan.isSuspended) { - suspendDuration = currTime - scan.suspendStartTime; - totalSuspendTime += suspendDuration; - } + for (LastScan scan : mOngoingScans.values()) { + scanDuration = currTime - scan.timestamp; - totalScanTime += scanDuration; + if (scan.isSuspended) { + suspendDuration = currTime - scan.suspendStartTime; totalSuspendTime += suspendDuration; - activeDuration = scanDuration - scan.suspendDuration - suspendDuration; - totalActiveTime += activeDuration; - switch (scan.scanMode) { - case ScanSettings.SCAN_MODE_OPPORTUNISTIC: - oppScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_LOW_POWER: - lowPowerScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_BALANCED: - balancedScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_LOW_LATENCY: - lowLatencyScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_AMBIENT_DISCOVERY: - ambientDiscoveryScan += activeDuration; - break; - } + } + + totalScanTime += scanDuration; + totalSuspendTime += suspendDuration; + activeDuration = scanDuration - scan.suspendDuration - suspendDuration; + totalActiveTime += activeDuration; + switch (scan.scanMode) { + case ScanSettings.SCAN_MODE_OPPORTUNISTIC: + oppScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_LOW_POWER: + lowPowerScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_BALANCED: + balancedScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_LOW_LATENCY: + lowLatencyScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_AMBIENT_DISCOVERY: + ambientDiscoveryScan += activeDuration; + break; } } + long Score = (oppScanTime * OPPORTUNISTIC_WEIGHT + lowPowerScanTime * LOW_POWER_WEIGHT @@ -1117,8 +1107,7 @@ class AppScanStats { if (!mOngoingScans.isEmpty()) { sb.append("\n Ongoing scans :"); - for (Integer key : mOngoingScans.keySet()) { - LastScan scan = mOngoingScans.get(key); + for (LastScan scan : mOngoingScans.values()) { Date timestamp = new Date(currentTime - currTime + scan.timestamp); sb.append("\n ").append(DATE_FORMAT.get().format(timestamp)).append(" - "); sb.append((currTime - scan.timestamp)).append("ms "); diff --git a/android/app/src/com/com/android/bluetooth/le_scan/BatchScanThrottler.java b/android/app/src/com/android/bluetooth/le_scan/BatchScanThrottler.java index 4fd324dcf9..3cc06fffe4 100644 --- a/android/app/src/com/com/android/bluetooth/le_scan/BatchScanThrottler.java +++ b/android/app/src/com/android/bluetooth/le_scan/BatchScanThrottler.java @@ -91,9 +91,9 @@ class BatchScanThrottler { : UNFILTERED_DELAY_FLOOR_MS; long intervalMillis = Long.MAX_VALUE; for (ScanClient client : batchClients) { - if (client.settings.getReportDelayMillis() > 0) { - long clientIntervalMillis = client.settings.getReportDelayMillis(); - if ((client.filters == null || client.filters.isEmpty()) + if (client.mSettings.getReportDelayMillis() > 0) { + long clientIntervalMillis = client.mSettings.getReportDelayMillis(); + if ((client.mFilters == null || client.mFilters.isEmpty()) && clientIntervalMillis < unfilteredFloor) { clientIntervalMillis = unfilteredFloor; } diff --git a/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java b/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java index feb30fd9c9..57729351c6 100644 --- a/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java +++ b/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java @@ -135,7 +135,7 @@ class MsftAdvMonitor { return mAddress; } - private boolean dataMaskIsEmpty(byte[] mask) { + private static boolean dataMaskIsEmpty(byte[] mask) { if (mask == null || mask.length == 0) return true; if (mask.length == 1 && mask[0] == 0) return true; return false; diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanClient.java b/android/app/src/com/android/bluetooth/le_scan/ScanClient.java index f3513b3927..b0ace25b49 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanClient.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanClient.java @@ -26,30 +26,30 @@ import java.util.Objects; /** Helper class identifying a client that has requested LE scan results. */ class ScanClient { - public int scannerId; - public ScanSettings settings; - public int scanModeApp; - public boolean started = false; - public boolean isInternalClient = false; - public int appUid; - public List<ScanFilter> filters; - // App associated with the scan client died. - public boolean appDied; - public boolean hasLocationPermission; - public UserHandle userHandle; - public boolean isQApp; - public boolean eligibleForSanitizedExposureNotification; - public boolean hasNetworkSettingsPermission; - public boolean hasNetworkSetupWizardPermission; - public boolean hasScanWithoutLocationPermission; - public boolean hasDisavowedLocation; - public List<String> associatedDevices; - - public AppScanStats stats = null; - private static final ScanSettings DEFAULT_SCAN_SETTINGS = new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build(); + final int mScannerId; + final int mAppUid; + final List<ScanFilter> mFilters; + + ScanSettings mSettings; + int mScanModeApp; + boolean mStarted = false; + boolean mIsInternalClient = false; + // App associated with the scan client died. + boolean mAppDied; + boolean mHasLocationPermission; + UserHandle mUserHandle; + boolean mIsQApp; + boolean mEligibleForSanitizedExposureNotification; + boolean mHasNetworkSettingsPermission; + boolean mHasNetworkSetupWizardPermission; + boolean mHasScanWithoutLocationPermission; + boolean mHasDisavowedLocation; + List<String> mAssociatedDevices; + AppScanStats mStats = null; + ScanClient(int scannerId) { this(scannerId, DEFAULT_SCAN_SETTINGS, null); } @@ -59,11 +59,11 @@ class ScanClient { } ScanClient(int scannerId, ScanSettings settings, List<ScanFilter> filters, int appUid) { - this.scannerId = scannerId; - this.settings = settings; - this.scanModeApp = settings.getScanMode(); - this.filters = filters; - this.appUid = appUid; + mScannerId = scannerId; + mSettings = settings; + mScanModeApp = settings.getScanMode(); + mFilters = filters; + mAppUid = appUid; } @Override @@ -74,27 +74,27 @@ class ScanClient { if (!(obj instanceof ScanClient other)) { return false; } - return scannerId == other.scannerId; + return mScannerId == other.mScannerId; } @Override public int hashCode() { - return Objects.hash(scannerId); + return Objects.hash(mScannerId); } @Override public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(" [ScanClient") - .append(" scanModeApp ") - .append(scanModeApp) + StringBuilder sb = new StringBuilder(" [ScanClient"); + sb.append(" scanModeApp ") + .append(mScanModeApp) .append(" scanModeUsed ") - .append(settings.getScanMode()); - if (stats != null && stats.mAppName != null) { - sb.append(" [appScanStats ").append(stats.mAppName).append("]"); + .append(mSettings.getScanMode()); + + if (mStats != null && mStats.mAppName != null) { + sb.append(" [appScanStats ").append(mStats.mAppName).append("]"); } - sb.append("]"); - return sb.toString(); + + return sb.append("]").toString(); } /** @@ -103,20 +103,20 @@ class ScanClient { * @return true if scan settings are updated, false otherwise. */ boolean updateScanMode(int newScanMode) { - if (settings.getScanMode() == newScanMode) { + if (mSettings.getScanMode() == newScanMode) { return false; } - ScanSettings.Builder builder = new ScanSettings.Builder(); - settings = - builder.setScanMode(newScanMode) - .setCallbackType(settings.getCallbackType()) - .setScanResultType(settings.getScanResultType()) - .setReportDelay(settings.getReportDelayMillis()) - .setNumOfMatches(settings.getNumOfMatches()) - .setMatchMode(settings.getMatchMode()) - .setLegacy(settings.getLegacy()) - .setPhy(settings.getPhy()) + mSettings = + new ScanSettings.Builder() + .setScanMode(newScanMode) + .setCallbackType(mSettings.getCallbackType()) + .setScanResultType(mSettings.getScanResultType()) + .setReportDelay(mSettings.getReportDelayMillis()) + .setNumOfMatches(mSettings.getNumOfMatches()) + .setMatchMode(mSettings.getMatchMode()) + .setLegacy(mSettings.getLegacy()) + .setPhy(mSettings.getPhy()) .build(); return true; } diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanController.java b/android/app/src/com/android/bluetooth/le_scan/ScanController.java index 2c641500cb..f0ea7894ea 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanController.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanController.java @@ -71,6 +71,8 @@ import com.android.internal.annotations.VisibleForTesting; import libcore.util.HexEncoding; +import com.google.protobuf.ByteString; + import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; @@ -316,7 +318,7 @@ public class ScanController { return true; } - private ScanResult getSanitizedExposureNotification(ScanResult result) { + private static ScanResult getSanitizedExposureNotification(ScanResult result) { ScanRecord record = result.getScanRecord(); // Remove the flags part of the payload, if present if (record.getBytes().length > EXPOSURE_NOTIFICATION_FLAGS_LENGTH @@ -424,13 +426,13 @@ public class ScanController { BluetoothAdapter.getDefaultAdapter().getRemoteLeDevice(address, addressType); for (ScanClient client : mScanManager.getRegularScanQueue()) { - ScannerMap.ScannerApp app = mScannerMap.getById(client.scannerId); + ScannerMap.ScannerApp app = mScannerMap.getById(client.mScannerId); if (app == null) { Log.v(TAG, "App is null; skip."); continue; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; byte[] scanRecordData; // This is for compatibility with applications that assume fixed size scan data. if (settings.getLegacy()) { @@ -460,23 +462,23 @@ public class ScanController { scanRecord, SystemClock.elapsedRealtimeNanos()); - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { if (mLocationDenylistPredicate.test(result)) { - Log.i(TAG, "Skipping client " + client.scannerId + " for location deny list"); + Log.i(TAG, "Skipping client " + client.mScannerId + " for location deny list"); continue; } } boolean hasPermission = hasScanResultPermission(client); if (!hasPermission) { - for (String associatedDevice : client.associatedDevices) { + for (String associatedDevice : client.mAssociatedDevices) { if (associatedDevice.equalsIgnoreCase(address)) { hasPermission = true; break; } } } - if (!hasPermission && client.eligibleForSanitizedExposureNotification) { + if (!hasPermission && client.mEligibleForSanitizedExposureNotification) { ScanResult sanitized = getSanitizedExposureNotification(result); if (sanitized != null) { hasPermission = true; @@ -499,7 +501,7 @@ public class ScanController { } try { - app.mAppScanStats.addResult(client.scannerId); + app.mAppScanStats.addResult(client.mScannerId); if (app.mCallback != null) { app.mCallback.onScanResult(result); } else { @@ -526,8 +528,8 @@ public class ScanController { } catch (PendingIntent.CanceledException e) { final long token = Binder.clearCallingIdentity(); try { - stopScanInternal(client.scannerId); - unregisterScannerInternal(client.scannerId); + stopScanInternal(client.mScannerId); + unregisterScannerInternal(client.mScannerId); } finally { Binder.restoreCallingIdentity(token); } @@ -588,35 +590,35 @@ public class ScanController { /** Determines if the given scan client has the appropriate permissions to receive callbacks. */ private boolean hasScanResultPermission(final ScanClient client) { - if (leaudioBassScanWithInternalScanController() && client.isInternalClient) { + if (leaudioBassScanWithInternalScanController() && client.mIsInternalClient) { // Bypass permission check for internal clients return true; } - if (client.hasNetworkSettingsPermission - || client.hasNetworkSetupWizardPermission - || client.hasScanWithoutLocationPermission) { + if (client.mHasNetworkSettingsPermission + || client.mHasNetworkSetupWizardPermission + || client.mHasScanWithoutLocationPermission) { return true; } - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { return true; } - return client.hasLocationPermission - && !Utils.blockedByLocationOff(mAdapterService, client.userHandle); + return client.mHasLocationPermission + && !Utils.blockedByLocationOff(mAdapterService, client.mUserHandle); } // Check if a scan record matches a specific filters. - private boolean matchesFilters(ScanClient client, ScanResult scanResult) { + private static boolean matchesFilters(ScanClient client, ScanResult scanResult) { return matchesFilters(client, scanResult, null); } // Check if a scan record matches a specific filters or original address - private boolean matchesFilters( + private static boolean matchesFilters( ScanClient client, ScanResult scanResult, String originalAddress) { - if (client.filters == null || client.filters.isEmpty()) { + if (client.mFilters == null || client.mFilters.isEmpty()) { // TODO: Do we really wanna return true here? return true; } - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { // Need to check the filter matches, and the original address without changing the API if (filter.matches(scanResult)) { return true; @@ -630,15 +632,15 @@ public class ScanController { } private void handleDeadScanClient(ScanClient client) { - if (client.appDied) { - Log.w(TAG, "Already dead client " + client.scannerId); + if (client.mAppDied) { + Log.w(TAG, "Already dead client " + client.mScannerId); return; } - client.appDied = true; - if (client.stats != null) { - client.stats.isAppDead = true; + client.mAppDied = true; + if (client.mStats != null) { + client.mStats.isAppDead = true; } - stopScanInternal(client.scannerId); + stopScanInternal(client.mScannerId); } /** Callback method for scan filter enablement/disablement. */ @@ -710,7 +712,7 @@ public class ScanController { ScanClient findBatchScanClientById(int scannerId) { for (ScanClient client : mScanManager.getBatchScanQueue()) { - if (client.scannerId == scannerId) { + if (client.mScannerId == scannerId) { return client; } } @@ -762,7 +764,7 @@ public class ScanController { } else { permittedResults = new ArrayList<ScanResult>(); for (ScanResult scanResult : results) { - for (String associatedDevice : client.associatedDevices) { + for (String associatedDevice : client.mAssociatedDevices) { if (associatedDevice.equalsIgnoreCase( scanResult.getDevice().getAddress())) { permittedResults.add(scanResult); @@ -771,7 +773,7 @@ public class ScanController { } } - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { permittedResults.removeIf(mLocationDenylistPredicate); } if (permittedResults.isEmpty()) { @@ -811,7 +813,7 @@ public class ScanController { if (mScanManager.isAutoBatchScanClientEnabled(client)) { Log.d(TAG, "sendBatchScanResults() to onScanResult()" + client); for (ScanResult result : results) { - app.mAppScanStats.addResult(client.scannerId); + app.mAppScanStats.addResult(client.mScannerId); app.mCallback.onScanResult(result); } } else { @@ -832,7 +834,7 @@ public class ScanController { // Check and deliver scan results for different scan clients. private void deliverBatchScan(ScanClient client, Set<ScanResult> allResults) throws RemoteException { - ScannerMap.ScannerApp app = mScannerMap.getById(client.scannerId); + ScannerMap.ScannerApp app = mScannerMap.getById(client.mScannerId); if (app == null) { return; } @@ -843,7 +845,7 @@ public class ScanController { } else { permittedResults = new ArrayList<ScanResult>(); for (ScanResult scanResult : allResults) { - for (String associatedDevice : client.associatedDevices) { + for (String associatedDevice : client.mAssociatedDevices) { if (associatedDevice.equalsIgnoreCase(scanResult.getDevice().getAddress())) { permittedResults.add(scanResult); } @@ -851,7 +853,7 @@ public class ScanController { } } - if (client.filters == null || client.filters.isEmpty()) { + if (client.mFilters == null || client.mFilters.isEmpty()) { sendBatchScanResults(app, client, permittedResults); return; } @@ -943,7 +945,7 @@ public class ScanController { } // Reverse byte array. - private void reverse(byte[] address) { + private static void reverse(byte[] address) { int len = address.length; for (int i = 0; i < len / 2; ++i) { byte b = address[i]; @@ -966,10 +968,10 @@ public class ScanController { AdvtFilterOnFoundOnLostInfo createOnTrackAdvFoundLostObject( int clientIf, - int advPktLen, - byte[] advPkt, - int scanRspLen, - byte[] scanRsp, + int advPacketLen, + byte[] advPacket, + int scanResponseLen, + byte[] scanResponse, int filtIndex, int advState, int advInfoPresent, @@ -978,13 +980,12 @@ public class ScanController { int txPower, int rssiValue, int timeStamp) { - return new AdvtFilterOnFoundOnLostInfo( clientIf, - advPktLen, - advPkt, - scanRspLen, - scanRsp, + advPacketLen, + ByteString.copyFrom(advPacket), + scanResponseLen, + ByteString.copyFrom(scanResponse), filtIndex, advState, advInfoPresent, @@ -999,15 +1000,15 @@ public class ScanController { Log.d( TAG, "onTrackAdvFoundLost() - scannerId= " - + trackingInfo.getClientIf() + + trackingInfo.clientIf() + " address = " - + trackingInfo.getAddress() + + trackingInfo.address() + " addressType = " - + trackingInfo.getAddressType() + + trackingInfo.addressType() + " adv_state = " - + trackingInfo.getAdvState()); + + trackingInfo.advState()); - ScannerMap.ScannerApp app = mScannerMap.getById(trackingInfo.getClientIf()); + ScannerMap.ScannerApp app = mScannerMap.getById(trackingInfo.clientIf()); if (app == null) { Log.e(TAG, "app is null"); return; @@ -1015,19 +1016,18 @@ public class ScanController { BluetoothDevice device = BluetoothAdapter.getDefaultAdapter() - .getRemoteLeDevice( - trackingInfo.getAddress(), trackingInfo.getAddressType()); - int advertiserState = trackingInfo.getAdvState(); + .getRemoteLeDevice(trackingInfo.address(), trackingInfo.addressType()); + int advertiserState = trackingInfo.advState(); ScanResult result = new ScanResult( device, ScanRecord.parseFromBytes(trackingInfo.getResult()), - trackingInfo.getRSSIValue(), + trackingInfo.rssiValue(), SystemClock.elapsedRealtimeNanos()); for (ScanClient client : mScanManager.getRegularScanQueue()) { - if (client.scannerId == trackingInfo.getClientIf()) { - ScanSettings settings = client.settings; + if (client.mScannerId == trackingInfo.clientIf()) { + ScanSettings settings = client.mSettings; if ((advertiserState == ADVT_STATE_ONFOUND) && ((settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) != 0)) { @@ -1052,7 +1052,7 @@ public class ScanController { "Not reporting onlost/onfound : " + advertiserState + " scannerId = " - + client.scannerId + + client.mScannerId + " callbackType " + settings.getCallbackType()); } @@ -1229,35 +1229,35 @@ public class ScanController { settings = enforceReportDelayFloor(settings); enforcePrivilegedPermissionIfNeeded(filters); final ScanClient scanClient = new ScanClient(scannerId, settings, filters); - scanClient.userHandle = Binder.getCallingUserHandle(); + scanClient.mUserHandle = Binder.getCallingUserHandle(); mAppOps.checkPackage(Binder.getCallingUid(), callingPackage); - scanClient.eligibleForSanitizedExposureNotification = + scanClient.mEligibleForSanitizedExposureNotification = callingPackage.equals(mExposureNotificationPackage); - scanClient.hasDisavowedLocation = + scanClient.mHasDisavowedLocation = Utils.hasDisavowedLocationForScan( mAdapterService, attributionSource, mTestModeEnabled); - scanClient.isQApp = + scanClient.mIsQApp = checkCallerTargetSdk(mAdapterService, callingPackage, Build.VERSION_CODES.Q); - if (!scanClient.hasDisavowedLocation) { - if (scanClient.isQApp) { - scanClient.hasLocationPermission = + if (!scanClient.mHasDisavowedLocation) { + if (scanClient.mIsQApp) { + scanClient.mHasLocationPermission = Utils.checkCallerHasFineLocation( - mAdapterService, attributionSource, scanClient.userHandle); + mAdapterService, attributionSource, scanClient.mUserHandle); } else { - scanClient.hasLocationPermission = + scanClient.mHasLocationPermission = Utils.checkCallerHasCoarseOrFineLocation( - mAdapterService, attributionSource, scanClient.userHandle); + mAdapterService, attributionSource, scanClient.mUserHandle); } } - scanClient.hasNetworkSettingsPermission = + scanClient.mHasNetworkSettingsPermission = Utils.checkCallerHasNetworkSettingsPermission(mAdapterService); - scanClient.hasNetworkSetupWizardPermission = + scanClient.mHasNetworkSetupWizardPermission = Utils.checkCallerHasNetworkSetupWizardPermission(mAdapterService); - scanClient.hasScanWithoutLocationPermission = + scanClient.mHasScanWithoutLocationPermission = Utils.checkCallerHasScanWithoutLocationPermission(mAdapterService); - scanClient.associatedDevices = getAssociatedDevices(callingPackage); + scanClient.mAssociatedDevices = getAssociatedDevices(callingPackage); startScan(scannerId, settings, filters, scanClient); } @@ -1265,18 +1265,18 @@ public class ScanController { /** Intended for internal use within the Bluetooth app. Bypass permission check */ public void startScanInternal(int scannerId, ScanSettings settings, List<ScanFilter> filters) { final ScanClient scanClient = new ScanClient(scannerId, settings, filters); - scanClient.isInternalClient = true; - scanClient.userHandle = Binder.getCallingUserHandle(); - scanClient.eligibleForSanitizedExposureNotification = false; - scanClient.hasDisavowedLocation = false; - scanClient.isQApp = true; - scanClient.hasNetworkSettingsPermission = + scanClient.mIsInternalClient = true; + scanClient.mUserHandle = Binder.getCallingUserHandle(); + scanClient.mEligibleForSanitizedExposureNotification = false; + scanClient.mHasDisavowedLocation = false; + scanClient.mIsQApp = true; + scanClient.mHasNetworkSettingsPermission = Utils.checkCallerHasNetworkSettingsPermission(mAdapterService); - scanClient.hasNetworkSetupWizardPermission = + scanClient.mHasNetworkSetupWizardPermission = Utils.checkCallerHasNetworkSetupWizardPermission(mAdapterService); - scanClient.hasScanWithoutLocationPermission = + scanClient.mHasScanWithoutLocationPermission = Utils.checkCallerHasScanWithoutLocationPermission(mAdapterService); - scanClient.associatedDevices = Collections.emptyList(); + scanClient.mAssociatedDevices = Collections.emptyList(); startScan(scannerId, settings, filters, scanClient); } @@ -1285,7 +1285,7 @@ public class ScanController { int scannerId, ScanSettings settings, List<ScanFilter> filters, ScanClient scanClient) { AppScanStats app = mScannerMap.getAppScanStatsById(scannerId); if (app != null) { - scanClient.stats = app; + scanClient.mStats = app; boolean isFilteredScan = (filters != null) && !filters.isEmpty(); boolean isCallbackScan = false; @@ -1392,20 +1392,21 @@ public class ScanController { final PendingIntentInfo piInfo = app.mInfo; final ScanClient scanClient = new ScanClient(scannerId, piInfo.settings, piInfo.filters, piInfo.callingUid); - scanClient.hasLocationPermission = app.mHasLocationPermission; - scanClient.userHandle = app.mUserHandle; - scanClient.isQApp = checkCallerTargetSdk(mAdapterService, app.mName, Build.VERSION_CODES.Q); - scanClient.eligibleForSanitizedExposureNotification = + scanClient.mHasLocationPermission = app.mHasLocationPermission; + scanClient.mUserHandle = app.mUserHandle; + scanClient.mIsQApp = + checkCallerTargetSdk(mAdapterService, app.mName, Build.VERSION_CODES.Q); + scanClient.mEligibleForSanitizedExposureNotification = app.mEligibleForSanitizedExposureNotification; - scanClient.hasNetworkSettingsPermission = app.mHasNetworkSettingsPermission; - scanClient.hasNetworkSetupWizardPermission = app.mHasNetworkSetupWizardPermission; - scanClient.hasScanWithoutLocationPermission = app.mHasScanWithoutLocationPermission; - scanClient.associatedDevices = app.mAssociatedDevices; - scanClient.hasDisavowedLocation = app.mHasDisavowedLocation; + scanClient.mHasNetworkSettingsPermission = app.mHasNetworkSettingsPermission; + scanClient.mHasNetworkSetupWizardPermission = app.mHasNetworkSetupWizardPermission; + scanClient.mHasScanWithoutLocationPermission = app.mHasScanWithoutLocationPermission; + scanClient.mAssociatedDevices = app.mAssociatedDevices; + scanClient.mHasDisavowedLocation = app.mHasDisavowedLocation; AppScanStats scanStats = mScannerMap.getAppScanStatsById(scannerId); if (scanStats != null) { - scanClient.stats = scanStats; + scanClient.mStats = scanStats; boolean isFilteredScan = (piInfo.filters != null) && !piInfo.filters.isEmpty(); scanStats.recordScanStart( piInfo.settings, @@ -1575,12 +1576,12 @@ public class ScanController { private ScanClient getScanClient(int clientIf) { for (ScanClient client : mScanManager.getRegularScanQueue()) { - if (client.scannerId == clientIf) { + if (client.mScannerId == clientIf) { return client; } } for (ScanClient client : mScanManager.getBatchScanQueue()) { - if (client.scannerId == clientIf) { + if (client.mScannerId == clientIf) { return client; } } @@ -1733,5 +1734,4 @@ public class ScanController { builder.addAllScanEvent(mScanEvents); } } - } diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java b/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java index b2b0b7eec0..b5614ea927 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java @@ -293,7 +293,8 @@ import java.util.UUID; } } - private byte[] concatenate(ParcelUuid serviceDataUuid, byte[] serviceData, boolean isMask) { + private static byte[] concatenate( + ParcelUuid serviceDataUuid, byte[] serviceData, boolean isMask) { byte[] uuid = BluetoothUuid.uuidToBytes(serviceDataUuid); int dataLen = uuid.length + serviceData.length; diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java index 211b0174c0..a397d034a8 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java @@ -16,6 +16,10 @@ package com.android.bluetooth.le_scan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.bluetooth.le.ScanSettings.getScanModeString; import android.app.ActivityManager; @@ -268,7 +272,7 @@ public class ScanManager { // construct this every time. Set<ScanClient> fullBatchClients = new HashSet<ScanClient>(); for (ScanClient client : mBatchClients) { - if (client.settings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) { + if (client.mSettings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) { fullBatchClients.add(client); } } @@ -397,10 +401,10 @@ public class ScanManager { TAG, "Cannot start unfiltered scan in screen-off. This scan will be resumed " + "later: " - + client.scannerId); + + client.mScannerId); mSuspendedScanClients.add(client); - if (client.stats != null) { - client.stats.recordScanSuspend(client.scannerId); + if (client.mStats != null) { + client.mStats.recordScanSuspend(client.mScannerId); } return; } @@ -411,10 +415,10 @@ public class ScanManager { TAG, "Cannot start unfiltered scan in location-off. This scan will be" + " resumed when location is on: " - + client.scannerId); + + client.mScannerId); mSuspendedScanClients.add(client); - if (client.stats != null) { - client.stats.recordScanSuspend(client.scannerId); + if (client.mStats != null) { + client.mStats.recordScanSuspend(client.mScannerId); } return; } @@ -451,11 +455,11 @@ public class ScanManager { + mAdapterService.getScanTimeoutMillis() + ")" + "to scannerId " - + client.scannerId); + + client.mScannerId); } } } - client.started = true; + client.mStarted = true; } private boolean requiresScreenOn(ScanClient client) { @@ -463,18 +467,18 @@ public class ScanManager { return !mScanNative.isOpportunisticScanClient(client) && !isFiltered; } - private boolean requiresLocationOn(ScanClient client) { + private static boolean requiresLocationOn(ScanClient client) { boolean isFiltered = isFilteredScan(client); - return !client.hasDisavowedLocation && !isFiltered; + return !client.mHasDisavowedLocation && !isFiltered; } - private boolean isFilteredScan(ScanClient client) { - if ((client.filters == null) || client.filters.isEmpty()) { + private static boolean isFilteredScan(ScanClient client) { + if ((client.mFilters == null) || client.mFilters.isEmpty()) { return false; } boolean atLeastOneValidFilter = false; - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { // A valid filter need at least one field not empty if (!filter.isAllFieldsEmpty()) { atLeastOneValidFilter = true; @@ -507,9 +511,9 @@ public class ScanManager { } mScanNative.stopBatchScan(client); } - if (client.appDied) { - Log.d(TAG, "app died, unregister scanner - " + client.scannerId); - mScanController.unregisterScannerInternal(client.scannerId); + if (client.mAppDied) { + Log.d(TAG, "app died, unregister scanner - " + client.mScannerId); + mScanController.unregisterScannerInternal(client.mScannerId); } } @@ -519,23 +523,23 @@ public class ScanManager { Log.d(TAG, "There is no batch scan client to flush " + client); return; } - mScanNative.flushBatchResults(client.scannerId); + mScanNative.flushBatchResults(client.mScannerId); } - private boolean isBatchClient(ScanClient client) { - if (client == null || client.settings == null) { + private static boolean isBatchClient(ScanClient client) { + if (client == null || client.mSettings == null) { return false; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; return settings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES && settings.getReportDelayMillis() != 0; } private boolean isScanSupported(ScanClient client) { - if (client == null || client.settings == null) { + if (client == null || client.mSettings == null) { return true; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; if (isFilteringSupported()) { return true; } @@ -602,8 +606,8 @@ public class ScanManager { if ((requiresScreenOn(client) && !mScreenOn) || (requiresLocationOn(client) && !mLocationManager.isLocationEnabled())) { /*Suspend unfiltered scans*/ - if (client.stats != null) { - client.stats.recordScanSuspend(client.scannerId); + if (client.mStats != null) { + client.mStats.recordScanSuspend(client.mScannerId); } Log.d(TAG, "suspend scan " + client); handleStopScan(client); @@ -653,8 +657,8 @@ public class ScanManager { TAG, "Scan mode update during setAutoBatchScanClient() to " + getScanModeString(ScanSettings.SCAN_MODE_SCREEN_OFF)); - if (client.stats != null) { - client.stats.setAutoBatchScan(client.scannerId, true); + if (client.mStats != null) { + client.mStats.setAutoBatchScan(client.mScannerId, true); } } @@ -662,13 +666,13 @@ public class ScanManager { if (!isAutoBatchScanClientEnabled(client)) { return; } - client.updateScanMode(client.scanModeApp); + client.updateScanMode(client.mScanModeApp); Log.d( TAG, "Scan mode update during clearAutoBatchScanClient() to " - + getScanModeString(client.scanModeApp)); - if (client.stats != null) { - client.stats.setAutoBatchScan(client.scannerId, false); + + getScanModeString(client.mScanModeApp)); + if (client.mStats != null) { + client.mStats.setAutoBatchScan(client.mScannerId, false); } } @@ -688,13 +692,13 @@ public class ScanManager { if (mScanNative.isOpportunisticScanClient(client)) { return false; } - int updatedScanMode = client.scanModeApp; + int updatedScanMode = client.mScanModeApp; if (!isAppForeground(client) || mScanNative.isForceDowngradedScanClient(client)) { updatedScanMode = ScanSettings.SCAN_MODE_SCREEN_OFF; } else { // The following codes are effectively only for services // Apps are either already or will be soon handled by handleImportanceChange(). - switch (client.scanModeApp) { + switch (client.mScanModeApp) { case ScanSettings.SCAN_MODE_LOW_POWER: updatedScanMode = ScanSettings.SCAN_MODE_SCREEN_OFF; break; @@ -713,7 +717,7 @@ public class ScanManager { Log.d( TAG, "Scan mode update during screen off from " - + getScanModeString(client.scanModeApp) + + getScanModeString(client.mScanModeApp) + " to " + getScanModeString(updatedScanMode)); return client.updateScanMode(updatedScanMode); @@ -724,7 +728,7 @@ public class ScanManager { * background triggering onUidImportance(). */ private boolean isAppForeground(ScanClient client) { - return mIsUidForegroundMap.get(client.appUid, DEFAULT_UID_IS_FOREGROUND); + return mIsUidForegroundMap.get(client.mAppUid, DEFAULT_UID_IS_FOREGROUND); } private void fetchAppForegroundState(ScanClient client) { @@ -732,7 +736,7 @@ public class ScanManager { if (mActivityManager == null || packageManager == null) { return; } - String[] packages = packageManager.getPackagesForUid(client.appUid); + String[] packages = packageManager.getPackagesForUid(client.mAppUid); if (packages == null || packages.length == 0) { return; } @@ -744,7 +748,7 @@ public class ScanManager { boolean isForeground = importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE; - mIsUidForegroundMap.put(client.appUid, isForeground); + mIsUidForegroundMap.put(client.mAppUid, isForeground); } private boolean updateScanModeBeforeStart(ScanClient client) { @@ -766,10 +770,10 @@ public class ScanManager { } private boolean upgradeScanModeBeforeStart(ScanClient client) { - if (client.started || mAdapterService.getScanUpgradeDurationMillis() == 0) { + if (client.mStarted || mAdapterService.getScanUpgradeDurationMillis() == 0) { return false; } - if (client.stats == null || client.stats.hasRecentScan()) { + if (client.mStats == null || client.mStats.hasRecentScan()) { return false; } if (!isAppForeground(client) || isBatchClient(client)) { @@ -782,7 +786,7 @@ public class ScanManager { Log.d( TAG, "scanMode is upgraded to " - + getScanModeString(client.settings.getScanMode()) + + getScanModeString(client.mSettings.getScanMode()) + " for " + client); sendMessageDelayed(msg, mAdapterService.getScanUpgradeDurationMillis()); @@ -791,8 +795,8 @@ public class ScanManager { return false; } - private boolean upgradeScanModeByOneLevel(ScanClient client) { - switch (client.scanModeApp) { + private static boolean upgradeScanModeByOneLevel(ScanClient client) { + switch (client.mScanModeApp) { case ScanSettings.SCAN_MODE_LOW_POWER: return client.updateScanMode(ScanSettings.SCAN_MODE_BALANCED); case ScanSettings.SCAN_MODE_BALANCED: @@ -806,15 +810,15 @@ public class ScanManager { } void revertScanModeUpgrade(ScanClient client) { - if (mPriorityMap.get(client.settings.getScanMode()) - <= mPriorityMap.get(client.scanModeApp)) { + if (mPriorityMap.get(client.mSettings.getScanMode()) + <= mPriorityMap.get(client.mScanModeApp)) { return; } - if (client.updateScanMode(client.scanModeApp)) { + if (client.updateScanMode(client.mScanModeApp)) { Log.d( TAG, "scanMode upgrade is reverted to " - + getScanModeString(client.scanModeApp) + + getScanModeString(client.mScanModeApp) + " for " + client); mScanNative.configureRegularScanParams(); @@ -826,7 +830,7 @@ public class ScanManager { return false; } int scanMode = - isAppForeground(client) ? client.scanModeApp : SCAN_MODE_APP_IN_BACKGROUND; + isAppForeground(client) ? client.mScanModeApp : SCAN_MODE_APP_IN_BACKGROUND; int maxScanMode = mScanNative.isForceDowngradedScanClient(client) ? SCAN_MODE_FORCE_DOWNGRADED @@ -834,20 +838,20 @@ public class ScanManager { Log.d( TAG, "Scan mode update during screen on from " - + getScanModeString(client.scanModeApp) + + getScanModeString(client.mScanModeApp) + " to " + getScanModeString(getMinScanMode(scanMode, maxScanMode))); return client.updateScanMode(getMinScanMode(scanMode, maxScanMode)); } private boolean downgradeScanModeFromMaxDuty(ScanClient client) { - if ((client.stats == null) || mAdapterService.getScanDowngradeDurationMillis() == 0) { + if ((client.mStats == null) || mAdapterService.getScanDowngradeDurationMillis() == 0) { return false; } int updatedScanMode = - getMinScanMode(client.settings.getScanMode(), SCAN_MODE_MAX_IN_CONCURRENCY); + getMinScanMode(client.mSettings.getScanMode(), SCAN_MODE_MAX_IN_CONCURRENCY); if (client.updateScanMode(updatedScanMode)) { - client.stats.setScanDowngrade(client.scannerId, true); + client.mStats.setScanDowngrade(client.mScannerId, true); Log.d( TAG, "downgradeScanModeFromMaxDuty() to " @@ -863,8 +867,8 @@ public class ScanManager { if (!mScanNative.isDowngradedScanClient(client)) { return false; } - if (client.stats != null) { - client.stats.setScanDowngrade(client.scannerId, false); + if (client.mStats != null) { + client.mStats.setScanDowngrade(client.mScannerId, false); } Log.d(TAG, "revertDowngradeScanModeFromMaxDuty() for " + client); if (mScreenOn) { @@ -893,8 +897,8 @@ public class ScanManager { ScanClient client = iterator.next(); if ((!requiresScreenOn(client) || mScreenOn) && (!requiresLocationOn(client) || mLocationManager.isLocationEnabled())) { - if (client.stats != null) { - client.stats.recordScanResume(client.scannerId); + if (client.mStats != null) { + client.mStats.recordScanResume(client.mScannerId); } Log.d(TAG, "resume scan " + client); handleStartScan(client); @@ -1087,10 +1091,10 @@ public class ScanManager { ScanClient client1m = getAggressiveClient(mRegularScanClients, true, false); ScanClient clientCoded = getAggressiveClient(mRegularScanClients, false, false); if (client1m != null) { - newScanSetting1m = client1m.settings.getScanMode(); + newScanSetting1m = client1m.mSettings.getScanMode(); } if (clientCoded != null) { - newScanSettingCoded = clientCoded.settings.getScanMode(); + newScanSettingCoded = clientCoded.mSettings.getScanMode(); } int curPhyMask = @@ -1142,10 +1146,10 @@ public class ScanManager { + " / " + clientCoded); mNativeInterface.gattSetScanParameters( - client1m == null ? 0 : client1m.scannerId, + client1m == null ? 0 : client1m.mScannerId, scanInterval1m, scanWindow1m, - clientCoded == null ? 0 : clientCoded.scannerId, + clientCoded == null ? 0 : clientCoded.mScannerId, scanIntervalCoded, scanWindowCoded, scanPhyMask); @@ -1167,7 +1171,7 @@ public class ScanManager { if (!isBatch && !isPhyConfigured(client, use1mPhy)) { continue; } - int priority = mPriorityMap.get(client.settings.getScanMode()); + int priority = mPriorityMap.get(client.mSettings.getScanMode()); if (priority > currentScanModePriority) { result = client; currentScanModePriority = priority; @@ -1181,12 +1185,12 @@ public class ScanManager { // When the flag is off the PHY setting is ignored and all clients scan on 1m return use1mPhy; } - if (client.settings.getPhy() == ScanSettings.PHY_LE_ALL_SUPPORTED) { + if (client.mSettings.getPhy() == ScanSettings.PHY_LE_ALL_SUPPORTED) { return true; } return use1mPhy - ? client.settings.getPhy() == BluetoothDevice.PHY_LE_1M - : client.settings.getPhy() == BluetoothDevice.PHY_LE_CODED; + ? client.mSettings.getPhy() == BluetoothDevice.PHY_LE_1M + : client.mSettings.getPhy() == BluetoothDevice.PHY_LE_CODED; } private static boolean shouldUpdateScan(int newScanSetting, int oldScanSetting) { @@ -1196,12 +1200,12 @@ public class ScanManager { } private int getScanWindow(@Nullable ScanClient client) { - return client == null ? 0 : Utils.millsToUnit(getScanWindowMillis(client.settings)); + return client == null ? 0 : Utils.millsToUnit(getScanWindowMillis(client.mSettings)); } private int getScanInterval(@Nullable ScanClient client) { // convert scanWindow and scanInterval from ms to LE scan units(0.625ms) - return client == null ? 0 : Utils.millsToUnit(getScanIntervalMillis(client.settings)); + return client == null ? 0 : Utils.millsToUnit(getScanIntervalMillis(client.mSettings)); } private void recordScanRadioStart( @@ -1221,13 +1225,13 @@ public class ScanManager { : clientCoded; } if (chosenClient != null - && chosenClient.stats != null + && chosenClient.mStats != null && !AppScanStats.recordScanRadioStart( - chosenClient.scanModeApp, - chosenClient.scannerId, - chosenClient.stats, - getScanWindowMillis(chosenClient.settings), - getScanIntervalMillis(chosenClient.settings), + chosenClient.mScanModeApp, + chosenClient.mScannerId, + chosenClient.mStats, + getScanWindowMillis(chosenClient.mSettings), + getScanIntervalMillis(chosenClient.mSettings), mTimeProvider)) { Log.w(TAG, "Scan radio already started"); } @@ -1247,18 +1251,18 @@ public class ScanManager { // Start scan native only for the first client. if (numRegularScanClients() == 1 - && client.settings != null - && client.settings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) { + && client.mSettings != null + && client.mSettings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) { Log.d(TAG, "start gattClientScanNative from startRegularScan()"); mNativeInterface.gattClientScan(true); if (!Flags.bleScanAdvMetricsRedesign()) { - if (client.stats != null + if (client.mStats != null && !AppScanStats.recordScanRadioStart( - client.settings.getScanMode(), - client.scannerId, - client.stats, - getScanWindowMillis(client.settings), - getScanIntervalMillis(client.settings), + client.mSettings.getScanMode(), + client.mScannerId, + client.mStats, + getScanWindowMillis(client.mSettings), + getScanIntervalMillis(client.mSettings), mTimeProvider)) { Log.w(TAG, "Scan radio already started"); } @@ -1269,7 +1273,7 @@ public class ScanManager { private int numRegularScanClients() { int num = 0; for (ScanClient client : mRegularScanClients) { - if (client.settings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) { + if (client.mSettings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) { num++; } } @@ -1288,46 +1292,46 @@ public class ScanManager { } } - private boolean isExemptFromScanTimeout(ScanClient client) { + private static boolean isExemptFromScanTimeout(ScanClient client) { return isOpportunisticScanClient(client) || isFirstMatchScanClient(client); } - private boolean isExemptFromAutoBatchScanUpdate(ScanClient client) { + private static boolean isExemptFromAutoBatchScanUpdate(ScanClient client) { return isOpportunisticScanClient(client) || !isAllMatchesAutoBatchScanClient(client); } - private boolean isAutoBatchScanClientEnabled(ScanClient client) { - return client.stats != null && client.stats.isAutoBatchScan(client.scannerId); + private static boolean isAutoBatchScanClientEnabled(ScanClient client) { + return client.mStats != null && client.mStats.isAutoBatchScan(client.mScannerId); } - private boolean isAllMatchesAutoBatchScanClient(ScanClient client) { - return client.settings.getCallbackType() + private static boolean isAllMatchesAutoBatchScanClient(ScanClient client) { + return client.mSettings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH; } - private boolean isOpportunisticScanClient(ScanClient client) { - return client.settings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; + private static boolean isOpportunisticScanClient(ScanClient client) { + return client.mSettings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; } - private boolean isTimeoutScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanTimeout(client.scannerId); + private static boolean isTimeoutScanClient(ScanClient client) { + return (client.mStats != null) && client.mStats.isScanTimeout(client.mScannerId); } - private boolean isDowngradedScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanDowngraded(client.scannerId); + private static boolean isDowngradedScanClient(ScanClient client) { + return (client.mStats != null) && client.mStats.isScanDowngraded(client.mScannerId); } - private boolean isForceDowngradedScanClient(ScanClient client) { + private static boolean isForceDowngradedScanClient(ScanClient client) { return isTimeoutScanClient(client) || isDowngradedScanClient(client); } - private boolean isFirstMatchScanClient(ScanClient client) { - return (client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) + private static boolean isFirstMatchScanClient(ScanClient client) { + return (client.mSettings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) != 0; } private void resetBatchScan(ScanClient client) { - int scannerId = client.scannerId; + int scannerId = client.mScannerId; BatchScanParams batchScanParams = getBatchScanParams(); // Stop batch if batch scan params changed and previous params is not null. if (mBatchScanParams != null && (!mBatchScanParams.equals(batchScanParams))) { @@ -1346,9 +1350,9 @@ public class ScanManager { int resultType = getResultType(batchScanParams); int fullScanPercent = getFullScanStoragePercent(resultType); resetCountDownLatch(); - Log.d(TAG, "configuring batch scan storage, appIf " + client.scannerId); + Log.d(TAG, "configuring batch scan storage, appIf " + client.mScannerId); mNativeInterface.gattClientConfigBatchScanStorage( - client.scannerId, fullScanPercent, 100 - fullScanPercent, notifyThreshold); + client.mScannerId, fullScanPercent, 100 - fullScanPercent, notifyThreshold); waitForCallback(); resetCountDownLatch(); int scanInterval = @@ -1368,7 +1372,7 @@ public class ScanManager { setBatchAlarm(); } - private int getFullScanStoragePercent(int resultType) { + private static int getFullScanStoragePercent(int resultType) { switch (resultType) { case SCAN_RESULT_TYPE_FULL: return 100; @@ -1388,15 +1392,15 @@ public class ScanManager { BatchScanParams params = new BatchScanParams(); ScanClient winner = getAggressiveClient(mBatchClients, true, true); if (winner != null) { - params.mScanMode = winner.settings.getScanMode(); + params.mScanMode = winner.mSettings.getScanMode(); } // TODO: split full batch scan results and truncated batch scan results to different // collections. for (ScanClient client : mBatchClients) { - if (client.settings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) { - params.mFullScanScannerId = client.scannerId; + if (client.mSettings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) { + params.mFullScanScannerId = client.mScannerId; } else { - params.mTruncatedScanScannerId = client.scannerId; + params.mTruncatedScanScannerId = client.mScannerId; } } return params; @@ -1472,8 +1476,8 @@ public class ScanManager { int deliveryMode = getDeliveryMode(client); if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) { // Decrement the count of trackable advertisements in use - int entriesToFreePerFilter = getNumOfTrackingAdvertisements(client.settings); - for (int i = 0; i < client.filters.size(); i++) { + int entriesToFreePerFilter = getNumOfTrackingAdvertisements(client.mSettings); + for (int i = 0; i < client.mFilters.size(); i++) { if (!manageAllocationOfTrackingAdvertisement(entriesToFreePerFilter, false)) { Log.e( TAG, @@ -1481,7 +1485,7 @@ public class ScanManager { + entriesToFreePerFilter); try { mScanController.onScanManagerErrorCallback( - client.scannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR); + client.mScannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR); } catch (RemoteException e) { Log.e(TAG, "failed on onScanManagerCallback at freeing", e); } @@ -1498,7 +1502,7 @@ public class ScanManager { } if (!mIsMsftSupported) { - removeScanFilters(client.scannerId); + removeScanFilters(client.mScannerId); } else { removeFiltersMsft(client); } @@ -1506,31 +1510,31 @@ public class ScanManager { void regularScanTimeout(ScanClient client) { if (!isExemptFromScanTimeout(client) - && (client.stats == null || client.stats.isScanningTooLong())) { + && (client.mStats == null || client.mStats.isScanningTooLong())) { Log.d(TAG, "regularScanTimeout - client scan time was too long"); - if (client.filters == null || client.filters.isEmpty()) { + if (client.mFilters == null || client.mFilters.isEmpty()) { Log.w( TAG, "Moving unfiltered scan client to opportunistic scan (scannerId " - + client.scannerId + + client.mScannerId + ")"); setOpportunisticScanClient(client); - removeScanFilters(client.scannerId); + removeScanFilters(client.mScannerId); } else { Log.w( TAG, "Moving filtered scan client to downgraded scan (scannerId " - + client.scannerId + + client.mScannerId + ")"); - int scanMode = client.settings.getScanMode(); + int scanMode = client.mSettings.getScanMode(); int maxScanMode = SCAN_MODE_FORCE_DOWNGRADED; client.updateScanMode(getMinScanMode(scanMode, maxScanMode)); } - if (client.stats != null) { - client.stats.setScanTimeout(client.scannerId); - client.stats.recordScanTimeoutCountMetrics( - client.scannerId, mAdapterService.getScanTimeoutMillis()); + if (client.mStats != null) { + client.mStats.setScanTimeout(client.mScannerId); + client.mStats.recordScanTimeoutCountMetrics( + client.mScannerId, mAdapterService.getScanTimeoutMillis()); } } @@ -1549,19 +1553,19 @@ public class ScanManager { // TODO: Add constructor to ScanSettings.Builder // that can copy values from an existing ScanSettings object ScanSettings.Builder builder = new ScanSettings.Builder(); - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; builder.setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC); builder.setCallbackType(settings.getCallbackType()); builder.setScanResultType(settings.getScanResultType()); builder.setReportDelay(settings.getReportDelayMillis()); builder.setNumOfMatches(settings.getNumOfMatches()); - client.settings = builder.build(); + client.mSettings = builder.build(); } // Find the regular scan client information. ScanClient getRegularScanClient(int scannerId) { for (ScanClient client : mRegularScanClients) { - if (client.scannerId == scannerId) { + if (client.mScannerId == scannerId) { return client; } } @@ -1570,7 +1574,7 @@ public class ScanManager { ScanClient getSuspendedScanClient(int scannerId) { for (ScanClient client : mSuspendedScanClients) { - if (client.scannerId == scannerId) { + if (client.mScannerId == scannerId) { return client; } } @@ -1579,7 +1583,7 @@ public class ScanManager { void stopBatchScan(ScanClient client) { mBatchClients.remove(client); - removeScanFilters(client.scannerId); + removeScanFilters(client.mScannerId); if (!isOpportunisticScanClient(client)) { resetBatchScan(client); } @@ -1615,9 +1619,9 @@ public class ScanManager { private long getBatchTriggerIntervalMillis() { long intervalMillis = Long.MAX_VALUE; for (ScanClient client : mBatchClients) { - if (client.settings != null && client.settings.getReportDelayMillis() > 0) { + if (client.mSettings != null && client.mSettings.getReportDelayMillis() > 0) { intervalMillis = - Math.min(intervalMillis, client.settings.getReportDelayMillis()); + Math.min(intervalMillis, client.mSettings.getReportDelayMillis()); } } return intervalMillis; @@ -1627,7 +1631,7 @@ public class ScanManager { // If no offload filter can/needs to be set, set ALL_PASS filter. // Otherwise offload all filters to hardware and enable all filters. private void configureScanFilters(ScanClient client) { - int scannerId = client.scannerId; + int scannerId = client.mScannerId; int deliveryMode = getDeliveryMode(client); int trackEntries = 0; @@ -1656,7 +1660,7 @@ public class ScanManager { waitForCallback(); } else { Deque<Integer> clientFilterIndices = new ArrayDeque<Integer>(); - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { ScanFilterQueue queue = new ScanFilterQueue(); queue.addScanFilter(filter); int featureSelection = queue.getFeatureSelection(); @@ -1669,15 +1673,15 @@ public class ScanManager { resetCountDownLatch(); if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) { - trackEntries = getNumOfTrackingAdvertisements(client.settings); + trackEntries = getNumOfTrackingAdvertisements(client.mSettings); if (!manageAllocationOfTrackingAdvertisement(trackEntries, true)) { Log.e( TAG, "No hardware resources for onfound/onlost filter " + trackEntries); - if (client.stats != null) { - client.stats.recordTrackingHwFilterNotAvailableCountMetrics( - client.scannerId, + if (client.mStats != null) { + client.mStats.recordTrackingHwFilterNotAvailableCountMetrics( + client.mScannerId, mAdapterService.getTotalNumOfTrackableAdvertisements()); } try { @@ -1706,10 +1710,10 @@ public class ScanManager { } if (deliveryMode == DELIVERY_MODE_BATCH) { - mAllPassBatchClients.add(client.scannerId); + mAllPassBatchClients.add(client.mScannerId); return mAllPassBatchClients.size() == 1; } else { - mAllPassRegularClients.add(client.scannerId); + mAllPassRegularClients.add(client.mScannerId); return mAllPassRegularClients.size() == 1; } } @@ -1745,7 +1749,7 @@ public class ScanManager { private ScanClient getBatchScanClient(int scannerId) { for (ScanClient client : mBatchClients) { - if (client.scannerId == scannerId) { + if (client.mScannerId == scannerId) { return client; } } @@ -1753,7 +1757,7 @@ public class ScanManager { } /** Return batch scan result type value defined in bt stack. */ - private int getResultType(BatchScanParams params) { + private static int getResultType(BatchScanParams params) { if (params.mFullScanScannerId != -1 && params.mTruncatedScanScannerId != -1) { return SCAN_RESULT_TYPE_BOTH; } @@ -1771,13 +1775,13 @@ public class ScanManager { if (client == null) { return true; } - if (client.filters == null || client.filters.isEmpty()) { + if (client.mFilters == null || client.mFilters.isEmpty()) { return true; } - if (client.filters.size() > mFilterIndexStack.size()) { - if (client.stats != null) { - client.stats.recordHwFilterNotAvailableCountMetrics( - client.scannerId, + if (client.mFilters.size() > mFilterIndexStack.size()) { + if (client.mStats != null) { + client.mStats.recordHwFilterNotAvailableCountMetrics( + client.mScannerId, mAdapterService.getNumOfOffloadedScanFilterSupported()); } return true; @@ -1811,7 +1815,7 @@ public class ScanManager { int numOfTrackingEntries) { int deliveryMode = getDeliveryMode(client); int rssiThreshold = Byte.MIN_VALUE; - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; int onFoundTimeout = getOnFoundOnLostTimeoutMillis(settings, true); int onFoundCount = getOnFoundOnLostSightings(settings); int onLostTimeout = 10000; @@ -1843,11 +1847,11 @@ public class ScanManager { } // Get delivery mode based on scan settings. - private int getDeliveryMode(ScanClient client) { + private static int getDeliveryMode(ScanClient client) { if (client == null) { return DELIVERY_MODE_IMMEDIATE; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; if (settings == null) { return DELIVERY_MODE_IMMEDIATE; } @@ -1951,7 +1955,7 @@ public class ScanManager { return phy; } - private int getOnFoundOnLostTimeoutMillis(ScanSettings settings, boolean onFound) { + private static int getOnFoundOnLostTimeoutMillis(ScanSettings settings, boolean onFound) { int factor; int timeout = ONLOST_ONFOUND_BASE_TIMEOUT_MS; @@ -1966,7 +1970,7 @@ public class ScanManager { return (timeout * factor); } - private int getOnFoundOnLostSightings(ScanSettings settings) { + private static int getOnFoundOnLostSightings(ScanSettings settings) { if (settings == null) { return ONFOUND_SIGHTINGS_AGGRESSIVE; } @@ -2051,16 +2055,16 @@ public class ScanManager { } if (client == null - || client.filters == null - || client.filters.isEmpty() - || client.filters.size() > mFilterIndexStack.size()) { + || client.mFilters == null + || client.mFilters.isEmpty() + || client.mFilters.size() > mFilterIndexStack.size()) { // Use all-pass filter updateScanMsft(); return; } Deque<Integer> clientFilterIndices = new ArrayDeque<>(); - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { MsftAdvMonitor monitor = new MsftAdvMonitor(filter); if (monitor.getAddress().bd_addr != null) { @@ -2104,13 +2108,13 @@ public class ScanManager { clientFilterIndices.add(existingFilterIndex); } - mClientFilterIndexMap.put(client.scannerId, clientFilterIndices); + mClientFilterIndexMap.put(client.mScannerId, clientFilterIndices); updateScanMsft(); } private void removeFiltersMsft(ScanClient client) { - Deque<Integer> clientFilterIndices = mClientFilterIndexMap.remove(client.scannerId); + Deque<Integer> clientFilterIndices = mClientFilterIndexMap.remove(client.mScannerId); if (clientFilterIndices != null) { for (int filterIndex : clientFilterIndices) { if (mMsftAdvMonitorMergedPatternList.remove(filterIndex)) { @@ -2130,11 +2134,11 @@ public class ScanManager { !mRegularScanClients.stream() .anyMatch( c -> - c.settings != null - && c.settings.getScanMode() + c.mSettings != null + && c.mSettings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC && !this.mClientFilterIndexMap.containsKey( - c.scannerId)); + c.mScannerId)); if (scanEnabledMsft != shouldEnableScanMsft) { resetCountDownLatch(); mNativeInterface.gattClientMsftAdvMonitorEnable(shouldEnableScanMsft); @@ -2222,7 +2226,7 @@ public class ScanManager { private boolean updateCountersAndCheckForConnectingState(int state, int prevState) { switch (prevState) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: if (mProfilesConnecting > 0) { mProfilesConnecting--; } else { @@ -2231,7 +2235,7 @@ public class ScanManager { "Invalid state transition, " + prevState + " -> " + state); } break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: if (mProfilesConnected > 0) { mProfilesConnected--; } else { @@ -2240,7 +2244,7 @@ public class ScanManager { "Invalid state transition, " + prevState + " -> " + state); } break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: if (mProfilesDisconnecting > 0) { mProfilesDisconnecting--; } else { @@ -2251,16 +2255,16 @@ public class ScanManager { break; } switch (state) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: mProfilesConnecting++; break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: mProfilesConnected++; break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: mProfilesDisconnecting++; break; - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: break; default: } @@ -2287,11 +2291,11 @@ public class ScanManager { } for (ScanClient client : mRegularScanClients) { - if (client.appUid != uid || mScanNative.isOpportunisticScanClient(client)) { + if (client.mAppUid != uid || mScanNative.isOpportunisticScanClient(client)) { continue; } if (isForeground) { - int scanMode = client.scanModeApp; + int scanMode = client.mScanModeApp; int maxScanMode = mScanNative.isForceDowngradedScanClient(client) ? SCAN_MODE_FORCE_DOWNGRADED @@ -2300,7 +2304,7 @@ public class ScanManager { updatedScanParams = true; } } else { - int scanMode = client.settings.getScanMode(); + int scanMode = client.mSettings.getScanMode(); int maxScanMode = mScreenOn ? SCAN_MODE_APP_IN_BACKGROUND : ScanSettings.SCAN_MODE_SCREEN_OFF; if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) { @@ -2311,7 +2315,7 @@ public class ScanManager { TAG, ("uid " + uid) + (" isForeground " + isForeground) - + (" scanMode " + getScanModeString(client.settings.getScanMode()))); + + (" scanMode " + getScanModeString(client.mSettings.getScanMode()))); } if (updatedScanParams) { diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanNativeInterface.java b/android/app/src/com/android/bluetooth/le_scan/ScanNativeInterface.java index c317c86cc8..2973dc5e56 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanNativeInterface.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanNativeInterface.java @@ -387,10 +387,10 @@ public class ScanNativeInterface { @Nullable AdvtFilterOnFoundOnLostInfo createOnTrackAdvFoundLostObject( int clientIf, - int advPktLen, - byte[] advPkt, - int scanRspLen, - byte[] scanRsp, + int advPacketLen, + byte[] advPacket, + int scanResponseLen, + byte[] scanResponse, int filtIndex, int advState, int advInfoPresent, @@ -405,10 +405,10 @@ public class ScanNativeInterface { } return mScanController.createOnTrackAdvFoundLostObject( clientIf, - advPktLen, - advPkt, - scanRspLen, - scanRsp, + advPacketLen, + advPacket, + scanResponseLen, + scanResponse, filtIndex, advState, advInfoPresent, diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java index 01590dba0f..d3d87e660a 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java @@ -467,7 +467,7 @@ public class BluetoothMapContent { } } - private void setProtected( + private static void setProtected( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -485,7 +485,7 @@ public class BluetoothMapContent { } } - private void setThreadId( + private static void setThreadId( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -507,7 +507,7 @@ public class BluetoothMapContent { } } - private void setThreadName( + private static void setThreadName( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -522,7 +522,7 @@ public class BluetoothMapContent { } } - private void setSent( + private static void setSent( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -547,7 +547,7 @@ public class BluetoothMapContent { } } - private void setRead( + private static void setRead( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -566,7 +566,7 @@ public class BluetoothMapContent { e.setRead((read == 1), ((ap.getParameterMask() & MASK_READ) != 0)); } - private void setPriority( + private static void setPriority( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -691,7 +691,8 @@ public class BluetoothMapContent { } } - private void setReceptionStatus(BluetoothMapMessageListingElement e, BluetoothMapAppParams ap) { + private static void setReceptionStatus( + BluetoothMapMessageListingElement e, BluetoothMapAppParams ap) { if ((ap.getParameterMask() & MASK_RECEPTION_STATUS) != 0) { String status = "complete"; Log.v(TAG, "setReceptionStatus: " + status); @@ -756,7 +757,7 @@ public class BluetoothMapContent { } } - private TYPE getType(FilterInfo fi) { + private static TYPE getType(FilterInfo fi) { TYPE type = null; Log.d(TAG, "getType: for filterMsgType" + fi.mMsgType); if (fi.mMsgType == FilterInfo.TYPE_SMS) { @@ -1286,7 +1287,7 @@ public class BluetoothMapContent { } } - private void setHandle(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi) { + private static void setHandle(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi) { long handle = -1; if (fi.mMsgType == FilterInfo.TYPE_SMS) { handle = c.getLong(fi.mSmsColId); @@ -1640,10 +1641,8 @@ public class BluetoothMapContent { return matchOriginator(c, fi, ap) && matchRecipient(c, fi, ap); } - /* - * Where filter functions - */ - private String setWhereFilterFolderTypeSms(String folder) { + /* Where filter functions */ + private static String setWhereFilterFolderTypeSms(String folder) { String where = ""; if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) { where = Sms.TYPE + " = 1 AND " + Sms.THREAD_ID + " <> -1"; @@ -1676,7 +1675,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeMms(String folder) { + private static String setWhereFilterFolderTypeMms(String folder) { String where = ""; if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) { where = Mms.MESSAGE_BOX + " = 1 AND " + Mms.THREAD_ID + " <> -1"; @@ -1700,7 +1699,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeEmail(long folderId) { + private static String setWhereFilterFolderTypeEmail(long folderId) { String where = ""; if (folderId >= 0) { where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId; @@ -1716,7 +1715,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeIm(long folderId) { + private static String setWhereFilterFolderTypeIm(long folderId) { String where = ""; if (folderId > BluetoothMapContract.FOLDER_ID_OTHER) { where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId; @@ -1732,7 +1731,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderType( + private static String setWhereFilterFolderType( BluetoothMapFolderElement folderElement, FilterInfo fi) { String where = "1=1"; if (!folderElement.shouldIgnore()) { @@ -1750,7 +1749,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterReadStatus(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterReadStatus(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; if (ap.getFilterReadStatus() != -1) { if (fi.mMsgType == FilterInfo.TYPE_SMS) { @@ -1781,7 +1780,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterPeriod(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterPeriod(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; if ((ap.getFilterPeriodBegin() != -1)) { @@ -1815,7 +1814,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterOriginatorEmail(BluetoothMapAppParams ap) { + private static String setWhereFilterOriginatorEmail(BluetoothMapAppParams ap) { String where = ""; String orig = ap.getFilterOriginator(); @@ -1832,7 +1831,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterOriginatorIM(BluetoothMapAppParams ap) { + private static String setWhereFilterOriginatorIM(BluetoothMapAppParams ap) { String where = ""; String orig = ap.getFilterOriginator(); @@ -1849,7 +1848,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterPriority(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterPriority(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; int pri = ap.getFilterPriority(); /*only MMS have priority info */ @@ -1875,7 +1874,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) { + private static String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) { String where = ""; String recip = ap.getFilterRecipient(); @@ -1900,7 +1899,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterMessageHandle(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterMessageHandle(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; long id = -1; String msgHandle = ap.getFilterMsgHandleString(); @@ -1920,7 +1919,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterThreadId(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterThreadId(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; long id = -1; String msgHandle = ap.getFilterConvoIdString(); @@ -1941,7 +1940,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilter( + private static String setWhereFilter( BluetoothMapFolderElement folderElement, FilterInfo fi, BluetoothMapAppParams ap) { StringBuilder where = new StringBuilder(setWhereFilterFolderType(folderElement, fi)); @@ -2083,7 +2082,7 @@ public class BluetoothMapContent { * * @return boolean true if email is selected, false if not */ - private boolean emailSelected(BluetoothMapAppParams ap) { + private static boolean emailSelected(BluetoothMapAppParams ap) { int msgType = ap.getFilterMessageType(); Log.d(TAG, "emailSelected msgType: " + msgType); @@ -2105,7 +2104,7 @@ public class BluetoothMapContent { * * @return boolean true if im is selected, false if not */ - private boolean imSelected(BluetoothMapAppParams ap) { + private static boolean imSelected(BluetoothMapAppParams ap) { int msgType = ap.getFilterMessageType(); Log.d(TAG, "imSelected msgType: " + msgType); @@ -3381,7 +3380,7 @@ public class BluetoothMapContent { * @param contentUri the URI to append parameters to * @return the new URI with the appended parameters (if any) */ - private Uri appendConvoListQueryParameters(BluetoothMapAppParams ap, Uri contentUri) { + private static Uri appendConvoListQueryParameters(BluetoothMapAppParams ap, Uri contentUri) { Uri.Builder newUri = contentUri.buildUpon(); String str = ap.getFilterRecipient(); if (str != null) { @@ -3531,7 +3530,7 @@ public class BluetoothMapContent { * * @return the folder name. */ - private String getFolderName(int type, int threadId) { + private static String getFolderName(int type, int threadId) { if (threadId == -1) { return BluetoothMapContract.FOLDER_NAME_DELETED; @@ -3563,7 +3562,7 @@ public class BluetoothMapContent { long id = BluetoothMapUtils.getCpHandle(handle); if (appParams.getFractionRequest() == BluetoothMapAppParams.FRACTION_REQUEST_NEXT) { throw new IllegalArgumentException( - "FRACTION_REQUEST_NEXT does not make sence as" + "FRACTION_REQUEST_NEXT does not make sense as" + " we always return the full message."); } switch (type) { diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java index 4e06253415..77430eb319 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java @@ -221,7 +221,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { } /** Add base (Inbox/Outbox/Sent/Deleted) */ - private void addBaseFolders(BluetoothMapFolderElement root) { + private static void addBaseFolders(BluetoothMapFolderElement root) { root.addFolder(BluetoothMapContract.FOLDER_NAME_INBOX); // root/telecom/msg/inbox root.addFolder(BluetoothMapContract.FOLDER_NAME_OUTBOX); root.addFolder(BluetoothMapContract.FOLDER_NAME_SENT); @@ -229,7 +229,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { } /** Add SMS / MMS Base folders */ - private void addSmsMmsFolders(BluetoothMapFolderElement root) { + private static void addSmsMmsFolders(BluetoothMapFolderElement root) { root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_INBOX); // root/telecom/msg/inbox root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_OUTBOX); root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_SENT); @@ -237,7 +237,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_DRAFT); } - private void addImFolders(BluetoothMapFolderElement root) throws RemoteException { + private static void addImFolders(BluetoothMapFolderElement root) throws RemoteException { // Select all parent folders root.addImFolder( BluetoothMapContract.FOLDER_NAME_INBOX, diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java index d1850815b0..b8d3f4df3c 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java @@ -17,6 +17,10 @@ package com.android.bluetooth.map; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -648,9 +652,9 @@ public class BluetoothMapService extends ProfileService { if (getState() == BluetoothMap.STATE_CONNECTED && getRemoteDevice() != null && getRemoteDevice().equals(device)) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } else { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } } @@ -678,7 +682,7 @@ public class BluetoothMapService extends ProfileService { device, BluetoothProfile.MAP, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -1276,7 +1280,7 @@ public class BluetoothMapService extends ProfileService { return false; } - return service.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED; + return service.getConnectionState(device) == STATE_CONNECTED; } catch (RuntimeException e) { ContentProfileErrorReportUtils.report( BluetoothProfile.MAP, @@ -1356,7 +1360,7 @@ public class BluetoothMapService extends ProfileService { try { BluetoothMapService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -1395,7 +1399,7 @@ public class BluetoothMapService extends ProfileService { try { BluetoothMapService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } return service.getConnectionPolicy(device); diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java index e7049b86f3..b22065ac28 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java @@ -381,7 +381,7 @@ public class BluetoothMapSmsPdu { } @SuppressWarnings("JavaUtilDate") // TODO: b/365629730 -- prefer Instant or LocalDate - private void gsmWriteDate(ByteArrayOutputStream header, long time) { + private static void gsmWriteDate(ByteArrayOutputStream header, long time) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss"); Date date = new Date(time); String timeStr = format.format(date); // Format to YYMMDDTHHMMSS UTC time diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java index 6e5204576a..a93f85dd3b 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java @@ -742,7 +742,7 @@ public class BluetoothMapbMessageMime extends BluetoothMapbMessage { newPart.mData = decodeBody(body, mMyEncoding, mCharset); } - private byte[] decodeBody(String body, String encoding, String charset) { + private static byte[] decodeBody(String body, String encoding, String charset) { if (encoding != null && Ascii.toUpperCase(encoding).contains("BASE64")) { return Base64.decode(body, Base64.DEFAULT); } else if (encoding != null && Ascii.toUpperCase(encoding).contains("QUOTED-PRINTABLE")) { diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java b/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java index 741290dea5..8f37895bfc 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java @@ -522,7 +522,7 @@ public class BluetoothMnsObexClient { BluetoothProtoEnums.BLUETOOTH_MNS_OBEX_CLIENT, BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION, 12); - handleSendException(e.toString()); + Log.e(TAG, "Error when sending event", e); error = true; } catch (IndexOutOfBoundsException e) { ContentProfileErrorReportUtils.report( @@ -530,7 +530,7 @@ public class BluetoothMnsObexClient { BluetoothProtoEnums.BLUETOOTH_MNS_OBEX_CLIENT, BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION, 13); - handleSendException(e.toString()); + Log.e(TAG, "Error when sending event", e); error = true; } finally { try { @@ -571,10 +571,6 @@ public class BluetoothMnsObexClient { return responseCode; } - private void handleSendException(String exception) { - Log.e(TAG, "Error when sending event: " + exception); - } - private void notifyUpdateWakeLock() { if (mCallback != null) { Message msg = Message.obtain(mCallback); diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java index 109bc1411a..eee34a4aa3 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java @@ -524,7 +524,7 @@ class MapClientContent { return Telephony.Threads.getOrCreateThreadId(mContext, messageContacts); } - private void getRecipientsFromMessage(Bmessage message, Set<String> messageContacts) { + private static void getRecipientsFromMessage(Bmessage message, Set<String> messageContacts) { List<VCardEntry> recipients = message.getRecipients(); for (VCardEntry recipient : recipients) { List<VCardEntry.PhoneData> phoneData = recipient.getPhoneList(); @@ -535,7 +535,7 @@ class MapClientContent { } } - private String getOriginatorNumber(Bmessage message) { + private static String getOriginatorNumber(Bmessage message) { VCardEntry originator = message.getOriginator(); if (originator == null) { return null; @@ -549,7 +549,7 @@ class MapClientContent { return PhoneNumberUtils.extractNetworkPortion(phoneData.get(0).getNumber()); } - private String getFirstRecipientNumber(Bmessage message) { + private static String getFirstRecipientNumber(Bmessage message) { List<VCardEntry> recipients = message.getRecipients(); if (recipients == null || recipients.isEmpty()) { return null; @@ -794,7 +794,7 @@ class MapClientContent { return messages; } - private Type getMessageTypeFromUri(Uri uri) { + private static Type getMessageTypeFromUri(Uri uri) { if (Sms.CONTENT_URI.equals(uri) || Sms.Inbox.CONTENT_URI.equals(uri) || Sms.Sent.CONTENT_URI.equals(uri)) { diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java index 506c2a3bb7..33736621dc 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java @@ -18,6 +18,12 @@ package com.android.bluetooth.mapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -134,7 +140,7 @@ public class MapClientService extends ProfileService { throw new IllegalArgumentException("Null device"); } Log.d(TAG, "connect(device= " + device + "): devices=" + mMapInstanceMap.keySet()); - if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) { Log.w( TAG, "Connection not allowed: <" @@ -168,8 +174,7 @@ public class MapClientService extends ProfileService { // statemachine already exists in the map. int state = getConnectionState(device); - if (state == BluetoothProfile.STATE_CONNECTED - || state == BluetoothProfile.STATE_CONNECTING) { + if (state == STATE_CONNECTED || state == STATE_CONNECTING) { Log.w(TAG, "Received connect request while already connecting/connected."); return true; } @@ -206,8 +211,7 @@ public class MapClientService extends ProfileService { return false; } int connectionState = mapStateMachine.getState(); - if (connectionState != BluetoothProfile.STATE_CONNECTED - && connectionState != BluetoothProfile.STATE_CONNECTING) { + if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) { return false; } mapStateMachine.disconnect(); @@ -244,9 +248,7 @@ public class MapClientService extends ProfileService { public synchronized int getConnectionState(BluetoothDevice device) { MceStateMachine mapStateMachine = mMapInstanceMap.get(device); // a map state machine instance doesn't exist yet, create a new one if we can. - return (mapStateMachine == null) - ? BluetoothProfile.STATE_DISCONNECTED - : mapStateMachine.getState(); + return (mapStateMachine == null) ? STATE_DISCONNECTED : mapStateMachine.getState(); } /** @@ -270,9 +272,9 @@ public class MapClientService extends ProfileService { device, BluetoothProfile.MAP_CLIENT, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -359,7 +361,7 @@ public class MapClientService extends ProfileService { while (iterator.hasNext()) { Map.Entry<BluetoothDevice, MceStateMachine> profileConnection = (Map.Entry) iterator.next(); - if (profileConnection.getValue().getState() == BluetoothProfile.STATE_DISCONNECTED) { + if (profileConnection.getValue().getState() == STATE_DISCONNECTED) { iterator.remove(); } } @@ -518,7 +520,7 @@ public class MapClientService extends ProfileService { MapClientService service = getServiceAndEnforcePrivileged(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -543,7 +545,7 @@ public class MapClientService extends ProfileService { MapClientService service = getServiceAndEnforcePrivileged(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } return service.getConnectionPolicy(device); @@ -591,7 +593,7 @@ public class MapClientService extends ProfileService { return; } - if (stateMachine.getState() == BluetoothProfile.STATE_CONNECTED) { + if (stateMachine.getState() == STATE_CONNECTED) { stateMachine.disconnect(); } } diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java index 2c3420af84..f5f53a7378 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java +++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java @@ -41,6 +41,10 @@ package com.android.bluetooth.mapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.RECEIVE_SMS; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -165,8 +169,8 @@ class MceStateMachine extends StateMachine { private final AdapterService mAdapterService; // Connectivity States - private int mPreviousState = BluetoothProfile.STATE_DISCONNECTED; - private int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED; + private int mPreviousState = STATE_DISCONNECTED; + private int mMostRecentState = STATE_DISCONNECTED; private MasClient mMasClient; private MapClientContent mDatabase; @@ -266,8 +270,7 @@ class MceStateMachine extends StateMachine { } private void initStateMachine() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; - + mPreviousState = STATE_DISCONNECTED; addState(mDisconnected); addState(mConnecting); @@ -307,7 +310,7 @@ class MceStateMachine extends StateMachine { + prevState + ", new=" + state); - if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) { + if (prevState != state && state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.MAP_CLIENT); } setState(state); @@ -360,7 +363,7 @@ class MceStateMachine extends StateMachine { if (contacts == null || contacts.length <= 0) { return false; } - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { Bmessage bmsg = new Bmessage(); // Set type and status. bmsg.setType(getDefaultMessageType()); @@ -413,7 +416,7 @@ class MceStateMachine extends StateMachine { synchronized boolean getMessage(String handle) { Log.d(TAG, "getMessage" + handle); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { sendMessage(MSG_INBOUND_MESSAGE, handle); return true; } @@ -422,7 +425,7 @@ class MceStateMachine extends StateMachine { synchronized boolean getUnreadMessages() { Log.d(TAG, "getMessage"); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { sendMessage(MSG_GET_MESSAGE_LISTING, FOLDER_INBOX); return true; } @@ -430,7 +433,7 @@ class MceStateMachine extends StateMachine { } synchronized int getSupportedFeatures() { - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED && mMasClient != null) { + if (mMostRecentState == STATE_CONNECTED && mMasClient != null) { Log.d(TAG, "returning getSupportedFeatures from SDP record"); return mMasClient.getSdpMasRecord().getSupportedFeatures(); } @@ -440,7 +443,7 @@ class MceStateMachine extends StateMachine { synchronized boolean setMessageStatus(String handle, int status) { Log.d(TAG, "setMessageStatus(" + handle + ", " + status + ")"); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { RequestSetMessageStatus.StatusIndicator statusIndicator; byte value; switch (status) { @@ -478,11 +481,11 @@ class MceStateMachine extends StateMachine { return false; } - private String getContactURIFromPhone(String number) { + private static String getContactURIFromPhone(String number) { return PhoneAccount.SCHEME_TEL + ":" + number; } - private String getContactURIFromEmail(String email) { + private static String getContactURIFromEmail(String email) { return SCHEME_MAILTO + "://" + email; } @@ -536,14 +539,14 @@ class MceStateMachine extends StateMachine { Utils.getLoggableAddress(mDevice) + " [Disconnected]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTED); - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; + onConnectionStateChanged(mPreviousState, STATE_DISCONNECTED); + mPreviousState = STATE_DISCONNECTED; quit(); } @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; + mPreviousState = STATE_DISCONNECTED; } } @@ -555,7 +558,7 @@ class MceStateMachine extends StateMachine { Utils.getLoggableAddress(mDevice) + " [Connecting]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTING); + onConnectionStateChanged(mPreviousState, STATE_CONNECTING); // When commanded to connect begin SDP to find the MAS server. mDevice.sdpSearch(BluetoothUuid.MAS); @@ -646,7 +649,7 @@ class MceStateMachine extends StateMachine { @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_CONNECTING; + mPreviousState = STATE_CONNECTING; removeMessages(MSG_CONNECTING_TIMEOUT); } } @@ -671,7 +674,7 @@ class MceStateMachine extends StateMachine { if (mDatabase == null) { mDatabase = new MapClientContent(mService, callbacks, mDevice); } - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTED); + onConnectionStateChanged(mPreviousState, STATE_CONNECTED); if (Utils.isPtsTestMode()) return; mMasClient.makeRequest(new RequestSetPath(FOLDER_TELECOM)); @@ -862,7 +865,7 @@ class MceStateMachine extends StateMachine { public void exit() { mDatabase.cleanUp(); mDatabase = null; - mPreviousState = BluetoothProfile.STATE_CONNECTED; + mPreviousState = STATE_CONNECTED; } /** @@ -1195,7 +1198,7 @@ class MceStateMachine extends StateMachine { * Retrieves the URIs of all the participants of a group conversation, besides the sender of * the message. */ - private String[] getRecipientsUri(List<VCardEntry> recipients) { + private static String[] getRecipientsUri(List<VCardEntry> recipients) { Set<String> uris = new HashSet<>(); for (VCardEntry recipient : recipients) { @@ -1272,7 +1275,7 @@ class MceStateMachine extends StateMachine { + " [Disconnecting]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTING); + onConnectionStateChanged(mPreviousState, STATE_DISCONNECTING); if (mMasClient != null) { mMasClient.makeRequest(new RequestSetNotificationRegistration(false)); @@ -1316,7 +1319,7 @@ class MceStateMachine extends StateMachine { @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTING; + mPreviousState = STATE_DISCONNECTING; removeMessages(MSG_DISCONNECTING_TIMEOUT); } } @@ -1326,7 +1329,7 @@ class MceStateMachine extends StateMachine { sendMessage(MSG_NOTIFICATION, ev); } - private String getMessageName(int what) { + private static String getMessageName(int what) { switch (what) { case MSG_MAS_CONNECTED: return "MSG_MAS_CONNECTED"; diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsService.java b/android/app/src/com/android/bluetooth/mapclient/MnsService.java index 99cee09481..b3194e70e7 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MnsService.java +++ b/android/app/src/com/android/bluetooth/mapclient/MnsService.java @@ -16,8 +16,9 @@ package com.android.bluetooth.mapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSocket; import android.util.Log; @@ -123,7 +124,7 @@ public class MnsService { + " (name: " + Utils.getName(device)); return false; - } else if (stateMachine.getState() != BluetoothProfile.STATE_CONNECTED) { + } else if (stateMachine.getState() != STATE_CONNECTED) { Log.e( TAG, "Error: statemachine for device: " diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java index a5d0c2e996..7550b90850 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java @@ -148,7 +148,7 @@ class BmessageBuilder { mBmsg.append(VCARD_END).append(CRLF); } - private String buildVcardN(VCardEntry vcard) { + private static String buildVcardN(VCardEntry vcard) { NameData nd = vcard.getNameData(); StringBuilder sb = new StringBuilder(); diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java b/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java index a1e3be04eb..8dbd8d349d 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java @@ -128,7 +128,7 @@ public class EventReport { return ev; } - private Type parseType(String type) throws IllegalArgumentException { + private static Type parseType(String type) throws IllegalArgumentException { for (Type t : Type.values()) { if (t.toString().equals(type)) { return t; @@ -138,7 +138,7 @@ public class EventReport { throw new IllegalArgumentException("Invalid value for type: " + type); } - private Bmessage.Type parseMsgType(String msgType) throws IllegalArgumentException { + private static Bmessage.Type parseMsgType(String msgType) throws IllegalArgumentException { for (Bmessage.Type t : Bmessage.Type.values()) { if (t.name().equals(msgType)) { return t; diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/Message.java b/android/app/src/com/android/bluetooth/mapclient/obex/Message.java index 0cfaf74660..8a2e9d3370 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/Message.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/Message.java @@ -130,11 +130,11 @@ public class Message { mProtected = yesnoToBoolean(attrs.get("protected")); } - private boolean yesnoToBoolean(String yesno) { + private static boolean yesnoToBoolean(String yesno) { return "yes".equals(yesno); } - private Type strToType(String s) { + private static Type strToType(String s) { if ("EMAIL".equals(s)) { return Type.EMAIL; } else if ("SMS_GSM".equals(s)) { @@ -148,7 +148,7 @@ public class Message { return Type.UNKNOWN; } - private ReceptionStatus strToReceptionStatus(String s) { + private static ReceptionStatus strToReceptionStatus(String s) { if ("complete".equals(s)) { return ReceptionStatus.COMPLETE; } else if ("fractioned".equals(s)) { diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java index 71b178cce8..afca4d5de8 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java @@ -243,7 +243,7 @@ class RequestGetMessagesListingForOwnNumber extends Request { + (" maxCount=" + maxCount)); } - private byte messageTypeBasedOnFolder(String folderName) { + private static byte messageTypeBasedOnFolder(String folderName) { byte messageType = (byte) (MessagesFilter.MESSAGE_TYPE_SMS_GSM diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java index a011fe26c4..c0ba4f12bb 100644 --- a/android/app/src/com/android/bluetooth/mcp/McpService.java +++ b/android/app/src/com/android/bluetooth/mcp/McpService.java @@ -18,9 +18,9 @@ package com.android.bluetooth.mcp; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothMcpServiceManager; import android.content.AttributionSource; import android.content.Context; @@ -180,8 +180,7 @@ public class McpService extends ProfileService { return BluetoothDevice.ACCESS_UNKNOWN; } - if (leAudioService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (leAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.d(TAG, "MCS authorization allowed based on supported LeAudio service"); setDeviceAuthorized(device, true); return BluetoothDevice.ACCESS_ALLOWED; diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java index 8c0f093b27..662f00721f 100644 --- a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java +++ b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java @@ -23,6 +23,8 @@ import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY; import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_READ; import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE; import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -438,12 +440,12 @@ public class MediaControlGattService implements MediaControlGattServiceInterface } }); - private long millisecondsToMcsInterval(long interval) { + private static long millisecondsToMcsInterval(long interval) { /* MCS presents time in 0.01s intervals */ return interval / 10; } - private long mcsIntervalToMilliseconds(long interval) { + private static long mcsIntervalToMilliseconds(long interval) { /* MCS presents time in 0.01s intervals */ return interval * 10L; } @@ -935,7 +937,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange"); - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { ClearUnauthorizedGattOperations(device); } } @@ -1259,7 +1261,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface public boolean isDeviceConnected(BluetoothDevice device) { return mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT_SERVER) - == BluetoothProfile.STATE_CONNECTED; + == STATE_CONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java index 51708116aa..8e5a95ffd7 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java @@ -615,7 +615,8 @@ class BluetoothOppNotification { } } - if (inboundNum > 0 && outboundNum > 0) { + // When removing flag oppRemoveEmptyGroupNotification, remove the summary ID too. + if (!Flags.oppRemoveEmptyGroupNotification() && inboundNum > 0 && outboundNum > 0) { Notification.Builder b = new Notification.Builder(mContext, OPP_NOTIFICATION_CHANNEL) .setGroup(NOTIFICATION_GROUP_KEY_TRANSFER_COMPLETE) @@ -631,11 +632,6 @@ class BluetoothOppNotification { .setLocalOnly(true); mNotificationMgr.notify(NOTIFICATION_ID_COMPLETE_SUMMARY, b.build()); - } else if (Flags.oppRemoveEmptyGroupNotification() && inboundNum == 0 && outboundNum == 0) { - if (mNotificationMgr != null) { - mNotificationMgr.cancel(NOTIFICATION_ID_COMPLETE_SUMMARY); - Log.v(TAG, "empty group summary notification was removed."); - } } } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java index 49b6e9ad66..13dc28f2a2 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java @@ -86,7 +86,7 @@ public class BluetoothOppPreference { mChannels = (HashMap<String, Integer>) mChannelPreference.getAll(); } - private String getChannelKey(BluetoothDevice remoteDevice, int uuid) { + private static String getChannelKey(BluetoothDevice remoteDevice, int uuid) { return getBrEdrAddress(remoteDevice) + "_" + Integer.toHexString(uuid); } @@ -177,7 +177,7 @@ public class BluetoothOppPreference { } @SuppressLint("AndroidFrameworkRequiresPermission") - private String getBrEdrAddress(BluetoothDevice device) { + private static String getBrEdrAddress(BluetoothDevice device) { if (Flags.identityAddressNullIfNotKnown()) { return Utils.getBrEdrAddress(device); } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java index 5113d4b9e0..eb9b7f91c4 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java @@ -285,7 +285,7 @@ public class BluetoothOppReceiver extends BroadcastReceiver { } } - private void cancelNotification(Context context, int id) { + private static void cancelNotification(Context context, int id) { NotificationManager notMgr = context.getSystemService(NotificationManager.class); if (notMgr == null) { return; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java index 7b7f1087d3..7ce5ef6bb2 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java @@ -1019,7 +1019,7 @@ public class BluetoothOppTransfer implements BluetoothOppBatch.BluetoothOppBatch } } - private String getBrEdrAddress(BluetoothDevice device) { + private static String getBrEdrAddress(BluetoothDevice device) { if (Flags.identityAddressNullIfNotKnown()) { return Utils.getBrEdrAddress(device); } diff --git a/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java b/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java index a586f5d1a9..5143392d03 100644 --- a/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java +++ b/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java @@ -267,7 +267,7 @@ public class BluetoothTetheringNetworkFactory extends NetworkFactory { terminate(); } - private NetworkCapabilities initNetworkCapabilities() { + private static NetworkCapabilities initNetworkCapabilities() { final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_BLUETOOTH) diff --git a/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java b/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java index 2cce9d1ced..76e91d8477 100644 --- a/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java +++ b/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java @@ -16,10 +16,14 @@ package com.android.bluetooth.pan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static java.util.Objects.requireNonNull; import android.bluetooth.BluetoothPan; -import android.bluetooth.BluetoothProfile; import android.util.Log; import com.android.internal.annotations.VisibleForTesting; @@ -71,16 +75,16 @@ public class PanNativeInterface { static int convertHalState(int halState) { switch (halState) { case CONN_STATE_CONNECTED: - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; case CONN_STATE_CONNECTING: - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; case CONN_STATE_DISCONNECTED: - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case CONN_STATE_DISCONNECTING: - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; default: Log.e(TAG, "Invalid pan connection state: " + halState); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/pan/PanService.java b/android/app/src/com/android/bluetooth/pan/PanService.java index 3717f797ee..d873628c12 100644 --- a/android/app/src/com/android/bluetooth/pan/PanService.java +++ b/android/app/src/com/android/bluetooth/pan/PanService.java @@ -19,6 +19,12 @@ package com.android.bluetooth.pan; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.TETHER_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.bluetooth.BluetoothUtils.logRemoteException; import static java.util.Objects.requireNonNull; @@ -178,11 +184,7 @@ public class PanService extends ProfileService { setPanService(null); - int[] desiredStates = { - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTING - }; + int[] desiredStates = {STATE_CONNECTING, STATE_CONNECTED, STATE_DISCONNECTING}; List<BluetoothDevice> devList = getDevicesMatchingConnectionStates(desiredStates); for (BluetoothDevice device : devList) { BluetoothPanDevice panDevice = mPanDevices.get(device); @@ -191,12 +193,13 @@ public class PanService extends ProfileService { handlePanDeviceStateChange( device, mPanIfName, - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, panDevice.mLocalRole, panDevice.mRemoteRole); } } mPanDevices.clear(); + mHandler.removeCallbacksAndMessages(null); } private final Handler mHandler = @@ -215,13 +218,13 @@ public class PanService extends ProfileService { handlePanDeviceStateChange( connectDevice, null, - BluetoothProfile.STATE_CONNECTING, + STATE_CONNECTING, BluetoothPan.LOCAL_PANU_ROLE, BluetoothPan.REMOTE_NAP_ROLE); handlePanDeviceStateChange( connectDevice, null, - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, BluetoothPan.LOCAL_PANU_ROLE, BluetoothPan.REMOTE_NAP_ROLE); } @@ -237,13 +240,13 @@ public class PanService extends ProfileService { handlePanDeviceStateChange( disconnectDevice, mPanIfName, - BluetoothProfile.STATE_DISCONNECTING, + STATE_DISCONNECTING, BluetoothPan.LOCAL_PANU_ROLE, BluetoothPan.REMOTE_NAP_ROLE); handlePanDeviceStateChange( disconnectDevice, mPanIfName, - BluetoothProfile.STATE_DISCONNECTED, + STATE_DISCONNECTED, BluetoothPan.LOCAL_PANU_ROLE, BluetoothPan.REMOTE_NAP_ROLE); } @@ -411,7 +414,7 @@ public class PanService extends ProfileService { Log.w(TAG, "Guest user does not have the permission to change the WiFi network"); return false; } - if (getConnectionState(device) != BluetoothProfile.STATE_DISCONNECTED) { + if (getConnectionState(device) != STATE_DISCONNECTED) { Log.e(TAG, "Pan Device not disconnected: " + device); return false; } @@ -502,9 +505,9 @@ public class PanService extends ProfileService { device, BluetoothProfile.PAN, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -526,7 +529,7 @@ public class PanService extends ProfileService { public List<BluetoothDevice> getConnectedDevices() { List<BluetoothDevice> devices = - getDevicesMatchingConnectionStates(new int[] {BluetoothProfile.STATE_CONNECTED}); + getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}); return devices; } @@ -607,7 +610,7 @@ public class PanService extends ProfileService { BluetoothPanDevice panDevice = mPanDevices.get(device); if (panDevice == null) { Log.i(TAG, "state " + state + " Num of connected pan devices: " + mPanDevices.size()); - prevState = BluetoothProfile.STATE_DISCONNECTED; + prevState = STATE_DISCONNECTED; panDevice = new BluetoothPanDevice(state, localRole, remoteRole); mPanDevices.put(device, panDevice); } else { @@ -622,8 +625,7 @@ public class PanService extends ProfileService { // connect call will put us in STATE_DISCONNECTED. Then, the disconnect completes and // changes the state to STATE_DISCONNECTING. All future calls to BluetoothPan#connect // will fail until the caller explicitly calls BluetoothPan#disconnect. - if (prevState == BluetoothProfile.STATE_DISCONNECTED - && state == BluetoothProfile.STATE_DISCONNECTING) { + if (prevState == STATE_DISCONNECTED && state == STATE_DISCONNECTING) { Log.d(TAG, "Ignoring state change from " + prevState + " to " + state); mPanDevices.remove(device); return; @@ -634,7 +636,7 @@ public class PanService extends ProfileService { return; } if (remoteRole == BluetoothPan.LOCAL_PANU_ROLE) { - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { if ((!mTetherOn) || (localRole == BluetoothPan.LOCAL_PANU_ROLE)) { Log.d( TAG, @@ -658,7 +660,7 @@ public class PanService extends ProfileService { logRemoteException(TAG, e); } } - } else if (state == BluetoothProfile.STATE_DISCONNECTED) { + } else if (state == STATE_DISCONNECTED) { mPanDevices.remove(device); Log.i( TAG, @@ -683,12 +685,12 @@ public class PanService extends ProfileService { + state + ", prevState = " + prevState); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { mNetworkFactory = new BluetoothTetheringNetworkFactory( getBaseContext(), getMainLooper(), this); mNetworkFactory.startReverseTether(iface); - } else if (state == BluetoothProfile.STATE_DISCONNECTED) { + } else if (state == STATE_DISCONNECTED) { if (mNetworkFactory != null) { mNetworkFactory.stopReverseTether(); mNetworkFactory = null; @@ -696,7 +698,7 @@ public class PanService extends ProfileService { mPanDevices.remove(device); } } - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PAN); } mAdapterService.updateProfileConnectionAdapterProperties( diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java index b79bd5b1f1..c755e1b67c 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java @@ -620,7 +620,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } } - private boolean isNameMatchTarget(String name, String target) { + private static boolean isNameMatchTarget(String name, String target) { if (name == null) { return false; } @@ -642,7 +642,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } /** check whether path is legal */ - private boolean isLegalPath(final String str) { + private static boolean isLegalPath(final String str) { if (str.length() == 0) { return true; } @@ -1070,7 +1070,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } /** Function to send vcard data to client */ - private int pushBytes(Operation op, final String vcardString) { + private static int pushBytes(Operation op, final String vcardString) { if (vcardString == null) { Log.w(TAG, "vcardString is null!"); return ResponseCodes.OBEX_HTTP_OK; diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java index 305adbe571..a63006065d 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java @@ -20,6 +20,9 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.bluetooth.BluetoothDevice.ACCESS_ALLOWED; import static android.bluetooth.BluetoothDevice.ACCESS_REJECTED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -626,7 +629,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect synchronized (mPbapStateMachineMap) { PbapStateMachine sm = mPbapStateMachineMap.get(device); if (sm == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return sm.getConnectionState(); } @@ -675,7 +678,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect device, BluetoothProfile.PBAP, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -906,7 +909,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect Log.d(TAG, "getPhonebookAccessPermission() = " + permission); if (permission == ACCESS_ALLOWED) { - setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); stateMachine.sendMessage(PbapStateMachine.AUTHORIZED); } else if (permission == ACCESS_REJECTED) { stateMachine.sendMessage(PbapStateMachine.REJECTED); diff --git a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java index 254d8d50d2..06820a1955 100644 --- a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java +++ b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java @@ -17,6 +17,10 @@ package com.android.bluetooth.pbap; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.app.Notification; @@ -181,7 +185,7 @@ public class PbapStateMachine extends StateMachine { /** Broadcast connection state change for this state machine */ void broadcastStateTransitions() { - int prevStateInt = BluetoothProfile.STATE_DISCONNECTED; + int prevStateInt = STATE_DISCONNECTED; if (mPrevState != null) { prevStateInt = mPrevState.getConnectionStateInt(); } @@ -232,7 +236,7 @@ public class PbapStateMachine extends StateMachine { class WaitingForAuth extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } @Override @@ -292,7 +296,7 @@ public class PbapStateMachine extends StateMachine { class Finished extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @Override @@ -328,7 +332,7 @@ public class PbapStateMachine extends StateMachine { class Connected extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } @Override @@ -345,7 +349,7 @@ public class PbapStateMachine extends StateMachine { } broadcastStateTransitions(); MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PBAP); - mService.setConnectionPolicy(mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED); } @Override @@ -483,7 +487,7 @@ public class PbapStateMachine extends StateMachine { synchronized int getConnectionState() { PbapStateBase state = (PbapStateBase) getCurrentState(); if (state == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return state.getConnectionStateInt(); } diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java index 868e9d2472..f3bcd1e7b5 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java @@ -18,10 +18,11 @@ package com.android.bluetooth.pbapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.RequiresPermission; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothPbapClient; import android.content.AttributionSource; import android.util.Log; @@ -119,7 +120,7 @@ class PbapClientBinder extends IBluetoothPbapClient.Stub implements IProfileServ Log.d(TAG, "getConnectionState(device=" + device + ")"); PbapClientService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); } @@ -141,7 +142,7 @@ class PbapClientBinder extends IBluetoothPbapClient.Stub implements IProfileServ Log.d(TAG, "getConnectionPolicy(device=" + device + ")"); PbapClientService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } return service.getConnectionPolicy(device); } diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java index a7c5a36011..9d064c7598 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java @@ -315,7 +315,7 @@ class PbapClientContactsStorage { } @SuppressWarnings("NonApiType") // For convenience, as applyBatch above takes an ArrayList above - private ArrayList<ContentProviderOperation> constructInsertOperationsForContact( + private static ArrayList<ContentProviderOperation> constructInsertOperationsForContact( VCardEntry contact, ArrayList<ContentProviderOperation> operations, ContentResolver contactsProvider) { @@ -481,7 +481,7 @@ class PbapClientContactsStorage { // TODO: b/365629730 -- JavaUtilDate: prefer Instant or LocalDate // NonApiType: For convenience, as the applyBatch API actually takes an ArrayList above @SuppressWarnings({"JavaUtilDate", "NonApiType"}) - private ArrayList<ContentProviderOperation> constructInsertOperationsForCallLog( + private static ArrayList<ContentProviderOperation> constructInsertOperationsForCallLog( Account account, int type, VCardEntry call, diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java index abaff2061f..213c9c5fa5 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java @@ -16,6 +16,11 @@ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static java.util.Objects.requireNonNull; import android.accounts.Account; @@ -25,6 +30,7 @@ import android.bluetooth.BluetoothUuid; import android.bluetooth.SdpPseRecord; import android.content.ComponentName; import android.os.Handler; +import android.os.HandlerThread; import android.os.Looper; import android.os.ParcelUuid; import android.os.Parcelable; @@ -88,7 +94,7 @@ public class PbapClientService extends ProfileService { + oldState + ", new=" + newState); - if (oldState != newState && newState == BluetoothProfile.STATE_DISCONNECTED) { + if (oldState != newState && newState == STATE_DISCONNECTED) { removeDevice(mDevice); } } @@ -294,7 +300,7 @@ public class PbapClientService extends ProfileService { PbapClientStateMachine pbapClientStateMachine = mPbapClientStateMachineMap.get(device); if (pbapClientStateMachine != null) { int state = pbapClientStateMachine.getConnectionState(); - if (state != BluetoothProfile.STATE_DISCONNECTED) { + if (state != STATE_DISCONNECTED) { Log.w(TAG, "Removing connected device, device=" + device + ", state=" + state); } mPbapClientStateMachineMap.remove(device); @@ -360,7 +366,7 @@ public class PbapClientService extends ProfileService { */ public void handleHeadsetClientConnectionStateChanged( BluetoothDevice device, int oldState, int newState) { - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { Log.d(TAG, "Received intent to disconnect HFP with " + device); if (Flags.pbapClientStorageRefactor()) { Account account = mPbapClientContactsStorage.getStorageAccountForDevice(device); @@ -438,7 +444,7 @@ public class PbapClientService extends ProfileService { return; } - if (getConnectionState(device) == BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState(device) == STATE_CONNECTED) { disconnect(device); } } @@ -523,7 +529,7 @@ public class PbapClientService extends ProfileService { throw new IllegalArgumentException("Null device"); } Log.d(TAG, "connect(device=" + device.getAddress() + ")"); - if (getConnectionPolicy(device) <= BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (getConnectionPolicy(device) <= CONNECTION_POLICY_FORBIDDEN) { return false; } @@ -533,7 +539,10 @@ public class PbapClientService extends ProfileService { synchronized (mPbapClientStateMachineOldMap) { PbapClientStateMachineOld smOld = mPbapClientStateMachineOldMap.get(device); if (smOld == null && mPbapClientStateMachineOldMap.size() < MAXIMUM_DEVICES) { - smOld = new PbapClientStateMachineOld(this, device); + HandlerThread smThread = new HandlerThread("PbapClientStateMachineOld"); + smThread.start(); + + smOld = new PbapClientStateMachineOld(this, device, smThread); smOld.start(); mPbapClientStateMachineOldMap.put(device, smOld); return true; @@ -581,7 +590,7 @@ public class PbapClientService extends ProfileService { * @return The list of connected PBAP Server devices */ public List<BluetoothDevice> getConnectedDevices() { - int[] desiredStates = {BluetoothProfile.STATE_CONNECTED}; + int[] desiredStates = {STATE_CONNECTED}; return getDevicesMatchingConnectionStates(desiredStates); } @@ -641,14 +650,14 @@ public class PbapClientService extends ProfileService { if (Flags.pbapClientStorageRefactor()) { PbapClientStateMachine pbapClientStateMachine = getDeviceStateMachine(device); if (pbapClientStateMachine == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } else { return pbapClientStateMachine.getConnectionState(); } } else { PbapClientStateMachineOld smOld = mPbapClientStateMachineOldMap.get(device); if (smOld == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } else { return smOld.getConnectionState(device); } @@ -679,9 +688,9 @@ public class PbapClientService extends ProfileService { device, BluetoothProfile.PBAP_CLIENT, connectionPolicy)) { return false; } - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy == CONNECTION_POLICY_ALLOWED) { connect(device); - } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java index 2023bfa90a..9e7c4083aa 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java @@ -18,6 +18,10 @@ package com.android.bluetooth.pbapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.accounts.Account; import android.bluetooth.BluetoothDevice; @@ -222,7 +226,7 @@ class PbapClientStateMachine extends StateMachine { } }; - private int mCurrentState = BluetoothProfile.STATE_DISCONNECTED; + private int mCurrentState = STATE_DISCONNECTED; private State mDisconnected; private State mConnecting; private State mConnected; @@ -359,9 +363,9 @@ class PbapClientStateMachine extends StateMachine { @Override public void enter() { debug("Disconnected: Enter, from=" + eventToString(getCurrentMessage().what)); - if (mCurrentState != BluetoothProfile.STATE_DISCONNECTED) { + if (mCurrentState != STATE_DISCONNECTED) { // Only broadcast a state change that came from something other than disconnected - onConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED); + onConnectionStateChanged(STATE_DISCONNECTED); // Quit processing on this handler. This makes this object one time use. The // connection state changed callback event will trigger the service to clean up @@ -391,7 +395,7 @@ class PbapClientStateMachine extends StateMachine { @Override public void enter() { debug("Connecting: Enter from=" + eventToString(getCurrentMessage().what)); - onConnectionStateChanged(BluetoothProfile.STATE_CONNECTING); + onConnectionStateChanged(STATE_CONNECTING); // We can't connect over OBEX until we known where/how to connect. We need the SDP // record details to do this. Thus, being connected means we received a valid SDP record @@ -504,11 +508,11 @@ class PbapClientStateMachine extends StateMachine { @Override public void enter() { debug("Connected: Enter, from=" + eventToString(getCurrentMessage().what)); - if (mCurrentState != BluetoothProfile.STATE_CONNECTING) { + if (mCurrentState != STATE_CONNECTING) { return; } - onConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); + onConnectionStateChanged(STATE_CONNECTED); mHasDownloaded = false; @@ -796,10 +800,10 @@ class PbapClientStateMachine extends StateMachine { @Override public void enter() { debug("Disconnecting: Enter, from=" + eventToString(getCurrentMessage().what)); - onConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING); + onConnectionStateChanged(STATE_DISCONNECTING); // Disconnect - if (mObexClient.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (mObexClient.getConnectionState() != STATE_DISCONNECTED) { mObexClient.disconnect(); sendMessageDelayed(MSG_DISCONNECT_TIMEOUT, DISCONNECT_TIMEOUT_MS); } else { @@ -854,12 +858,12 @@ class PbapClientStateMachine extends StateMachine { protected void onQuitting() { Log.d(TAG, "State machine is force quitting"); switch (mCurrentState) { - case BluetoothProfile.STATE_CONNECTED: - onConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING); + case STATE_CONNECTED: + onConnectionStateChanged(STATE_DISCONNECTING); // intentional fallthrough-- we want to broadcast both state changes - case BluetoothProfile.STATE_CONNECTING: - case BluetoothProfile.STATE_DISCONNECTING: - onConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED); + case STATE_CONNECTING: + case STATE_DISCONNECTING: + onConnectionStateChanged(STATE_DISCONNECTED); cleanup(); break; default: @@ -904,7 +908,7 @@ class PbapClientStateMachine extends StateMachine { private void onConnectionStateChanged(int state) { int prevState = mCurrentState; - if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) { + if (prevState != state && state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PBAP_CLIENT); } @@ -939,9 +943,9 @@ class PbapClientStateMachine extends StateMachine { @Override public void onConnectionStateChanged(int oldState, int newState) { info("Obex client connection state changed: " + oldState + " -> " + newState); - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { obtainMessage(MSG_OBEX_CLIENT_DISCONNECTED).sendToTarget(); - } else if (newState == BluetoothProfile.STATE_CONNECTED) { + } else if (newState == STATE_CONNECTED) { obtainMessage(MSG_OBEX_CLIENT_CONNECTED).sendToTarget(); } } diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java index c07dadc62c..bf2cade8ee 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java @@ -43,6 +43,10 @@ package com.android.bluetooth.pbapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothPbapClient; @@ -68,6 +72,8 @@ import com.android.internal.util.IState; import com.android.internal.util.State; import com.android.internal.util.StateMachine; +import com.google.common.util.concurrent.Uninterruptibles; + import java.util.ArrayList; import java.util.List; @@ -116,20 +122,24 @@ class PbapClientStateMachineOld extends StateMachine { private PbapClientConnectionHandler mConnectionHandler; private HandlerThread mHandlerThread = null; private UserManager mUserManager = null; + private final HandlerThread mSmHandlerThread; // mMostRecentState maintains previous state for broadcasting transitions. - private int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED; + private int mMostRecentState = STATE_DISCONNECTED; - PbapClientStateMachineOld(PbapClientService svc, BluetoothDevice device) { - this(svc, device, null); + PbapClientStateMachineOld( + PbapClientService svc, BluetoothDevice device, HandlerThread handlerThread) { + this(svc, device, null, handlerThread); } @VisibleForTesting PbapClientStateMachineOld( PbapClientService svc, BluetoothDevice device, - PbapClientConnectionHandler connectionHandler) { - super(TAG); + PbapClientConnectionHandler connectionHandler, + HandlerThread handlerThread) { + super(TAG, handlerThread.getLooper()); + mSmHandlerThread = handlerThread; if (Flags.pbapClientStorageRefactor()) { Log.w(TAG, "This object is no longer used in this configuration"); @@ -157,9 +167,8 @@ class PbapClientStateMachineOld extends StateMachine { @Override public void enter() { Log.d(TAG, "Enter Disconnected: " + getCurrentMessage().what); - onConnectionStateChanged( - mCurrentDevice, mMostRecentState, BluetoothProfile.STATE_DISCONNECTED); - mMostRecentState = BluetoothProfile.STATE_DISCONNECTED; + onConnectionStateChanged(mCurrentDevice, mMostRecentState, STATE_DISCONNECTED); + mMostRecentState = STATE_DISCONNECTED; quit(); } } @@ -169,10 +178,9 @@ class PbapClientStateMachineOld extends StateMachine { @Override public void enter() { Log.d(TAG, "Enter Connecting: " + getCurrentMessage().what); - onConnectionStateChanged( - mCurrentDevice, mMostRecentState, BluetoothProfile.STATE_CONNECTING); + onConnectionStateChanged(mCurrentDevice, mMostRecentState, STATE_CONNECTING); mCurrentDevice.sdpSearch(BluetoothUuid.PBAP_PSE); - mMostRecentState = BluetoothProfile.STATE_CONNECTING; + mMostRecentState = STATE_CONNECTING; // Create a separate handler instance and thread for performing // connect/download/disconnect operations as they may be time consuming and error prone. @@ -266,9 +274,8 @@ class PbapClientStateMachineOld extends StateMachine { @Override public void enter() { Log.d(TAG, "Enter Disconnecting: " + getCurrentMessage().what); - onConnectionStateChanged( - mCurrentDevice, mMostRecentState, BluetoothProfile.STATE_DISCONNECTING); - mMostRecentState = BluetoothProfile.STATE_DISCONNECTING; + onConnectionStateChanged(mCurrentDevice, mMostRecentState, STATE_DISCONNECTING); + mMostRecentState = STATE_DISCONNECTING; PbapClientConnectionHandler connectionHandler = mConnectionHandler; if (connectionHandler != null) { connectionHandler @@ -324,9 +331,8 @@ class PbapClientStateMachineOld extends StateMachine { @Override public void enter() { Log.d(TAG, "Enter Connected: " + getCurrentMessage().what); - onConnectionStateChanged( - mCurrentDevice, mMostRecentState, BluetoothProfile.STATE_CONNECTED); - mMostRecentState = BluetoothProfile.STATE_CONNECTED; + onConnectionStateChanged(mCurrentDevice, mMostRecentState, STATE_CONNECTED); + mMostRecentState = STATE_CONNECTED; downloadIfReady(); } @@ -397,7 +403,7 @@ class PbapClientStateMachineOld extends StateMachine { Log.w(TAG, "onConnectionStateChanged with invalid device"); return; } - if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) { + if (prevState != state && state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PBAP_CLIENT); } Log.d(TAG, "Connection state " + device + ": " + prevState + "->" + state); @@ -436,8 +442,11 @@ class PbapClientStateMachineOld extends StateMachine { HandlerThread handlerThread = mHandlerThread; if (handlerThread != null) { handlerThread.quitSafely(); + Uninterruptibles.joinUninterruptibly(handlerThread); mHandlerThread = null; } + mSmHandlerThread.quitSafely(); + Uninterruptibles.joinUninterruptibly(mSmHandlerThread); quitNow(); } @@ -449,16 +458,16 @@ class PbapClientStateMachineOld extends StateMachine { public int getConnectionState() { IState currentState = getCurrentState(); if (currentState instanceof Disconnected) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } else if (currentState instanceof Connecting) { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } else if (currentState instanceof Connected) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } else if (currentState instanceof Disconnecting) { - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; } Log.w(TAG, "Unknown State"); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) { @@ -481,14 +490,14 @@ class PbapClientStateMachineOld extends StateMachine { public int getConnectionState(BluetoothDevice device) { if (device == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } synchronized (mLock) { if (device.equals(mCurrentDevice)) { return getConnectionState(); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } public BluetoothDevice getDevice() { @@ -496,7 +505,7 @@ class PbapClientStateMachineOld extends StateMachine { * Disconnected is the only state where device can change, and to prevent the race * condition of reporting a valid device while disconnected fix the report here. Note that * Synchronization of the state and device is not possible with current state machine - * desingn since the actual Transition happens sometime after the transitionTo method. + * design since the actual Transition happens sometime after the transitionTo method. */ if (getCurrentState() instanceof Disconnected) { return null; diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java index 896962ee10..e8b461b797 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java @@ -18,6 +18,10 @@ package com.android.bluetooth.pbapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -85,7 +89,7 @@ class PbapClientObexClient { private final BluetoothDevice mDevice; private final int mLocalSupportedFeatures; - private int mState = BluetoothProfile.STATE_DISCONNECTED; + private int mState = STATE_DISCONNECTED; private AtomicInteger mPsm = new AtomicInteger(L2CAP_INVALID_PSM); private AtomicInteger mChannelId = new AtomicInteger(RFCOMM_INVALID_CHANNEL_ID); @@ -234,7 +238,7 @@ class PbapClientObexClient { * @return True if connected, False otherwise */ public boolean isConnected() { - return getConnectionState() == BluetoothProfile.STATE_CONNECTED; + return getConnectionState() == STATE_CONNECTED; } /** @@ -355,7 +359,7 @@ class PbapClientObexClient { if (mThread != null) { mThread.quit(); } - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); } /** Handles this PBAP Client OBEX Client's requests */ @@ -370,7 +374,7 @@ class PbapClientObexClient { debug("Handling Message, type=" + messageToString(msg.what)); switch (msg.what) { case MSG_CONNECT: - if (getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (getConnectionState() != STATE_DISCONNECTED) { warn("Cannot connect, device not disconnected"); return; } @@ -402,13 +406,13 @@ class PbapClientObexClient { return; } - setConnectionState(BluetoothProfile.STATE_CONNECTING); + setConnectionState(STATE_CONNECTING); mSocket = connectSocket(transport, psmOrChannel); if (mSocket == null) { mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); return; } @@ -418,22 +422,22 @@ class PbapClientObexClient { mSocket = null; mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); return; } - setConnectionState(BluetoothProfile.STATE_CONNECTED); + setConnectionState(STATE_CONNECTED); break; case MSG_DISCONNECT: removeCallbacksAndMessages(null); - if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState() != STATE_CONNECTED) { warn("Cannot disconnect, device not connected"); return; } - setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + setConnectionState(STATE_DISCONNECTING); // To disconnect, first bring down the OBEX session, then bring down the // underlying transport/socket. If there are any errors while bringing down the @@ -449,7 +453,7 @@ class PbapClientObexClient { mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); break; case MSG_REQUEST: diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java index b3e6cb21fc..81582c462b 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java @@ -145,7 +145,7 @@ public class PbapPhonebook { * any other {@link VCardException} or succeeds (i.e., no {@link VCardException}). * @throws IOException if there's an issue reading the {@link InputStream}. */ - private boolean parsedWithVcardVersionException(VCardParser parser, InputStream in) + private static boolean parsedWithVcardVersionException(VCardParser parser, InputStream in) throws IOException { try { parser.parse(in); @@ -170,7 +170,7 @@ public class PbapPhonebook { /** * Get the offset associated with this PbapPhonebook object * - * <p>The offset respresents the start index of the remote contacts pull + * <p>The offset represents the start index of the remote contacts pull * * @return an int representing the offset index where this pull started from */ diff --git a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java index d8f0feb047..b97d860bc6 100644 --- a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java +++ b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java @@ -48,7 +48,7 @@ public class SapRilReceiverHidl implements ISapRilReceiver { public static final int RIL_MAX_COMMAND_BYTES = (8 * 1024); public byte[] buffer = new byte[RIL_MAX_COMMAND_BYTES]; - private ArrayList<Byte> primitiveArrayToContainerArrayList(byte[] arr) { + private static ArrayList<Byte> primitiveArrayToContainerArrayList(byte[] arr) { ArrayList<Byte> arrayList = new ArrayList<>(arr.length); for (byte b : arr) { arrayList.add(b); diff --git a/android/app/src/com/android/bluetooth/sap/SapService.java b/android/app/src/com/android/bluetooth/sap/SapService.java index ac76fd3fa7..277acc4cf2 100644 --- a/android/app/src/com/android/bluetooth/sap/SapService.java +++ b/android/app/src/com/android/bluetooth/sap/SapService.java @@ -18,6 +18,11 @@ package com.android.bluetooth.sap; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -534,7 +539,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo private synchronized void setState(int state, int result) { if (state != mState) { Log.d(TAG, "Sap state " + mState + " -> " + state + ", result = " + result); - if (state == BluetoothProfile.STATE_CONNECTED) { + if (state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.SAP); } int prevState = mState; @@ -617,9 +622,9 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo if (getState() == BluetoothSap.STATE_CONNECTED && getRemoteDevice() != null && getRemoteDevice().equals(device)) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } else { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } } @@ -645,7 +650,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo mAdapterService .getDatabase() .setProfileConnectionPolicy(device, BluetoothProfile.SAP, connectionPolicy); - if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) { disconnect(device); } return true; @@ -820,9 +825,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo BluetoothDevice.ACCESS_ALLOWED); Log.v(TAG, "setSimAccessPermission(ACCESS_ALLOWED) result=" + result); } - boolean result = - setConnectionPolicy( - mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + boolean result = setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED); Log.d(TAG, "setConnectionPolicy ALLOWED, result = " + result); try { @@ -843,8 +846,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo Log.v(TAG, "setSimAccessPermission(ACCESS_REJECTED) result=" + result); } boolean result = - setConnectionPolicy( - mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN); Log.d(TAG, "setConnectionPolicy FORBIDDEN, result = " + result); // Ensure proper cleanup, and prepare for new connect. mSessionStatusHandler.sendEmptyMessage(MSG_SERVERSESSION_CLOSE); @@ -955,7 +957,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo return false; } - return service.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED; + return service.getConnectionState(device) == STATE_CONNECTED; } @Override @@ -1001,7 +1003,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo SapService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -1022,7 +1024,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) { SapService service = getService(source); if (service == null) { - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } return service.getConnectionPolicy(device); diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java index 6cf2642366..d9e9dfb8f0 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java @@ -18,6 +18,7 @@ package com.android.bluetooth.tbs; import static android.bluetooth.BluetoothDevice.METADATA_GTBS_CCCD; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -28,7 +29,6 @@ import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattServerCallback; import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothProfile; import android.net.Uri; import android.os.Handler; import android.os.Looper; @@ -1491,7 +1491,7 @@ public class TbsGatt { BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange"); - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { clearUnauthorizedGattOperationss(device); } } diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java index b49eee0a03..b88f6e7d9c 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java @@ -1021,7 +1021,7 @@ public class TbsGeneric { } }; - private String callControlRequestOpcodeStr(int opcode) { + private static String callControlRequestOpcodeStr(int opcode) { switch (opcode) { case TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT: return "ACCEPT"; diff --git a/android/app/src/com/android/bluetooth/tbs/TbsService.java b/android/app/src/com/android/bluetooth/tbs/TbsService.java index 58a1736bc8..6a29848ef6 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsService.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsService.java @@ -19,13 +19,13 @@ package com.android.bluetooth.tbs; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static java.util.Objects.requireNonNull; import android.annotation.RequiresPermission; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothLeCall; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothLeCallControl; import android.bluetooth.IBluetoothLeCallControlCallback; import android.content.AttributionSource; @@ -178,8 +178,7 @@ public class TbsService extends ProfileService { return BluetoothDevice.ACCESS_UNKNOWN; } - if (leAudioService.getConnectionPolicy(device) - > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) { + if (leAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) { Log.d(TAG, "TBS authorization allowed based on supported LeAudio service"); setDeviceAuthorized(device, true); return BluetoothDevice.ACCESS_ALLOWED; diff --git a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java index 076ea0cf4e..99b0efc2a3 100644 --- a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java +++ b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java @@ -1395,7 +1395,7 @@ public class BluetoothInCallService extends InCallService { return bluetoothCallState; } - private int getBtCallState(BluetoothCall call, boolean isForeground) { + private static int getBtCallState(BluetoothCall call, boolean isForeground) { switch (call.getState()) { case Call.STATE_NEW: case Call.STATE_DISCONNECTED: @@ -1611,7 +1611,7 @@ public class BluetoothInCallService extends InCallService { } } - private Integer getTbsCallState(BluetoothCall call) { + private static Integer getTbsCallState(BluetoothCall call) { switch (call.getState()) { case Call.STATE_ACTIVE: return BluetoothLeCall.STATE_ACTIVE; diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java index 90add03ed7..68e368fd2a 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java @@ -43,7 +43,7 @@ public class VolumeControlNativeInterface { cleanupNative(); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java index 324c39a0be..6adc1df93f 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java @@ -1917,7 +1917,7 @@ public class VolumeControlService extends ProfileService { service.unmuteGroup(groupId); } - private void postAndWait(Handler handler, Runnable runnable) { + private static void postAndWait(Handler handler, Runnable runnable) { FutureTask<Void> task = new FutureTask(Executors.callable(runnable)); handler.post(task); @@ -1972,7 +1972,7 @@ public class VolumeControlService extends ProfileService { postAndWait(service.mHandler, () -> service.notifyNewRegisteredCallback(callback)); } - private void validateBluetoothDevice(BluetoothDevice device) { + private static void validateBluetoothDevice(BluetoothDevice device) { requireNonNull(device); String address = device.getAddress(); if (!BluetoothAdapter.checkBluetoothAddress(address)) { diff --git a/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java index 439186e4fa..08f6bc11f8 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java @@ -23,6 +23,7 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF; import static android.bluetooth.BluetoothAdapter.STATE_ON; import static android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF; import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; import static com.google.common.truth.Truth.assertThat; @@ -202,9 +203,7 @@ public class AdapterServiceTest { doReturn(true).when(mMockLeAudioService).isAvailable(); LeAudioService.setLeAudioService(mMockLeAudioService); - doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED) - .when(mMockLeAudioService) - .getConnectionPolicy(any()); + doReturn(CONNECTION_POLICY_ALLOWED).when(mMockLeAudioService).getConnectionPolicy(any()); AdapterNativeInterface.setInstance(mNativeInterface); BluetoothKeystoreNativeInterface.setInstance(mKeystoreNativeInterface); diff --git a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java index 201d380a12..d31d579e47 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java @@ -159,8 +159,8 @@ public class BluetoothOppBtEnablingActivityTest { assertThat(finishCalled.get()).isTrue(); } - private void assertActivityState(ActivityScenario activityScenario, Lifecycle.State state) - throws Exception { + private static void assertActivityState( + ActivityScenario activityScenario, Lifecycle.State state) throws Exception { // TODO: Change this into an event driven systems Thread.sleep(3_000); assertThat(activityScenario.getState()).isEqualTo(state); diff --git a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java index c64ea81912..3396591ef1 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java @@ -208,8 +208,8 @@ public class BluetoothOppLauncherActivityTest { assertActivityState(scenario, Lifecycle.State.DESTROYED); } - private void assertActivityState(ActivityScenario activityScenario, Lifecycle.State state) - throws Exception { + private static void assertActivityState( + ActivityScenario activityScenario, Lifecycle.State state) throws Exception { Thread.sleep(2_000); assertThat(activityScenario.getState()).isEqualTo(state); } diff --git a/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java index 515d0d4cf5..a9eea3da60 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java @@ -1928,7 +1928,7 @@ public class BluetoothInCallServiceTest { verify(firstCall).conference(any(BluetoothCall.class)); } - private void addCallCapability(BluetoothCall call, int capability) { + private static void addCallCapability(BluetoothCall call, int capability) { doReturn(true).when(call).can(eq(capability)); } @@ -1979,11 +1979,11 @@ public class BluetoothInCallServiceTest { makeQuickConnectionServiceComponentName(), id, Binder.getCallingUserHandle()); } - private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { + private static PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { return new PhoneAccount.Builder(makeQuickAccountHandle(id), "label" + idx); } - private PhoneAccount makeQuickAccount(String id, int idx) { + private static PhoneAccount makeQuickAccount(String id, int idx) { return makeQuickAccountBuilder(id, idx) .setAddress(Uri.parse(TEST_ACCOUNT_ADDRESS + idx)) .setSubscriptionAddress(Uri.parse("tel:555-000" + idx)) @@ -1992,7 +1992,7 @@ public class BluetoothInCallServiceTest { .build(); } - private BluetoothCall getMockCall(UUID uuid) { + private static BluetoothCall getMockCall(UUID uuid) { BluetoothCall call = mock(com.android.bluetooth.telephony.BluetoothCall.class); Integer integerUuid = uuid.hashCode(); doReturn(integerUuid).when(call).getId(); diff --git a/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java index 9223d82c5d..79ebced7de 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java @@ -297,11 +297,11 @@ public class CallInfoTest { makeQuickConnectionServiceComponentName(), id, Process.myUserHandle()); } - private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { + private static PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { return new PhoneAccount.Builder(makeQuickAccountHandle(id), "label" + idx); } - private PhoneAccount makeQuickAccount(String id, int idx) { + private static PhoneAccount makeQuickAccount(String id, int idx) { return makeQuickAccountBuilder(id, idx) .setAddress(Uri.parse(TEST_ACCOUNT_ADDRESS + idx)) .setSubscriptionAddress(Uri.parse("tel:555-000" + idx)) @@ -310,7 +310,7 @@ public class CallInfoTest { .build(); } - private BluetoothCall getMockCall() { + private static BluetoothCall getMockCall() { return mock(BluetoothCall.class); } } diff --git a/android/app/tests/unit/AndroidTest.xml b/android/app/tests/unit/AndroidTest.xml index f640db51d4..7196d996d0 100644 --- a/android/app/tests/unit/AndroidTest.xml +++ b/android/app/tests/unit/AndroidTest.xml @@ -69,5 +69,6 @@ class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController"> <option name="enable" value="true" /> <option name="mainline-module-package-name" value="com.android.bt" /> + <option name="mainline-module-package-name" value="com.google.android.bt" /> </object> </configuration> diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java index a6bf4950ca..d0c253523a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java @@ -767,7 +767,8 @@ public class A2dpCodecConfigTest { } } - private BluetoothCodecConfig getDefaultCodecConfigByType(int codecType, int codecPriority) { + private static BluetoothCodecConfig getDefaultCodecConfigByType( + int codecType, int codecPriority) { for (BluetoothCodecConfig codecConfig : sDefaultCodecConfigs) { if (codecConfig.getCodecType() != codecType) { continue; @@ -794,7 +795,7 @@ public class A2dpCodecConfigTest { return null; } - private BluetoothCodecConfig getCodecCapabilitiesByType(int codecType) { + private static BluetoothCodecConfig getCodecCapabilitiesByType(int codecType) { for (BluetoothCodecConfig codecCapabilities : sCodecCapabilities) { if (codecCapabilities.getCodecType() != codecType) { continue; diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java index 0f41af59dd..eb3def2b89 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java @@ -17,6 +17,8 @@ package com.android.bluetooth.a2dp; import static android.bluetooth.BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -29,7 +31,6 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothCodecConfig; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.AttributionSource; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; @@ -89,7 +90,7 @@ public class A2dpServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, sSource); verify(mA2dpService).getDevicesMatchingConnectionStates(states); @@ -121,7 +122,7 @@ public class A2dpServiceBinderTest { @Test public void setConnectionPolicy() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(sDevice, connectionPolicy, sSource); verify(mA2dpService).setConnectionPolicy(sDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java index d6e88738f2..407a1d2b35 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.a2dp; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -205,19 +208,17 @@ public class A2dpServiceTest { @Test public void testGetPriority() { when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - assertThat(mA2dpService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); + assertThat(mA2dpService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_UNKNOWN); when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); assertThat(mA2dpService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .isEqualTo(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); - assertThat(mA2dpService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); + assertThat(mA2dpService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); } /** Test okToConnect method using various test cases */ @@ -228,62 +229,43 @@ public class A2dpServiceTest { testOkToConnectCase( mDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase( mDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); - testOkToConnectCase( - mDevice, - BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false); testOkToConnectCase( mDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); testOkToConnectCase( - mDevice, - BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase( mDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true); testOkToConnectCase( - mDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - true); - testOkToConnectCase( - mDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); - testOkToConnectCase( - mDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - true); + mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_ALLOWED, true); testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false); testOkToConnectCase( mDevice, badBondState, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); - testOkToConnectCase( - mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase(mDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase( mDevice, badBondState, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToConnectCase(mDevice, badBondState, badPriorityValue, false); } @@ -293,7 +275,7 @@ public class A2dpServiceTest { public void testOutgoingConnectMissingAudioSinkUuid() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -314,7 +296,7 @@ public class A2dpServiceTest { // Set the device priority to PRIORITY_OFF so connect() should fail when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Send a connect request assertThat(mA2dpService.connect(mDevice)).isFalse(); @@ -325,7 +307,7 @@ public class A2dpServiceTest { public void testOutgoingConnectTimeout() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -353,7 +335,7 @@ public class A2dpServiceTest { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -417,7 +399,7 @@ public class A2dpServiceTest { BluetoothDevice testDevice = getTestDevice(i); testDevices[i] = testDevice; when(mDatabaseManager.getProfileConnectionPolicy(testDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); // Send a connect request assertThat(mA2dpService.connect(testDevice)).isTrue(); dispatchAtLeastOneMessage(); @@ -441,7 +423,7 @@ public class A2dpServiceTest { // Prepare and connect the extra test device. The connect request should fail extraTestDevice = getTestDevice(MAX_CONNECTED_AUDIO_DEVICES); when(mDatabaseManager.getProfileConnectionPolicy(extraTestDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); // Send a connect request assertThat(mA2dpService.connect(extraTestDevice)).isFalse(); } @@ -454,7 +436,7 @@ public class A2dpServiceTest { public void testCreateStateMachineStackEvents() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -537,7 +519,7 @@ public class A2dpServiceTest { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -552,8 +534,7 @@ public class A2dpServiceTest { assertThat(mA2dpService.getDevices()).doesNotContain(mDevice); // A2DP stack event: CONNECTION_STATE_CONNECTED - state machine should be created - generateConnectionMessageFromNative( - mDevice, STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + generateConnectionMessageFromNative(mDevice, STATE_CONNECTED, STATE_DISCONNECTED); assertThat(mA2dpService.getConnectionState(mDevice)).isEqualTo(STATE_CONNECTED); assertThat(mA2dpService.getDevices()).contains(mDevice); @@ -597,7 +578,7 @@ public class A2dpServiceTest { public void testDeleteDisconnectedStateMachineUnbondEvents() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -650,7 +631,7 @@ public class A2dpServiceTest { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -720,7 +701,7 @@ public class A2dpServiceTest { public void testDeleteStateMachineDisconnectEvents() { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class)); doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class)); @@ -1045,7 +1026,7 @@ public class A2dpServiceTest { // Update the device priority so okToConnect() returns true when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); doReturn(true).when(mMockNativeInterface).connectA2dp(device); doReturn(true).when(mMockNativeInterface).disconnectA2dp(device); doReturn(true) @@ -1287,7 +1268,7 @@ public class A2dpServiceTest { .setA2dpOptionalCodecsEnabled(mDevice, BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED); } - private BluetoothCodecConfig buildBluetoothCodecConfig( + private static BluetoothCodecConfig buildBluetoothCodecConfig( int sourceCodecType, int codecPriority, int sampleRate, diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java index 3c653bf444..24ead6e4b8 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.a2dpsink; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.AttributionSource; import org.junit.After; @@ -75,7 +77,7 @@ public class A2dpSinkServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.getDevicesMatchingConnectionStates(states, source); @@ -94,7 +96,7 @@ public class A2dpSinkServiceBinderTest { @Test public void setConnectionPolicy() { BluetoothDevice device = getTestDevice(0); - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.setConnectionPolicy(device, connectionPolicy, source); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java index 21dc3d7f34..5d13e09c9b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java @@ -15,6 +15,9 @@ */ package com.android.bluetooth.a2dpsink; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -31,7 +34,6 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothAudioConfig; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.media.AudioFormat; import androidx.test.runner.AndroidJUnit4; @@ -132,7 +134,7 @@ public class A2dpSinkStateMachineTest { @Test public void testAllowedIncomingConnectionInDisconnected() { - mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED); sendConnectionEvent(STATE_CONNECTING); assertThat(mStateMachine.getState()).isEqualTo(STATE_CONNECTING); @@ -141,7 +143,7 @@ public class A2dpSinkStateMachineTest { @Test public void testForbiddenIncomingConnectionInDisconnected() { - mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN); sendConnectionEvent(STATE_CONNECTING); verify(mNativeInterface).disconnectA2dpSink(mDevice); @@ -150,7 +152,7 @@ public class A2dpSinkStateMachineTest { @Test public void testUnknownIncomingConnectionInDisconnected() { - mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_UNKNOWN); sendConnectionEvent(STATE_CONNECTING); assertThat(mStateMachine.getState()).isEqualTo(STATE_CONNECTING); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java index 25723ab0c9..5470187c0a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java @@ -15,12 +15,16 @@ */ package com.android.bluetooth.a2dpsink; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.getTestDevice; import static com.google.common.truth.Truth.assertThat; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.runner.AndroidJUnit4; @@ -33,22 +37,22 @@ public class StackEventTest { @Test public void testCreateConnectionStateChangedDisconnectedEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_DISCONNECTED); + testConnectionStateChangedBase(STATE_DISCONNECTED); } @Test public void testCreateConnectionStateChangedConnectingEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_CONNECTING); + testConnectionStateChangedBase(STATE_CONNECTING); } @Test public void testCreateConnectionStateChangedConnectedEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_CONNECTED); + testConnectionStateChangedBase(STATE_CONNECTED); } @Test public void testCreateConnectionStateChangedDisconnectingEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_DISCONNECTING); + testConnectionStateChangedBase(STATE_DISCONNECTING); } private void testConnectionStateChangedBase(int state) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java index 94c59c7424..dfa391c909 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java @@ -143,7 +143,7 @@ public class BrowserPlayerWrapperTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaDescription getMediaDescription( + private static MediaDescription getMediaDescription( String id, String title, String artist, @@ -169,7 +169,7 @@ public class BrowserPlayerWrapperTest { return builder.build(); } - private MediaItem getMediaItem(MediaDescription description, int flags) { + private static MediaItem getMediaItem(MediaDescription description, int flags) { return new MediaItem(description, flags); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java index cfb35313b8..d74b4ecd5b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java @@ -124,7 +124,7 @@ public class ImageTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaMetadata getMediaMetadataWithoutArt() { + private static MediaMetadata getMediaMetadataWithoutArt() { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -134,7 +134,7 @@ public class ImageTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { + private static MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -145,7 +145,7 @@ public class ImageTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithUri(String field, String uri) { + private static MediaMetadata getMediaMetadataWithUri(String field, String uri) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -156,7 +156,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithoutArt() { + private static MediaDescription getMediaDescriptionWithoutArt() { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -164,7 +164,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithBitmap(Bitmap image) { + private static MediaDescription getMediaDescriptionWithBitmap(Bitmap image) { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -173,7 +173,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithUri(Uri uri) { + private static MediaDescription getMediaDescriptionWithUri(Uri uri) { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -182,13 +182,13 @@ public class ImageTest { return builder.build(); } - private Bundle getBundleWithBitmap(String field, Bitmap image) { + private static Bundle getBundleWithBitmap(String field, Bitmap image) { Bundle bundle = new Bundle(); bundle.putParcelable(field, image); return bundle; } - private Bundle getBundleWithUri(String field, String uri) { + private static Bundle getBundleWithUri(String field, String uri) { Bundle bundle = new Bundle(); bundle.putString(field, uri); return bundle; diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java index b7a7baede7..7a084783fb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java @@ -131,7 +131,7 @@ public class MediaPlayerListTest { .dropShellPermissionIdentity(); } - private MediaData prepareMediaData(int playbackState) { + private static MediaData prepareMediaData(int playbackState) { PlaybackState.Builder builder = new PlaybackState.Builder(); builder.setState(playbackState, 0, 1); ArrayList<Metadata> list = new ArrayList<Metadata>(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java index d7f7cb56cc..0ad8530e75 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java @@ -130,7 +130,7 @@ public class MetadataTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaMetadata getMediaMetadata() { + private static MediaMetadata getMediaMetadata() { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -149,7 +149,7 @@ public class MetadataTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { + private static MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -168,7 +168,7 @@ public class MetadataTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithUri(String field, Uri uri) { + private static MediaMetadata getMediaMetadataWithUri(String field, Uri uri) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -187,7 +187,7 @@ public class MetadataTest { return builder.build(); } - private MediaDescription getMediaDescription(Bitmap bitmap, Uri uri, Bundle extras) { + private static MediaDescription getMediaDescription(Bitmap bitmap, Uri uri, Bundle extras) { MediaDescription.Builder builder = new MediaDescription.Builder() .setMediaId(SONG_MEDIA_ID) @@ -206,15 +206,15 @@ public class MetadataTest { return builder.build(); } - private MediaItem getMediaItem(MediaDescription description) { + private static MediaItem getMediaItem(MediaDescription description) { return new MediaItem(description, 0 /* not browsable/playable */); } - private QueueItem getQueueItem(MediaDescription description) { + private static QueueItem getQueueItem(MediaDescription description) { return new QueueItem(description, 1 /* queue ID */); } - private Bundle getBundle() { + private static Bundle getBundle() { Bundle bundle = new Bundle(); bundle.putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID); bundle.putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE); @@ -227,19 +227,19 @@ public class MetadataTest { return bundle; } - private Bundle getBundleWithBitmap(String field, Bitmap image) { + private static Bundle getBundleWithBitmap(String field, Bitmap image) { Bundle bundle = getBundle(); bundle.putParcelable(field, image); return bundle; } - private Bundle getBundleWithUri(String field, Uri uri) { + private static Bundle getBundleWithUri(String field, Uri uri) { Bundle bundle = getBundle(); bundle.putString(field, uri.toString()); return bundle; } - private void assertMetadata( + private static void assertMetadata( String mediaId, String title, String artist, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java index da529d669b..93c2fe0678 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java @@ -161,7 +161,8 @@ public class AvrcpBipObexServerTest { * <p>Our server will use: - getReceivedHeader - sendHeaders - getMaxPacketSize - * openOutputStream */ - private Operation makeOperation(HeaderSet requestHeaders, OutputStream os) throws Exception { + private static Operation makeOperation(HeaderSet requestHeaders, OutputStream os) + throws Exception { Operation op = mock(Operation.class); when(op.getReceivedHeader()).thenReturn(requestHeaders); when(op.getMaxPacketSize()).thenReturn(256); @@ -169,7 +170,7 @@ public class AvrcpBipObexServerTest { return op; } - private byte[] makeDescriptor(int encoding, int width, int height) { + private static byte[] makeDescriptor(int encoding, int width, int height) { return new BipImageDescriptor.Builder() .setEncoding(encoding) .setFixedDimensions(width, height) diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java index 27bca93454..172692a4e9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java @@ -151,7 +151,7 @@ public class AvrcpTargetServiceTest { assertThat(AvrcpTargetService.isQueueUpdated(firstQueue, secondQueue)).isTrue(); } - private Metadata createEmptyMetadata() { + private static Metadata createEmptyMetadata() { Metadata.Builder builder = new Metadata.Builder(); return builder.useDefaults().build(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java index f9585fe54e..bcf90f4066 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java @@ -81,19 +81,19 @@ public class CoverArtTest { return BitmapFactory.decodeStream(imageInputStream); } - private Bitmap toBitmap(byte[] imageBytes) { + private static Bitmap toBitmap(byte[] imageBytes) { ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes); return BitmapFactory.decodeStream(inputStream); } - private BipImageDescriptor getDescriptor(int encoding, int width, int height) { + private static BipImageDescriptor getDescriptor(int encoding, int width, int height) { return new BipImageDescriptor.Builder() .setEncoding(encoding) .setFixedDimensions(width, height) .build(); } - private boolean containsThumbnailFormat(BipImageProperties properties) { + private static boolean containsThumbnailFormat(BipImageProperties properties) { if (properties == null) return false; for (BipImageFormat format : properties.getNativeFormats()) { @@ -117,7 +117,7 @@ public class CoverArtTest { return false; } - private boolean isThumbnailFormat(Bitmap image) { + private static boolean isThumbnailFormat(Bitmap image) { if (image == null) return false; return (200 == image.getHeight() && 200 == image.getWidth()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java index d4213b5b9f..d88f8122be 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.getConnectionStateName; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -24,7 +27,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Intent; import androidx.test.filters.SmallTest; @@ -95,28 +97,9 @@ public class AvrcpBipClientTest { @Test public void setConnectionState() { - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING); - - assertThat(mClient.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTING); - } - - @Test - public void getConnectionState() { - mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTED); - assertThat(mClient.getStateName()).isEqualTo("Disconnected"); - - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING); - assertThat(mClient.getStateName()).isEqualTo("Connecting"); - - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTED); - assertThat(mClient.getStateName()).isEqualTo("Connected"); - - mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTING); - assertThat(mClient.getStateName()).isEqualTo("Disconnecting"); + mClient.setConnectionState(STATE_CONNECTING); - int invalidState = 4; - mClient.setConnectionState(invalidState); - assertThat(mClient.getStateName()).isEqualTo("Unknown"); + assertThat(mClient.getState()).isEqualTo(STATE_CONNECTING); } @Test @@ -125,7 +108,7 @@ public class AvrcpBipClientTest { "<AvrcpBipClient" + (" device=" + mDevice) + (" psm=" + TEST_PSM) - + (" state=" + mClient.getStateName()) + + (" state=" + getConnectionStateName(mClient.getState())) + ">"; assertThat(mClient.toString()).isEqualTo(expected); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java index ac5c5dce3d..dd12985a44 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java @@ -16,13 +16,14 @@ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; @@ -58,7 +59,7 @@ public class AvrcpControllerServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java index 15d0d54926..e082270619 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java @@ -15,6 +15,9 @@ */ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -31,7 +34,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.Intent; import android.media.AudioManager; @@ -121,14 +123,14 @@ public class AvrcpControllerServiceTest { @Test public void disconnect_whenDisconnected_returnsFalse() { - when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_DISCONNECTED); + when(mStateMachine.getState()).thenReturn(STATE_DISCONNECTED); assertThat(mService.disconnect(mDevice)).isFalse(); } @Test public void disconnect_whenDisconnected_returnsTrue() { - when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachine.getState()).thenReturn(STATE_CONNECTED); assertThat(mService.disconnect(mDevice)).isTrue(); verify(mStateMachine).disconnect(); @@ -146,7 +148,7 @@ public class AvrcpControllerServiceTest { @Test public void getConnectedDevices() { when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mDevice}); - when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachine.getState()).thenReturn(STATE_CONNECTED); assertThat(mService.getConnectedDevices()).contains(mDevice); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java index 7898edcd63..368eac6c00 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.avrcpcontroller; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -101,7 +103,7 @@ public class AvrcpControllerStateMachineTest { public void setUp() throws Exception { mBrowseTree = new BrowseTree(null); - doReturn(BluetoothProfile.STATE_DISCONNECTED).when(mCoverArtManager).getState(any()); + doReturn(STATE_DISCONNECTED).when(mCoverArtManager).getState(any()); doReturn(15).when(mAudioManager).getStreamMaxVolume(anyInt()); doReturn(8).when(mAudioManager).getStreamVolume(anyInt()); @@ -157,13 +159,13 @@ public class AvrcpControllerStateMachineTest { /** Destroy a state machine you created to test */ private void destroyStateMachine(AvrcpControllerStateMachine sm) { - if (sm == null || sm.getState() == BluetoothProfile.STATE_DISCONNECTED) return; + if (sm == null || sm.getState() == STATE_DISCONNECTED) return; sm.disconnect(); TestUtils.waitForLooperToBeIdle(sm.getHandler().getLooper()); // is disconnected - assertThat(sm.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(sm.getState()).isEqualTo(STATE_DISCONNECTED); // told mAvrcpControllerService to remove it verify(mAvrcpControllerService).removeStateMachine(eq(sm)); @@ -203,9 +205,9 @@ public class AvrcpControllerStateMachineTest { .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Connected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_CONNECTED); - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } private AvrcpItem makeTrack( @@ -239,7 +241,7 @@ public class AvrcpControllerStateMachineTest { return builder.build(); } - private AvrcpPlayer makePlayer( + private static AvrcpPlayer makePlayer( BluetoothDevice device, int playerId, String playerName, @@ -356,10 +358,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } @@ -385,10 +387,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } @@ -414,10 +416,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java index 580de97ba5..c1b0f52616 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java @@ -178,7 +178,7 @@ public class AvrcpPlayerTest { assertThat(avrcpPlayer.notifyImageDownload(uuid, uri)).isTrue(); } - private void setSupportedFeature(byte[] supportedFeatures, int feature) { + private static void setSupportedFeature(byte[] supportedFeatures, int feature) { int byteNumber = feature / 8; byte bitMask = (byte) (1 << (feature % 8)); supportedFeatures[byteNumber] = (byte) (supportedFeatures[byteNumber] | bitMask); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java index 3500d0e0c7..02a63b298b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java @@ -33,7 +33,8 @@ import java.util.TimeZone; @RunWith(AndroidJUnit4.class) public class BipAttachmentFormatTest { - private Date makeDate(int month, int day, int year, int hours, int min, int sec, TimeZone tz) { + private static Date makeDate( + int month, int day, int year, int hours, int min, int sec, TimeZone tz) { Calendar.Builder builder = new Calendar.Builder(); /* Note that Calendar months are zero-based in Java framework */ @@ -43,12 +44,12 @@ public class BipAttachmentFormatTest { return builder.build().getTime(); } - private Date makeDate(int month, int day, int year, int hours, int min, int sec) { + private static Date makeDate(int month, int day, int year, int hours, int min, int sec) { return makeDate(month, day, year, hours, min, sec, null); } @SuppressLint("UndefinedEquals") - private void testParse( + private static void testParse( String contentType, String charset, String name, @@ -83,7 +84,7 @@ public class BipAttachmentFormatTest { } @SuppressLint("UndefinedEquals") - private void testCreate( + private static void testCreate( String contentType, String charset, String name, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java index 9b3032c657..bf3b29a00d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java @@ -34,7 +34,8 @@ import java.util.TimeZone; @RunWith(AndroidJUnit4.class) public class BipDatetimeTest { - private Date makeDate(int month, int day, int year, int hours, int min, int sec, TimeZone tz) { + private static Date makeDate( + int month, int day, int year, int hours, int min, int sec, TimeZone tz) { Calendar.Builder builder = new Calendar.Builder(); /* Note that Calendar months are zero-based in Java framework */ @@ -44,11 +45,12 @@ public class BipDatetimeTest { return builder.build().getTime(); } - private Date makeDate(int month, int day, int year, int hours, int min, int sec) { + private static Date makeDate(int month, int day, int year, int hours, int min, int sec) { return makeDate(month, day, year, hours, min, sec, null); } - private String makeTzAdjustedString(int month, int day, int year, int hours, int min, int sec) { + private static String makeTzAdjustedString( + int month, int day, int year, int hours, int min, int sec) { Calendar cal = Calendar.getInstance(); cal.setTime(makeDate(month, day, year, hours, min, sec)); cal.setTimeZone(TimeZone.getDefault()); @@ -64,7 +66,8 @@ public class BipDatetimeTest { } @SuppressLint("UndefinedEquals") - private void testParse(String date, Date expectedDate, boolean isUtc, String expectedStr) { + private static void testParse( + String date, Date expectedDate, boolean isUtc, String expectedStr) { BipDateTime bipDateTime = new BipDateTime(date); assertThat(bipDateTime.getTime()).isEqualTo(expectedDate); assertThat(bipDateTime.isUtc()).isEqualTo(isUtc); @@ -72,7 +75,7 @@ public class BipDatetimeTest { } @SuppressLint("UndefinedEquals") - private void testCreate(Date date, String dateStr) { + private static void testCreate(Date date, String dateStr) { BipDateTime bipDate = new BipDateTime(date); assertThat(bipDate.getTime()).isEqualTo(date); assertThat(bipDate.isUtc()).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java index 99f4a5281a..712c304c33 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class BipEncodingTest { - private void testParse( + private static void testParse( String input, int encodingType, String encodingStr, @@ -40,7 +40,7 @@ public class BipEncodingTest { assertThat(encoding.isAndroidSupported()).isEqualTo(isAndroidSupported); } - private void testParseMany( + private static void testParseMany( String[] inputs, int encodingType, String encodingStr, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java index 6e767249e9..8f11f9218f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java @@ -108,7 +108,7 @@ public class BipImagePropertiesTest { private static final String IMAGE_PROPERTIES_END = "</image-properties>"; - private InputStream toUtf8Stream(String s) { + private static InputStream toUtf8Stream(String s) { return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java index 88f093966a..8d2146218a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class BipPixelTest { - private void testParse( + private static void testParse( String input, int pixelType, int minWidth, @@ -44,7 +44,7 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testFixed(int width, int height, String pixelStr) { + private static void testFixed(int width, int height, String pixelStr) { BipPixel pixel = BipPixel.createFixed(width, height); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_FIXED); assertThat(pixel.getMinWidth()).isEqualTo(width); @@ -54,7 +54,7 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testResizableModified( + private static void testResizableModified( int minWidth, int minHeight, int maxWidth, int maxHeight, String pixelStr) { BipPixel pixel = BipPixel.createResizableModified(minWidth, minHeight, maxWidth, maxHeight); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO); @@ -65,7 +65,8 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testResizableFixed(int minWidth, int maxWidth, int maxHeight, String pixelStr) { + private static void testResizableFixed( + int minWidth, int maxWidth, int maxHeight, String pixelStr) { int minHeight = (minWidth * maxHeight) / maxWidth; // spec defined BipPixel pixel = BipPixel.createResizableFixed(minWidth, maxWidth, maxHeight); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java index 832aaf268a..3e0e17db4b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.bass_client; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.EXTRA_PREVIOUS_STATE; import static android.bluetooth.BluetoothProfile.EXTRA_STATE; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; @@ -355,9 +358,9 @@ public class BassClientServiceTest { mBassClientService.cleanup(); when(mDatabaseManager.getProfileConnectionPolicy( mCurrentDevice, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); assertThat(mBassClientService.getConnectionPolicy(mCurrentDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .isEqualTo(CONNECTION_POLICY_UNKNOWN); } /** @@ -369,7 +372,7 @@ public class BassClientServiceTest { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); assertThat(mBassClientService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) @@ -386,7 +389,7 @@ public class BassClientServiceTest { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); BluetoothDevice nullDevice = null; assertThat(mBassClientService.connect(nullDevice)).isFalse(); @@ -401,7 +404,7 @@ public class BassClientServiceTest { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); assertThat(mCurrentDevice).isNotNull(); assertThat(mBassClientService.connect(mCurrentDevice)).isFalse(); @@ -451,7 +454,7 @@ public class BassClientServiceTest { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); // Mock the CSIP group List<BluetoothDevice> groupDevices = new ArrayList<>(); @@ -1233,7 +1236,7 @@ public class BassClientServiceTest { .isEqualTo(TEST_BROADCAST_ID); } - private byte[] getScanRecord(int broadcastId) { + private static byte[] getScanRecord(int broadcastId) { return new byte[] { 0x02, 0x01, @@ -1318,7 +1321,7 @@ public class BassClientServiceTest { generateScanResult(scanResult); } - private byte[] getPAScanRecord() { + private static byte[] getPAScanRecord() { return new byte[] { (byte) 0x02, (byte) 0x01, @@ -1442,7 +1445,7 @@ public class BassClientServiceTest { } } - private BluetoothLeBroadcastReceiveState injectRemoteSourceState( + private static BluetoothLeBroadcastReceiveState injectRemoteSourceState( BassClientStateMachine sm, BluetoothLeBroadcastMetadata meta, int sourceId, @@ -7649,20 +7652,14 @@ public class BassClientServiceTest { prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Connect again first sink - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7675,35 +7672,23 @@ public class BassClientServiceTest { } // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Disconnect second sink cause remove metada for both devices - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice1)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice1)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice1, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice1, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice1), TEST_SOURCE_ID + 1); // Connect again both devices - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice1)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice1)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7739,20 +7724,14 @@ public class BassClientServiceTest { } // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Connect again first sink - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7773,35 +7752,23 @@ public class BassClientServiceTest { } // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Disconnect second sink cause remove metada for both devices - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice1)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice1)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice1, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice1, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice1), TEST_SOURCE_ID + 1); // Connect again both devices - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice1)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice1)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7830,14 +7797,10 @@ public class BassClientServiceTest { prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Remove second source should remove metadata for both @@ -7848,9 +7811,7 @@ public class BassClientServiceTest { } // Connect again first sink - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7887,14 +7848,10 @@ public class BassClientServiceTest { } // Disconnect first sink not cause removing metadata - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Remove second source should remove metadata for both @@ -7905,9 +7862,7 @@ public class BassClientServiceTest { } // Connect again first sink - doReturn(BluetoothProfile.STATE_CONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected(); prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false); @@ -7937,14 +7892,10 @@ public class BassClientServiceTest { mBassClientService.addSource(mCurrentDevice1, meta, /* isGroupOp */ false); // Disconnect first sink should remove pendingSourceToAdd for it - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Sync established should add source on only one sink @@ -7986,14 +7937,10 @@ public class BassClientServiceTest { mBassClientService.addSource(mCurrentDevice, meta, /* isGroupOp */ true); // Disconnect first sink should remove pendingSourceToAdd for it - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(mStateMachines.get(mCurrentDevice)) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState(); doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected(); mBassClientService.connectionStateChanged( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); // Sync established should add source on only one sink diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java index 0862f73ee5..30dd8cb708 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java @@ -19,6 +19,10 @@ package com.android.bluetooth.bass_client; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.bluetooth.BluetoothGatt.GATT_FAILURE; import static android.bluetooth.BluetoothGatt.GATT_SUCCESS; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; @@ -104,6 +108,7 @@ import com.android.bluetooth.btservice.MetricsLogger; import com.android.bluetooth.flags.Flags; import com.google.common.primitives.Bytes; +import com.google.common.util.concurrent.Uninterruptibles; import org.hamcrest.Matcher; import org.hamcrest.core.AllOf; @@ -190,14 +195,14 @@ public class BassClientStateMachineTest { mBassClientStateMachine.start(); } - private int classTypeToConnectionState(Class type) { + private static int classTypeToConnectionState(Class type) { if (type == BassClientStateMachine.Disconnected.class) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } else if (type == BassClientStateMachine.Connecting.class) { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } else if (type == BassClientStateMachine.Connected.class || type == BassClientStateMachine.ConnectedProcessing.class) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } else { assertWithMessage("Invalid class type given: " + type).fail(); return 0; @@ -213,14 +218,14 @@ public class BassClientStateMachineTest { MetricsLogger.setInstanceForTesting(null); mBassClientStateMachine.doQuit(); mHandlerThread.quit(); + Uninterruptibles.joinUninterruptibly(mHandlerThread); TestUtils.clearAdapterService(mAdapterService); } /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - assertThat(mBassClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mBassClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } /** @@ -288,14 +293,13 @@ public class BassClientStateMachineTest { any(String[].class), any(BroadcastOptions.class)); assertThat(intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + .isEqualTo(STATE_CONNECTING); assertThat(mBassClientStateMachine.getCurrentState()) .isInstanceOf(BassClientStateMachine.Connecting.class); assertThat(mBassClientStateMachine.mGattCallback).isNotNull(); - mBassClientStateMachine.notifyConnectionStateChanged( - GATT_SUCCESS, BluetoothProfile.STATE_CONNECTED); + mBassClientStateMachine.notifyConnectionStateChanged(GATT_SUCCESS, STATE_CONNECTED); // Verify that the expected number of broadcasts are executed: // - two calls to broadcastConnectionState(): Disconnected -> Connecting -> Connected @@ -326,7 +330,7 @@ public class BassClientStateMachineTest { any(String[].class), any(BroadcastOptions.class)); assertThat(intentArgument1.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + .isEqualTo(STATE_CONNECTING); assertThat(mBassClientStateMachine.getCurrentState()) .isInstanceOf(BassClientStateMachine.Connecting.class); @@ -339,7 +343,7 @@ public class BassClientStateMachineTest { any(String[].class), any(BroadcastOptions.class)); assertThat(intentArgument2.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mBassClientStateMachine.getCurrentState()) .isInstanceOf(BassClientStateMachine.Disconnected.class); @@ -376,7 +380,7 @@ public class BassClientStateMachineTest { mBassClientStateMachine.obtainMessage(BassClientStateMachine.DISCONNECT), BassClientStateMachine.Connecting.class); mBassClientStateMachine.sendMessage( - CONNECTION_STATE_CHANGED, Integer.valueOf(BluetoothProfile.STATE_CONNECTED)); + CONNECTION_STATE_CHANGED, Integer.valueOf(STATE_CONNECTED)); // disconnected -> connecting ---CONNECTION_STATE_CHANGED(connected)---> connected --> // disconnected @@ -386,13 +390,11 @@ public class BassClientStateMachineTest { BassClientStateMachine.Connecting.class); sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage( - CONNECTION_STATE_CHANGED, - Integer.valueOf(BluetoothProfile.STATE_CONNECTED)), + CONNECTION_STATE_CHANGED, Integer.valueOf(STATE_CONNECTED)), BassClientStateMachine.Connected.class); sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage( - CONNECTION_STATE_CHANGED, - Integer.valueOf(BluetoothProfile.STATE_DISCONNECTED)), + CONNECTION_STATE_CHANGED, Integer.valueOf(STATE_DISCONNECTED)), BassClientStateMachine.Disconnected.class); // disconnected -> connecting ---CONNECTION_STATE_CHANGED(non-connected) --> disconnected @@ -401,8 +403,7 @@ public class BassClientStateMachineTest { BassClientStateMachine.Connecting.class); sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage( - CONNECTION_STATE_CHANGED, - Integer.valueOf(BluetoothProfile.STATE_DISCONNECTED)), + CONNECTION_STATE_CHANGED, Integer.valueOf(STATE_DISCONNECTED)), BassClientStateMachine.Disconnected.class); // change default state to connected for the next tests @@ -411,8 +412,7 @@ public class BassClientStateMachineTest { BassClientStateMachine.Connecting.class); sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage( - CONNECTION_STATE_CHANGED, - Integer.valueOf(BluetoothProfile.STATE_CONNECTED)), + CONNECTION_STATE_CHANGED, Integer.valueOf(STATE_CONNECTED)), BassClientStateMachine.Connected.class); // connected ----READ_BASS_CHARACTERISTICS---> connectedProcessing --GATT_TXN_PROCESSED @@ -545,8 +545,8 @@ public class BassClientStateMachineTest { // disallow connection allowConnection(false); - int status = BluetoothProfile.STATE_CONNECTING; - int newState = BluetoothProfile.STATE_CONNECTED; + int status = STATE_CONNECTING; + int newState = STATE_CONNECTED; cb.onConnectionStateChange(null, status, newState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -559,8 +559,8 @@ public class BassClientStateMachineTest { mBassClientStateMachine.mBluetoothGatt = btGatt; allowConnection(true); mBassClientStateMachine.mDiscoveryInitiated = false; - status = BluetoothProfile.STATE_DISCONNECTED; - newState = BluetoothProfile.STATE_CONNECTED; + status = STATE_DISCONNECTED; + newState = STATE_CONNECTED; cb.onConnectionStateChange(null, status, newState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -581,8 +581,8 @@ public class BassClientStateMachineTest { mBassClientStateMachine.mBluetoothGatt = btGatt; allowConnection(false); - int status = BluetoothProfile.STATE_CONNECTING; - int newState = BluetoothProfile.STATE_DISCONNECTED; + int status = STATE_CONNECTING; + int newState = STATE_DISCONNECTED; cb.onConnectionStateChange(null, status, newState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1363,7 +1363,7 @@ public class BassClientStateMachineTest { Message msgToConnectingState = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msgToConnectingState.obj = BluetoothProfile.STATE_CONNECTING; + msgToConnectingState.obj = STATE_CONNECTING; mBassClientStateMachine.sendMessage(msgToConnectingState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1371,7 +1371,7 @@ public class BassClientStateMachineTest { Message msgToConnectedState = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msgToConnectedState.obj = BluetoothProfile.STATE_CONNECTED; + msgToConnectedState.obj = STATE_CONNECTED; sendMessageAndVerifyTransition(msgToConnectedState, BassClientStateMachine.Connected.class); } @@ -1421,7 +1421,7 @@ public class BassClientStateMachineTest { initToConnectingState(); Message msg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msg.obj = BluetoothProfile.STATE_CONNECTING; + msg.obj = STATE_CONNECTING; BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; @@ -1435,7 +1435,7 @@ public class BassClientStateMachineTest { initToConnectingState(); Message msg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msg.obj = BluetoothProfile.STATE_CONNECTED; + msg.obj = STATE_CONNECTED; sendMessageAndVerifyTransition(msg, BassClientStateMachine.Connected.class); } @@ -1500,7 +1500,7 @@ public class BassClientStateMachineTest { initToConnectedState(); Message connectedMsg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - connectedMsg.obj = BluetoothProfile.STATE_CONNECTED; + connectedMsg.obj = STATE_CONNECTED; mBassClientStateMachine.sendMessage(connectedMsg); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1510,7 +1510,7 @@ public class BassClientStateMachineTest { Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; Message noneConnectedMsg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - noneConnectedMsg.obj = BluetoothProfile.STATE_DISCONNECTING; + noneConnectedMsg.obj = STATE_DISCONNECTING; sendMessageAndVerifyTransition(noneConnectedMsg, BassClientStateMachine.Disconnected.class); verify(btGatt).close(); assertThat(mBassClientStateMachine.mBluetoothGatt).isNull(); @@ -1952,7 +1952,7 @@ public class BassClientStateMachineTest { Message msgToConnectedState = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msgToConnectedState.obj = BluetoothProfile.STATE_CONNECTED; + msgToConnectedState.obj = STATE_CONNECTED; mBassClientStateMachine.sendMessage(msgToConnectedState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1963,7 +1963,7 @@ public class BassClientStateMachineTest { mBassClientStateMachine.mBluetoothGatt = btGatt; Message msgToNoneConnectedState = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msgToNoneConnectedState.obj = BluetoothProfile.STATE_DISCONNECTING; + msgToNoneConnectedState.obj = STATE_DISCONNECTING; sendMessageAndVerifyTransition( msgToNoneConnectedState, BassClientStateMachine.Disconnected.class); verify(btGatt).close(); @@ -2633,7 +2633,7 @@ public class BassClientStateMachineTest { initToConnectingState(); Message msg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msg.obj = BluetoothProfile.STATE_CONNECTED; + msg.obj = STATE_CONNECTED; sendMessageAndVerifyTransition(msg, BassClientStateMachine.Connected.class); Mockito.clearInvocations(mBassClientService); } @@ -2656,7 +2656,7 @@ public class BassClientStateMachineTest { Mockito.clearInvocations(mBassClientService); } - private boolean isConnectionIntentExpected(Class currentType, Class nextType) { + private static boolean isConnectionIntentExpected(Class currentType, Class nextType) { if (currentType == nextType) { return false; // Same state, no intent expected } @@ -2725,7 +2725,8 @@ public class BassClientStateMachineTest { return builder.build(); } - private byte[] convertMetadataToUpdateSourceByteArray(BluetoothLeBroadcastMetadata metaData) { + private static byte[] convertMetadataToUpdateSourceByteArray( + BluetoothLeBroadcastMetadata metaData) { int numSubGroups = metaData.getSubgroups().size(); byte[] res = new byte[UPDATE_SOURCE_FIXED_LENGTH + numSubGroups * 5]; @@ -2764,7 +2765,7 @@ public class BassClientStateMachineTest { return res; } - private BluetoothLeBroadcastMetadata getMetadataToPauseStream( + private static BluetoothLeBroadcastMetadata getMetadataToPauseStream( BluetoothLeBroadcastMetadata metadata) { BluetoothLeBroadcastMetadata.Builder metadataToUpdateBuilder = new BluetoothLeBroadcastMetadata.Builder(metadata); @@ -2921,7 +2922,7 @@ public class BassClientStateMachineTest { .isEqualTo(Bytes.concat(metadataHeader, metadataPayload)); } - private BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { + private static BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { final long testAudioLocationFrontLeft = 0x01; final long testAudioLocationFrontRight = 0x02; // For BluetoothLeAudioContentMetadata diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java index aa3a14ff1e..d51e857efe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.bass_client; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; @@ -30,7 +32,6 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothLeBroadcastAssistantCallback; import android.bluetooth.le.ScanFilter; import android.content.AttributionSource; @@ -109,16 +110,13 @@ public class BleBroadcastAssistantBinderTest { @Test public void setConnectionPolicy() { - mBinder.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, mAttributionSource); - verify(mService).setConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource); + verify(mService).setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED); mBinder.cleanup(); assertThat( mBinder.setConnectionPolicy( - mDevice, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - mAttributionSource)) + mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource)) .isFalse(); } @@ -129,7 +127,7 @@ public class BleBroadcastAssistantBinderTest { mBinder.cleanup(); assertThat(mBinder.getConnectionPolicy(mDevice, mAttributionSource)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .isEqualTo(CONNECTION_POLICY_FORBIDDEN); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java index ff5324e4b0..e86952a165 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java @@ -138,7 +138,7 @@ public class PeriodicAdvertisementResultTest { } /** Helper to generate test data for public broadcast. */ - private PublicBroadcastData generatePublicBroadcastData() { + private static PublicBroadcastData generatePublicBroadcastData() { PublicBroadcastData.PublicBroadcastInfo info = new PublicBroadcastData.PublicBroadcastInfo(); info.isEncrypted = true; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java index e07cc3780b..0dc5c6de3a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java @@ -16,6 +16,12 @@ package com.android.bluetooth.btservice; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -606,9 +612,7 @@ public class ActiveDeviceManagerTest { when(mHeadsetService.getFallbackDevice()).thenReturn(mA2dpHeadsetDevice); mDatabaseManager.setProfileConnectionPolicy( - mA2dpHeadsetDevice, - BluetoothProfile.A2DP, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mA2dpHeadsetDevice, BluetoothProfile.A2DP, CONNECTION_POLICY_FORBIDDEN); a2dpDisconnected(mA2dpHeadsetDevice); mTestLooper.dispatchAll(); verify(mHeadsetService, times(2)).setActiveDevice(mA2dpHeadsetDevice); @@ -637,9 +641,7 @@ public class ActiveDeviceManagerTest { when(mHeadsetService.getFallbackDevice()).thenReturn(mA2dpHeadsetDevice); mDatabaseManager.setProfileConnectionPolicy( - mSecondaryAudioDevice, - BluetoothProfile.HEADSET, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mSecondaryAudioDevice, BluetoothProfile.HEADSET, CONNECTION_POLICY_FORBIDDEN); headsetDisconnected(mSecondaryAudioDevice); mTestLooper.dispatchAll(); verify(mHeadsetService, times(3)).setActiveDevice(mA2dpHeadsetDevice); @@ -1829,18 +1831,13 @@ public class ActiveDeviceManagerTest { mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.HEADSET, - supportHfp - ? BluetoothProfile.CONNECTION_POLICY_ALLOWED - : BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + supportHfp ? CONNECTION_POLICY_ALLOWED : CONNECTION_POLICY_UNKNOWN); mDeviceConnectionStack.add(device); mMostRecentDevice = device; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.A2DP, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.A2DP, device, STATE_DISCONNECTED, STATE_CONNECTED); } /** Helper to indicate A2dp disconnected for a device. */ @@ -1852,10 +1849,7 @@ public class ActiveDeviceManagerTest { : null; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.A2DP, - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothProfile.A2DP, device, STATE_CONNECTED, STATE_DISCONNECTED); } /** Helper to indicate A2dp active device changed for a device. */ @@ -1872,18 +1866,13 @@ public class ActiveDeviceManagerTest { mDatabaseManager.setProfileConnectionPolicy( device, BluetoothProfile.A2DP, - supportA2dp - ? BluetoothProfile.CONNECTION_POLICY_ALLOWED - : BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + supportA2dp ? CONNECTION_POLICY_ALLOWED : CONNECTION_POLICY_UNKNOWN); mDeviceConnectionStack.add(device); mMostRecentDevice = device; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HEADSET, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.HEADSET, device, STATE_DISCONNECTED, STATE_CONNECTED); } /** Helper to indicate Headset disconnected for a device. */ @@ -1895,10 +1884,7 @@ public class ActiveDeviceManagerTest { : null; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HEADSET, - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothProfile.HEADSET, device, STATE_CONNECTED, STATE_DISCONNECTED); } /** Helper to indicate Headset active device changed for a device. */ @@ -1916,10 +1902,7 @@ public class ActiveDeviceManagerTest { mMostRecentDevice = device; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HEARING_AID, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.HEARING_AID, device, STATE_DISCONNECTED, STATE_CONNECTED); } /** Helper to indicate Hearing Aid disconnected for a device. */ @@ -1931,10 +1914,7 @@ public class ActiveDeviceManagerTest { : null; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HEARING_AID, - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothProfile.HEARING_AID, device, STATE_CONNECTED, STATE_DISCONNECTED); } /** Helper to indicate Hearing Aid active device changed for a device. */ @@ -1951,10 +1931,7 @@ public class ActiveDeviceManagerTest { mMostRecentDevice = device; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.LE_AUDIO, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.LE_AUDIO, device, STATE_DISCONNECTED, STATE_CONNECTED); } /** Helper to indicate LE Audio disconnected for a device. */ @@ -1966,10 +1943,7 @@ public class ActiveDeviceManagerTest { : null; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.LE_AUDIO, - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothProfile.LE_AUDIO, device, STATE_CONNECTED, STATE_DISCONNECTED); } /** Helper to indicate LE Audio active device changed for a device. */ @@ -1987,10 +1961,7 @@ public class ActiveDeviceManagerTest { mMostRecentDevice = device; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HAP_CLIENT, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.HAP_CLIENT, device, STATE_DISCONNECTED, STATE_CONNECTED); } /** Helper to indicate LE Hearing Aid disconnected for a device. */ @@ -2002,10 +1973,7 @@ public class ActiveDeviceManagerTest { : null; mActiveDeviceManager.profileConnectionStateChanged( - BluetoothProfile.HAP_CLIENT, - device, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + BluetoothProfile.HAP_CLIENT, device, STATE_CONNECTED, STATE_DISCONNECTED); } private class TestDatabaseManager extends DatabaseManager { @@ -2036,9 +2004,9 @@ public class ActiveDeviceManagerTest { if (device == null) { return false; } - if (policy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN - && policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && policy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (policy != CONNECTION_POLICY_UNKNOWN + && policy != CONNECTION_POLICY_FORBIDDEN + && policy != CONNECTION_POLICY_ALLOWED) { return false; } SparseIntArray policyMap = mProfileConnectionPolicy.get(device); @@ -2054,9 +2022,9 @@ public class ActiveDeviceManagerTest { public int getProfileConnectionPolicy(BluetoothDevice device, int profile) { SparseIntArray policy = mProfileConnectionPolicy.get(device); if (policy == null) { - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } - return policy.get(profile, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + return policy.get(profile, CONNECTION_POLICY_FORBIDDEN); } } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java index 36541709ff..3477993ad0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java @@ -23,6 +23,10 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF; import static android.bluetooth.BluetoothAdapter.STATE_ON; import static android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF; import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -221,9 +225,7 @@ public class AdapterServiceTest { doReturn(true).when(mMockLeAudioService).isAvailable(); LeAudioService.setLeAudioService(mMockLeAudioService); - doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED) - .when(mMockLeAudioService) - .getConnectionPolicy(any()); + doReturn(CONNECTION_POLICY_ALLOWED).when(mMockLeAudioService).getConnectionPolicy(any()); AdapterNativeInterface.setInstance(mNativeInterface); BluetoothKeystoreNativeInterface.setInstance(mKeystoreNativeInterface); @@ -1053,7 +1055,7 @@ public class AdapterServiceTest { @EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE) public void testGattConnectionToLeAudioDevice_whenDeviceIsNotConnected_success() { int groupId = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1075,7 +1077,7 @@ public class AdapterServiceTest { @EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE) public void testGattConnectionToLeAudioDevice_whenDeviceIsConnected_ignore() { int groupId = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1097,7 +1099,7 @@ public class AdapterServiceTest { @EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE) public void testGattConnectionToLeAudioDevice_whenLeAudioIsNotAllowed_ignore() { int groupId = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_DISCONNECTED; + int getConnectionState_LeAudioService = STATE_DISCONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1109,9 +1111,7 @@ public class AdapterServiceTest { getConnectionState_LeAudioService, getConnectionState_AdapterService); - doReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) - .when(mMockLeAudioService) - .getConnectionPolicy(any()); + doReturn(CONNECTION_POLICY_FORBIDDEN).when(mMockLeAudioService).getConnectionPolicy(any()); mAdapterService.notifyDirectLeGattClientConnect(1, mDevice); order.verify(mMockLeAudioService, never()).setAutoActiveModeState(groupId, false); @@ -1124,7 +1124,7 @@ public class AdapterServiceTest { int groupId = 1; int clientIf = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1152,7 +1152,7 @@ public class AdapterServiceTest { int groupId = 1; int clientIf = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_DISCONNECTED; + int getConnectionState_LeAudioService = STATE_DISCONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_DISCONNECTED; InOrder order = prepareLeAudioWithConnectedDevices( @@ -1179,7 +1179,7 @@ public class AdapterServiceTest { public void testGattConnectionToLeAudioDevice_triggerDisconnecting() { int groupId = 1; int clientIf = 1; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1211,7 +1211,7 @@ public class AdapterServiceTest { int clientIf = 1; int clientIfTwo = 2; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1259,7 +1259,7 @@ public class AdapterServiceTest { int clientIf = 1; int clientIfTwo = 2; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; @@ -1308,7 +1308,7 @@ public class AdapterServiceTest { int clientIf = 1; int clientIfTwo = 2; - int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED; + int getConnectionState_LeAudioService = STATE_CONNECTED; int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE | BluetoothDevice.CONNECTION_STATE_CONNECTED; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java index f20773d067..7da94bf876 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java @@ -1,6 +1,9 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; @@ -275,7 +278,7 @@ public class RemoteDevicesTest { // Verify that resetting battery level changes it back to BluetoothDevice // .BATTERY_LEVEL_UNKNOWN mRemoteDevices.onHeadsetConnectionStateChanged( - mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); + mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED); // Verify BATTERY_LEVEL_CHANGED intent is sent after first reset verify(mAdapterService, times(2)) .sendBroadcast( @@ -324,7 +327,7 @@ public class RemoteDevicesTest { // Verify that battery level is not reset mRemoteDevices.onHeadsetConnectionStateChanged( - mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); + mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED); assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull(); assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) @@ -590,7 +593,7 @@ public class RemoteDevicesTest { // Verify that resetting battery level changes it back to BluetoothDevice // .BATTERY_LEVEL_UNKNOWN mRemoteDevices.onHeadsetClientConnectionStateChanged( - mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); + mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED); // Verify BATTERY_LEVEL_CHANGED intent is sent after first reset verify(mAdapterService, times(2)) @@ -641,7 +644,7 @@ public class RemoteDevicesTest { // Verify that battery level is not reset. mRemoteDevices.onHeadsetClientConnectionStateChanged( - mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED); + mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED); assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull(); assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) @@ -855,7 +858,7 @@ public class RemoteDevicesTest { private static BatteryService setBatteryServiceForTesting(BluetoothDevice device) { BatteryService newService = mock(BatteryService.class); - when(newService.getConnectionState(device)).thenReturn(BluetoothProfile.STATE_CONNECTED); + when(newService.getConnectionState(device)).thenReturn(STATE_CONNECTED); when(newService.isAvailable()).thenReturn(true); BatteryService oldService = BatteryService.getBatteryService(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java index 1e666f7dd4..2a49540088 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java @@ -17,6 +17,8 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -26,7 +28,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.*; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.Bundle; import android.os.HandlerThread; @@ -167,28 +168,28 @@ public class SilenceDeviceManagerTest { /** Helper to indicate A2dp connected for a device. */ private void a2dpConnected(BluetoothDevice device) { mSilenceDeviceManager.a2dpConnectionStateChanged( - device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + device, STATE_DISCONNECTED, STATE_CONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } /** Helper to indicate A2dp disconnected for a device. */ private void a2dpDisconnected(BluetoothDevice device) { mSilenceDeviceManager.a2dpConnectionStateChanged( - device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + device, STATE_CONNECTED, STATE_DISCONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } /** Helper to indicate Headset connected for a device. */ private void headsetConnected(BluetoothDevice device) { mSilenceDeviceManager.hfpConnectionStateChanged( - device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + device, STATE_DISCONNECTED, STATE_CONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } /** Helper to indicate Headset disconnected for a device. */ private void headsetDisconnected(BluetoothDevice device) { mSilenceDeviceManager.hfpConnectionStateChanged( - device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED); + device, STATE_CONNECTED, STATE_DISCONNECTED); TestUtils.waitForLooperToFinishScheduledTask(mLooper); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java index b436231bbb..30374d57ae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java @@ -127,11 +127,11 @@ public final class BluetoothKeystoreServiceTest { mBluetoothKeystoreService = null; } - private boolean isPrimaryUser() { + private static boolean isPrimaryUser() { return Binder.getCallingUid() == Process.BLUETOOTH_UID; } - private void overwriteConfigFile(List<String> data) { + private static void overwriteConfigFile(List<String> data) { try { Files.write(Paths.get(CONFIG_FILE_PATH), data); } catch (IOException e) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java index c06dbb5d08..e05c0a0d26 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java @@ -16,6 +16,10 @@ package com.android.bluetooth.btservice.storage; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -143,7 +147,7 @@ public final class DatabaseManagerTest { for (int id = 0; id < BluetoothProfile.MAX_PROFILE_ID; id++) { assertThat(mDatabaseManager.getProfileConnectionPolicy(mDevice, id)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .isEqualTo(CONNECTION_POLICY_UNKNOWN); } assertThat(mDatabaseManager.getA2dpSupportsOptionalCodecs(mDevice)) @@ -168,41 +172,23 @@ public final class DatabaseManagerTest { // Cases of device not in database testSetGetProfileConnectionPolicyCase( - false, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - true); + false, CONNECTION_POLICY_UNKNOWN, CONNECTION_POLICY_UNKNOWN, true); testSetGetProfileConnectionPolicyCase( - false, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - true); + false, CONNECTION_POLICY_FORBIDDEN, CONNECTION_POLICY_FORBIDDEN, true); testSetGetProfileConnectionPolicyCase( - false, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - true); + false, CONNECTION_POLICY_ALLOWED, CONNECTION_POLICY_ALLOWED, true); testSetGetProfileConnectionPolicyCase( - false, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + false, badConnectionPolicy, CONNECTION_POLICY_UNKNOWN, false); // Cases of device already in database testSetGetProfileConnectionPolicyCase( - true, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - true); + true, CONNECTION_POLICY_UNKNOWN, CONNECTION_POLICY_UNKNOWN, true); testSetGetProfileConnectionPolicyCase( - true, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - true); + true, CONNECTION_POLICY_FORBIDDEN, CONNECTION_POLICY_FORBIDDEN, true); testSetGetProfileConnectionPolicyCase( - true, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - true); + true, CONNECTION_POLICY_ALLOWED, CONNECTION_POLICY_ALLOWED, true); testSetGetProfileConnectionPolicyCase( - true, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); + true, badConnectionPolicy, CONNECTION_POLICY_UNKNOWN, false); } @Test @@ -1431,6 +1417,28 @@ public final class DatabaseManagerTest { } } + @Test + public void testDatabaseMigration_121_122() throws IOException { + // Create a database with version 121 + SupportSQLiteDatabase db = testHelper.createDatabase(DB_NAME, 121); + + // insert a device to the database + ContentValues device = contentValuesDevice_121(); + assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device)).isNotEqualTo(-1); + + // Migrate database from 121 to 122 + db.close(); + db = + testHelper.runMigrationsAndValidate( + DB_NAME, 122, true, MetadataDatabase.MIGRATION_121_122); + Cursor cursor = db.query("SELECT * FROM metadata"); + assertHasColumn(cursor, "key_missing_count", true); + while (cursor.moveToNext()) { + // Check the new columns was added with default value + assertColumnIntData(cursor, "key_missing_count", 0); + } + } + private ContentValues createContentValuesDeviceCommon() { ContentValues device = new ContentValues(); device.put("address", mDevice.getAddress()); @@ -1615,6 +1623,12 @@ public final class DatabaseManagerTest { return device; } + private ContentValues contentValuesDevice_121() { + ContentValues device = contentValuesDevice_120(); + device.put("is_preferred_microphone_for_calls", 1); + return device; + } + /** Helper function to check whether the database has the expected column */ void assertHasColumn(Cursor cursor, String columnName, boolean hasColumn) { if (hasColumn) { @@ -1685,8 +1699,8 @@ public final class DatabaseManagerTest { // Check number of metadata in the database if (!stored) { - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_FORBIDDEN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { // Database won't be updated assertThat(list).isEmpty(); return; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json new file mode 100644 index 0000000000..43a8f11132 --- /dev/null +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json @@ -0,0 +1,357 @@ +{ + "formatVersion": 1, + "database": { + "version": 122, + "identityHash": "a80cd402e29589764a3e3cf412150d60", + "entities": [ + { + "tableName": "metadata", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `migrated` INTEGER NOT NULL, `a2dpSupportsOptionalCodecs` INTEGER NOT NULL, `a2dpOptionalCodecsEnabled` INTEGER NOT NULL, `last_active_time` INTEGER NOT NULL, `is_active_a2dp_device` INTEGER NOT NULL, `isActiveHfpDevice` INTEGER NOT NULL, `preferred_output_only_profile` INTEGER NOT NULL, `preferred_duplex_profile` INTEGER NOT NULL, `active_audio_device_policy` INTEGER NOT NULL, `is_preferred_microphone_for_calls` INTEGER NOT NULL, `key_missing_count` INTEGER NOT NULL, `a2dp_connection_policy` INTEGER, `a2dp_sink_connection_policy` INTEGER, `hfp_connection_policy` INTEGER, `hfp_client_connection_policy` INTEGER, `hid_host_connection_policy` INTEGER, `pan_connection_policy` INTEGER, `pbap_connection_policy` INTEGER, `pbap_client_connection_policy` INTEGER, `map_connection_policy` INTEGER, `sap_connection_policy` INTEGER, `hearing_aid_connection_policy` INTEGER, `hap_client_connection_policy` INTEGER, `map_client_connection_policy` INTEGER, `le_audio_connection_policy` INTEGER, `volume_control_connection_policy` INTEGER, `csip_set_coordinator_connection_policy` INTEGER, `le_call_control_connection_policy` INTEGER, `bass_client_connection_policy` INTEGER, `battery_connection_policy` INTEGER, `manufacturer_name` BLOB, `model_name` BLOB, `software_version` BLOB, `hardware_version` BLOB, `companion_app` BLOB, `main_icon` BLOB, `is_untethered_headset` BLOB, `untethered_left_icon` BLOB, `untethered_right_icon` BLOB, `untethered_case_icon` BLOB, `untethered_left_battery` BLOB, `untethered_right_battery` BLOB, `untethered_case_battery` BLOB, `untethered_left_charging` BLOB, `untethered_right_charging` BLOB, `untethered_case_charging` BLOB, `enhanced_settings_ui_uri` BLOB, `device_type` BLOB, `main_battery` BLOB, `main_charging` BLOB, `main_low_battery_threshold` BLOB, `untethered_left_low_battery_threshold` BLOB, `untethered_right_low_battery_threshold` BLOB, `untethered_case_low_battery_threshold` BLOB, `spatial_audio` BLOB, `fastpair_customized` BLOB, `le_audio` BLOB, `gmcs_cccd` BLOB, `gtbs_cccd` BLOB, `exclusive_manager` BLOB, `call_establish_audio_policy` INTEGER, `connecting_time_audio_policy` INTEGER, `in_band_ringtone_audio_policy` INTEGER, PRIMARY KEY(`address`))", + "fields": [ + { + "fieldPath": "address", + "columnName": "address", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "migrated", + "columnName": "migrated", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "a2dpSupportsOptionalCodecs", + "columnName": "a2dpSupportsOptionalCodecs", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "a2dpOptionalCodecsEnabled", + "columnName": "a2dpOptionalCodecsEnabled", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "last_active_time", + "columnName": "last_active_time", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "is_active_a2dp_device", + "columnName": "is_active_a2dp_device", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "isActiveHfpDevice", + "columnName": "isActiveHfpDevice", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "preferred_output_only_profile", + "columnName": "preferred_output_only_profile", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "preferred_duplex_profile", + "columnName": "preferred_duplex_profile", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "active_audio_device_policy", + "columnName": "active_audio_device_policy", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "is_preferred_microphone_for_calls", + "columnName": "is_preferred_microphone_for_calls", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "key_missing_count", + "columnName": "key_missing_count", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "profileConnectionPolicies.a2dp_connection_policy", + "columnName": "a2dp_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.a2dp_sink_connection_policy", + "columnName": "a2dp_sink_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hfp_connection_policy", + "columnName": "hfp_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hfp_client_connection_policy", + "columnName": "hfp_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hid_host_connection_policy", + "columnName": "hid_host_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pan_connection_policy", + "columnName": "pan_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pbap_connection_policy", + "columnName": "pbap_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.pbap_client_connection_policy", + "columnName": "pbap_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.map_connection_policy", + "columnName": "map_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.sap_connection_policy", + "columnName": "sap_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hearing_aid_connection_policy", + "columnName": "hearing_aid_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.hap_client_connection_policy", + "columnName": "hap_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.map_client_connection_policy", + "columnName": "map_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.le_audio_connection_policy", + "columnName": "le_audio_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.volume_control_connection_policy", + "columnName": "volume_control_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.csip_set_coordinator_connection_policy", + "columnName": "csip_set_coordinator_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.le_call_control_connection_policy", + "columnName": "le_call_control_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.bass_client_connection_policy", + "columnName": "bass_client_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "profileConnectionPolicies.battery_connection_policy", + "columnName": "battery_connection_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "publicMetadata.manufacturer_name", + "columnName": "manufacturer_name", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.model_name", + "columnName": "model_name", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.software_version", + "columnName": "software_version", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.hardware_version", + "columnName": "hardware_version", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.companion_app", + "columnName": "companion_app", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_icon", + "columnName": "main_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.is_untethered_headset", + "columnName": "is_untethered_headset", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_icon", + "columnName": "untethered_left_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_icon", + "columnName": "untethered_right_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_icon", + "columnName": "untethered_case_icon", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_battery", + "columnName": "untethered_left_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_battery", + "columnName": "untethered_right_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_battery", + "columnName": "untethered_case_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_charging", + "columnName": "untethered_left_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_charging", + "columnName": "untethered_right_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_charging", + "columnName": "untethered_case_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.enhanced_settings_ui_uri", + "columnName": "enhanced_settings_ui_uri", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.device_type", + "columnName": "device_type", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_battery", + "columnName": "main_battery", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_charging", + "columnName": "main_charging", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.main_low_battery_threshold", + "columnName": "main_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_left_low_battery_threshold", + "columnName": "untethered_left_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_right_low_battery_threshold", + "columnName": "untethered_right_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.untethered_case_low_battery_threshold", + "columnName": "untethered_case_low_battery_threshold", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.spatial_audio", + "columnName": "spatial_audio", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.fastpair_customized", + "columnName": "fastpair_customized", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.le_audio", + "columnName": "le_audio", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.gmcs_cccd", + "columnName": "gmcs_cccd", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.gtbs_cccd", + "columnName": "gtbs_cccd", + "affinity": "BLOB" + }, + { + "fieldPath": "publicMetadata.exclusive_manager", + "columnName": "exclusive_manager", + "affinity": "BLOB" + }, + { + "fieldPath": "audioPolicyMetadata.callEstablishAudioPolicy", + "columnName": "call_establish_audio_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "audioPolicyMetadata.connectingTimeAudioPolicy", + "columnName": "connecting_time_audio_policy", + "affinity": "INTEGER" + }, + { + "fieldPath": "audioPolicyMetadata.inBandRingtoneAudioPolicy", + "columnName": "in_band_ringtone_audio_policy", + "affinity": "INTEGER" + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "address" + ] + } + } + ], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a80cd402e29589764a3e3cf412150d60')" + ] + } +}
\ No newline at end of file diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java index 6ea19c5477..69e8546ac3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.csip; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -23,7 +26,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothCsipSetCoordinatorLockCallback; import android.content.AttributionSource; import android.os.ParcelUuid; @@ -56,7 +58,7 @@ public class BluetoothCsisBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } @@ -69,7 +71,7 @@ public class BluetoothCsisBinderTest { @Test public void setConnectionPolicy() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java index ba9de2c181..ac64b097ae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java @@ -443,7 +443,7 @@ public class CsipSetCoordinatorServiceTest { } /** Helper function to get byte array for a device address */ - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { return Utils.getBytesFromAddress(device.getAddress()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java index f982200eb6..a246d76b8f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.gatt; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static org.mockito.Mockito.mock; @@ -24,7 +26,6 @@ import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothGattCallback; import android.bluetooth.IBluetoothGattServerCallback; import android.content.AttributionSource; @@ -64,7 +65,7 @@ public class GattServiceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java index 4cba08d39f..a0c3042d07 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.gatt; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -30,7 +32,6 @@ import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothGatt; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothStatusCodes; import android.bluetooth.IBluetoothGattCallback; import android.bluetooth.IBluetoothGattServerCallback; @@ -404,7 +405,7 @@ public class GattServiceTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; BluetoothDevice testDevice = getTestDevice(90); BluetoothDevice[] bluetoothDevices = new BluetoothDevice[] {testDevice}; diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java index a0a123dcd9..7f079c79b7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.hap; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -27,7 +30,6 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothHapClientCallback; import android.content.AttributionSource; @@ -95,28 +97,20 @@ public class HapClientBinderTest { public void setConnectionPolicy() { assertThrows( NullPointerException.class, - () -> - mBinder.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, null)); + () -> mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, null)); assertThrows( NullPointerException.class, () -> mBinder.setConnectionPolicy( - null, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - mAttributionSource)); + null, CONNECTION_POLICY_ALLOWED, mAttributionSource)); assertThrows( IllegalArgumentException.class, () -> mBinder.setConnectionPolicy( - mDevice, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - mAttributionSource)); - - mBinder.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, mAttributionSource); - verify(mHapClientService) - .setConnectionPolicy(eq(mDevice), eq(BluetoothProfile.CONNECTION_POLICY_ALLOWED)); + mDevice, CONNECTION_POLICY_UNKNOWN, mAttributionSource)); + + mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource); + verify(mHapClientService).setConnectionPolicy(eq(mDevice), eq(CONNECTION_POLICY_ALLOWED)); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java index 85ba8fdb4e..a67995ffae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java @@ -16,12 +16,13 @@ package com.android.bluetooth.hap; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothHapPresetInfo; -import android.bluetooth.BluetoothProfile; import com.android.bluetooth.btservice.AdapterService; @@ -51,7 +52,7 @@ public class HapClientNativeCallbackTest { @Test public void onConnectionStateChanged() { - int state = BluetoothProfile.STATE_CONNECTED; + int state = STATE_CONNECTED; mNativeCallback.onConnectionStateChanged(state, null); verify(mHapClientService).messageFromNative(mEvent.capture()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java index 86923a6ca6..272e2e0b45 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java @@ -710,7 +710,7 @@ public class HapClientServiceTest { } /** Helper function to get byte array for a device address */ - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java index 0dff31a1c0..ac7c90a213 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.hearingaid; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -27,7 +29,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import com.android.bluetooth.Utils; @@ -73,19 +74,19 @@ public class HearingAidNativeInterfaceTest { public void onConnectionStateChanged() { BluetoothDevice device = getTestDevice(0); mNativeInterface.onConnectionStateChanged( - BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); + STATE_CONNECTED, mNativeInterface.getByteAddress(device)); ArgumentCaptor<HearingAidStackEvent> event = ArgumentCaptor.forClass(HearingAidStackEvent.class); verify(mService).messageFromNative(event.capture()); assertThat(event.getValue().type) .isEqualTo(HearingAidStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); - assertThat(event.getValue().valueInt1).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(event.getValue().valueInt1).isEqualTo(STATE_CONNECTED); Mockito.clearInvocations(mService); HearingAidService.setHearingAidService(null); mNativeInterface.onConnectionStateChanged( - BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); + STATE_CONNECTED, mNativeInterface.getByteAddress(device)); verify(mService, never()).messageFromNative(any()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java index 4dffd067b5..b6f71f6dc9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.hfp; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.AttributionSource; import org.junit.Before; @@ -65,7 +67,7 @@ public class BluetoothHeadsetBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } @@ -78,7 +80,7 @@ public class BluetoothHeadsetBinderTest { @Test public void setConnectionPolicy() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java index 46b8d2539d..0905e185d4 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java @@ -16,6 +16,12 @@ package com.android.bluetooth.hfp; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasData; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; @@ -215,8 +221,7 @@ public class HeadsetServiceAndStateMachineTest { assertThat(HeadsetService.getHeadsetService()).isEqualTo(mHeadsetService); // Verify default connection and audio states BluetoothDevice device = getTestDevice(0); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getAudioState(device)) .isEqualTo(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); } @@ -228,7 +233,7 @@ public class HeadsetServiceAndStateMachineTest { @Test public void testConnectFromApi() { BluetoothDevice device = getTestDevice(0); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEADSET); mBondedDevices.add(device); @@ -242,14 +247,10 @@ public class HeadsetServiceAndStateMachineTest { mAdapterService, mNativeInterface, mSystemInterface); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED); verify(mNativeInterface).connectHfp(device); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); - assertThat( - mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTING})) + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING); + assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTING})) .containsExactly(device); // Get feedback from native to put device into connected state HeadsetStackEvent connectedEvent = @@ -259,13 +260,9 @@ public class HeadsetServiceAndStateMachineTest { device); mHeadsetService.messageFromNative(connectedEvent); mTestLooper.dispatchAll(); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); - assertThat( - mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + verifyConnectionStateIntent(device, STATE_CONNECTED, STATE_CONNECTING); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED); + assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED})) .containsExactly(device); } @@ -277,7 +274,7 @@ public class HeadsetServiceAndStateMachineTest { @Test public void testUnbondDevice_disconnectBeforeUnbond() { BluetoothDevice device = getTestDevice(0); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEADSET); mBondedDevices.add(device); @@ -291,8 +288,7 @@ public class HeadsetServiceAndStateMachineTest { mAdapterService, mNativeInterface, mSystemInterface); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED); verify(mNativeInterface).connectHfp(device); // Get feedback from native layer to go back to disconnected state HeadsetStackEvent connectedEvent = @@ -302,8 +298,7 @@ public class HeadsetServiceAndStateMachineTest { device); mHeadsetService.messageFromNative(connectedEvent); mTestLooper.dispatchAll(); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); + verifyConnectionStateIntent(device, STATE_DISCONNECTED, STATE_CONNECTING); mHeadsetService.handleBondStateChanged( device, BluetoothDevice.BOND_BONDED, BluetoothDevice.BOND_NONE); @@ -323,7 +318,7 @@ public class HeadsetServiceAndStateMachineTest { @Test public void testUnbondDevice_disconnectAfterUnbond() { BluetoothDevice device = getTestDevice(0); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEADSET); mBondedDevices.add(device); @@ -338,8 +333,7 @@ public class HeadsetServiceAndStateMachineTest { mNativeInterface, mSystemInterface); verify(mNativeInterface).connectHfp(device); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED); // Get feedback from native layer to go to connected state HeadsetStackEvent connectedEvent = new HeadsetStackEvent( @@ -348,10 +342,8 @@ public class HeadsetServiceAndStateMachineTest { device); mHeadsetService.messageFromNative(connectedEvent); mTestLooper.dispatchAll(); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + verifyConnectionStateIntent(device, STATE_CONNECTED, STATE_CONNECTING); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()).containsExactly(device); // Check that the state machine is not destroyed @@ -367,8 +359,7 @@ public class HeadsetServiceAndStateMachineTest { mHeadsetService.messageFromNative(connectingEvent); mTestLooper.dispatchAll(); - verifyConnectionStateIntent( - device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + verifyConnectionStateIntent(device, STATE_DISCONNECTED, STATE_CONNECTED); // Check that the state machine is destroyed after another async call ArgumentCaptor<HeadsetStateMachine> stateMachineArgument = @@ -392,7 +383,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -431,7 +422,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -475,7 +466,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -526,7 +517,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -620,7 +611,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -1187,7 +1178,7 @@ public class HeadsetServiceAndStateMachineTest { .containsExactlyElementsIn(mBondedDevices); assertThat( mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + new int[] {STATE_CONNECTED})) .containsExactlyElementsIn(mBondedDevices); } List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices(); @@ -1580,16 +1571,16 @@ public class HeadsetServiceAndStateMachineTest { verify(mNativeInterface).sendBsir(eq(device), eq(true)); // this device is a HFP only device - doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED) + doReturn(CONNECTION_POLICY_ALLOWED) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEADSET); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.A2DP); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEARING_AID); - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO); @@ -1788,7 +1779,7 @@ public class HeadsetServiceAndStateMachineTest { } private void connectTestDevice(BluetoothDevice device) { - doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + doReturn(CONNECTION_POLICY_UNKNOWN) .when(mDatabaseManager) .getProfileConnectionPolicy(device, BluetoothProfile.HEADSET); doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService).getBondState(eq(device)); @@ -1812,20 +1803,11 @@ public class HeadsetServiceAndStateMachineTest { mSystemInterface); verify(mActiveDeviceManager) .profileConnectionStateChanged( - BluetoothProfile.HEADSET, - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + BluetoothProfile.HEADSET, device, STATE_DISCONNECTED, STATE_CONNECTING); verify(mSilenceDeviceManager) - .hfpConnectionStateChanged( - device, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); - assertThat( - mHeadsetService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTING})) + .hfpConnectionStateChanged(device, STATE_DISCONNECTED, STATE_CONNECTING); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING); + assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTING})) .containsExactly(device); // Get feedback from native to put device into connected state HeadsetStackEvent slcConnectedEvent = @@ -1837,17 +1819,10 @@ public class HeadsetServiceAndStateMachineTest { mTestLooper.dispatchAll(); verify(mActiveDeviceManager) .profileConnectionStateChanged( - BluetoothProfile.HEADSET, - device, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.HEADSET, device, STATE_CONNECTING, STATE_CONNECTED); verify(mSilenceDeviceManager) - .hfpConnectionStateChanged( - device, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .hfpConnectionStateChanged(device, STATE_CONNECTING, STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED); } @SafeVarargs diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java index 91d9038a51..18a53db436 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java @@ -16,6 +16,13 @@ package com.android.bluetooth.hfp; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -160,9 +167,7 @@ public class HeadsetServiceTest { assertThat(mCurrentDevice).isNotNull(); final HeadsetStateMachine stateMachine = mock(HeadsetStateMachine.class); - doReturn(BluetoothProfile.STATE_DISCONNECTED) - .when(stateMachine) - .getConnectionState(); + doReturn(STATE_DISCONNECTED).when(stateMachine).getConnectionState(); doReturn(BluetoothHeadset.STATE_AUDIO_DISCONNECTED) .when(stateMachine) .getAudioState(); @@ -197,7 +202,7 @@ public class HeadsetServiceTest { // Verify default connection and audio states mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getAudioState(mCurrentDevice)) .isEqualTo(BluetoothHeadset.STATE_AUDIO_DISCONNECTED); } @@ -211,65 +216,50 @@ public class HeadsetServiceTest { testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase( - mCurrentDevice, - BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mCurrentDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase( - mCurrentDevice, - BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mCurrentDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false); testOkToAcceptConnectionCase( - mCurrentDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - true); + mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true); testOkToAcceptConnectionCase( - mCurrentDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false); testOkToAcceptConnectionCase( - mCurrentDevice, - BluetoothDevice.BOND_BONDED, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, - true); + mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_ALLOWED, true); testOkToAcceptConnectionCase( mCurrentDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false); testOkToAcceptConnectionCase( mCurrentDevice, badBondState, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, + CONNECTION_POLICY_UNKNOWN, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase( - mCurrentDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + mCurrentDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false); testOkToAcceptConnectionCase( mCurrentDevice, badBondState, - BluetoothProfile.CONNECTION_POLICY_ALLOWED, + CONNECTION_POLICY_ALLOWED, Flags.donotValidateBondStateFromProfiles()); testOkToAcceptConnectionCase(mCurrentDevice, badBondState, badPriorityValue, false); } @@ -283,7 +273,7 @@ public class HeadsetServiceTest { public void testConnectDevice_connectDeviceBelowLimit() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) @@ -297,14 +287,10 @@ public class HeadsetServiceTest { verify(mStateMachines.get(mCurrentDevice)) .sendMessage(HeadsetStateMachine.CONNECT, mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTING); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTING); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice)); // 2nd connection attempt will fail assertThat(mHeadsetService.connect(mCurrentDevice)).isFalse(); @@ -340,10 +326,8 @@ public class HeadsetServiceTest { verify(mStateMachines.get(mCurrentDevice)) .sendMessage(HeadsetStateMachine.STACK_EVENT, connectedEvent); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice)); // Test disconnect from native HeadsetStackEvent disconnectEvent = @@ -355,9 +339,9 @@ public class HeadsetServiceTest { verify(mStateMachines.get(mCurrentDevice)) .sendMessage(HeadsetStateMachine.STACK_EVENT, disconnectEvent); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + .thenReturn(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectedDevices()).isEmpty(); } @@ -413,7 +397,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); @@ -439,16 +423,16 @@ public class HeadsetServiceTest { .sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class)); // Put device to connecting when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + .thenReturn(STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); } @@ -465,7 +449,7 @@ public class HeadsetServiceTest { eq(mNativeInterface), eq(mSystemInterface)); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); } @@ -479,7 +463,7 @@ public class HeadsetServiceTest { public void testConnectAudio_withOneDevice() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) @@ -493,17 +477,13 @@ public class HeadsetServiceTest { verify(mStateMachines.get(mCurrentDevice)) .sendMessage(HeadsetStateMachine.CONNECT, mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice)); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED); // Test connect audio - set the device first as the active device assertThat(mHeadsetService.setActiveDevice(mCurrentDevice)).isTrue(); assertThat(mHeadsetService.connectAudio(mCurrentDevice)) @@ -541,7 +521,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); @@ -567,26 +547,22 @@ public class HeadsetServiceTest { .sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class)); // Put device to connecting when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + .thenReturn(STATE_CONNECTING); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Try to connect audio @@ -637,7 +613,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); @@ -663,26 +639,22 @@ public class HeadsetServiceTest { .sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class)); // Put device to connecting when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + .thenReturn(STATE_CONNECTING); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); } @@ -727,7 +699,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); doAnswer( invocation -> { BluetoothDevice[] devicesArray = @@ -763,28 +735,24 @@ public class HeadsetServiceTest { when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + .thenReturn(STATE_CONNECTING); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED); } // Try to connect audio BluetoothDevice firstDevice = connectedDevices.get(0); @@ -813,7 +781,7 @@ public class HeadsetServiceTest { public void testConnectAudio_deviceDisconnected() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) @@ -829,14 +797,12 @@ public class HeadsetServiceTest { when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); // Put device in disconnected state when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_DISCONNECTED); + .thenReturn(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectedDevices()).isEmpty(); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTED); + mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED); // connectAudio should fail assertThat(mHeadsetService.connectAudio(mCurrentDevice)) .isEqualTo(BluetoothStatusCodes.ERROR_NOT_ACTIVE_DEVICE); @@ -884,7 +850,7 @@ public class HeadsetServiceTest { 0, 0, HeadsetHalConstants.CALL_STATE_IDLE, TEST_PHONE_NUMBER, 128, ""); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); final ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); // Connect one device @@ -903,29 +869,22 @@ public class HeadsetServiceTest { // Put device to connecting when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTING); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED); // Change phone state mHeadsetService.phoneStateChanged( headsetCallState.mNumActive, @@ -985,7 +944,7 @@ public class HeadsetServiceTest { final ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); @@ -1013,28 +972,24 @@ public class HeadsetServiceTest { when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); + .thenReturn(STATE_CONNECTING); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); // Put device to connected connectedDevices.add(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED); assertThat(mHeadsetService.setActiveDevice(mCurrentDevice)).isTrue(); } // Change phone state @@ -1064,7 +1019,7 @@ public class HeadsetServiceTest { public void testClccResponse_withOneDevice() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); verify(mObjectsFactory) @@ -1076,10 +1031,8 @@ public class HeadsetServiceTest { mNativeInterface, mSystemInterface); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); - assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED); mHeadsetService.clccResponse(1, 0, 0, 0, false, "8225319000", 0); // index 0 is the end mark of CLCC response. mHeadsetService.clccResponse(0, 0, 0, 0, false, "8225319000", 0); @@ -1097,7 +1050,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 2; i >= 0; i--) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); @@ -1111,7 +1064,7 @@ public class HeadsetServiceTest { mSystemInterface); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); connectedDevices.add(mCurrentDevice); // index 0 is the end mark of CLCC response. mHeadsetService.clccResponse(i, 0, 0, 0, false, "8225319000", 0); @@ -1129,13 +1082,13 @@ public class HeadsetServiceTest { public void testSetSilenceMode() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 0; i < 2; i++) { mCurrentDevice = getTestDevice(i); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + .thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).setSilenceDevice(anyBoolean())) .thenReturn(true); } @@ -1168,14 +1121,13 @@ public class HeadsetServiceTest { public void testSetActiveDevice_AudioNotAllowed() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); mHeadsetService.setForceScoAudio(false); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); assertThat(mHeadsetService.setActiveDevice(null)).isTrue(); when(mSystemInterface.isInCall()).thenReturn(true); @@ -1260,19 +1212,16 @@ public class HeadsetServiceTest { public void testConnectDeviceNotAllowedInbandRingPolicy_InbandRingStatus() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue(); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs()) .thenReturn(SystemClock.uptimeMillis()); assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice)); mHeadsetService.onConnectionStateChangedFromStateMachine( - mCurrentDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED); + mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED); mHeadsetService.setActiveDevice(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getHfpCallAudioPolicy()) @@ -1302,13 +1251,12 @@ public class HeadsetServiceTest { public void testIncomingCallDeviceConnect_InbandRingStatus() { when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); mCurrentDevice = getTestDevice(0); connectDeviceHelper(mCurrentDevice); when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); when(mSystemInterface.isRinging()).thenReturn(true); mHeadsetService.setActiveDevice(mCurrentDevice); @@ -1326,7 +1274,7 @@ public class HeadsetServiceTest { ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>(); when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); for (int i = 2; i >= 0; i--) { mCurrentDevice = getTestDevice(i); connectDeviceHelper(mCurrentDevice); @@ -1349,17 +1297,13 @@ public class HeadsetServiceTest { mCurrentDevice = device; when(mDatabaseManager.getProfileConnectionPolicy( any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); assertThat(mHeadsetService.connect(device)).isTrue(); when(mStateMachines.get(device).getDevice()).thenReturn(device); - when(mStateMachines.get(device).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTING); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); - when(mStateMachines.get(mCurrentDevice).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); - assertThat(mHeadsetService.getConnectionState(device)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(device).getConnectionState()).thenReturn(STATE_CONNECTING); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING); + when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED); + assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetService.getConnectedDevices()).contains(device); } @@ -1390,7 +1334,6 @@ public class HeadsetServiceTest { mNativeInterface, mSystemInterface); when(mStateMachines.get(device).getDevice()).thenReturn(device); - when(mStateMachines.get(device).getConnectionState()) - .thenReturn(BluetoothProfile.STATE_CONNECTED); + when(mStateMachines.get(device).getConnectionState()).thenReturn(STATE_CONNECTED); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java index 7f23f6683e..0e124efc3c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java @@ -18,6 +18,11 @@ package com.android.bluetooth.hfp; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.media.audio.Flags.FLAG_DEPRECATE_STREAM_BT_SCO; import static com.android.bluetooth.TestUtils.MockitoRule; @@ -29,7 +34,6 @@ import static org.mockito.Mockito.*; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothStatusCodes; import android.content.ContentResolver; import android.content.Intent; @@ -69,6 +73,8 @@ import com.android.bluetooth.btservice.SilenceDeviceManager; import com.android.bluetooth.btservice.storage.DatabaseManager; import com.android.bluetooth.flags.Flags; +import com.google.common.util.concurrent.Uninterruptibles; + import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -150,7 +156,7 @@ public class HeadsetStateMachineTest { .getContext() .getPackageManager()); when(mHeadsetService.getConnectionPolicy(any(BluetoothDevice.class))) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); when(mHeadsetService.getForceScoAudio()).thenReturn(true); when(mHeadsetService.okToAcceptConnection(any(BluetoothDevice.class), anyBoolean())) .thenReturn(true); @@ -176,6 +182,7 @@ public class HeadsetStateMachineTest { public void tearDown() throws Exception { HeadsetObjectsFactory.getInstance().destroyStateMachine(mHeadsetStateMachine); mHandlerThread.quit(); + Uninterruptibles.joinUninterruptibly(mHandlerThread); InstrumentationRegistry.getInstrumentation() .getUiAutomation() .dropShellPermissionIdentity(); @@ -184,8 +191,7 @@ public class HeadsetStateMachineTest { /** Test that default state is Disconnected */ @Test public void testDefaultDisconnectedState() { - assertThat(mHeadsetStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mHeadsetStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -194,8 +200,7 @@ public class HeadsetStateMachineTest { @Test public void testSetupConnectedState() { setUpConnectedState(); - assertThat(mHeadsetStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mHeadsetStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connected.class); } @@ -211,10 +216,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTING, STATE_DISCONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connecting.class); } @@ -237,10 +239,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTING, STATE_DISCONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connecting.class); } @@ -263,10 +262,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTING, STATE_DISCONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connecting.class); } @@ -308,10 +304,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTED, STATE_CONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -329,10 +322,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTED, STATE_CONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -386,10 +376,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTED, STATE_CONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connected.class); } @@ -416,10 +403,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTED, STATE_DISCONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -439,10 +423,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_DISCONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTED, STATE_DISCONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -469,10 +450,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_DISCONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTED, STATE_DISCONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connected.class); } @@ -491,10 +469,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTING, STATE_CONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); } @@ -521,10 +496,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTING, STATE_CONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); } @@ -551,10 +523,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTED, STATE_CONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); } @@ -739,8 +708,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTED, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); @@ -774,8 +743,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTING, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); @@ -909,8 +878,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTED, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); @@ -941,8 +910,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTING, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); @@ -1092,8 +1061,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTING, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); @@ -1127,8 +1096,8 @@ public class HeadsetStateMachineTest { mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 2)); HeadsetTestUtils.verifyConnectionStateBroadcast( mDevice, - BluetoothProfile.STATE_DISCONNECTED, - BluetoothProfile.STATE_CONNECTED, + STATE_DISCONNECTED, + STATE_CONNECTED, mIntentArgument.getAllValues().get(mIntentArgument.getAllValues().size() - 1)); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnected.class); @@ -2098,10 +2067,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTING, STATE_DISCONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connecting.class); return 1; @@ -2127,10 +2093,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_DISCONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTING, STATE_DISCONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connecting.class); mHeadsetStateMachine.sendMessage( @@ -2146,10 +2109,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_CONNECTED, - BluetoothProfile.STATE_CONNECTING, - mIntentArgument.getValue()); + mDevice, STATE_CONNECTED, STATE_CONNECTING, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Connected.class); return 2; @@ -2229,10 +2189,7 @@ public class HeadsetStateMachineTest { eq(BLUETOOTH_CONNECT), any(Bundle.class)); HeadsetTestUtils.verifyConnectionStateBroadcast( - mDevice, - BluetoothProfile.STATE_DISCONNECTING, - BluetoothProfile.STATE_CONNECTED, - mIntentArgument.getValue()); + mDevice, STATE_DISCONNECTING, STATE_CONNECTED, mIntentArgument.getValue()); assertThat(mHeadsetStateMachine.getCurrentState()) .isInstanceOf(HeadsetStateMachine.Disconnecting.class); return numBroadcastsSent; diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java index 5ae51566b7..e96fc3a9a6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.hfpclient; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; @@ -72,7 +74,7 @@ public class HeadsetClientServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -87,7 +89,7 @@ public class HeadsetClientServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java index 43659c2422..cf9aaecf49 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java @@ -946,7 +946,7 @@ public class HeadsetClientStateMachineTest { assertThat(currentCalls.get(0)).isEqualTo(call); } - private void assertName(int message, String message_name) { + private static void assertName(int message, String message_name) { assertThat(HeadsetClientStateMachine.getMessageName(message)).isEqualTo(message_name); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java index 6bd0681322..d622a00666 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java @@ -36,7 +36,7 @@ public class HfpClientCallTest { private final BluetoothDevice mDevice = getTestDevice(32); - private void assertCall( + private static void assertCall( BluetoothDevice device, int id, int state, diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java index 455d2d2b76..d6cffe4f20 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java @@ -16,6 +16,10 @@ package com.android.bluetooth.hfpclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -30,7 +34,6 @@ import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.content.ComponentName; import android.content.Context; import android.content.res.Resources; @@ -146,7 +149,7 @@ public class HfpClientConnectionServiceTest { private void setupDeviceConnection(BluetoothDevice device) throws Exception { mHfpClientConnectionService.onConnectionStateChanged( - device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING); + device, STATE_CONNECTED, STATE_CONNECTING); HfpClientDeviceBlock block = mHfpClientConnectionService.findBlockForDevice(mDevice); assertThat(block).isNotNull(); assertThat(block.getDevice()).isEqualTo(mDevice); @@ -172,7 +175,7 @@ public class HfpClientConnectionServiceTest { createService(); setupDeviceConnection(mDevice); HfpClientConnectionService.onConnectionStateChanged( - mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED); + mDevice, STATE_DISCONNECTED, STATE_CONNECTED); assertThat(mHfpClientConnectionService.findBlockForDevice(mDevice)).isNull(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java index 52c220d86b..4b11bc7b2a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.hid; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -27,7 +30,6 @@ import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHidDeviceAppQosSettings; import android.bluetooth.BluetoothHidDeviceAppSdpSettings; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothHidDeviceCallback; import android.content.AttributionSource; @@ -138,7 +140,7 @@ public class BluetoothHidDeviceBinderTest { @Test public void setConnectionPolicy() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); } @@ -164,7 +166,7 @@ public class BluetoothHidDeviceBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mService).getDevicesMatchingConnectionStates(states); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java index 74f80c6fdb..946d9a7c93 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.hid; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.platform.test.flag.junit.SetFlagsRule; import androidx.test.filters.SmallTest; @@ -69,13 +71,12 @@ public class HidHostServiceBinderTest { public void getConnectedDevices_callsServiceMethod() { mBinder.getConnectedDevices(null); - verify(mService) - .getDevicesMatchingConnectionStates(new int[] {BluetoothProfile.STATE_CONNECTED}); + verify(mService).getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}); } @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -90,7 +91,7 @@ public class HidHostServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java index 923a9cb7bc..e0093fc003 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.le_audio; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -27,7 +30,6 @@ import android.bluetooth.BluetoothLeAudioCodecConfig; import android.bluetooth.BluetoothLeAudioContentMetadata; import android.bluetooth.BluetoothLeBroadcastSettings; import android.bluetooth.BluetoothLeBroadcastSubgroupSettings; -import android.bluetooth.BluetoothProfile; import android.bluetooth.IBluetoothLeAudioCallback; import android.bluetooth.IBluetoothLeBroadcastCallback; import android.content.AttributionSource; @@ -95,7 +97,7 @@ public class LeAudioBinderTest { @Test public void getDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_DISCONNECTED}; + int[] states = new int[] {STATE_DISCONNECTED}; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.getDevicesMatchingConnectionStates(states, source); @@ -148,7 +150,7 @@ public class LeAudioBinderTest { @Test public void setConnectionPolicy() { BluetoothDevice device = getTestDevice(0); - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + int connectionPolicy = CONNECTION_POLICY_UNKNOWN; AttributionSource source = new AttributionSource.Builder(0).build(); mBinder.setConnectionPolicy(device, connectionPolicy, source); @@ -339,7 +341,7 @@ public class LeAudioBinderTest { verify(mService).setCodecConfigPreference(groupId, inputConfig, outputConfig); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata() { + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata() { BluetoothLeAudioContentMetadata metadata = new BluetoothLeAudioContentMetadata.Builder().build(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java index 3f5a55bcca..c89dd20667 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java @@ -642,7 +642,7 @@ public class LeAudioBroadcastServiceTest { verify(mCallbacks).onBroadcastUpdateFailed(anyInt(), anyInt()); } - private BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { + private static BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { BluetoothLeAudioCodecConfigMetadata codecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT) @@ -1685,7 +1685,7 @@ public class LeAudioBroadcastServiceTest { } } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode, int numOfGroups) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java index 3252bdec45..97905daf65 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java @@ -19,6 +19,8 @@ package com.android.bluetooth.le_audio; import static android.bluetooth.BluetoothDevice.BOND_BONDED; import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.EXTRA_PREVIOUS_STATE; import static android.bluetooth.BluetoothProfile.EXTRA_STATE; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; @@ -290,7 +292,7 @@ public class LeAudioServiceTest { // Make sure the device is known to the service and is not forbidden to connect mService.createDeviceDescriptor(mSingleDevice, true); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); // Verify the device is enabled in the service when policy is not FORBIDDEN during BT Enable mService.handleBluetoothEnabled(); @@ -300,7 +302,7 @@ public class LeAudioServiceTest { when(mDatabaseManager.setProfileConnectionPolicy( eq(mSingleDevice), eq(BluetoothProfile.LE_AUDIO), anyInt())) .thenReturn(true); - mService.setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN); verify(mNativeInterface).setEnableState(eq(mSingleDevice), eq(false)); } @@ -315,15 +317,15 @@ public class LeAudioServiceTest { @Test public void testGetSetPriority() { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); assertWithMessage("Initial device priority") - .that(BluetoothProfile.CONNECTION_POLICY_UNKNOWN) + .that(CONNECTION_POLICY_UNKNOWN) .isEqualTo(mService.getConnectionPolicy(mLeftDevice)); when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); assertWithMessage("Setting device priority to PRIORITY_OFF") - .that(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) + .that(CONNECTION_POLICY_FORBIDDEN) .isEqualTo(mService.getConnectionPolicy(mLeftDevice)); when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) @@ -355,41 +357,25 @@ public class LeAudioServiceTest { int badPriorityValue = 1024; int badBondState = 42; testOkToConnectCase( - mSingleDevice, - BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - false); + mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_UNKNOWN, false); testOkToConnectCase( - mSingleDevice, - BluetoothDevice.BOND_NONE, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase( mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_ALLOWED, false); testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false); testOkToConnectCase( - mSingleDevice, - BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_UNKNOWN, - false); + mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_UNKNOWN, false); testOkToConnectCase( - mSingleDevice, - BluetoothDevice.BOND_BONDING, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - false); + mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase( mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_ALLOWED, false); testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false); - testOkToConnectCase( - mSingleDevice, BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true); - testOkToConnectCase( - mSingleDevice, BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true); + testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_ALLOWED, true); testOkToConnectCase(mSingleDevice, BOND_BONDED, badPriorityValue, false); - testOkToConnectCase( - mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false); - testOkToConnectCase( - mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false); + testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_UNKNOWN, false); + testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false); testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_ALLOWED, false); testOkToConnectCase(mSingleDevice, badBondState, badPriorityValue, false); } @@ -401,9 +387,9 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Return No UUID doReturn(new ParcelUuid[] {}) @@ -419,7 +405,7 @@ public class LeAudioServiceTest { public void testOutgoingConnectPriorityOff() { // Set the device priority to PRIORITY_OFF so connect() should fail when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Send a connect request assertWithMessage("Connect expected to fail").that(mService.connect(mLeftDevice)).isFalse(); @@ -432,9 +418,9 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Send a connect request assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); @@ -509,7 +495,7 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Send a connect request assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); @@ -595,9 +581,9 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Create device descriptor with connect request assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); @@ -650,9 +636,9 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Create device descriptor with connect request assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); @@ -705,9 +691,9 @@ public class LeAudioServiceTest { when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO)) .thenReturn(CONNECTION_POLICY_ALLOWED); when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); // Create device descriptor with connect request assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue(); @@ -827,7 +813,7 @@ public class LeAudioServiceTest { when(mHapClientService.setConnectionPolicy(any(), anyInt())).thenReturn(true); when(mBassClientService.setConnectionPolicy(any(), anyInt())).thenReturn(true); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_ALLOWED)).isTrue(); @@ -857,22 +843,18 @@ public class LeAudioServiceTest { assertThat(mService.getConnectionState(mSingleDevice)).isEqualTo(STATE_CONNECTED); // Set connection policy to forbidden - assertThat( - mService.setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); // Verify connection policy for CSIP and VCP are also set verify(mVolumeControlService) - .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN); verify(mCsipSetCoordinatorService) - .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - verify(mHapClientService) - .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN); + verify(mHapClientService).setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN); if (BluetoothProperties.isProfileBapBroadcastAssistEnabled().orElse(false)) { verify(mBassClientService) - .setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN); } // Verify the connection state broadcast, and that we are in Connecting state verifyConnectionStateIntent(mSingleDevice, STATE_DISCONNECTING, STATE_CONNECTED); @@ -899,7 +881,7 @@ public class LeAudioServiceTest { List<BluetoothDevice> prevConnectedDevices = mService.getConnectedDevices(); when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); // Send a connect request assertWithMessage("Connect failed").that(mService.connect(device)).isTrue(); @@ -1286,7 +1268,7 @@ public class LeAudioServiceTest { verify(mTbsService, times(0)).clearInbandRingtoneSupport(mSingleDevice); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode, int numOfGroups) { @@ -1630,14 +1612,10 @@ public class LeAudioServiceTest { verify(mDatabaseManager) .setProfileConnectionPolicy( - mLeftDevice, - BluetoothProfile.LE_AUDIO, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mLeftDevice, BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_FORBIDDEN); verify(mDatabaseManager) .setProfileConnectionPolicy( - mRightDevice, - BluetoothProfile.LE_AUDIO, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + mRightDevice, BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_FORBIDDEN); } private void sendEventAndVerifyIntentForGroupStatusChanged(int groupId, int groupStatus) { @@ -2230,8 +2208,6 @@ public class LeAudioServiceTest { /** Test volume setting for broadcast sink devices */ @Test public void testSetVolumeForBroadcastSinks() { - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_VOLUME_CONTROL_WITH_SET_VOLUME); - int groupId = 1; int groupId2 = 2; int volume = 100; @@ -2438,7 +2414,7 @@ public class LeAudioServiceTest { .when(mDatabaseManager) .setProfileConnectionPolicy(any(BluetoothDevice.class), anyInt(), anyInt()); when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); // Ensures GATT server services are not authorized when the device does not have a group assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_ALLOWED)).isTrue(); @@ -2451,9 +2427,7 @@ public class LeAudioServiceTest { verify(mTbsService).setDeviceAuthorized(mSingleDevice, true); // Ensure that disconnecting unauthorizes GATT server services - assertThat( - mService.setConnectionPolicy( - mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); verify(mMcpService).setDeviceAuthorized(mSingleDevice, false); verify(mTbsService).setDeviceAuthorized(mSingleDevice, false); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java index b58868cff8..b3aa96fcfb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java @@ -17,6 +17,10 @@ package com.android.bluetooth.le_audio; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.le_audio.LeAudioStateMachine.CONNECT; @@ -34,7 +38,6 @@ import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.Bundle; import android.os.HandlerThread; @@ -97,8 +100,7 @@ public class LeAudioStateMachineTest { /** Test that default state is disconnected */ @Test public void testDefaultDisconnectedState() { - assertThat(mLeAudioStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mLeAudioStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } /** @@ -144,8 +146,7 @@ public class LeAudioStateMachineTest { // Verify that one connection state change is notifyed verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_CONNECTING), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTING), anyInt()); // Check that we are in Connecting state assertThat(mLeAudioStateMachine.getCurrentState()) @@ -161,11 +162,9 @@ public class LeAudioStateMachineTest { // Verify that the expected number of notification are called: // - two calls to notifyConnectionStateChanged(): Disconnected -> Connecting -> Connected verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_CONNECTING), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTING), anyInt()); verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_CONNECTED), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTED), anyInt()); // Check that we are in Connected state assertThat(mLeAudioStateMachine.getCurrentState()) .isInstanceOf(LeAudioStateMachine.Connected.class); @@ -183,8 +182,7 @@ public class LeAudioStateMachineTest { // Verify that one connection state change is notified verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_CONNECTING), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTING), anyInt()); // Check that we are in Connecting state assertThat(mLeAudioStateMachine.getCurrentState()) @@ -192,8 +190,7 @@ public class LeAudioStateMachineTest { // Verify that one connection state change is notified verify(mLeAudioService, timeout(LeAudioStateMachine.sConnectTimeoutMs * 2L)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_DISCONNECTED), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_DISCONNECTED), anyInt()); // Check that we are in Disconnected state assertThat(mLeAudioStateMachine.getCurrentState()) @@ -216,8 +213,7 @@ public class LeAudioStateMachineTest { // Verify that one connection state change is notified verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_CONNECTING), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTING), anyInt()); // Check that we are in Connecting state assertThat(mLeAudioStateMachine.getCurrentState()) @@ -225,8 +221,7 @@ public class LeAudioStateMachineTest { // Verify that one connection state change is notified verify(mLeAudioService, timeout(LeAudioStateMachine.sConnectTimeoutMs * 2L)) - .notifyConnectionStateChanged( - any(), eq(BluetoothProfile.STATE_DISCONNECTED), anyInt()); + .notifyConnectionStateChanged(any(), eq(STATE_DISCONNECTED), anyInt()); // Check that we are in Disconnected state assertThat(mLeAudioStateMachine.getCurrentState()) @@ -248,10 +243,7 @@ public class LeAudioStateMachineTest { sendAndDispatchMessage(CONNECT, mDevice); // Verify that one connection state change is notified verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .notifyConnectionStateChanged(any(), eq(STATE_CONNECTING), eq(STATE_DISCONNECTED)); assertThat(mLeAudioStateMachine.getCurrentState()) .isInstanceOf(LeAudioStateMachine.Connecting.class); @@ -261,10 +253,7 @@ public class LeAudioStateMachineTest { sendAndDispatchMessage(DISCONNECT, mDevice); // Verify that one connection state change is notified verify(mLeAudioService, timeout(TIMEOUT_MS)) - .notifyConnectionStateChanged( - any(), - eq(BluetoothProfile.STATE_DISCONNECTED), - eq(BluetoothProfile.STATE_CONNECTING)); + .notifyConnectionStateChanged(any(), eq(STATE_DISCONNECTED), eq(STATE_CONNECTING)); assertThat(mLeAudioStateMachine.getCurrentState()) .isInstanceOf(LeAudioStateMachine.Disconnected.class); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java index c56769fa96..aec90ecf29 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfoTest.java @@ -16,66 +16,69 @@ package com.android.bluetooth.le_scan; -import static com.google.common.truth.Truth.assertThat; - import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; +import com.google.common.truth.Expect; +import com.google.protobuf.ByteString; + +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -/** Test cases for {@link AdvtFilterOnFoundOnLostInfoTest}. */ +/** Test cases for {@link AdvtFilterOnFoundOnLostInfo}. */ @SmallTest @RunWith(AndroidJUnit4.class) public class AdvtFilterOnFoundOnLostInfoTest { + @Rule public Expect expect = Expect.create(); + @Test public void advtFilterOnFoundOnLostInfoParams() { int clientIf = 0; - int advPktLen = 1; - byte[] advPkt = new byte[] {0x02}; - int scanRspLen = 3; - byte[] scanRsp = new byte[] {0x04}; + int advPacketLen = 1; + ByteString advPacket = ByteString.copyFrom(new byte[] {0x02}); + int scanResponseLen = 3; + ByteString scanResponse = ByteString.copyFrom(new byte[] {0x04}); int filtIndex = 5; int advState = 6; int advInfoPresent = 7; String address = "00:11:22:33:FF:EE"; - int addrType = 8; + int addressType = 8; int txPower = 9; int rssiValue = 10; int timeStamp = 11; + byte[] resultByteArray = new byte[] {2, 4}; AdvtFilterOnFoundOnLostInfo advtFilterOnFoundOnLostInfo = new AdvtFilterOnFoundOnLostInfo( clientIf, - advPktLen, - advPkt, - scanRspLen, - scanRsp, + advPacketLen, + advPacket, + scanResponseLen, + scanResponse, filtIndex, advState, advInfoPresent, address, - addrType, + addressType, txPower, rssiValue, timeStamp); - assertThat(advtFilterOnFoundOnLostInfo.getClientIf()).isEqualTo(clientIf); - assertThat(advtFilterOnFoundOnLostInfo.getFiltIndex()).isEqualTo(filtIndex); - assertThat(advtFilterOnFoundOnLostInfo.getAdvState()).isEqualTo(advState); - assertThat(advtFilterOnFoundOnLostInfo.getTxPower()).isEqualTo(txPower); - assertThat(advtFilterOnFoundOnLostInfo.getTimeStamp()).isEqualTo(timeStamp); - assertThat(advtFilterOnFoundOnLostInfo.getRSSIValue()).isEqualTo(rssiValue); - assertThat(advtFilterOnFoundOnLostInfo.getAdvInfoPresent()).isEqualTo(advInfoPresent); - assertThat(advtFilterOnFoundOnLostInfo.getAddress()).isEqualTo(address); - assertThat(advtFilterOnFoundOnLostInfo.getAddressType()).isEqualTo(addrType); - assertThat(advtFilterOnFoundOnLostInfo.getAdvPacketData()).isEqualTo(advPkt); - assertThat(advtFilterOnFoundOnLostInfo.getAdvPacketLen()).isEqualTo(advPktLen); - assertThat(advtFilterOnFoundOnLostInfo.getScanRspData()).isEqualTo(scanRsp); - assertThat(advtFilterOnFoundOnLostInfo.getScanRspLen()).isEqualTo(scanRspLen); - - byte[] resultByteArray = new byte[] {2, 4}; - assertThat(advtFilterOnFoundOnLostInfo.getResult()).isEqualTo(resultByteArray); + expect.that(advtFilterOnFoundOnLostInfo.clientIf()).isEqualTo(clientIf); + expect.that(advtFilterOnFoundOnLostInfo.advPacketLen()).isEqualTo(advPacketLen); + expect.that(advtFilterOnFoundOnLostInfo.advPacket()).isEqualTo(advPacket); + expect.that(advtFilterOnFoundOnLostInfo.scanResponseLen()).isEqualTo(scanResponseLen); + expect.that(advtFilterOnFoundOnLostInfo.scanResponse()).isEqualTo(scanResponse); + expect.that(advtFilterOnFoundOnLostInfo.filtIndex()).isEqualTo(filtIndex); + expect.that(advtFilterOnFoundOnLostInfo.advState()).isEqualTo(advState); + expect.that(advtFilterOnFoundOnLostInfo.advInfoPresent()).isEqualTo(advInfoPresent); + expect.that(advtFilterOnFoundOnLostInfo.address()).isEqualTo(address); + expect.that(advtFilterOnFoundOnLostInfo.addressType()).isEqualTo(addressType); + expect.that(advtFilterOnFoundOnLostInfo.txPower()).isEqualTo(txPower); + expect.that(advtFilterOnFoundOnLostInfo.rssiValue()).isEqualTo(rssiValue); + expect.that(advtFilterOnFoundOnLostInfo.timeStamp()).isEqualTo(timeStamp); + expect.that(advtFilterOnFoundOnLostInfo.getResult()).isEqualTo(resultByteArray); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java index 5e8f59fef5..2beee25a7e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java @@ -164,7 +164,8 @@ public class BatchScanThrottlerTest { .isEqualTo(backoffIntervals[backoffIntervals.length - 1]); } - private long adjustExpectedInterval(long interval, boolean isFiltered, boolean isScreenOn) { + private static long adjustExpectedInterval( + long interval, boolean isFiltered, boolean isScreenOn) { if (isFiltered) { return interval; } @@ -175,13 +176,13 @@ public class BatchScanThrottlerTest { return Math.max(interval, threshold); } - private long[] getBackoffIntervals(long baseInterval) { + private static long[] getBackoffIntervals(long baseInterval) { return LongStream.range(0, BatchScanThrottler.BACKOFF_MULTIPLIERS.length) .map(x -> BatchScanThrottler.BACKOFF_MULTIPLIERS[(int) x] * baseInterval) .toArray(); } - private ScanClient createBatchScanClient(long reportDelayMillis, boolean isFiltered) { + private static ScanClient createBatchScanClient(long reportDelayMillis, boolean isFiltered) { ScanSettings scanSettings = new ScanSettings.Builder() .setScanMode(SCAN_MODE_BALANCED) @@ -191,7 +192,7 @@ public class BatchScanThrottlerTest { return new ScanClient(1, scanSettings, createScanFilterList(isFiltered), 1); } - private List<ScanFilter> createScanFilterList(boolean isFiltered) { + private static List<ScanFilter> createScanFilterList(boolean isFiltered) { List<ScanFilter> scanFilterList = null; if (isFiltered) { scanFilterList = List.of(new ScanFilter.Builder().setDeviceName("TestName").build()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java index b7bbf9e2a7..6e396df67e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java @@ -44,7 +44,7 @@ public final class MsftAdvMonitorTest { private static final byte[] FAST_PAIR_SERVICE_DATA = new byte[] {(byte) 0xfc, (byte) 0x12, (byte) 0x8e}; - private void assertMonitorConstants(MsftAdvMonitor monitor) { + private static void assertMonitorConstants(MsftAdvMonitor monitor) { MsftAdvMonitor.Monitor mMonitor = monitor.getMonitor(); assertThat(mMonitor.rssi_threshold_high).isEqualTo(RSSI_THRESHOLD_HIGH); assertThat(mMonitor.rssi_threshold_low).isEqualTo(RSSI_THRESHOLD_LOW); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java index d25f67b2d8..5765b8357e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.le_scan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -59,6 +62,7 @@ import com.android.bluetooth.btservice.CompanionManager; import com.android.bluetooth.gatt.GattNativeInterface; import com.android.bluetooth.gatt.GattObjectsFactory; +import com.google.protobuf.ByteString; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; @@ -191,7 +195,7 @@ public class ScanControllerTest { new ArgumentMatcher<ScanClient>() { @Override public boolean matches(ScanClient client) { - return mPiInfo.callingUid == client.appUid; + return mPiInfo.callingUid == client.mAppUid; } })); } @@ -210,14 +214,13 @@ public class ScanControllerTest { Set<ScanClient> scanClientSet = new HashSet<>(); ScanClient scanClient = new ScanClient(scannerId); - scanClient.associatedDevices = new ArrayList<>(); - scanClient.scannerId = scannerId; + scanClient.mAssociatedDevices = new ArrayList<>(); if (expectResults) { - scanClient.hasScanWithoutLocationPermission = true; + scanClient.mHasScanWithoutLocationPermission = true; } scanClientSet.add(scanClient); doReturn(scanClientSet).when(mScanManager).getFullBatchScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); IScannerCallback callback = mock(IScannerCallback.class); mApp.mCallback = callback; @@ -245,14 +248,13 @@ public class ScanControllerTest { Set<ScanClient> scanClientSet = new HashSet<>(); ScanClient scanClient = new ScanClient(scannerId); - scanClient.associatedDevices = new ArrayList<>(); + scanClient.mAssociatedDevices = new ArrayList<>(); if (expectResults) { - scanClient.associatedDevices.add("02:00:00:00:00:00"); + scanClient.mAssociatedDevices.add("02:00:00:00:00:00"); } - scanClient.scannerId = scannerId; scanClientSet.add(scanClient); doReturn(scanClientSet).when(mScanManager).getBatchScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); IScannerCallback callback = mock(IScannerCallback.class); mApp.mCallback = callback; @@ -330,9 +332,8 @@ public class ScanControllerTest { byte[] advData = new byte[0]; ScanClient scanClient = new ScanClient(scannerId); - scanClient.scannerId = scannerId; - scanClient.hasNetworkSettingsPermission = true; - scanClient.settings = + scanClient.mHasNetworkSettingsPermission = true; + scanClient.mSettings = new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .setLegacy(false) @@ -343,13 +344,13 @@ public class ScanControllerTest { mApp.mCallback = callback; mApp.mAppScanStats = appScanStats; - scanClient.stats = appScanStats; + scanClient.mStats = appScanStats; Set<ScanClient> scanClientSet = Collections.singleton(scanClient); doReturn(address).when(mAdapterService).getIdentityAddress(anyString()); doReturn(scanClientSet).when(mScanManager).getRegularScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); - doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); + doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scanClient.mScannerId); // Simulate remote client crash doThrow(new RemoteException()).when(callback).onScanResult(any()); @@ -367,7 +368,7 @@ public class ScanControllerTest { advData, address); - assertThat(scanClient.appDied).isTrue(); + assertThat(scanClient.mAppDied).isTrue(); verify(appScanStats).recordScanStop(scannerId); } @@ -413,23 +414,19 @@ public class ScanControllerTest { @Test public void profileConnectionStateChanged_notifyScanManager() { mScanController.notifyProfileConnectionStateChange( - BluetoothProfile.A2DP, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.A2DP, STATE_CONNECTING, STATE_CONNECTED); verify(mScanManager) .handleBluetoothProfileConnectionStateChanged( - BluetoothProfile.A2DP, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.A2DP, STATE_CONNECTING, STATE_CONNECTED); } @Test public void onTrackAdvFoundLost() throws Exception { int scannerId = 1; - int advPktLen = 1; - byte[] advPkt = new byte[] {0x02}; - int scanRspLen = 3; - byte[] scanRsp = new byte[] {0x04}; + int advPacketLen = 1; + byte[] advPacket = new byte[] {0x02}; + int scanResponseLen = 3; + byte[] scanResponse = new byte[] {0x04}; int filtIndex = 5; int advState = ScanController.ADVT_STATE_ONFOUND; @@ -441,8 +438,8 @@ public class ScanControllerTest { int timeStamp = 11; ScanClient scanClient = new ScanClient(scannerId); - scanClient.hasNetworkSettingsPermission = true; - scanClient.settings = + scanClient.mHasNetworkSettingsPermission = true; + scanClient.mSettings = new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH) .setLegacy(false) @@ -461,10 +458,10 @@ public class ScanControllerTest { AdvtFilterOnFoundOnLostInfo advtFilterOnFoundOnLostInfo = new AdvtFilterOnFoundOnLostInfo( scannerId, - advPktLen, - advPkt, - scanRspLen, - scanRsp, + advPacketLen, + ByteString.copyFrom(advPacket), + scanResponseLen, + ByteString.copyFrom(scanResponse), filtIndex, advState, advInfoPresent, diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java index 08952664e7..3359c2b48a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java @@ -240,7 +240,8 @@ public class ScanFilterQueueTest { testServiceDataFilter(filter, true); } - private void testServiceDataFilter(ScanFilter filter, boolean partialServiceDataMatchResult) { + private static void testServiceDataFilter( + ScanFilter filter, boolean partialServiceDataMatchResult) { ScanFilterQueue queue = new ScanFilterQueue(); queue.addScanFilter(filter); ScanFilterQueue.Entry entry = queue.pop(); @@ -288,7 +289,7 @@ public class ScanFilterQueueTest { .isEqualTo(partialServiceDataMatchResult); } - private boolean serviceDataMatches(byte[] filterData, byte[] resultData, byte[] mask) { + private static boolean serviceDataMatches(byte[] filterData, byte[] resultData, byte[] mask) { if (filterData.length > resultData.length || filterData.length != mask.length) { return false; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java index 78e0475a0c..d19e0c7251 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java @@ -304,8 +304,8 @@ public class ScanManagerTest { mClientId = mClientId + 1; ScanClient client = new ScanClient(mClientId, scanSettings, scanFilterList, appUid); - client.stats = appScanStats; - client.stats.recordScanStart( + client.mStats = appScanStats; + client.mStats.recordScanStart( scanSettings, scanFilterList, isFiltered, false, mClientId, null); return client; } @@ -362,7 +362,8 @@ public class ScanManagerTest { mMockAppScanStats); } - private List<ScanFilter> createScanFilterList(boolean isFiltered, boolean isEmptyFilter) { + private static List<ScanFilter> createScanFilterList( + boolean isFiltered, boolean isEmptyFilter) { List<ScanFilter> scanFilterList = null; if (isFiltered) { scanFilterList = new ArrayList<>(); @@ -398,7 +399,7 @@ public class ScanManagerTest { return scanSettings; } - private ScanSettings createScanSettingsWithPhy(int scanMode, int phy) { + private static ScanSettings createScanSettingsWithPhy(int scanMode, int phy) { ScanSettings scanSettings; scanSettings = new ScanSettings.Builder().setScanMode(scanMode).setPhy(phy).build(); @@ -411,37 +412,37 @@ public class ScanManagerTest { ScanSettings scanSettings = createScanSettingsWithPhy(scanMode, phy); ScanClient client = new ScanClient(id, scanSettings, scanFilterList); - client.stats = mMockAppScanStats; - client.stats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null); + client.mStats = mMockAppScanStats; + client.mStats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null); return client; } - private Message createStartStopScanMessage(boolean isStartScan, Object obj) { + private static Message createStartStopScanMessage(boolean isStartScan, Object obj) { Message message = new Message(); message.what = isStartScan ? ScanManager.MSG_START_BLE_SCAN : ScanManager.MSG_STOP_BLE_SCAN; message.obj = obj; return message; } - private Message createScreenOnOffMessage(boolean isScreenOn) { + private static Message createScreenOnOffMessage(boolean isScreenOn) { Message message = new Message(); message.what = isScreenOn ? ScanManager.MSG_SCREEN_ON : ScanManager.MSG_SCREEN_OFF; message.obj = null; return message; } - private Message createLocationOnOffMessage(boolean isLocationOn) { + private static Message createLocationOnOffMessage(boolean isLocationOn) { Message message = new Message(); message.what = isLocationOn ? ScanManager.MSG_RESUME_SCANS : ScanManager.MSG_SUSPEND_SCANS; message.obj = null; return message; } - private Message createImportanceMessage(boolean isForeground) { + private static Message createImportanceMessage(boolean isForeground) { return createImportanceMessage(isForeground, Binder.getCallingUid()); } - private Message createImportanceMessage(boolean isForeground, int uid) { + private static Message createImportanceMessage(boolean isForeground, int uid) { final int importance = isForeground ? ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE @@ -452,7 +453,7 @@ public class ScanManagerTest { return message; } - private Message createConnectingMessage(boolean isConnectingOn) { + private static Message createConnectingMessage(boolean isConnectingOn) { Message message = new Message(); message.what = isConnectingOn ? ScanManager.MSG_START_CONNECTING : ScanManager.MSG_STOP_CONNECTING; @@ -478,7 +479,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client); assertThat(mScanManager.getSuspendedScanQueue()).contains(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -506,7 +507,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); } } @@ -529,7 +530,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client); assertThat(mScanManager.getSuspendedScanQueue()).contains(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -551,7 +552,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -573,7 +574,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -601,12 +602,12 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client); assertThat(mScanManager.getSuspendedScanQueue()).contains(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); } } @@ -634,12 +635,12 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); } } @@ -660,24 +661,24 @@ public class ScanManagerTest { ScanClient client = createScanClient(isFiltered, scanMode); // Start scan sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Wait for scan timeout advanceTime(DEFAULT_SCAN_TIMEOUT_MILLIS); mLooper.dispatchAll(); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); - assertThat(client.stats.isScanTimeout(client.scannerId)).isTrue(); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mStats.isScanTimeout(client.mScannerId)).isTrue(); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Set as background app sendMessageWaitForProcessed(createImportanceMessage(false)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Set as foreground app sendMessageWaitForProcessed(createImportanceMessage(true)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -698,7 +699,7 @@ public class ScanManagerTest { ScanClient client = createScanClient(isFiltered, scanMode); // Start scan, this sends scan timeout message with delay sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Move time forward so scan timeout message can be dispatched advanceTime(DEFAULT_SCAN_TIMEOUT_MILLIS); // Since we are using a TestLooper, need to mock AppScanStats.isScanningTooLong @@ -706,20 +707,20 @@ public class ScanManagerTest { // return true because no real time is elapsed doReturn(true).when(mMockAppScanStats).isScanningTooLong(); syncHandler(ScanManager.MSG_SCAN_TIMEOUT); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); - assertThat(client.stats.isScanTimeout(client.scannerId)).isTrue(); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mStats.isScanTimeout(client.mScannerId)).isTrue(); // Turn off screen sendMessageWaitForProcessed(createScreenOnOffMessage(false)); - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF); // Set as background app sendMessageWaitForProcessed(createImportanceMessage(false)); - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF); // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Set as foreground app sendMessageWaitForProcessed(createImportanceMessage(true)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -770,17 +771,17 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Set as background app sendMessageWaitForProcessed(createImportanceMessage(false)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Set as foreground app sendMessageWaitForProcessed(createImportanceMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); }); } @@ -803,17 +804,17 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Set as background app sendMessageWaitForProcessed(createImportanceMessage(false)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Set as foreground app sendMessageWaitForProcessed(createImportanceMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); }); } @@ -846,11 +847,11 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Wait for upgrade duration advanceTime(DEFAULT_SCAN_UPGRADE_DURATION_MILLIS); mLooper.dispatchAll(); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); } } @@ -884,7 +885,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Wait for upgrade and downgrade duration int max_duration = DEFAULT_SCAN_UPGRADE_DURATION_MILLIS @@ -893,7 +894,7 @@ public class ScanManagerTest { : DEFAULT_SCAN_DOWNGRADE_DURATION_BT_CONNECTING_MILLIS; advanceTime(max_duration); mLooper.dispatchAll(); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); }); } @@ -927,14 +928,14 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Set connecting state sendMessageWaitForProcessed(createConnectingMessage(true)); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); // Wait for downgrade duration advanceTime(DEFAULT_SCAN_DOWNGRADE_DURATION_BT_CONNECTING_MILLIS); mLooper.dispatchAll(); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); } } @@ -968,7 +969,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Set connecting state sendMessageWaitForProcessed(createConnectingMessage(true)); // Turn off screen @@ -979,7 +980,7 @@ public class ScanManagerTest { mLooper.dispatchAll(); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); } } @@ -1008,7 +1009,7 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); // Set connecting state sendMessageWaitForProcessed(createConnectingMessage(true)); // Set as background app @@ -1018,7 +1019,7 @@ public class ScanManagerTest { mLooper.dispatchAll(); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode); }); } @@ -1123,7 +1124,7 @@ public class ScanManagerTest { // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); assertThat(mScanManager.getBatchScanQueue()).doesNotContain(client); assertThat(mScanManager.getBatchScanParams()).isNull(); @@ -1166,7 +1167,7 @@ public class ScanManagerTest { // Turn on screen sendMessageWaitForProcessed(createScreenOnOffMessage(true)); assertThat(mScanManager.getRegularScanQueue()).contains(client); - assertThat(client.settings.getScanMode()).isEqualTo(scanMode); + assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); assertThat(mScanManager.getBatchScanQueue()).doesNotContain(client); assertThat(mScanManager.getBatchScanParams()).isNull(); @@ -1291,7 +1292,7 @@ public class ScanManagerTest { advanceTime(scanTestDuration); // Record scan stop - client.stats.recordScanStop(mClientId); + client.mStats.recordScanStop(mClientId); // Verify that the app scan stop is logged mInOrder.verify(mMetricsLogger) .logAppScanStateChanged( @@ -1493,12 +1494,12 @@ public class ScanManagerTest { // Verify radio scan stop is logged with the third app when screen turns on mInOrder.verify(mMetricsLogger) .logRadioScanStopped( - eq(new int[] {mostAggressiveClient.appUid}), - eq(new String[] {TEST_PACKAGE_NAME + mostAggressiveClient.appUid}), + eq(new int[] {mostAggressiveClient.mAppUid}), + eq(new String[] {TEST_PACKAGE_NAME + mostAggressiveClient.mAppUid}), eq( BluetoothStatsLog .LE_APP_SCAN_STATE_CHANGED__LE_SCAN_TYPE__SCAN_TYPE_REGULAR), - eq(AppScanStats.convertScanMode(mostAggressiveClient.scanModeApp)), + eq(AppScanStats.convertScanMode(mostAggressiveClient.mScanModeApp)), eq((long) SCAN_MODE_SCREEN_OFF_LOW_POWER_INTERVAL_MS), eq((long) SCAN_MODE_SCREEN_OFF_LOW_POWER_WINDOW_MS), eq(false), @@ -1801,11 +1802,11 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); // Set connecting state sendMessageWaitForProcessed(createConnectingMessage(true)); // SCAN_MODE_LOW_LATENCY is now downgraded to SCAN_MODE_BALANCED - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_BALANCED); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_BALANCED); } @Test @@ -1825,13 +1826,13 @@ public class ScanManagerTest { sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); assertThat(mScanManager.getRegularScanQueue()).contains(client); assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client); - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); // Set AppScanStats to null - client.stats = null; + client.mStats = null; // Set connecting state sendMessageWaitForProcessed(createConnectingMessage(true)); // Since AppScanStats is null, no downgrade takes place for scan mode - assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); + assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY); } @Test @@ -1943,7 +1944,7 @@ public class ScanManagerTest { // Start scan sendMessageWaitForProcessed(createStartStopScanMessage(true, client)); - assertThat(client.settings.getPhy()).isEqualTo(phy); + assertThat(client.mSettings.getPhy()).isEqualTo(phy); verify(mScanNativeInterface) .gattSetScanParameters( eq(expect1m ? mClientId : 0), @@ -1975,7 +1976,7 @@ public class ScanManagerTest { // Start scan on 1m sendMessageWaitForProcessed(createStartStopScanMessage(true, client1m)); - assertThat(client1m.settings.getPhy()).isEqualTo(PHY_LE_1M); + assertThat(client1m.mSettings.getPhy()).isEqualTo(PHY_LE_1M); verify(mScanNativeInterface) .gattSetScanParameters( eq(clientId1m), @@ -1994,7 +1995,7 @@ public class ScanManagerTest { // Start scan on coded sendMessageWaitForProcessed(createStartStopScanMessage(true, clientCoded)); - assertThat(clientCoded.settings.getPhy()).isEqualTo(PHY_LE_CODED); + assertThat(clientCoded.mSettings.getPhy()).isEqualTo(PHY_LE_CODED); verify(mScanNativeInterface) .gattSetScanParameters( eq(clientId1m), diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java index 221e8ad214..a336954afe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java @@ -2413,15 +2413,16 @@ public class BluetoothMapContentObserverTest { verify(mProviderClient, never()).query(any(), any(), any(), any(), any(), any()); } - private BluetoothMapContentObserver.Msg createSimpleMsg() { + private static BluetoothMapContentObserver.Msg createSimpleMsg() { return new BluetoothMapContentObserver.Msg(1, 1L, 1); } - private BluetoothMapContentObserver.Msg createMsgWithTypeAndThreadId(int type, int threadId) { + private static BluetoothMapContentObserver.Msg createMsgWithTypeAndThreadId( + int type, int threadId) { return new BluetoothMapContentObserver.Msg(1, type, threadId, 1); } - private void setFolderStructureWithTelecomAndMsg( + private static void setFolderStructureWithTelecomAndMsg( BluetoothMapFolderElement folderElement, String folderName, long folderId) { folderElement.addFolder("telecom"); folderElement.getSubFolder("telecom").addFolder("msg"); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java index b2c3d00c54..4d53d787b6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java @@ -290,7 +290,7 @@ public class BluetoothMapObexServerTest { assertThat(mParams.getFilterMessageType()).isEqualTo(expectedMask); } - private void setUpBluetoothMapAppParams(BluetoothMapAppParams params) { + private static void setUpBluetoothMapAppParams(BluetoothMapAppParams params) { params.setPresenceAvailability(1); params.setPresenceStatus("test_presence_status"); params.setLastActivity(0); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java index 72a3c75168..6410ebf3f0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.map; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; @@ -65,7 +67,7 @@ public class BluetoothMapServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -80,7 +82,7 @@ public class BluetoothMapServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java index 85d8ba6f15..2f6604a486 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java @@ -15,6 +15,8 @@ */ package com.android.bluetooth.map; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -26,7 +28,6 @@ import static org.mockito.Mockito.when; import android.app.AlarmManager; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Context; import android.telephony.TelephonyManager; @@ -86,9 +87,7 @@ public class BluetoothMapServiceTest { public void getDevicesMatchingConnectionStates_whenNoDeviceIsConnected_returnsEmptyList() { when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mDevice}); - assertThat( - mService.getDevicesMatchingConnectionStates( - new int[] {BluetoothProfile.STATE_CONNECTED})) + assertThat(mService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED})) .isEmpty(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java index 431314a7af..d3e98577a6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java @@ -15,13 +15,15 @@ */ package com.android.bluetooth.mapclient; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.net.Uri; import androidx.test.filters.MediumTest; @@ -72,7 +74,7 @@ public class MapClientServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -87,7 +89,7 @@ public class MapClientServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java index ce23a13dce..c75333efcf 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java @@ -18,6 +18,9 @@ package com.android.bluetooth.mapclient; import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -171,7 +174,7 @@ public class MapClientServiceTest { @Test public void disconnect_whenConnected_returnsTrue() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); when(sm.getState()).thenReturn(connectionState); mService.getInstanceMap().put(mRemoteDevice, sm); @@ -183,13 +186,12 @@ public class MapClientServiceTest { @Test public void getConnectionState_whenNotConnected() { - assertThat(mService.getConnectionState(mRemoteDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mService.getConnectionState(mRemoteDevice)).isEqualTo(STATE_DISCONNECTED); } @Test public void getConnectionState_whenConnected() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); when(sm.getState()).thenReturn(connectionState); mService.getInstanceMap().put(mRemoteDevice, sm); @@ -199,7 +201,7 @@ public class MapClientServiceTest { @Test public void getConnectedDevices() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); BluetoothDevice[] bondedDevices = new BluetoothDevice[] {mRemoteDevice}; when(mAdapterService.getBondedDevices()).thenReturn(bondedDevices); @@ -278,7 +280,7 @@ public class MapClientServiceTest { @Test public void aclDisconnectedNoTransport_whenConnected_doesNotCallDisconnect() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); mService.getInstanceMap().put(mRemoteDevice, sm); when(sm.getState()).thenReturn(connectionState); @@ -291,7 +293,7 @@ public class MapClientServiceTest { @Test public void aclDisconnectedLeTransport_whenConnected_doesNotCallDisconnect() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); mService.getInstanceMap().put(mRemoteDevice, sm); when(sm.getState()).thenReturn(connectionState); @@ -304,7 +306,7 @@ public class MapClientServiceTest { @Test public void aclDisconnectedBrEdrTransport_whenConnected_callsDisconnect() { - int connectionState = BluetoothProfile.STATE_CONNECTED; + int connectionState = STATE_CONNECTED; MceStateMachine sm = mock(MceStateMachine.class); mService.getInstanceMap().put(mRemoteDevice, sm); when(sm.getState()).thenReturn(connectionState); @@ -375,8 +377,7 @@ public class MapClientServiceTest { assertThat(mService.getInstanceMap().keySet()).containsExactly(mRemoteDevice); mTestLooper.dispatchAll(); - assertThat(mService.getConnectionState(mRemoteDevice)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mService.getConnectionState(mRemoteDevice)).isEqualTo(STATE_CONNECTING); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java index 2975803aaf..15763b79c3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.pan; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; @@ -72,7 +74,7 @@ public class PanServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -87,7 +89,7 @@ public class PanServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java index 25368e4b16..c9f20f430a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java @@ -16,11 +16,18 @@ package com.android.bluetooth.pan; import static android.bluetooth.BluetoothPan.PAN_ROLE_NONE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static android.net.TetheringManager.TETHERING_BLUETOOTH; import static android.net.TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; +import static com.android.bluetooth.TestUtils.mockGetSystemService; import static com.google.common.truth.Truth.assertThat; @@ -41,7 +48,6 @@ import androidx.test.filters.MediumTest; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.runner.AndroidJUnit4; -import com.android.bluetooth.TestUtils; import com.android.bluetooth.btservice.AdapterService; import com.android.bluetooth.btservice.storage.DatabaseManager; import com.android.bluetooth.pan.PanService.BluetoothPanDevice; @@ -64,7 +70,6 @@ public class PanServiceTest { @Mock private UserManager mMockUserManager; private static final byte[] REMOTE_DEVICE_ADDRESS_AS_ARRAY = new byte[] {0, 0, 0, 0, 0, 0}; - private static final int TIMEOUT_MS = 5_000; private final BluetoothDevice mRemoteDevice = getTestDevice(0); @@ -77,10 +82,9 @@ public class PanServiceTest { public void setUp() { doReturn(mTargetContext.getResources()).when(mAdapterService).getResources(); doReturn(mDatabaseManager).when(mAdapterService).getDatabase(); - TestUtils.mockGetSystemService( + mockGetSystemService( mAdapterService, Context.USER_SERVICE, UserManager.class, mMockUserManager); - TestUtils.mockGetSystemService( - mAdapterService, Context.TETHERING_SERVICE, TetheringManager.class); + mockGetSystemService(mAdapterService, Context.TETHERING_SERVICE, TetheringManager.class); mService = new PanService(mAdapterService, mNativeInterface); mService.setAvailable(true); @@ -108,8 +112,7 @@ public class PanServiceTest { when(mMockUserManager.isGuestUser()).thenReturn(false); mService.mPanDevices.put( mRemoteDevice, - new BluetoothPanDevice( - BluetoothProfile.STATE_CONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); + new BluetoothPanDevice(STATE_CONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); assertThat(mService.connect(mRemoteDevice)).isFalse(); } @@ -119,8 +122,7 @@ public class PanServiceTest { when(mMockUserManager.isGuestUser()).thenReturn(false); mService.mPanDevices.put( mRemoteDevice, - new BluetoothPanDevice( - BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); + new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); assertThat(mService.connect(mRemoteDevice)).isTrue(); verify(mNativeInterface, timeout(TIMEOUT_MS)).connect(any()); @@ -135,23 +137,22 @@ public class PanServiceTest { @Test public void convertHalState() { assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_CONNECTED)) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + .isEqualTo(STATE_CONNECTED); assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_CONNECTING)) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + .isEqualTo(STATE_CONNECTING); assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_DISCONNECTED)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_DISCONNECTING)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + .isEqualTo(STATE_DISCONNECTING); assertThat(PanNativeInterface.convertHalState(-24664)) // illegal value - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); } @Test public void dump() { mService.mPanDevices.put( mRemoteDevice, - new BluetoothPanDevice( - BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); + new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); mService.dump(new StringBuilder()); } @@ -174,7 +175,7 @@ public class PanServiceTest { @Test public void setConnectionPolicy_whenDatabaseManagerRefuses_returnsFalse() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; when(mDatabaseManager.setProfileConnectionPolicy( mRemoteDevice, BluetoothProfile.PAN, connectionPolicy)) .thenReturn(false); @@ -185,24 +186,15 @@ public class PanServiceTest { @Test public void setConnectionPolicy_returnsTrue() { when(mDatabaseManager.setProfileConnectionPolicy( - mRemoteDevice, - BluetoothProfile.PAN, - BluetoothProfile.CONNECTION_POLICY_ALLOWED)) + mRemoteDevice, BluetoothProfile.PAN, CONNECTION_POLICY_ALLOWED)) .thenReturn(true); - assertThat( - mService.setConnectionPolicy( - mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) - .isTrue(); + assertThat(mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED)).isTrue(); verify(mNativeInterface, timeout(TIMEOUT_MS)).connect(any()); when(mDatabaseManager.setProfileConnectionPolicy( - mRemoteDevice, - BluetoothProfile.PAN, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + mRemoteDevice, BluetoothProfile.PAN, CONNECTION_POLICY_FORBIDDEN)) .thenReturn(true); - assertThat( - mService.setConnectionPolicy( - mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + assertThat(mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); verify(mNativeInterface, timeout(TIMEOUT_MS)).disconnect(any()); } @@ -230,8 +222,7 @@ public class PanServiceTest { mService.mIsTethering = true; mService.mPanDevices.put( mRemoteDevice, - new BluetoothPanDevice( - BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); + new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE)); TetheringInterface iface = new TetheringInterface(TETHERING_BLUETOOTH, "iface"); mService.mTetheringCallback.onError(iface, TETHER_ERROR_SERVICE_UNAVAIL); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java index ec398bd913..becc52e836 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java @@ -16,13 +16,15 @@ package com.android.bluetooth.pbap; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.filters.MediumTest; import androidx.test.runner.AndroidJUnit4; @@ -65,7 +67,7 @@ public class BluetoothPbapServiceBinderTest { @Test public void getDevicesMatchingConnectionStates_callsServiceMethod() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mBinder.getDevicesMatchingConnectionStates(states, null); verify(mService).getDevicesMatchingConnectionStates(states); @@ -80,7 +82,7 @@ public class BluetoothPbapServiceBinderTest { @Test public void setConnectionPolicy_callsServiceMethod() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mBinder.setConnectionPolicy(mDevice, connectionPolicy, null); verify(mService).setConnectionPolicy(mDevice, connectionPolicy); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java index 0b7a0f6da6..d3a4de5fed 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java @@ -15,6 +15,8 @@ */ package com.android.bluetooth.pbap; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -168,9 +170,9 @@ public class BluetoothPbapServiceTest { public void getDevicesMatchingConnectionStates() { PbapStateMachine sm = mock(PbapStateMachine.class); mService.mPbapStateMachineMap.put(mRemoteDevice, sm); - when(sm.getConnectionState()).thenReturn(BluetoothProfile.STATE_CONNECTED); + when(sm.getConnectionState()).thenReturn(STATE_CONNECTED); - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; assertThat(mService.getDevicesMatchingConnectionStates(states)).contains(mRemoteDevice); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java index 1302bb4c08..b696cef960 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java @@ -235,7 +235,7 @@ public class BluetoothPbapVcardManagerNestedClassesTest { assertThat(getContactsIdFromCursor(resultCursor, 2)).isEqualTo(1004); } - private long getContactsIdFromCursor(Cursor cursor, int position) { + private static long getContactsIdFromCursor(Cursor cursor, int position) { int index = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID); cursor.moveToPosition(position); return cursor.getLong(index); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java index 8b4cd83b86..e8ef9baedc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java @@ -16,6 +16,10 @@ package com.android.bluetooth.pbap; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -24,7 +28,6 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.*; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.HandlerThread; @@ -81,8 +84,7 @@ public class PbapStateMachineTest { /** Test that initial state is WaitingForAuth */ @Test public void testInitialState() { - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.WaitingForAuth.class); } @@ -92,8 +94,7 @@ public class PbapStateMachineTest { @Test public void testStateTransition_WaitingForAuthToFinished() { mPbapStateMachine.sendMessage(PbapStateMachine.REJECTED); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Finished.class); } @@ -103,8 +104,7 @@ public class PbapStateMachineTest { @Test public void testStateTransition_WaitingForAuthToConnected() { mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Connected.class); } @@ -114,15 +114,13 @@ public class PbapStateMachineTest { @Test public void testStateTransition_ConnectedToFinished() { mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Connected.class); // PBAP OBEX transport is done. mPbapStateMachine.sendMessage(PbapStateMachine.DISCONNECT); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Finished.class); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java index fdadac66b8..b3669a14f6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java @@ -198,7 +198,7 @@ public class CallLogPullRequestTest { assertThat(contact.getTimesContacted()).isEqualTo(1); } - private VCardProperty createProperty(String name, String value) { + private static VCardProperty createProperty(String name, String value) { VCardProperty property = new VCardProperty(); property.setName(name); property.setValues(value); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java index 5126cd500e..4fc428ebbe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java @@ -402,7 +402,7 @@ public class PbapClientAccountManagerTest { mBroadcastReceiver.onReceive(mMockContext, intent); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), "com.android.bluetooth.pbabclient.account"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java index 21f4d58849..aff8f250a7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java @@ -16,6 +16,11 @@ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -28,7 +33,6 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.AttributionSource; import androidx.test.filters.MediumTest; @@ -93,7 +97,7 @@ public class PbapClientBinderTest { @Test public void testGetDevicesMatchingConnectionStates() { - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; mPbapClientBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mMockService).getDevicesMatchingConnectionStates(eq(states)); } @@ -106,7 +110,7 @@ public class PbapClientBinderTest { @Test public void testSetConnectionPolicy() { - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; mPbapClientBinder.setConnectionPolicy(mTestDevice, connectionPolicy, mAttributionSource); verify(mMockService).setConnectionPolicy(eq(mTestDevice), eq(connectionPolicy)); } @@ -148,7 +152,7 @@ public class PbapClientBinderTest { @Test public void testGetDevicesMatchingConnectionStates_afterCleanup_returnsEmptyList() { mPbapClientBinder.cleanup(); - int[] states = new int[] {BluetoothProfile.STATE_CONNECTED}; + int[] states = new int[] {STATE_CONNECTED}; List<BluetoothDevice> devices = mPbapClientBinder.getDevicesMatchingConnectionStates(states, mAttributionSource); verify(mMockService, never()).getDevicesMatchingConnectionStates(any(int[].class)); @@ -160,13 +164,13 @@ public class PbapClientBinderTest { mPbapClientBinder.cleanup(); int state = mPbapClientBinder.getConnectionState(mTestDevice, mAttributionSource); verify(mMockService, never()).getConnectionState(any(BluetoothDevice.class)); - assertThat(state).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(state).isEqualTo(STATE_DISCONNECTED); } @Test public void testSetConnectionPolicy_afterCleanup_returnsFalse() { mPbapClientBinder.cleanup(); - int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED; + int connectionPolicy = CONNECTION_POLICY_ALLOWED; boolean result = mPbapClientBinder.setConnectionPolicy( mTestDevice, connectionPolicy, mAttributionSource); @@ -179,6 +183,6 @@ public class PbapClientBinderTest { mPbapClientBinder.cleanup(); int result = mPbapClientBinder.getConnectionPolicy(mTestDevice, mAttributionSource); verify(mMockService, never()).getConnectionPolicy(any(BluetoothDevice.class)); - assertThat(result).isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + assertThat(result).isEqualTo(CONNECTION_POLICY_UNKNOWN); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java index 168f9b782c..66070377ed 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java @@ -552,11 +552,11 @@ public class PbapClientContactsStorageTest { assertThat(mStorage.isStorageReady()).isTrue(); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), ACCOUNT_TYPE); } - private List<VCardEntry> getMockContacts(int numContacts) { + private static List<VCardEntry> getMockContacts(int numContacts) { List<VCardEntry> contacts = new ArrayList<VCardEntry>(); for (int i = 0; i < numContacts; i++) { VCardEntry card = new VCardEntry(VCardConfig.VCARD_TYPE_V21_GENERIC); @@ -570,7 +570,7 @@ public class PbapClientContactsStorageTest { return contacts; } - private List<VCardEntry> getMockCallHistory(int type, int numEntries) { + private static List<VCardEntry> getMockCallHistory(int type, int numEntries) { String typeIndicator = ""; if (type == CallLog.Calls.INCOMING_TYPE) { typeIndicator = "RECEIVED"; diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java index 0b0b4b1f91..fef6b763de 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java @@ -16,6 +16,11 @@ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -31,7 +36,6 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; import android.util.Log; import androidx.test.platform.app.InstrumentationRegistry; @@ -136,7 +140,7 @@ public class PbapClientObexClientTest { assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM); assertThat(mObexClient.getRfcommChannelId()) .isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mObexClient.isConnected()).isFalse(); } @@ -152,18 +156,13 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTED), - eq(BluetoothProfile.STATE_CONNECTING)); - verify(mMockCallback) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING)); + verify(mMockCallback).onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); assertThat(mObexClient.getTransportType()).isEqualTo(PbapClientObexClient.TRANSPORT_L2CAP); assertThat(mObexClient.getL2capPsm()).isEqualTo(TEST_L2CAP_PSM); assertThat(mObexClient.getRfcommChannelId()) .isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mObexClient.isConnected()).isTrue(); } @@ -175,17 +174,12 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTED), - eq(BluetoothProfile.STATE_CONNECTING)); - verify(mMockCallback) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING)); + verify(mMockCallback).onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); assertThat(mObexClient.getTransportType()).isEqualTo(PbapClientObexClient.TRANSPORT_RFCOMM); assertThat(mObexClient.getRfcommChannelId()).isEqualTo(TEST_RFCOMM_CHANNEL_ID); assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mObexClient.isConnected()).isTrue(); } @@ -297,7 +291,7 @@ public class PbapClientObexClientTest { assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM); assertThat(mObexClient.getRfcommChannelId()) .isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mObexClient.isConnected()).isFalse(); } @@ -309,7 +303,7 @@ public class PbapClientObexClientTest { verify(mMockCallback, never()).onConnectionStateChanged(anyInt(), anyInt()); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mObexClient.isConnected()).isFalse(); } @@ -321,14 +315,10 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -341,14 +331,10 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -387,14 +373,10 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -425,14 +407,10 @@ public class PbapClientObexClientTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } // ********************************************************************************************* @@ -449,7 +427,7 @@ public class PbapClientObexClientTest { mObexClient.close(); mTestLooper.dispatchAll(); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mObexClient.isConnected()).isFalse(); } @@ -463,14 +441,12 @@ public class PbapClientObexClientTest { // Timeout() is desirable, but we can't use test looper without receiving the // InterruptedExceptions verify(mMockCallback, timeout(2000)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); mObexClient.close(); mTestLooper.dispatchAll(); - assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } // ********************************************************************************************* diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java index 825d2730f4..3518b2d418 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java @@ -15,6 +15,10 @@ */ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -29,9 +33,9 @@ import static org.mockito.Mockito.verify; import android.app.BroadcastOptions; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.Intent; +import android.os.HandlerThread; import android.os.UserManager; import android.util.Log; @@ -64,25 +68,28 @@ public class PbapClientStateMachineOldTest { private final BluetoothDevice mDevice = getTestDevice(40); private final ArgumentCaptor<Intent> mIntentArgument = ArgumentCaptor.forClass(Intent.class); - private PbapClientStateMachineOld mPbapClientStateMachine = null; + private HandlerThread mHandlerThread; + private PbapClientStateMachineOld mPbapClientStateMachine; @Before - public void setUp() throws Exception { + public void setUp() { mockGetSystemService(mMockPbapClientService, Context.USER_SERVICE, UserManager.class); doCallRealMethod().when(mMockHandler).obtainMessage(anyInt(), any()); doCallRealMethod().when(mMockHandler).obtainMessage(anyInt()); + mHandlerThread = new HandlerThread("HeadsetStateMachineTestHandlerThread"); + mHandlerThread.start(); + mPbapClientStateMachine = - new PbapClientStateMachineOld(mMockPbapClientService, mDevice, mMockHandler); + new PbapClientStateMachineOld( + mMockPbapClientService, mDevice, mMockHandler, mHandlerThread); mPbapClientStateMachine.start(); } @After - public void tearDown() throws Exception { - if (mPbapClientStateMachine != null) { - mPbapClientStateMachine.doQuit(); - } + public void tearDown() { + mPbapClientStateMachine.doQuit(); } /** Test that default state is STATE_CONNECTING */ @@ -93,8 +100,7 @@ public class PbapClientStateMachineOldTest { // currently solved by waiting for looper to finish task TestUtils.waitForLooperToFinishScheduledTask( mPbapClientStateMachine.getHandler().getLooper()); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); } /** @@ -103,15 +109,13 @@ public class PbapClientStateMachineOldTest { */ @Test public void testStateTransitionFromConnectingToDisconnected() { - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); mPbapClientStateMachine.disconnect(mDevice); TestUtils.waitForLooperToFinishScheduledTask( mPbapClientStateMachine.getHandler().getLooper()); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTING); // wait until timeout occurs Mockito.clearInvocations(mMockPbapClientService); @@ -120,7 +124,6 @@ public class PbapClientStateMachineOldTest { mIntentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java index d8dc5d4e4b..4620f7467c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java @@ -16,6 +16,11 @@ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -38,7 +43,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import android.accounts.Account; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.SdpPseRecord; import android.content.Context; @@ -168,8 +172,7 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.disconnect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, never()).onConnectionStateChanged(anyInt(), anyInt()); } @@ -178,12 +181,9 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.connect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTED), - eq(BluetoothProfile.STATE_CONNECTING)); + .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING)); } // ********************************************************************************************* @@ -237,15 +237,10 @@ public class PbapClientStateMachineTest { verify(mMockObexClient, never()).connectL2cap(eq(L2CAP_PSM)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -260,8 +255,7 @@ public class PbapClientStateMachineTest { // We can't currently mock a BluetoothDevice to verify the sdpSearch() call, but we can // validate that the state machine stays in the same state and will adequately receive the // next valid SDP record that arrives. - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); mPbapClientStateMachine.onSdpResultReceived( SDP_SUCCESS, @@ -283,32 +277,22 @@ public class PbapClientStateMachineTest { verify(mMockObexClient, never()).connectL2cap(eq(L2CAP_PSM)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test public void testConnecting_receivedObexConnection_transitionToConnected() { testConnecting_receivedSdpResultWithTransportL2cap_connectionReqOnL2cap(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); } @Test @@ -318,15 +302,10 @@ public class PbapClientStateMachineTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -336,36 +315,24 @@ public class PbapClientStateMachineTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test public void testConnecting_receivedObexDisconnection_transitionToDisconnected() { testConnecting_receivedSdpResultWithTransportL2cap_connectionReqOnL2cap(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } // ********************************************************************************************* @@ -434,33 +401,23 @@ public class PbapClientStateMachineTest { mStorageCallback.onStorageAccountsChanged(mMockedAccounts, new ArrayList<Account>()); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); } @Test public void testConnected_receivedObexDisconnection_transitionToDisconnected() { testConnecting_receivedObexConnection_transitionToConnected(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -469,12 +426,9 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.disconnect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); } // ********************************************************************************************* @@ -520,10 +474,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertFavorites(any(Account.class), anyList()); @@ -547,10 +499,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_LOCAL_PHONEBOOK)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertLocalContacts(any(Account.class), anyList()); @@ -574,10 +524,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_LOCAL_PHONEBOOK)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, never()).insertLocalContacts(any(Account.class), anyList()); @@ -604,10 +552,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_SIM_CARD)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertSimContacts(any(Account.class), anyList()); @@ -631,10 +577,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_SIM_CARD)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertMissedCallHistory(any(Account.class), anyList()); @@ -656,10 +600,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(4)).insertFavorites(any(Account.class), anyList()); @@ -676,19 +618,14 @@ public class PbapClientStateMachineTest { SDP_SUCCESS, makeSdpRecord( L2CAP_PSM, INVALID_RFCOMM, SUPPORTED_FEATURES, NO_REPOSITORIES_SUPPORTED)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); // Verify we're connected - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); // Verify storage not hit verify(mMockStorage, never()).insertFavorites(any(Account.class), anyList()); @@ -712,10 +649,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); // Get storage callback @@ -757,18 +692,13 @@ public class PbapClientStateMachineTest { @Test public void testDisconnecting_clientDisconnects_transitionToDisconnected() { testEnterDisconnecting_clientConnected_disconnectIssued(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_CONNECTED, STATE_DISCONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -777,12 +707,9 @@ public class PbapClientStateMachineTest { mTestLooper.moveTimeForward(PbapClientStateMachine.DISCONNECT_TIMEOUT_MS); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -829,7 +756,7 @@ public class PbapClientStateMachineTest { return new PbapSdpRecord(mTestDevice, sdpRecord); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), "com.android.bluetooth.pbabclient.account"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java index 214a08bf27..6537f475b5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java @@ -548,7 +548,7 @@ public class PbapPhonebookTest { // * Utilities // ********************************************************************************************* - private InputStream toUtf8Stream(String s) { + private static InputStream toUtf8Stream(String s) { return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java index 77a5453bdf..d0e462ca66 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java @@ -71,14 +71,14 @@ public class PhonebookPullRequestTest { assertThat(mRequest.complete).isTrue(); } - private VCardProperty createProperty(String name, String value) { + private static VCardProperty createProperty(String name, String value) { VCardProperty property = new VCardProperty(); property.setName(name); property.setValues(value); return property; } - private VCardEntry createEntry(int propertyCount) { + private static VCardEntry createEntry(int propertyCount) { VCardEntry entry = new VCardEntry(); for (int i = 0; i < propertyCount; i++) { entry.addProperty(createProperty(VCardConstants.PROPERTY_TEL, Integer.toString(i))); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java index 5f50e76ca2..44744c837a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java @@ -168,7 +168,7 @@ public class RequestPullPhonebookMetadataTest { return sendResponse(op, replyHeaders, null); } - public byte[] shortToByteArray(short s) { + public static byte[] shortToByteArray(short s) { ByteBuffer ret = ByteBuffer.allocate(2); ret.putShort(s); return ret.array(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java index a7ea9feafa..d6336bcb34 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java @@ -16,6 +16,10 @@ package com.android.bluetooth.sap; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -82,20 +86,17 @@ public class SapServiceTest { @Test public void testGetConnectionPolicy() { when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); - assertThat(mService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN); + .thenReturn(CONNECTION_POLICY_UNKNOWN); + assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_UNKNOWN); when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); - assertThat(mService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + .thenReturn(CONNECTION_POLICY_FORBIDDEN); + assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_FORBIDDEN); when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP)) - .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + .thenReturn(CONNECTION_POLICY_ALLOWED); - assertThat(mService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java index ce797f2d30..c9c3c238e2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java @@ -82,7 +82,7 @@ public class DipTest { SdpManagerNativeInterface.setInstance(null); } - private void verifyDipSdpRecordIntent( + private static void verifyDipSdpRecordIntent( ArgumentCaptor<Intent> intentArgument, int status, BluetoothDevice device, diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java index 7a727f5d7f..4045cb9bfb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.vc; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED; import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_DEVICE_AVAILABLE; @@ -29,8 +31,6 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; -import android.bluetooth.BluetoothProfile; - import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.btservice.AdapterService; @@ -65,7 +65,7 @@ public class VolumeControlNativeCallbackTest { @Test public void onConnectionStateChanged() { - int state = BluetoothProfile.STATE_CONNECTED; + int state = STATE_CONNECTED; mNativeCallback.onConnectionStateChanged(state, null); verify(mService).messageFromNative(mEvent.capture()); diff --git a/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java b/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java index 62d87393bd..4dcb10d96f 100644 --- a/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java +++ b/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java @@ -17,6 +17,11 @@ package com.android.bluetooth.leaudio; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.app.Application; import android.bluetooth.*; import android.content.BroadcastReceiver; @@ -551,10 +556,9 @@ public class BluetoothProxy { final int toState = intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1); - if (toState == BluetoothProfile.STATE_CONNECTED - || toState == BluetoothProfile.STATE_DISCONNECTED) + if (toState == STATE_CONNECTED || toState == STATE_DISCONNECTED) svc_data.isConnectedMutable.postValue( - toState == BluetoothProfile.STATE_CONNECTED); + toState == STATE_CONNECTED); } } } @@ -1065,7 +1069,7 @@ public class BluetoothProxy { if (mBluetoothLeBroadcastAssistant != null) { boolean is_connected = mBluetoothLeBroadcastAssistant.getConnectionState(dev) - == BluetoothProfile.STATE_CONNECTED; + == STATE_CONNECTED; state_wrapper.bassData.isConnectedMutable.setValue(is_connected); } } @@ -1226,10 +1230,10 @@ public class BluetoothProxy { if (mBluetoothLeBroadcastAssistant != null) { if (connect) { mBluetoothLeBroadcastAssistant.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + device, CONNECTION_POLICY_ALLOWED); } else { mBluetoothLeBroadcastAssistant.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + device, CONNECTION_POLICY_FORBIDDEN); } } } @@ -1342,11 +1346,9 @@ public class BluetoothProxy { public void connectHap(BluetoothDevice device, boolean connect) { if (bluetoothHapClient != null) { if (connect) { - bluetoothHapClient.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_ALLOWED); + bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED); } else { - bluetoothHapClient.setConnectionPolicy( - device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN); + bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN); } } } @@ -1376,11 +1378,11 @@ public class BluetoothProxy { } switch (newState) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: device_wrapper.isGattBrConnectedMutable.postValue( false); break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: device_wrapper.isGattBrConnectedMutable.postValue(true); break; default: diff --git a/android/pandora/server/src/A2dp.kt b/android/pandora/server/src/A2dp.kt index 0b5a0d6640..ba7003961f 100644 --- a/android/pandora/server/src/A2dp.kt +++ b/android/pandora/server/src/A2dp.kt @@ -23,6 +23,8 @@ import android.bluetooth.BluetoothCodecStatus import android.bluetooth.BluetoothCodecType import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -98,13 +100,10 @@ class A2dp(val context: Context) : A2DPImplBase(), Closeable { .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { - it == BluetoothProfile.STATE_CONNECTED || - it == BluetoothProfile.STATE_DISCONNECTED - } + .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED } .first() - if (state == BluetoothProfile.STATE_DISCONNECTED) { + if (state == STATE_DISCONNECTED) { throw RuntimeException("openSource failed, A2DP has been disconnected") } } @@ -131,13 +130,10 @@ class A2dp(val context: Context) : A2DPImplBase(), Closeable { .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { - it == BluetoothProfile.STATE_CONNECTED || - it == BluetoothProfile.STATE_DISCONNECTED - } + .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED } .first() - if (state == BluetoothProfile.STATE_DISCONNECTED) { + if (state == STATE_DISCONNECTED) { throw RuntimeException("waitSource failed, A2DP has been disconnected") } } diff --git a/android/pandora/server/src/A2dpSink.kt b/android/pandora/server/src/A2dpSink.kt index 789c9edf72..931997d5a5 100644 --- a/android/pandora/server/src/A2dpSink.kt +++ b/android/pandora/server/src/A2dpSink.kt @@ -20,6 +20,9 @@ import android.bluetooth.BluetoothA2dpSink import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -67,13 +70,13 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable { override fun waitSink( request: WaitSinkRequest, - responseObserver: StreamObserver<WaitSinkResponse> + responseObserver: StreamObserver<WaitSinkResponse>, ) { grpcUnary<WaitSinkResponse>(scope, responseObserver) { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.i(TAG, "waitSink: device=$device") - if (bluetoothA2dpSink.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (bluetoothA2dpSink.getConnectionState(device) != STATE_CONNECTED) { val state = flow .filter { @@ -83,13 +86,10 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable { .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { - it == BluetoothProfile.STATE_CONNECTED || - it == BluetoothProfile.STATE_DISCONNECTED - } + .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED } .first() - if (state == BluetoothProfile.STATE_DISCONNECTED) { + if (state == STATE_DISCONNECTED) { throw RuntimeException("waitStream failed, A2DP has been disconnected") } } @@ -104,7 +104,7 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable { grpcUnary<CloseResponse>(scope, responseObserver) { val device = bluetoothAdapter.getRemoteDevice(request.sink.cookie.toString("UTF-8")) Log.i(TAG, "close: device=$device") - if (bluetoothA2dpSink.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (bluetoothA2dpSink.getConnectionState(device) != STATE_CONNECTED) { throw RuntimeException("Device is not connected, cannot close") } @@ -114,13 +114,8 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable { .filter { it.getBluetoothDeviceExtra() == device } .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - bluetoothA2dpSink.setConnectionPolicy( - device, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - ) - a2dpConnectionStateChangedFlow - .filter { it == BluetoothProfile.STATE_DISCONNECTED } - .first() + bluetoothA2dpSink.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN) + a2dpConnectionStateChangedFlow.filter { it == STATE_DISCONNECTED }.first() CloseResponse.getDefaultInstance() } diff --git a/android/pandora/server/src/Asha.kt b/android/pandora/server/src/Asha.kt index 0c2d37ab48..d97b4b8b65 100644 --- a/android/pandora/server/src/Asha.kt +++ b/android/pandora/server/src/Asha.kt @@ -20,6 +20,7 @@ import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothHearingAid import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.STATE_CONNECTED import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -79,7 +80,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { override fun waitPeripheral( request: WaitPeripheralRequest, - responseObserver: StreamObserver<WaitPeripheralResponse> + responseObserver: StreamObserver<WaitPeripheralResponse>, ) { grpcUnary<WaitPeripheralResponse>(scope, responseObserver) { Log.i(TAG, "waitPeripheral") @@ -87,9 +88,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.d(TAG, "connection address ${device.getAddress()}") - if ( - bluetoothHearingAid.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED - ) { + if (bluetoothHearingAid.getConnectionState(device) != STATE_CONNECTED) { Log.d(TAG, "wait for bluetoothHearingAid profile connection") flow .filter { @@ -97,7 +96,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { } .filter { it.getBluetoothDeviceExtra() == device } .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { it == BluetoothProfile.STATE_CONNECTED } + .filter { it == STATE_CONNECTED } .first() } @@ -113,9 +112,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.d(TAG, "connection address ${device.getAddress()}") - if ( - bluetoothHearingAid.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED - ) { + if (bluetoothHearingAid.getConnectionState(device) != STATE_CONNECTED) { throw RuntimeException("Hearing aid device is not connected, cannot start") } @@ -141,7 +138,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { ) { Log.d( TAG, - "TYPE_HEARING_AID added with address: ${addedDevice.address}" + "TYPE_HEARING_AID added with address: ${addedDevice.address}", ) trySendBlocking(null) } @@ -151,7 +148,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { audioManager.registerAudioDeviceCallback( audioDeviceCallback, - Handler(Looper.getMainLooper()) + Handler(Looper.getMainLooper()), ) awaitClose { audioManager.unregisterAudioDeviceCallback(audioDeviceCallback) } } @@ -182,7 +179,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { for (outputDevice in outputDevices) { Log.d( TAG, - "available output device in listener:${outputDevice.type}" + "available output device in listener:${outputDevice.type}", ) if (outputDevice.type == AudioDeviceInfo.TYPE_HEARING_AID) { val result = router.setPreferredDevice(outputDevice) @@ -196,7 +193,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { audioTrack!!.addOnRoutingChangedListener( audioRoutingListener, - Handler(Looper.getMainLooper()) + Handler(Looper.getMainLooper()), ) awaitClose { audioTrack!!.removeOnRoutingChangedListener(audioRoutingListener) } } @@ -206,7 +203,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { audioManager.setStreamVolume( AudioManager.STREAM_MUSIC, minVolume, - AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_SHOW_UI, ) StartResponse.getDefaultInstance() @@ -244,7 +241,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { audioManager.setStreamVolume( AudioManager.STREAM_MUSIC, maxVolume, - AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_SHOW_UI, ) } } @@ -261,10 +258,12 @@ class Asha(val context: Context) : AshaImplBase(), Closeable { ) } } + override fun onError(t: Throwable?) { Log.e(TAG, t.toString()) responseObserver.onError(t) } + override fun onCompleted() { Log.i(TAG, "onCompleted") responseObserver.onNext(PlaybackAudioResponse.getDefaultInstance()) diff --git a/android/pandora/server/src/GattInstance.kt b/android/pandora/server/src/GattInstance.kt index 655668c9a8..770f63c940 100644 --- a/android/pandora/server/src/GattInstance.kt +++ b/android/pandora/server/src/GattInstance.kt @@ -22,7 +22,8 @@ import android.bluetooth.BluetoothGattCallback import android.bluetooth.BluetoothGattCharacteristic import android.bluetooth.BluetoothGattDescriptor import android.bluetooth.BluetoothGattService -import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.bluetooth.BluetoothStatusCodes import android.content.Context import android.util.Log @@ -39,7 +40,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte public val mGatt: BluetoothGatt private var mServiceDiscovered = MutableStateFlow(false) - private var mConnectionState = MutableStateFlow(BluetoothProfile.STATE_DISCONNECTED) + private var mConnectionState = MutableStateFlow(STATE_DISCONNECTED) private var mValuesRead = MutableStateFlow(0) private var mValueWrote = MutableStateFlow(false) private var mOnCharacteristicChanged = MutableStateFlow(false) @@ -55,26 +56,31 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte var uuid: UUID?, var handle: Int, var value: ByteString?, - var status: AttStatusCode + var status: AttStatusCode, ) {} + private var mGattInstanceValuesRead = arrayListOf<GattInstanceValueRead>() class GattInstanceValueWrote(var uuid: UUID?, var handle: Int, var status: AttStatusCode) {} + private var mGattInstanceValueWrote = GattInstanceValueWrote(null, 0, AttStatusCode.UNKNOWN_ERROR) companion object GattManager { val gattInstances: MutableMap<String, GattInstance> = mutableMapOf<String, GattInstance>() + fun get(address: String): GattInstance { val instance = gattInstances.get(address) requireNotNull(instance) { "Unable to find GATT instance for $address" } return instance } + fun get(address: ByteString): GattInstance { val instance = gattInstances.get(address.toByteArray().decodeToString()) requireNotNull(instance) { "Unable to find GATT instance for $address" } return instance } + fun clearAllInstances() { gattInstances.clear() } @@ -85,11 +91,11 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte override fun onConnectionStateChange( bluetoothGatt: BluetoothGatt, status: Int, - newState: Int + newState: Int, ) { Log.i(TAG, "$mDevice connection state changed to $newState") mConnectionState.value = newState - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { gattInstances.remove(mDevice.address) } } @@ -105,7 +111,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte bluetoothGatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, value: ByteArray, - status: Int + status: Int, ) { Log.i(TAG, "onCharacteristicRead, status: $status") for (gattInstanceValueRead: GattInstanceValueRead in mGattInstanceValuesRead) { @@ -124,7 +130,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte bluetoothGatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, status: Int, - value: ByteArray + value: ByteArray, ) { Log.i(TAG, "onDescriptorRead, status: $status") for (gattInstanceValueRead: GattInstanceValueRead in mGattInstanceValuesRead) { @@ -142,7 +148,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte override fun onCharacteristicWrite( bluetoothGatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, - status: Int + status: Int, ) { Log.i(TAG, "onCharacteristicWrite, status: $status") mGattInstanceValueWrote.status = AttStatusCode.forNumber(status) @@ -152,7 +158,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte override fun onDescriptorWrite( bluetoothGatt: BluetoothGatt, descriptor: BluetoothGattDescriptor, - status: Int + status: Int, ) { Log.i(TAG, "onDescriptorWrite, status: $status") mGattInstanceValueWrote.status = AttStatusCode.forNumber(status) @@ -162,12 +168,12 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte override fun onCharacteristicChanged( bluetoothGatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic, - value: ByteArray + value: ByteArray, ) { Log.i( TAG, "onCharacteristicChanged, characteristic: " + - characteristic.getUuid().toString().uppercase() + characteristic.getUuid().toString().uppercase(), ) mCharacteristicChangedMap[characteristic] = true mOnCharacteristicChanged.value = true @@ -189,11 +195,11 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte } public fun isConnected(): Boolean { - return mConnectionState.value == BluetoothProfile.STATE_CONNECTED + return mConnectionState.value == STATE_CONNECTED } public fun isDisconnected(): Boolean { - return mConnectionState.value == BluetoothProfile.STATE_DISCONNECTED + return mConnectionState.value == STATE_DISCONNECTED } public fun isBonded(): Boolean { @@ -259,7 +265,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte characteristic.getUuid(), characteristic.getInstanceId(), ByteString.EMPTY, - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) ) if (mGatt.readCharacteristic(characteristic)) { @@ -272,7 +278,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte public suspend fun readCharacteristicUuidBlocking( uuid: UUID, startHandle: Int, - endHandle: Int + endHandle: Int, ): ArrayList<GattInstanceValueRead> { mGattInstanceValuesRead = arrayListOf() // Init mGattInstanceValuesRead with characteristics values. @@ -288,14 +294,14 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte uuid, characteristic.getInstanceId(), ByteString.EMPTY, - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) ) check( mGatt.readUsingCharacteristicUuid( uuid, characteristic.getInstanceId(), - characteristic.getInstanceId() + characteristic.getInstanceId(), ) ) waitForValuesRead() @@ -314,7 +320,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte uuid, startHandle, ByteString.EMPTY, - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) ) mGatt.readUsingCharacteristicUuid(uuid, startHandle, endHandle) @@ -332,7 +338,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte descriptor.getUuid(), descriptor.getInstanceId(), ByteString.EMPTY, - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) ) if (mGatt.readDescriptor(descriptor)) { @@ -344,18 +350,18 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte public suspend fun writeCharacteristicBlocking( characteristic: BluetoothGattCharacteristic, - value: ByteArray + value: ByteArray, ): GattInstanceValueWrote { GattInstanceValueWrote( characteristic.getUuid(), characteristic.getInstanceId(), - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) if ( mGatt.writeCharacteristic( characteristic, value, - BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT + BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT, ) == BluetoothStatusCodes.SUCCESS ) { waitForWriteEnd() @@ -365,12 +371,12 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte public suspend fun writeDescriptorBlocking( descriptor: BluetoothGattDescriptor, - value: ByteArray + value: ByteArray, ): GattInstanceValueWrote { GattInstanceValueWrote( descriptor.getUuid(), descriptor.getInstanceId(), - AttStatusCode.UNKNOWN_ERROR + AttStatusCode.UNKNOWN_ERROR, ) if (mGatt.writeDescriptor(descriptor, value) == BluetoothStatusCodes.SUCCESS) { waitForWriteEnd() diff --git a/android/pandora/server/src/Hap.kt b/android/pandora/server/src/Hap.kt index 416879b46c..ddecaeb773 100644 --- a/android/pandora/server/src/Hap.kt +++ b/android/pandora/server/src/Hap.kt @@ -26,6 +26,7 @@ import android.bluetooth.BluetoothLeAudio import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED +import android.bluetooth.BluetoothProfile.STATE_CONNECTED import android.content.Context import android.content.IntentFilter import android.media.AudioManager @@ -381,14 +382,14 @@ class Hap(val context: Context) : HAPImplBase(), Closeable { grpcUnary<Empty>(scope, responseObserver) { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.i(TAG, "waitPeripheral(${device}") - if (bluetoothHapClient.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (bluetoothHapClient.getConnectionState(device) != STATE_CONNECTED) { Log.d(TAG, "Manual call to setConnectionPolicy") bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED) Log.d(TAG, "now waiting for bluetoothHapClient profile connection") flow .filter { it.getBluetoothDeviceExtra() == device } .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { it == BluetoothProfile.STATE_CONNECTED } + .filter { it == STATE_CONNECTED } .first() } diff --git a/android/pandora/server/src/Hfp.kt b/android/pandora/server/src/Hfp.kt index 65f552463b..850d650256 100644 --- a/android/pandora/server/src/Hfp.kt +++ b/android/pandora/server/src/Hfp.kt @@ -21,6 +21,8 @@ import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothHeadset import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -92,7 +94,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { grpcUnary<Empty>(scope, responseObserver) { val device = request.connection.toBluetoothDevice(bluetoothAdapter) - bluetoothHfp.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED) + bluetoothHfp.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED) Empty.getDefaultInstance() } @@ -102,7 +104,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { grpcUnary<Empty>(scope, responseObserver) { val device = request.connection.toBluetoothDevice(bluetoothAdapter) - bluetoothHfp.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) + bluetoothHfp.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN) Empty.getDefaultInstance() } @@ -136,7 +138,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { grpcUnary(scope, responseObserver) { when (request.audioPath!!) { AudioPath.AUDIO_PATH_UNKNOWN, - AudioPath.UNRECOGNIZED, -> {} + AudioPath.UNRECOGNIZED -> {} AudioPath.AUDIO_PATH_HANDSFREE -> { check(bluetoothHfp.getActiveDevice() != null) inCallService.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH) @@ -195,7 +197,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { override fun makeCall( request: MakeCallRequest, - responseObserver: StreamObserver<MakeCallResponse> + responseObserver: StreamObserver<MakeCallResponse>, ) { grpcUnary(scope, responseObserver) { telecomManager.placeCall(Uri.fromParts("tel", request.number, null), Bundle()) @@ -205,7 +207,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { override fun setVoiceRecognition( request: SetVoiceRecognitionRequest, - responseObserver: StreamObserver<SetVoiceRecognitionResponse> + responseObserver: StreamObserver<SetVoiceRecognitionResponse>, ) { grpcUnary(scope, responseObserver) { if (request.enabled) { @@ -223,7 +225,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable { override fun clearCallHistory( request: ClearCallHistoryRequest, - responseObserver: StreamObserver<ClearCallHistoryResponse> + responseObserver: StreamObserver<ClearCallHistoryResponse>, ) { grpcUnary(scope, responseObserver) { context.contentResolver.delete(CallLog.Calls.CONTENT_URI, null, null) diff --git a/android/pandora/server/src/HfpHandsfree.kt b/android/pandora/server/src/HfpHandsfree.kt index 5571407dd4..77b0c957da 100644 --- a/android/pandora/server/src/HfpHandsfree.kt +++ b/android/pandora/server/src/HfpHandsfree.kt @@ -21,6 +21,8 @@ import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothHeadsetClient import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -68,12 +70,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun answerCallAsHandsfree( request: AnswerCallAsHandsfreeRequest, - responseObserver: StreamObserver<AnswerCallAsHandsfreeResponse> + responseObserver: StreamObserver<AnswerCallAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.acceptCall( request.connection.toBluetoothDevice(bluetoothAdapter), - BluetoothHeadsetClient.CALL_ACCEPT_NONE + BluetoothHeadsetClient.CALL_ACCEPT_NONE, ) AnswerCallAsHandsfreeResponse.getDefaultInstance() } @@ -81,7 +83,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun endCallAsHandsfree( request: EndCallAsHandsfreeRequest, - responseObserver: StreamObserver<EndCallAsHandsfreeResponse> + responseObserver: StreamObserver<EndCallAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { for (call in @@ -90,7 +92,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { )) { bluetoothHfpClient.terminateCall( request.connection.toBluetoothDevice(bluetoothAdapter), - call + call, ) } EndCallAsHandsfreeResponse.getDefaultInstance() @@ -99,7 +101,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun declineCallAsHandsfree( request: DeclineCallAsHandsfreeRequest, - responseObserver: StreamObserver<DeclineCallAsHandsfreeResponse> + responseObserver: StreamObserver<DeclineCallAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.rejectCall(request.connection.toBluetoothDevice(bluetoothAdapter)) @@ -109,7 +111,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun connectToAudioAsHandsfree( request: ConnectToAudioAsHandsfreeRequest, - responseObserver: StreamObserver<ConnectToAudioAsHandsfreeResponse> + responseObserver: StreamObserver<ConnectToAudioAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.connectAudio(request.connection.toBluetoothDevice(bluetoothAdapter)) @@ -119,7 +121,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun disconnectFromAudioAsHandsfree( request: DisconnectFromAudioAsHandsfreeRequest, - responseObserver: StreamObserver<DisconnectFromAudioAsHandsfreeResponse> + responseObserver: StreamObserver<DisconnectFromAudioAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.disconnectAudio( @@ -131,12 +133,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun makeCallAsHandsfree( request: MakeCallAsHandsfreeRequest, - responseObserver: StreamObserver<MakeCallAsHandsfreeResponse> + responseObserver: StreamObserver<MakeCallAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.dial( request.connection.toBluetoothDevice(bluetoothAdapter), - request.number + request.number, ) MakeCallAsHandsfreeResponse.getDefaultInstance() } @@ -144,7 +146,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun callTransferAsHandsfree( request: CallTransferAsHandsfreeRequest, - responseObserver: StreamObserver<CallTransferAsHandsfreeResponse> + responseObserver: StreamObserver<CallTransferAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.explicitCallTransfer( @@ -156,12 +158,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun enableSlcAsHandsfree( request: EnableSlcAsHandsfreeRequest, - responseObserver: StreamObserver<Empty> + responseObserver: StreamObserver<Empty>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.setConnectionPolicy( request.connection.toBluetoothDevice(bluetoothAdapter), - BluetoothProfile.CONNECTION_POLICY_ALLOWED + CONNECTION_POLICY_ALLOWED, ) Empty.getDefaultInstance() } @@ -169,12 +171,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun disableSlcAsHandsfree( request: DisableSlcAsHandsfreeRequest, - responseObserver: StreamObserver<Empty> + responseObserver: StreamObserver<Empty>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.setConnectionPolicy( request.connection.toBluetoothDevice(bluetoothAdapter), - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN + CONNECTION_POLICY_FORBIDDEN, ) Empty.getDefaultInstance() } @@ -182,7 +184,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun setVoiceRecognitionAsHandsfree( request: SetVoiceRecognitionAsHandsfreeRequest, - responseObserver: StreamObserver<SetVoiceRecognitionAsHandsfreeResponse> + responseObserver: StreamObserver<SetVoiceRecognitionAsHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { if (request.enabled) { @@ -200,12 +202,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable { override fun sendDtmfFromHandsfree( request: SendDtmfFromHandsfreeRequest, - responseObserver: StreamObserver<SendDtmfFromHandsfreeResponse> + responseObserver: StreamObserver<SendDtmfFromHandsfreeResponse>, ) { grpcUnary(scope, responseObserver) { bluetoothHfpClient.sendDTMF( request.connection.toBluetoothDevice(bluetoothAdapter), - request.code.toByte() + request.code.toByte(), ) SendDtmfFromHandsfreeResponse.getDefaultInstance() } diff --git a/android/pandora/server/src/Host.kt b/android/pandora/server/src/Host.kt index 196d87952a..c4243015f6 100644 --- a/android/pandora/server/src/Host.kt +++ b/android/pandora/server/src/Host.kt @@ -25,7 +25,7 @@ import android.bluetooth.BluetoothDevice.BOND_NONE import android.bluetooth.BluetoothDevice.TRANSPORT_BREDR import android.bluetooth.BluetoothDevice.TRANSPORT_LE import android.bluetooth.BluetoothManager -import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.STATE_CONNECTED import android.bluetooth.BluetoothUuid import android.bluetooth.le.AdvertiseCallback import android.bluetooth.le.AdvertiseData @@ -400,7 +400,7 @@ class Host( } catch (e: Exception) { Log.w(TAG, "Gatt instance doesn't exist. Android might be peripheral") val instance = GattInstance(bluetoothDevice, TRANSPORT_LE, context) - instance.waitForState(BluetoothProfile.STATE_CONNECTED) + instance.waitForState(STATE_CONNECTED) instance } if (gattInstance.isDisconnected()) { @@ -452,8 +452,7 @@ class Host( val bluetoothDevice = bluetoothAdapter.getRemoteLeDevice(address.decodeAsMacAddressToString(), type) initiatedConnection.add(bluetoothDevice) - GattInstance(bluetoothDevice, TRANSPORT_LE, context) - .waitForState(BluetoothProfile.STATE_CONNECTED) + GattInstance(bluetoothDevice, TRANSPORT_LE, context).waitForState(STATE_CONNECTED) ConnectLEResponse.newBuilder() .setConnection(bluetoothDevice.toConnection(TRANSPORT_LE)) .build() diff --git a/android/pandora/server/src/LeAudio.kt b/android/pandora/server/src/LeAudio.kt index 4abbb993fb..7e7e7e6147 100644 --- a/android/pandora/server/src/LeAudio.kt +++ b/android/pandora/server/src/LeAudio.kt @@ -20,6 +20,8 @@ import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothLeAudio import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.content.Context import android.content.Intent import android.content.IntentFilter @@ -73,7 +75,7 @@ class LeAudio(val context: Context) : LeAudioImplBase(), Closeable { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.i(TAG, "open: device=$device") - if (bluetoothLeAudio.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) { + if (bluetoothLeAudio.getConnectionState(device) != STATE_CONNECTED) { bluetoothLeAudio.connect(device) val state = flow @@ -85,13 +87,10 @@ class LeAudio(val context: Context) : LeAudioImplBase(), Closeable { .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { - it == BluetoothProfile.STATE_CONNECTED || - it == BluetoothProfile.STATE_DISCONNECTED - } + .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED } .first() - if (state == BluetoothProfile.STATE_DISCONNECTED) { + if (state == STATE_DISCONNECTED) { throw RuntimeException("open failed, LE_AUDIO has been disconnected") } } diff --git a/android/pandora/server/src/Pan.kt b/android/pandora/server/src/Pan.kt index b24287fa15..62334af83b 100644 --- a/android/pandora/server/src/Pan.kt +++ b/android/pandora/server/src/Pan.kt @@ -20,6 +20,7 @@ import android.bluetooth.BluetoothDevice.TRANSPORT_BREDR import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothPan import android.bluetooth.BluetoothProfile +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED import android.content.Context import android.net.TetheringManager import android.net.TetheringManager.TETHERING_BLUETOOTH @@ -72,7 +73,7 @@ class Pan(private val context: Context) : PANImplBase(), Closeable { override fun enableTethering( request: EnableTetheringRequest, - responseObserver: StreamObserver<EnableTetheringResponse> + responseObserver: StreamObserver<EnableTetheringResponse>, ) { grpcUnary<EnableTetheringResponse>(mScope, responseObserver) { Log.i(TAG, "enableTethering") @@ -80,7 +81,7 @@ class Pan(private val context: Context) : PANImplBase(), Closeable { mTetheringManager.startTethering( TETHERING_BLUETOOTH, Executors.newSingleThreadExecutor(), - mStartTetheringCallback + mStartTetheringCallback, ) mTetheringEnabled.first { it == true } } @@ -90,12 +91,12 @@ class Pan(private val context: Context) : PANImplBase(), Closeable { override fun connectPan( request: ConnectPanRequest, - responseObserver: StreamObserver<ConnectPanResponse> + responseObserver: StreamObserver<ConnectPanResponse>, ) { grpcUnary<ConnectPanResponse>(mScope, responseObserver) { Log.i(TAG, "connectPan") val device = request.address.toBluetoothDevice(bluetoothAdapter) - bluetoothPan.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED) + bluetoothPan.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED) bluetoothPan.connect(device) ConnectPanResponse.newBuilder() .setConnection(device.toConnection(TRANSPORT_BREDR)) diff --git a/android/pandora/server/src/Vcp.kt b/android/pandora/server/src/Vcp.kt index e1b6aa2b1c..6f19685bec 100644 --- a/android/pandora/server/src/Vcp.kt +++ b/android/pandora/server/src/Vcp.kt @@ -20,6 +20,7 @@ import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothProfile import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED +import android.bluetooth.BluetoothProfile.STATE_CONNECTED import android.bluetooth.BluetoothVolumeControl import android.content.Context import android.content.IntentFilter @@ -99,17 +100,14 @@ class Vcp(val context: Context) : VCPImplBase(), Closeable { grpcUnary<Empty>(scope, responseObserver) { val device = request.connection.toBluetoothDevice(bluetoothAdapter) Log.i(TAG, "waitPeripheral(${device}") - if ( - bluetoothVolumeControl.getConnectionState(device) != - BluetoothProfile.STATE_CONNECTED - ) { + if (bluetoothVolumeControl.getConnectionState(device) != STATE_CONNECTED) { Log.d(TAG, "Manual call to setConnectionPolicy") bluetoothVolumeControl.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED) Log.d(TAG, "wait for bluetoothVolumeControl profile connection") flow .filter { it.getBluetoothDeviceExtra() == device } .map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) } - .filter { it == BluetoothProfile.STATE_CONNECTED } + .filter { it == STATE_CONNECTED } .first() } diff --git a/apex/OWNERS b/apex/OWNERS index f05027c972..cc88477d0e 100644 --- a/apex/OWNERS +++ b/apex/OWNERS @@ -1,5 +1,4 @@ # Reviewers for /apex -eruffieux@google.com wescande@google.com diff --git a/flags/hfp.aconfig b/flags/hfp.aconfig index c0c799f315..473c52cdfd 100644 --- a/flags/hfp.aconfig +++ b/flags/hfp.aconfig @@ -15,12 +15,6 @@ flag { bug: "315234036" } -flag { - name: "retry_esco_with_zero_retransmission_effort" - namespace: "bluetooth" - description: "retry eSCO connection based on retransmission_effort" - bug: "316498257" -} flag { name: "hfp_software_datapath" diff --git a/flags/leaudio.aconfig b/flags/leaudio.aconfig index 0e5cce8f03..4535d65a98 100644 --- a/flags/leaudio.aconfig +++ b/flags/leaudio.aconfig @@ -86,16 +86,6 @@ flag { } flag { - name: "leaudio_broadcast_volume_control_with_set_volume" - namespace: "bluetooth" - description: "Set broadcast sink volume with setVolume API" - bug: "333761969" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { name: "run_clock_recovery_in_worker_thread" namespace: "bluetooth" description: "Fix thread ownership issue in clock_recovery" diff --git a/flags/opp.aconfig b/flags/opp.aconfig index 44dbfaf08f..73604961fe 100644 --- a/flags/opp.aconfig +++ b/flags/opp.aconfig @@ -34,7 +34,7 @@ flag { flag { name: "opp_remove_empty_group_notification" namespace: "bluetooth" - description: "Fix that group summary notification doesn't go away when all children are gone." + description: "As a solution of removing empty group notification, don't use group summary anymore" bug: "395546332" metadata { purpose: PURPOSE_BUGFIX diff --git a/flags/pairing.aconfig b/flags/pairing.aconfig index 5515e82d17..22f5d2b3d0 100644 --- a/flags/pairing.aconfig +++ b/flags/pairing.aconfig @@ -270,3 +270,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "auto_transport_pairing" + namespace: "bluetooth" + description: "Fix transport selection for auto transport pairing" + bug: "398329326" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/framework/java/android/bluetooth/BluetoothA2dp.java b/framework/java/android/bluetooth/BluetoothA2dp.java index da949d94d3..353365e6ef 100644 --- a/framework/java/android/bluetooth/BluetoothA2dp.java +++ b/framework/java/android/bluetooth/BluetoothA2dp.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.IntDef; import android.annotation.NonNull; @@ -446,7 +449,7 @@ public final class BluetoothA2dp implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -562,8 +565,8 @@ public final class BluetoothA2dp implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -618,7 +621,7 @@ public final class BluetoothA2dp implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** @@ -1093,38 +1096,12 @@ public final class BluetoothA2dp implements BluetoothProfile { return false; } - /** - * Helper for converting a state to a string. - * - * <p>For debug use only - strings are not internationalized. - * - * @hide - */ - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) - public static String stateToString(int state) { - switch (state) { - case STATE_DISCONNECTED: - return "disconnected"; - case STATE_CONNECTING: - return "connecting"; - case STATE_CONNECTED: - return "connected"; - case STATE_DISCONNECTING: - return "disconnecting"; - case STATE_PLAYING: - return "playing"; - case STATE_NOT_PLAYING: - return "not playing"; - default: - return "<unknown state " + state + ">"; - } - } - private boolean isEnabled() { if (mAdapter.getState() == BluetoothAdapter.STATE_ON) return true; return false; } + @SuppressWarnings("MethodCanBeStatic") private void verifyDeviceNotNull(BluetoothDevice device, String methodName) { if (device == null) { Log.e(TAG, methodName + ": device param is null"); @@ -1132,7 +1109,7 @@ public final class BluetoothA2dp implements BluetoothProfile { } } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothA2dpSink.java b/framework/java/android/bluetooth/BluetoothA2dpSink.java index 1cd9c6a5cb..c49bc1ea7a 100644 --- a/framework/java/android/bluetooth/BluetoothA2dpSink.java +++ b/framework/java/android/bluetooth/BluetoothA2dpSink.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -266,7 +269,7 @@ public final class BluetoothA2dpSink implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -338,8 +341,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -392,7 +395,7 @@ public final class BluetoothA2dpSink implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** @@ -421,32 +424,6 @@ public final class BluetoothA2dpSink implements BluetoothProfile { return false; } - /** - * Helper for converting a state to a string. - * - * <p>For debug use only - strings are not internationalized. - * - * @hide - */ - public static String stateToString(int state) { - switch (state) { - case STATE_DISCONNECTED: - return "disconnected"; - case STATE_CONNECTING: - return "connecting"; - case STATE_CONNECTED: - return "connected"; - case STATE_DISCONNECTING: - return "disconnecting"; - case BluetoothA2dp.STATE_PLAYING: - return "playing"; - case BluetoothA2dp.STATE_NOT_PLAYING: - return "not playing"; - default: - return "<unknown state " + state + ">"; - } - } - private boolean isEnabled() { return mAdapter.getState() == BluetoothAdapter.STATE_ON; } diff --git a/framework/java/android/bluetooth/BluetoothAdapter.java b/framework/java/android/bluetooth/BluetoothAdapter.java index 1d8bc20493..8f2edc546d 100644 --- a/framework/java/android/bluetooth/BluetoothAdapter.java +++ b/framework/java/android/bluetooth/BluetoothAdapter.java @@ -24,6 +24,9 @@ import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.BLUETOOTH_SCAN; import static android.Manifest.permission.LOCAL_MAC_ADDRESS; import static android.Manifest.permission.MODIFY_PHONE_STATE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN; import static android.bluetooth.BluetoothProfile.getProfileName; import static android.bluetooth.BluetoothStatusCodes.FEATURE_NOT_SUPPORTED; import static android.bluetooth.BluetoothUtils.executeFromBinder; @@ -3337,7 +3340,7 @@ public final class BluetoothAdapter { @RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) - private BluetoothServerSocket createNewRfcommSocketAndRecord( + private static BluetoothServerSocket createNewRfcommSocketAndRecord( String name, UUID uuid, boolean auth, boolean encrypt) throws IOException { BluetoothServerSocket socket; socket = @@ -4048,7 +4051,7 @@ public final class BluetoothAdapter { } } - private Set<BluetoothDevice> toDeviceSet(List<BluetoothDevice> devices) { + private static Set<BluetoothDevice> toDeviceSet(List<BluetoothDevice> devices) { Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(devices); return Collections.unmodifiableSet(deviceSet); } @@ -5560,16 +5563,16 @@ public final class BluetoothAdapter { public static @ConnectionPolicy int priorityToConnectionPolicy(int priority) { switch (priority) { case BluetoothProfile.PRIORITY_AUTO_CONNECT: - return BluetoothProfile.CONNECTION_POLICY_ALLOWED; + return CONNECTION_POLICY_ALLOWED; case BluetoothProfile.PRIORITY_ON: - return BluetoothProfile.CONNECTION_POLICY_ALLOWED; + return CONNECTION_POLICY_ALLOWED; case BluetoothProfile.PRIORITY_OFF: - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; case BluetoothProfile.PRIORITY_UNDEFINED: - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; default: Log.e(TAG, "setPriority: Invalid priority: " + priority); - return BluetoothProfile.CONNECTION_POLICY_UNKNOWN; + return CONNECTION_POLICY_UNKNOWN; } } @@ -5582,11 +5585,11 @@ public final class BluetoothAdapter { */ public static int connectionPolicyToPriority(@ConnectionPolicy int connectionPolicy) { switch (connectionPolicy) { - case BluetoothProfile.CONNECTION_POLICY_ALLOWED: + case CONNECTION_POLICY_ALLOWED: return BluetoothProfile.PRIORITY_ON; - case BluetoothProfile.CONNECTION_POLICY_FORBIDDEN: + case CONNECTION_POLICY_FORBIDDEN: return BluetoothProfile.PRIORITY_OFF; - case BluetoothProfile.CONNECTION_POLICY_UNKNOWN: + case CONNECTION_POLICY_UNKNOWN: return BluetoothProfile.PRIORITY_UNDEFINED; } return BluetoothProfile.PRIORITY_UNDEFINED; @@ -5807,7 +5810,8 @@ public final class BluetoothAdapter { } @RequiresPermission(BLUETOOTH_PRIVILEGED) - void unregisterFromService(IBluetooth service, IBluetoothHciVendorSpecificCallback stub) { + static void unregisterFromService( + IBluetooth service, IBluetoothHciVendorSpecificCallback stub) { if (service == null) { return; } diff --git a/framework/java/android/bluetooth/BluetoothAvrcpController.java b/framework/java/android/bluetooth/BluetoothAvrcpController.java index 8ced189723..bb8390f559 100644 --- a/framework/java/android/bluetooth/BluetoothAvrcpController.java +++ b/framework/java/android/bluetooth/BluetoothAvrcpController.java @@ -17,6 +17,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.RequiresNoPermission; import android.annotation.RequiresPermission; @@ -194,7 +195,7 @@ public final class BluetoothAvrcpController implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** diff --git a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java index 059e791bea..abec916a24 100644 --- a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java +++ b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.executeFromBinder; import static java.util.Objects.requireNonNull; @@ -444,7 +447,7 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -471,8 +474,8 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -508,7 +511,7 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } private boolean isEnabled() { diff --git a/framework/java/android/bluetooth/BluetoothDevice.java b/framework/java/android/bluetooth/BluetoothDevice.java index 0c3f4288e6..8c053201e9 100644 --- a/framework/java/android/bluetooth/BluetoothDevice.java +++ b/framework/java/android/bluetooth/BluetoothDevice.java @@ -896,8 +896,7 @@ public final class BluetoothDevice implements Parcelable, Attributable { * * @hide */ - @SystemApi - public static final int METADATA_EXCLUSIVE_MANAGER = 29; + @SystemApi public static final int METADATA_EXCLUSIVE_MANAGER = 29; private static final int METADATA_MAX_KEY = METADATA_EXCLUSIVE_MANAGER; @@ -1727,8 +1726,8 @@ public final class BluetoothDevice implements Parcelable, Attributable { /** * Returns the identity address and identity address type of this BluetoothDevice. An identity - * address is a public or static random Bluetooth LE device address that serves as a - * unique identifier. + * address is a public or static random Bluetooth LE device address that serves as a unique + * identifier. * * @return a {@link BluetoothAddress} containing identity address and identity address type. If * Bluetooth is not enabled or identity address type is not available, it will return a @@ -3791,6 +3790,31 @@ public final class BluetoothDevice implements Parcelable, Attributable { return true; } + /** + * Get the number of times {@link ACTION_KEY_MISSING} intent is thrown for this device since + * last successful encrypted connection + * + * @return number of times {@link ACTION_KEY_MISSING} intent is thrown for this device since + * last successful encrypted connection + * + * @hide + */ + @RequiresPermission(BLUETOOTH_CONNECT) + public int getKeyMissingCount() { + final IBluetooth service = getService(); + if (service == null || !isBluetoothEnabled()) { + Log.e(TAG, "Bluetooth is not enabled. Cannot get key missing counter."); + if (DBG) log(Log.getStackTraceString(new Throwable())); + } else { + try { + return service.getKeyMissingCount(this, mAttributionSource); + } catch (RemoteException e) { + Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); + } + } + return -1; + } + private static void log(String msg) { Log.d(TAG, msg); } diff --git a/framework/java/android/bluetooth/BluetoothGatt.java b/framework/java/android/bluetooth/BluetoothGatt.java index 3e3f3a207c..1ef8d2add6 100644 --- a/framework/java/android/bluetooth/BluetoothGatt.java +++ b/framework/java/android/bluetooth/BluetoothGatt.java @@ -18,6 +18,8 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.logRemoteException; import android.annotation.IntDef; @@ -268,7 +270,7 @@ public final class BluetoothGatt implements BluetoothProfile { callback.onConnectionStateChange( BluetoothGatt.this, GATT_FAILURE, - BluetoothProfile.STATE_DISCONNECTED); + STATE_DISCONNECTED); } } }); @@ -385,10 +387,7 @@ public final class BluetoothGatt implements BluetoothProfile { if (!address.equals(mDevice.getAddress())) { return; } - int profileState = - connected - ? BluetoothProfile.STATE_CONNECTED - : BluetoothProfile.STATE_DISCONNECTED; + int profileState = connected ? STATE_CONNECTED : STATE_DISCONNECTED; if (Flags.unregisterGattClientDisconnected() && !connected && !mAutoConnect) { unregisterApp(); diff --git a/framework/java/android/bluetooth/BluetoothGattCharacteristic.java b/framework/java/android/bluetooth/BluetoothGattCharacteristic.java index 9d7a95236b..15aebc083d 100644 --- a/framework/java/android/bluetooth/BluetoothGattCharacteristic.java +++ b/framework/java/android/bluetooth/BluetoothGattCharacteristic.java @@ -681,29 +681,29 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Returns the size of a give value type. */ - private int getTypeLen(int formatType) { + private static int getTypeLen(int formatType) { return formatType & 0xF; } /** Convert a signed byte to an unsigned int. */ - private int unsignedByteToInt(byte b) { + private static int unsignedByteToInt(byte b) { return b & 0xFF; } /** Convert signed bytes to a 16-bit unsigned int. */ - private int unsignedBytesToInt(byte b0, byte b1) { + private static int unsignedBytesToInt(byte b0, byte b1) { return (unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8)); } /** Convert signed bytes to a 32-bit unsigned int. */ - private int unsignedBytesToInt(byte b0, byte b1, byte b2, byte b3) { + private static int unsignedBytesToInt(byte b0, byte b1, byte b2, byte b3) { return (unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8)) + (unsignedByteToInt(b2) << 16) + (unsignedByteToInt(b3) << 24); } /** Convert signed bytes to a 16-bit short float value. */ - private float bytesToFloat(byte b0, byte b1) { + private static float bytesToFloat(byte b0, byte b1) { int mantissa = unsignedToSigned(unsignedByteToInt(b0) + ((unsignedByteToInt(b1) & 0x0F) << 8), 12); int exponent = unsignedToSigned(unsignedByteToInt(b1) >> 4, 4); @@ -711,7 +711,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert signed bytes to a 32-bit short float value. */ - private float bytesToFloat(byte b0, byte b1, byte b2, byte b3) { + private static float bytesToFloat(byte b0, byte b1, byte b2, byte b3) { int mantissa = unsignedToSigned( unsignedByteToInt(b0) @@ -722,7 +722,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert an unsigned integer value to a two's-complement encoded signed value. */ - private int unsignedToSigned(int unsigned, int size) { + private static int unsignedToSigned(int unsigned, int size) { if ((unsigned & (1 << (size - 1))) != 0) { unsigned = -1 * ((1 << (size - 1)) - (unsigned & ((1 << (size - 1)) - 1))); } @@ -730,7 +730,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert an integer into the signed bits of a given length. */ - private int intToSignedBits(int i, int size) { + private static int intToSignedBits(int i, int size) { if (i < 0) { i = (1 << (size - 1)) + (i & ((1 << (size - 1)) - 1)); } diff --git a/framework/java/android/bluetooth/BluetoothGattServer.java b/framework/java/android/bluetooth/BluetoothGattServer.java index 34002052b4..3a86c1d7b3 100644 --- a/framework/java/android/bluetooth/BluetoothGattServer.java +++ b/framework/java/android/bluetooth/BluetoothGattServer.java @@ -17,6 +17,8 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.IntDef; import android.annotation.NonNull; @@ -122,9 +124,7 @@ public final class BluetoothGattServer implements BluetoothProfile { mCallback.onConnectionStateChange( mAdapter.getRemoteDevice(address), status, - connected - ? BluetoothProfile.STATE_CONNECTED - : BluetoothProfile.STATE_DISCONNECTED); + connected ? STATE_CONNECTED : STATE_DISCONNECTED); } catch (Exception ex) { Log.w(TAG, "Unhandled exception in callback", ex); } diff --git a/framework/java/android/bluetooth/BluetoothHapClient.java b/framework/java/android/bluetooth/BluetoothHapClient.java index c11249bc9e..1699c5bf02 100644 --- a/framework/java/android/bluetooth/BluetoothHapClient.java +++ b/framework/java/android/bluetooth/BluetoothHapClient.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.callServiceIfEnabled; import static java.util.Objects.requireNonNull; @@ -576,8 +579,8 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable requireNonNull(device); boolean defaultValue = false; if (!isValidDevice(device) - || (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + || (connectionPolicy != CONNECTION_POLICY_FORBIDDEN + && connectionPolicy != CONNECTION_POLICY_ALLOWED)) { return defaultValue; } return callServiceIfEnabled( @@ -599,7 +602,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable @RequiresBluetoothConnectPermission @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) public @ConnectionPolicy int getConnectionPolicy(@Nullable BluetoothDevice device) { - int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + int defaultValue = CONNECTION_POLICY_FORBIDDEN; if (!isValidDevice(device)) { return defaultValue; } @@ -661,7 +664,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable @Override @BluetoothProfile.BtProfileState public int getConnectionState(@NonNull BluetoothDevice device) { - int defaultValue = BluetoothProfile.STATE_DISCONNECTED; + int defaultValue = STATE_DISCONNECTED; if (!isValidDevice(device)) { return defaultValue; } @@ -1085,7 +1088,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable s -> s.setPresetNameForGroup(groupId, presetIndex, name, mAttributionSource)); } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHeadset.java b/framework/java/android/bluetooth/BluetoothHeadset.java index dc99736bbf..10f8f3f422 100644 --- a/framework/java/android/bluetooth/BluetoothHeadset.java +++ b/framework/java/android/bluetooth/BluetoothHeadset.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.MODIFY_PHONE_STATE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -547,7 +550,7 @@ public final class BluetoothHeadset implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -579,8 +582,8 @@ public final class BluetoothHeadset implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -635,7 +638,7 @@ public final class BluetoothHeadset implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** diff --git a/framework/java/android/bluetooth/BluetoothHeadsetClient.java b/framework/java/android/bluetooth/BluetoothHeadsetClient.java index 3ef33cb845..14cb62c960 100644 --- a/framework/java/android/bluetooth/BluetoothHeadsetClient.java +++ b/framework/java/android/bluetooth/BluetoothHeadsetClient.java @@ -17,6 +17,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -795,7 +798,7 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -822,8 +825,8 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -860,7 +863,7 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** diff --git a/framework/java/android/bluetooth/BluetoothHearingAid.java b/framework/java/android/bluetooth/BluetoothHearingAid.java index 29b00611d2..d5ed621a37 100644 --- a/framework/java/android/bluetooth/BluetoothHearingAid.java +++ b/framework/java/android/bluetooth/BluetoothHearingAid.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.IntDef; import android.annotation.NonNull; @@ -470,7 +473,7 @@ public final class BluetoothHearingAid implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -563,8 +566,8 @@ public final class BluetoothHearingAid implements BluetoothProfile { if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -601,29 +604,7 @@ public final class BluetoothHearingAid implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; - } - - /** - * Helper for converting a state to a string. - * - * <p>For debug use only - strings are not internationalized. - * - * @hide - */ - public static String stateToString(int state) { - switch (state) { - case STATE_DISCONNECTED: - return "disconnected"; - case STATE_CONNECTING: - return "connecting"; - case STATE_CONNECTED: - return "connected"; - case STATE_DISCONNECTING: - return "disconnecting"; - default: - return "<unknown state " + state + ">"; - } + return CONNECTION_POLICY_FORBIDDEN; } /** @@ -775,14 +756,14 @@ public final class BluetoothHearingAid implements BluetoothProfile { return false; } - private void verifyDeviceNotNull(BluetoothDevice device, String methodName) { + private static void verifyDeviceNotNull(BluetoothDevice device, String methodName) { if (device == null) { Log.e(TAG, methodName + ": device param is null"); throw new IllegalArgumentException("Device cannot be null"); } } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHidDevice.java b/framework/java/android/bluetooth/BluetoothHidDevice.java index 230b5dfaaa..3098c80fdd 100644 --- a/framework/java/android/bluetooth/BluetoothHidDevice.java +++ b/framework/java/android/bluetooth/BluetoothHidDevice.java @@ -18,6 +18,8 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothUtils.executeFromBinder; import android.annotation.NonNull; @@ -770,8 +772,8 @@ public final class BluetoothHidDevice implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -786,7 +788,7 @@ public final class BluetoothHidDevice implements BluetoothProfile { return false; } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHidHost.java b/framework/java/android/bluetooth/BluetoothHidHost.java index 6e9759b1e5..7b67a90862 100644 --- a/framework/java/android/bluetooth/BluetoothHidHost.java +++ b/framework/java/android/bluetooth/BluetoothHidHost.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -386,7 +389,7 @@ public final class BluetoothHidHost implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -441,8 +444,8 @@ public final class BluetoothHidHost implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -556,7 +559,7 @@ public final class BluetoothHidHost implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java index d71068308f..4cc3b604fb 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudio.java +++ b/framework/java/android/bluetooth/BluetoothLeAudio.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -972,7 +975,7 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -1291,8 +1294,8 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (mAdapter.isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -1328,32 +1331,10 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } - /** - * Helper for converting a state to a string. - * - * <p>For debug use only - strings are not internationalized. - * - * @hide - */ - public static String stateToString(int state) { - switch (state) { - case STATE_DISCONNECTED: - return "disconnected"; - case STATE_CONNECTING: - return "connecting"; - case STATE_CONNECTED: - return "connected"; - case STATE_DISCONNECTING: - return "disconnecting"; - default: - return "<unknown state " + state + ">"; - } - } - - private boolean isValidDevice(@Nullable BluetoothDevice device) { + private static boolean isValidDevice(@Nullable BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java index 0541d4898c..22453839cd 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java @@ -304,7 +304,7 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { out.writeInt(mMaxOctetsPerFrame); } - private String sampleRateToString(@SampleRate int sampleRateBit) { + private static String sampleRateToString(@SampleRate int sampleRateBit) { switch (sampleRateBit) { case SAMPLE_RATE_NONE: return "None"; @@ -339,7 +339,7 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { } } - private String frameDurationToString(@FrameDuration int frameDurationBit) { + private static String frameDurationToString(@FrameDuration int frameDurationBit) { switch (frameDurationBit) { case FRAME_DURATION_NONE: return "None"; diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java index 2997cba518..7089529638 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java @@ -128,7 +128,7 @@ public final class BluetoothLeAudioCodecStatus implements Parcelable { return c1.containsAll(c2); } - private boolean isCodecConfigSelectable( + private static boolean isCodecConfigSelectable( BluetoothLeAudioCodecConfig codecConfig, BluetoothLeAudioCodecConfig selectableConfig) { if (codecConfig.getCodecType() != selectableConfig.getCodecType()) { return false; diff --git a/framework/java/android/bluetooth/BluetoothLeBroadcast.java b/framework/java/android/bluetooth/BluetoothLeBroadcast.java index eb65dd0841..4023184fee 100644 --- a/framework/java/android/bluetooth/BluetoothLeBroadcast.java +++ b/framework/java/android/bluetooth/BluetoothLeBroadcast.java @@ -778,7 +778,7 @@ public final class BluetoothLeBroadcast implements AutoCloseable, BluetoothProfi mAdapter.closeProfileProxy(this); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode) { BluetoothLeBroadcastSubgroupSettings.Builder subgroupBuilder = new BluetoothLeBroadcastSubgroupSettings.Builder() diff --git a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java index a0ce14ade0..63ddb8a03a 100644 --- a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java +++ b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -582,7 +585,7 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au log("getConnectionState(" + sink + ")"); requireNonNull(sink); final IBluetoothLeBroadcastAssistant service = getService(); - final int defaultValue = BluetoothProfile.STATE_DISCONNECTED; + final int defaultValue = STATE_DISCONNECTED; if (service == null) { Log.w(TAG, "Proxy not attached to service"); if (DBG) log(Log.getStackTraceString(new Throwable())); @@ -677,8 +680,8 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (mBluetoothAdapter.isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -706,7 +709,7 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au log("getConnectionPolicy()"); requireNonNull(device); final IBluetoothLeBroadcastAssistant service = getService(); - final int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + final int defaultValue = CONNECTION_POLICY_FORBIDDEN; if (service == null) { Log.w(TAG, "Proxy not attached to service"); if (DBG) log(Log.getStackTraceString(new Throwable())); diff --git a/framework/java/android/bluetooth/BluetoothManager.java b/framework/java/android/bluetooth/BluetoothManager.java index 00522d4f89..4dce4c790b 100644 --- a/framework/java/android/bluetooth/BluetoothManager.java +++ b/framework/java/android/bluetooth/BluetoothManager.java @@ -17,6 +17,8 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -100,11 +102,11 @@ public final class BluetoothManager { List<BluetoothDevice> connectedDevices = getConnectedDevices(profile); for (BluetoothDevice connectedDevice : connectedDevices) { if (device.equals(connectedDevice)) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -123,8 +125,7 @@ public final class BluetoothManager { @RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) public List<BluetoothDevice> getConnectedDevices(int profile) { - return getDevicesMatchingConnectionStates( - profile, new int[] {BluetoothProfile.STATE_CONNECTED}); + return getDevicesMatchingConnectionStates(profile, new int[] {STATE_CONNECTED}); } /** diff --git a/framework/java/android/bluetooth/BluetoothMap.java b/framework/java/android/bluetooth/BluetoothMap.java index 2f079d1a90..f88ec35dbb 100644 --- a/framework/java/android/bluetooth/BluetoothMap.java +++ b/framework/java/android/bluetooth/BluetoothMap.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -426,7 +429,7 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -478,8 +481,8 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -540,7 +543,7 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } private static void log(String msg) { diff --git a/framework/java/android/bluetooth/BluetoothMapClient.java b/framework/java/android/bluetooth/BluetoothMapClient.java index 0f6700df80..2b28da9f0c 100644 --- a/framework/java/android/bluetooth/BluetoothMapClient.java +++ b/framework/java/android/bluetooth/BluetoothMapClient.java @@ -20,6 +20,9 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.RECEIVE_SMS; import static android.Manifest.permission.SEND_SMS; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.Nullable; @@ -395,7 +398,7 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -439,8 +442,8 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -493,7 +496,7 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } /** diff --git a/framework/java/android/bluetooth/BluetoothPan.java b/framework/java/android/bluetooth/BluetoothPan.java index 6ecdc6fa2a..43b1469407 100644 --- a/framework/java/android/bluetooth/BluetoothPan.java +++ b/framework/java/android/bluetooth/BluetoothPan.java @@ -20,6 +20,9 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.TETHER_PRIVILEGED; import static android.annotation.SystemApi.Client.MODULE_LIBRARIES; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.executeFromBinder; import static java.util.Objects.requireNonNull; @@ -380,8 +383,8 @@ public final class BluetoothPan implements BluetoothProfile { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -478,7 +481,7 @@ public final class BluetoothPan implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** diff --git a/framework/java/android/bluetooth/BluetoothPbap.java b/framework/java/android/bluetooth/BluetoothPbap.java index d4c1dfcc7a..ecbbe0ab23 100644 --- a/framework/java/android/bluetooth/BluetoothPbap.java +++ b/framework/java/android/bluetooth/BluetoothPbap.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -193,11 +196,11 @@ public class BluetoothPbap implements BluetoothProfile { if (service == null) { Log.w(TAG, "Proxy not attached to service"); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } catch (RemoteException e) { Log.e(TAG, e.toString()); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -252,8 +255,8 @@ public class BluetoothPbap implements BluetoothProfile { try { final IBluetoothPbap service = getService(); if (service != null && isEnabled() && isValidDevice(device)) { - if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) { + if (connectionPolicy != CONNECTION_POLICY_FORBIDDEN + && connectionPolicy != CONNECTION_POLICY_ALLOWED) { return false; } return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); @@ -297,7 +300,7 @@ public class BluetoothPbap implements BluetoothProfile { return false; } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothPbapClient.java b/framework/java/android/bluetooth/BluetoothPbapClient.java index 0969c688f7..4c0eff490b 100644 --- a/framework/java/android/bluetooth/BluetoothPbapClient.java +++ b/framework/java/android/bluetooth/BluetoothPbapClient.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -298,7 +301,7 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } private static void log(String msg) { @@ -356,8 +359,8 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -412,6 +415,6 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } } diff --git a/framework/java/android/bluetooth/BluetoothSap.java b/framework/java/android/bluetooth/BluetoothSap.java index 843b369be0..aa4686d30a 100644 --- a/framework/java/android/bluetooth/BluetoothSap.java +++ b/framework/java/android/bluetooth/BluetoothSap.java @@ -18,6 +18,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -424,7 +427,7 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -470,8 +473,8 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable { if (DBG) log(Log.getStackTraceString(new Throwable())); } else if (isEnabled() && isValidDevice(device) - && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN + || connectionPolicy == CONNECTION_POLICY_ALLOWED)) { try { return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource); } catch (RemoteException e) { @@ -526,7 +529,7 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + return CONNECTION_POLICY_FORBIDDEN; } private static void log(String msg) { diff --git a/framework/java/android/bluetooth/BluetoothSocket.java b/framework/java/android/bluetooth/BluetoothSocket.java index c151a483ef..7c2f524fa0 100644 --- a/framework/java/android/bluetooth/BluetoothSocket.java +++ b/framework/java/android/bluetooth/BluetoothSocket.java @@ -1283,7 +1283,7 @@ public final class BluetoothSocket implements Closeable { return mPfd; } - private String convertAddr(final byte[] addr) { + private static String convertAddr(final byte[] addr) { return String.format( Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X", @@ -1394,7 +1394,7 @@ public final class BluetoothSocket implements Closeable { } } - private int readAll(InputStream is, byte[] b) throws IOException { + private static int readAll(InputStream is, byte[] b) throws IOException { int left = b.length; while (left > 0) { int ret = is.read(b, b.length - left, left); @@ -1415,7 +1415,7 @@ public final class BluetoothSocket implements Closeable { return b.length; } - private int readInt(InputStream is) throws IOException { + private static int readInt(InputStream is) throws IOException { byte[] ibytes = new byte[4]; int ret = readAll(is, ibytes); if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret); diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java index c5e89749e7..1cf3cedeba 100644 --- a/framework/java/android/bluetooth/BluetoothVolumeControl.java +++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java @@ -19,6 +19,9 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.callServiceIfEnabled; import static android.bluetooth.BluetoothUtils.executeFromBinder; @@ -376,7 +379,7 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose @RequiresPermission(BLUETOOTH_CONNECT) public int getConnectionState(BluetoothDevice device) { Log.d(TAG, "getConnectionState(" + device + ")"); - int defaultValue = BluetoothProfile.STATE_DISCONNECTED; + int defaultValue = STATE_DISCONNECTED; if (!isValidDevice(device)) { return defaultValue; @@ -634,8 +637,8 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose Log.d(TAG, "setConnectionPolicy(" + device + ", " + connectionPolicy + ")"); boolean defaultValue = false; if (!isValidDevice(device) - || (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN - && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED)) { + || (connectionPolicy != CONNECTION_POLICY_FORBIDDEN + && connectionPolicy != CONNECTION_POLICY_ALLOWED)) { return defaultValue; } return callServiceIfEnabled( @@ -657,7 +660,7 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED}) public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) { Log.v(TAG, "getConnectionPolicy(" + device + ")"); - int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + int defaultValue = CONNECTION_POLICY_FORBIDDEN; if (!isValidDevice(device)) { return defaultValue; } diff --git a/framework/java/android/bluetooth/OobData.java b/framework/java/android/bluetooth/OobData.java index e699ec541c..48b107c7c0 100644 --- a/framework/java/android/bluetooth/OobData.java +++ b/framework/java/android/bluetooth/OobData.java @@ -862,8 +862,7 @@ public final class OobData implements Parcelable { * @hide */ @Override - @NonNull - public String toString() { + public @NonNull String toString() { return "OobData: \n\t" // Both + "Device Address With Type: " @@ -900,13 +899,11 @@ public final class OobData implements Parcelable { + "\n\t"; } - @NonNull - private String toHexString(int b) { + private static @NonNull String toHexString(int b) { return toHexString(new byte[] {(byte) b}); } - @NonNull - private String toHexString(byte[] array) { + private static @NonNull String toHexString(byte[] array) { if (array == null) return "null"; StringBuilder builder = new StringBuilder(array.length * 2); for (byte b : array) { diff --git a/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java b/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java index d5c5f64df3..f4fee92e69 100644 --- a/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java +++ b/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java @@ -780,7 +780,7 @@ public final class BluetoothLeAdvertiser { return size; } - private int byteLength(byte[] array) { + private static int byteLength(byte[] array) { return array == null ? 0 : array.length; } @@ -896,7 +896,7 @@ public final class BluetoothLeAdvertiser { } @SuppressLint("AndroidFrameworkBluetoothPermission") - private void postStartSetFailure( + private static void postStartSetFailure( Handler handler, final AdvertisingSetCallback callback, final int error) { handler.post( new Runnable() { diff --git a/framework/java/android/bluetooth/le/BluetoothLeScanner.java b/framework/java/android/bluetooth/le/BluetoothLeScanner.java index 02f48fb8d8..cd94688f2b 100644 --- a/framework/java/android/bluetooth/le/BluetoothLeScanner.java +++ b/framework/java/android/bluetooth/le/BluetoothLeScanner.java @@ -636,7 +636,7 @@ public final class BluetoothLeScanner { return false; } - private boolean isSettingsAndFilterComboAllowed( + private static boolean isSettingsAndFilterComboAllowed( ScanSettings settings, List<ScanFilter> filterList) { final int callbackType = settings.getCallbackType(); // If onlost/onfound is requested, a non-empty filter is expected diff --git a/framework/java/android/bluetooth/le/ScanSettings.java b/framework/java/android/bluetooth/le/ScanSettings.java index 014df2f4f0..e78f46c8d4 100644 --- a/framework/java/android/bluetooth/le/ScanSettings.java +++ b/framework/java/android/bluetooth/le/ScanSettings.java @@ -357,7 +357,7 @@ public final class ScanSettings implements Parcelable { } // Returns true if the callbackType is valid. - private boolean isValidCallbackType(int callbackType) { + private static boolean isValidCallbackType(int callbackType) { if (callbackType == CALLBACK_TYPE_ALL_MATCHES || callbackType == CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH || callbackType == CALLBACK_TYPE_FIRST_MATCH diff --git a/framework/tests/bumble/doc/guide.md b/framework/tests/bumble/doc/guide.md index 69673844bd..a587ec4428 100644 --- a/framework/tests/bumble/doc/guide.md +++ b/framework/tests/bumble/doc/guide.md @@ -178,7 +178,7 @@ verify(gattCallback, timeout(TIMEOUT)) .onConnectionStateChange( any(), eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) + eq(STATE_CONNECTED) ) ``` ### 6. Discover and Verify GATT Services @@ -209,7 +209,7 @@ verify(gattCallback, timeout(TIMEOUT)) .onConnectionStateChange( any(), eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_DISCONNECTED) + eq(STATE_DISCONNECTED) ) ``` diff --git a/framework/tests/bumble/doc/overview.md b/framework/tests/bumble/doc/overview.md index 024e776235..99ca6a21b0 100644 --- a/framework/tests/bumble/doc/overview.md +++ b/framework/tests/bumble/doc/overview.md @@ -60,7 +60,7 @@ fun testGattConnect() { .onConnectionStateChange( any(), eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) + eq(STATE_CONNECTED) ) // 5. Disconnect from the Bumble device and expect a successful disconnection callback. @@ -69,7 +69,7 @@ fun testGattConnect() { .onConnectionStateChange( any(), eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_DISCONNECTED) + eq(STATE_DISCONNECTED) ) } ``` diff --git a/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt b/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt index 13ce995741..8efa65ba4e 100644 --- a/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt +++ b/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt @@ -16,6 +16,8 @@ package android.bluetooth +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanFilter import android.bluetooth.le.ScanResult @@ -98,14 +100,14 @@ public class DckGattTest() { val device = bluetoothAdapter.getRemoteLeDevice( Utils.BUMBLE_RANDOM_ADDRESS, - BluetoothDevice.ADDRESS_TYPE_RANDOM + BluetoothDevice.ADDRESS_TYPE_RANDOM, ) val gatt = device.connectGatt(context, false, gattCallbackMock) verify(gattCallbackMock, timeout(TIMEOUT)) .onConnectionStateChange( eq(gatt), eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) + eq(STATE_CONNECTED), ) advertiseContext.cancel(null) @@ -182,7 +184,7 @@ public class DckGattTest() { // Advertising data. Utils.BUMBLE_RANDOM_ADDRESS, BluetoothDevice - .ADDRESS_TYPE_RANDOM // Specify address type as RANDOM because the device + .ADDRESS_TYPE_RANDOM, // Specify address type as RANDOM because the device // advertises with this address type. ) @@ -193,11 +195,7 @@ public class DckGattTest() { // 5. Connect to the Bumble device and expect a successful connection callback. var bumbleGatt = bumbleDevice.connectGatt(context, false, gattCallback) verify(gattCallback, timeout(TIMEOUT)) - .onConnectionStateChange( - any(), - eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) - ) + .onConnectionStateChange(any(), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED)) // 6. Discover GATT services offered by Bumble and expect successful service discovery. bumbleGatt.discoverServices() @@ -210,11 +208,7 @@ public class DckGattTest() { // 8. Disconnect from the Bumble device and expect a successful disconnection callback. bumbleGatt.disconnect() verify(gattCallback, timeout(TIMEOUT)) - .onConnectionStateChange( - any(), - eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_DISCONNECTED) - ) + .onConnectionStateChange(any(), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_DISCONNECTED)) } /* @@ -241,7 +235,7 @@ public class DckGattTest() { .setDeviceAddress( TEST_ADDRESS_RANDOM_STATIC, BluetoothDevice.ADDRESS_TYPE_RANDOM, - Utils.BUMBLE_IRK + Utils.BUMBLE_IRK, ) .build() leScanner.startScan(listOf(scanFilter), scanSettings, scanCallbackMock) @@ -259,11 +253,7 @@ public class DckGattTest() { val device = scanResult.device val gatt = device.connectGatt(context, false, gattCallbackMock) verify(gattCallbackMock, timeout(TIMEOUT)) - .onConnectionStateChange( - eq(gatt), - eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) - ) + .onConnectionStateChange(eq(gatt), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED)) // Stop scan on DUT after GATT connect leScanner.stopScan(scanCallbackMock) @@ -305,11 +295,7 @@ public class DckGattTest() { val device = scanResult.device val gatt = device.connectGatt(context, false, gattCallbackMock) verify(gattCallbackMock, timeout(TIMEOUT)) - .onConnectionStateChange( - eq(gatt), - eq(BluetoothGatt.GATT_SUCCESS), - eq(BluetoothProfile.STATE_CONNECTED) - ) + .onConnectionStateChange(eq(gatt), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED)) } private fun advertiseWithBumble(withUuid: Boolean = false): GrpcContext.CancellableContext { diff --git a/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt b/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt index 32e09b9de7..909894612b 100644 --- a/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt +++ b/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt @@ -17,6 +17,7 @@ package android.bluetooth import android.app.PendingIntent +import android.bluetooth.BluetoothProfile.STATE_CONNECTED import android.bluetooth.le.BluetoothLeScanner import android.bluetooth.le.ScanCallback import android.bluetooth.le.ScanFilter @@ -93,7 +94,7 @@ class DckTestRule( fun scanWithCallback( scanFilter: ScanFilter, scanSettings: ScanSettings, - coroutine: CoroutineScope = scope + coroutine: CoroutineScope = scope, ) = callbackFlow { val callback = @@ -128,7 +129,7 @@ class DckTestRule( fun scanWithPendingIntent( scanFilter: ScanFilter, scanSettings: ScanSettings, - coroutine: CoroutineScope = scope + coroutine: CoroutineScope = scope, ) = callbackFlow { val intentFilter = IntentFilter(ACTION_DYNAMIC_RECEIVER_SCAN_RESULT) @@ -161,7 +162,7 @@ class DckTestRule( scanIntent, PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT or - PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT + PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT, ) leScanner.startScan(listOf(scanFilter), scanSettings, pendingIntent) @@ -189,7 +190,7 @@ class DckTestRule( override fun onConnectionStateChange( gatt: BluetoothGatt, status: Int, - newState: Int + newState: Int, ) { trySend(GattState(gatt, status, newState)) } @@ -294,7 +295,7 @@ class DckTestRule( trySend( intent.getIntExtra( BluetoothAdapter.EXTRA_STATE, - BluetoothAdapter.ERROR + BluetoothAdapter.ERROR, ) ) } @@ -313,12 +314,10 @@ class DckTestRule( val bumbleDevice = bluetoothAdapter.getRemoteLeDevice( Utils.BUMBLE_RANDOM_ADDRESS, - BluetoothDevice.ADDRESS_TYPE_RANDOM + BluetoothDevice.ADDRESS_TYPE_RANDOM, ) - withTimeout(TIMEOUT_MS) { - connectGatt(bumbleDevice).first { it.state == BluetoothProfile.STATE_CONNECTED } - } + withTimeout(TIMEOUT_MS) { connectGatt(bumbleDevice).first { it.state == STATE_CONNECTED } } } private fun reset() { diff --git a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java index a6abad4e48..fa52d8c607 100644 --- a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java +++ b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.bluetooth.BluetoothGatt.GATT_SUCCESS; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.google.common.truth.Truth.assertThat; @@ -225,7 +226,7 @@ public class GattClientTest { gatt.disconnect(); inOrder.verify(gattCallback, timeout(1000)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED)); gatt.connect(); inOrder.verify(gattCallback, timeout(1000)) @@ -235,7 +236,7 @@ public class GattClientTest { // be necessary. gatt.disconnect(); inOrder.verify(gattCallback, timeout(1000)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED)); gatt.close(); } @@ -362,9 +363,7 @@ public class GattClientTest { verify(gattCallback, timeout(35000)) .onConnectionStateChange( - any(), - eq(BluetoothGatt.GATT_CONNECTION_TIMEOUT), - eq(BluetoothProfile.STATE_DISCONNECTED)); + any(), eq(BluetoothGatt.GATT_CONNECTION_TIMEOUT), eq(STATE_DISCONNECTED)); } @Test @@ -562,7 +561,7 @@ public class GattClientTest { private void disconnectAndWaitDisconnection( BluetoothGatt gatt, BluetoothGattCallback callback) { - final int state = BluetoothProfile.STATE_DISCONNECTED; + final int state = STATE_DISCONNECTED; gatt.disconnect(); verify(callback, timeout(1000)).onConnectionStateChange(eq(gatt), anyInt(), eq(state)); @@ -741,8 +740,7 @@ public class GattClientTest { gatt.disconnect(); inOrder.verify(gattCallback, timeout(1000)) - .onConnectionStateChange( - any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED)); gatt.connect(); inOrder.verify(gattCallback, timeout(1000)) @@ -750,8 +748,7 @@ public class GattClientTest { gatt.disconnect(); inOrder.verify(gattCallback, timeout(1000)) - .onConnectionStateChange( - any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED)); } } finally { for (BluetoothGatt gatt : gatts) { diff --git a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java index 8991637b2a..be7e41609a 100644 --- a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java +++ b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java @@ -16,6 +16,8 @@ package android.bluetooth; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; @@ -91,7 +93,7 @@ public class GattServerConnectWithScanTest { gattServer.connect(device, false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -118,7 +120,7 @@ public class GattServerConnectWithScanTest { gattServer.connect(device, false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -142,7 +144,7 @@ public class GattServerConnectWithScanTest { try { gattServer.connect(mBumble.getRemoteDevice(), false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -166,7 +168,7 @@ public class GattServerConnectWithScanTest { try { gattServer.connect(mBumble.getRemoteDevice(), false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } diff --git a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java index 902f3c59f5..739c026333 100644 --- a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java +++ b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java @@ -16,6 +16,8 @@ package android.bluetooth; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; @@ -78,7 +80,7 @@ public class GattServerConnectWithoutScanTest { gattServer.connect(device, false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -104,7 +106,7 @@ public class GattServerConnectWithoutScanTest { gattServer.connect(device, false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -126,7 +128,7 @@ public class GattServerConnectWithoutScanTest { try { gattServer.connect(mBumble.getRemoteDevice(), false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } @@ -148,7 +150,7 @@ public class GattServerConnectWithoutScanTest { try { gattServer.connect(mBumble.getRemoteDevice(), false); verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS)) - .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED)); } finally { gattServer.close(); } diff --git a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt index 2c165d9d53..4b0999bb19 100644 --- a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt +++ b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt @@ -17,6 +17,7 @@ package android.bluetooth import android.Manifest import android.annotation.SuppressLint +import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN import android.bluetooth.test_utils.EnableBluetoothRule import android.content.BroadcastReceiver import android.content.Context @@ -123,21 +124,12 @@ class RfcommTest { mHost = Host(mContext) val bluetoothA2dp = getProfileProxy(mContext, BluetoothProfile.A2DP) as BluetoothA2dp - bluetoothA2dp.setConnectionPolicy( - mRemoteDevice, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - ) + bluetoothA2dp.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN) val bluetoothHfp = getProfileProxy(mContext, BluetoothProfile.HEADSET) as BluetoothHeadset - bluetoothHfp.setConnectionPolicy( - mRemoteDevice, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - ) + bluetoothHfp.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN) val bluetoothHidHost = getProfileProxy(mContext, BluetoothProfile.HID_HOST) as BluetoothHidHost - bluetoothHidHost.setConnectionPolicy( - mRemoteDevice, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, - ) + bluetoothHidHost.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN) if (mRemoteDevice.isConnected) { mHost.disconnectAndVerify(mRemoteDevice) } diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java index 26deb09327..23242f3869 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java @@ -18,6 +18,8 @@ package android.bluetooth.hid; import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR; import static android.bluetooth.BluetoothDevice.TRANSPORT_LE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -317,18 +319,12 @@ public class HidHeadTrackerTest { // Disable a2dp and HFP connetcion policy - if (mA2dpService.getConnectionPolicy(mBumbleDevice) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - mA2dpService.setConnectionPolicy( - mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (mA2dpService.getConnectionPolicy(mBumbleDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(mA2dpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } - if (mHfpService.getConnectionPolicy(mBumbleDevice) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - mHfpService.setConnectionPolicy( - mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (mHfpService.getConnectionPolicy(mBumbleDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(mHfpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java index be8ca125cd..fb89c738ad 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java @@ -18,6 +18,8 @@ package android.bluetooth.hid; import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR; import static android.bluetooth.BluetoothDevice.TRANSPORT_LE; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -310,17 +312,12 @@ public class HidHostDualModeTest { hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED)); - if (a2dpService.getConnectionPolicy(mDevice) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - a2dpService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (a2dpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(a2dpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } - if (hfpService.getConnectionPolicy(mDevice) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - hfpService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (hfpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(hfpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java index 6a94d6a3de..b92a8d17ba 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java @@ -17,6 +17,8 @@ package android.bluetooth.hid; import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; @@ -313,17 +315,12 @@ public class HidHostTest { hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED)); - if (a2dpService.getConnectionPolicy(mDevice) - == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - a2dpService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (a2dpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(a2dpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } - if (hfpService.getConnectionPolicy(mDevice) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) { - assertThat( - hfpService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + if (hfpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) { + assertThat(hfpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); } verifyConnectionState(mDevice, equalTo(TRANSPORT_BREDR), equalTo(STATE_CONNECTING)); @@ -380,8 +377,7 @@ public class HidHostTest { @Test public void hidReconnectionWhenConnectionPolicyChangeTest() throws Exception { - assertThat(mHidService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); mHidBlockingStub.disconnectHost(Empty.getDefaultInstance()); verifyProfileDisconnectionState(); @@ -392,17 +388,11 @@ public class HidHostTest { mHidBlockingStub.disconnectHost(Empty.getDefaultInstance()); verifyProfileDisconnectionState(); - assertThat( - mHidService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) - .isTrue(); + assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)).isTrue(); reconnectionFromRemoteAndVerifyDisconnectedState(); - assertThat( - mHidService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED)) - .isTrue(); + assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED)).isTrue(); verifyIntentReceived( hasAction(BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED), hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), @@ -435,8 +425,7 @@ public class HidHostTest { @Test public void hidReconnectionAfterBTrestartWithConnectionPolicyAllowedTest() throws Exception { - assertThat(mHidService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); bluetoothRestart(); @@ -460,13 +449,9 @@ public class HidHostTest { public void hidReconnectionAfterBTrestartWithConnectionPolicyiDisallowedTest() throws Exception { - assertThat(mHidService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); - assertThat( - mHidService.setConnectionPolicy( - mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) - .isTrue(); + assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)).isTrue(); bluetoothRestart(); reconnectionFromRemoteAndVerifyDisconnectedState(); @@ -486,8 +471,7 @@ public class HidHostTest { @Test public void hidReconnectionAfterDeviceRemovedTest() throws Exception { - assertThat(mHidService.getConnectionPolicy(mDevice)) - .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED); + assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED); mHidBlockingStub.disconnectHost(Empty.getDefaultInstance()); verifyProfileDisconnectionState(); diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java index c2fb973fba..c8f9388da0 100644 --- a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java +++ b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java @@ -16,6 +16,8 @@ package android.bluetooth.pairing; +import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN; + import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; @@ -786,13 +788,9 @@ public class PairingTest { .build(); // Disable all profiles other than A2DP as profile connections take too long - assertThat( - mHfpService.setConnectionPolicy( - mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + assertThat(mHfpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); - assertThat( - mHidService.setConnectionPolicy( - mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)) + assertThat(mHidService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN)) .isTrue(); testStep_BondBredr(intentReceiver); diff --git a/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt b/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt index c3e90213f3..9f06aa6c18 100644 --- a/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt +++ b/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt @@ -17,6 +17,8 @@ package android.bluetooth import android.Manifest +import android.bluetooth.BluetoothProfile.STATE_CONNECTED +import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED import android.bluetooth.test_utils.EnableBluetoothRule import android.content.Context import android.platform.test.annotations.RequiresFlagsEnabled @@ -75,7 +77,7 @@ public class DckL2capTest() : Closeable { private val bluetoothAdapter = bluetoothManager.adapter private val openedGatts: MutableList<BluetoothGatt> = mutableListOf() private var serviceDiscoveredFlow = MutableStateFlow(false) - private var connectionStateFlow = MutableStateFlow(BluetoothProfile.STATE_DISCONNECTED) + private var connectionStateFlow = MutableStateFlow(STATE_DISCONNECTED) private var dckSpsmFlow = MutableStateFlow(0) private var dckSpsm = 0 private var connectionHandle = BluetoothDevice.ERROR @@ -367,9 +369,7 @@ public class DckL2capTest() : Closeable { private fun readDckSpsm(gatt: BluetoothGatt) = runBlocking { Log.d(TAG, "readDckSpsm") launch { - withTimeout(GRPC_TIMEOUT) { - connectionStateFlow.first { it == BluetoothProfile.STATE_CONNECTED } - } + withTimeout(GRPC_TIMEOUT) { connectionStateFlow.first { it == STATE_CONNECTED } } Log.i(TAG, "Connected to GATT") gatt.discoverServices() withTimeout(GRPC_TIMEOUT) { serviceDiscoveredFlow.first { it == true } } diff --git a/offload/hal/ffi.rs b/offload/hal/ffi.rs index 762e3c9d6b..e8be51f7f5 100644 --- a/offload/hal/ffi.rs +++ b/offload/hal/ffi.rs @@ -12,7 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. -use core::{ffi::c_void, slice}; +use core::ffi::c_void; +use core::slice; use std::sync::{Mutex, RwLock}; /// Callbacks from C to Rust @@ -45,6 +46,7 @@ pub struct CInterface { send_acl: unsafe extern "C" fn(handle: *mut c_void, data: *const u8, len: usize), send_sco: unsafe extern "C" fn(handle: *mut c_void, data: *const u8, len: usize), send_iso: unsafe extern "C" fn(handle: *mut c_void, data: *const u8, len: usize), + client_died: unsafe extern "C" fn(handle: *mut c_void), } //SAFETY: CInterface is safe to send between threads because we require the C code @@ -146,6 +148,17 @@ impl<T: Callbacks> Ffi<T> { self.remove_client(); } + pub(crate) fn client_died(&self) { + let intf = self.intf.lock().unwrap(); + + // SAFETY: The C Code has initialized the `CInterface` with a valid + // function pointer and an initialized `handle`. + unsafe { + (intf.client_died)(intf.handle); + } + self.remove_client(); + } + fn set_client(&self, client: T) { *self.wrapper.write().unwrap() = Some(client); } diff --git a/offload/hal/include/hal/ffi.h b/offload/hal/include/hal/ffi.h index e066c68a09..f4d9b5ff4d 100644 --- a/offload/hal/include/hal/ffi.h +++ b/offload/hal/include/hal/ffi.h @@ -58,5 +58,6 @@ struct hal_interface { void (*send_acl)(void *handle, const uint8_t *data, size_t len); void (*send_sco)(void *handle, const uint8_t *data, size_t len); void (*send_iso)(void *handle, const uint8_t *data, size_t len); + void (*client_died)(void *handle); }; } diff --git a/offload/hal/service.rs b/offload/hal/service.rs index eb8c679b09..a72eea9200 100644 --- a/offload/hal/service.rs +++ b/offload/hal/service.rs @@ -13,9 +13,9 @@ // limitations under the License. use crate::ffi::{CInterface, CStatus, Callbacks, DataCallbacks, Ffi}; -use android_hardware_bluetooth::aidl::android::hardware::bluetooth::{ - IBluetoothHci::IBluetoothHci, IBluetoothHciCallbacks::IBluetoothHciCallbacks, Status::Status, -}; +use android_hardware_bluetooth::aidl::android::hardware::bluetooth::IBluetoothHci::IBluetoothHci; +use android_hardware_bluetooth::aidl::android::hardware::bluetooth::IBluetoothHciCallbacks::IBluetoothHciCallbacks; +use android_hardware_bluetooth::aidl::android::hardware::bluetooth::Status::Status; use binder::{DeathRecipient, ExceptionCode, IBinder, Interface, Result as BinderResult, Strong}; use bluetooth_offload_hci::{Module, ModuleBuilder}; use std::sync::{Arc, RwLock}; @@ -78,9 +78,7 @@ impl IBluetoothHci for HciHalProxy { DeathRecipient::new(move || { log::info!("Bluetooth stack has died"); let mut state = state.write().unwrap(); - if !matches!(*state, State::Closed) { - ffi.close(); - } + ffi.client_died(); *state = State::Closed; }) }; diff --git a/service/src/com/android/server/bluetooth/BluetoothManagerService.java b/service/src/com/android/server/bluetooth/BluetoothManagerService.java index 20d8dbf073..6cd63181da 100644 --- a/service/src/com/android/server/bluetooth/BluetoothManagerService.java +++ b/service/src/com/android/server/bluetooth/BluetoothManagerService.java @@ -692,7 +692,7 @@ class BluetoothManagerService { } /** Returns true if satellite mode is turned on. */ - private boolean isSatelliteModeOn() { + private static boolean isSatelliteModeOn() { return SatelliteModeListener.isOn(); } @@ -750,7 +750,7 @@ class BluetoothManagerService { Log.d(TAG, "loadStoredNameAndAddress: Name=" + mName + ", Address=" + logAddress(mAddress)); } - private String logAddress(String address) { + private static String logAddress(String address) { if (address == null) { return "[address is null]"; } @@ -1918,7 +1918,7 @@ class BluetoothManagerService { intent, UserHandle.ALL, null, getTempAllowlistBroadcastOptions()); } - private boolean isBleState(int state) { + private static boolean isBleState(int state) { switch (state) { case STATE_BLE_ON: case STATE_BLE_TURNING_ON: @@ -2233,7 +2233,7 @@ class BluetoothManagerService { } } - private void dumpBluetoothFlags(PrintWriter writer) { + private static void dumpBluetoothFlags(PrintWriter writer) { writer.println("🚩Flag dump:"); Arrays.stream(Flags.class.getDeclaredMethods()) .forEach( @@ -2500,8 +2500,8 @@ class BluetoothManagerService { disableComponents(pm, packageInfo.providers, packageName, null); } - private <T extends android.content.pm.ComponentInfo> void disableComponents( - PackageManager pm, T[] components, String packageName, List<String> componentsToKeep) { + private static <T extends android.content.pm.ComponentInfo> void disableComponents( + PackageManager pm, T[] components, String packageName, List<String> componentsToKeep) { if (components == null) { return; } diff --git a/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java b/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java index 40e6f4b4b7..07466e59c4 100644 --- a/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java +++ b/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java @@ -383,7 +383,7 @@ public class BluetoothServiceBinderTest { // ********************************************************************************************* // Utility method used in tests - private void verifyAndClearMock(Object o) { + private static void verifyAndClearMock(Object o) { assertThat(mockingDetails(o).isMock() || mockingDetails(o).isSpy()).isTrue(); verifyNoMoreInteractions(o); clearInvocations(o); diff --git a/system/audio_bluetooth_hw/device_port_proxy.cc b/system/audio_bluetooth_hw/device_port_proxy.cc index 088daf0c15..dc836a7ae8 100644 --- a/system/audio_bluetooth_hw/device_port_proxy.cc +++ b/system/audio_bluetooth_hw/device_port_proxy.cc @@ -688,17 +688,17 @@ void BluetoothAudioPortAidl::UpdateSourceMetadata(const source_metadata_v7* sour << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << ", " << source_metadata->track_count << " track(s)"; ssize_t track_count = source_metadata->track_count; - if (track_count == 0) { - return; - } SourceMetadata hal_source_metadata; - hal_source_metadata.tracks.resize(track_count); - for (int i = 0; i < track_count; i++) { - hal_source_metadata.tracks[i].usage = - static_cast<AudioUsage>(source_metadata->tracks[i].base.usage); - hal_source_metadata.tracks[i].contentType = - static_cast<AudioContentType>(source_metadata->tracks[i].base.content_type); - hal_source_metadata.tracks[i].tags = CovertAudioTagFromV7(source_metadata->tracks[i].tags); + + if (track_count != 0) { + hal_source_metadata.tracks.resize(track_count); + for (int i = 0; i < track_count; i++) { + hal_source_metadata.tracks[i].usage = + static_cast<AudioUsage>(source_metadata->tracks[i].base.usage); + hal_source_metadata.tracks[i].contentType = + static_cast<AudioContentType>(source_metadata->tracks[i].base.content_type); + hal_source_metadata.tracks[i].tags = CovertAudioTagFromV7(source_metadata->tracks[i].tags); + } } BluetoothAudioSessionControl::UpdateSourceMetadata(session_type_, hal_source_metadata); @@ -713,16 +713,16 @@ void BluetoothAudioPortAidl::UpdateSinkMetadata(const sink_metadata_v7* sink_met << ", cookie=" << StringPrintf("%#hx", cookie_) << ", state=" << state_ << ", " << sink_metadata->track_count << " track(s)"; ssize_t track_count = sink_metadata->track_count; - if (track_count == 0) { - return; - } SinkMetadata hal_sink_metadata; - hal_sink_metadata.tracks.resize(track_count); - for (int i = 0; i < track_count; i++) { - hal_sink_metadata.tracks[i].source = - static_cast<AudioSource>(sink_metadata->tracks[i].base.source); - hal_sink_metadata.tracks[i].gain = sink_metadata->tracks[i].base.gain; - hal_sink_metadata.tracks[i].tags = CovertAudioTagFromV7(sink_metadata->tracks[i].tags); + + if (track_count != 0) { + hal_sink_metadata.tracks.resize(track_count); + for (int i = 0; i < track_count; i++) { + hal_sink_metadata.tracks[i].source = + static_cast<AudioSource>(sink_metadata->tracks[i].base.source); + hal_sink_metadata.tracks[i].gain = sink_metadata->tracks[i].base.gain; + hal_sink_metadata.tracks[i].tags = CovertAudioTagFromV7(sink_metadata->tracks[i].tags); + } } BluetoothAudioSessionControl::UpdateSinkMetadata(session_type_, hal_sink_metadata); diff --git a/system/audio_hal_interface/aidl/a2dp/a2dp_provider_info.cc b/system/audio_hal_interface/aidl/a2dp/a2dp_provider_info.cc index 8ab27d06d2..445cb523a8 100644 --- a/system/audio_hal_interface/aidl/a2dp/a2dp_provider_info.cc +++ b/system/audio_hal_interface/aidl/a2dp/a2dp_provider_info.cc @@ -376,7 +376,11 @@ bool ProviderInfo::CodecCapabilities(btav_a2dp_codec_index_t codec_index, } } if (codec_config != nullptr) { - memset(codec_config, 0, sizeof(*codec_config)); + *codec_config = btav_a2dp_codec_config_t{ + .codec_type = codec_index, + .codec_priority = BTAV_A2DP_CODEC_PRIORITY_DEFAULT, + }; + for (auto const& channel_mode : transport.channelMode) { switch (channel_mode) { case ChannelMode::MONO: diff --git a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc index 0cf9d824ee..ec9f3a5bf2 100644 --- a/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc +++ b/system/audio_hal_interface/aidl/hearing_aid_software_encoding_aidl.cc @@ -20,10 +20,11 @@ #include <bluetooth/log.h> -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" #include "client_interface_aidl.h" #include "osi/include/properties.h" +#define AUDIO_STREAM_OUTPUT_BUFFER_SZ (28 * 512) + namespace std { template <> struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {}; diff --git a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc index e7d5ac8790..be7cf3a6b2 100644 --- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc +++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc @@ -189,11 +189,6 @@ bool LeAudioTransport::GetPresentationPosition(uint64_t* remote_delay_report_ns, void LeAudioTransport::SourceMetadataChanged(const source_metadata_v7_t& source_metadata) { auto track_count = source_metadata.track_count; - if (track_count == 0) { - log::warn(", invalid number of metadata changed tracks"); - return; - } - if (cached_source_metadata_.tracks != nullptr) { free(cached_source_metadata_.tracks); cached_source_metadata_.tracks = nullptr; @@ -201,9 +196,11 @@ void LeAudioTransport::SourceMetadataChanged(const source_metadata_v7_t& source_ log::info(", caching source metadata"); - playback_track_metadata_v7* tracks; - tracks = (playback_track_metadata_v7*)malloc(sizeof(*tracks) * track_count); - memcpy(tracks, source_metadata.tracks, sizeof(*tracks) * track_count); + playback_track_metadata_v7* tracks = nullptr; + if (track_count != 0) { + tracks = (playback_track_metadata_v7*)malloc(sizeof(*tracks) * track_count); + memcpy(tracks, source_metadata.tracks, sizeof(*tracks) * track_count); + } cached_source_metadata_.track_count = track_count; cached_source_metadata_.tracks = tracks; @@ -214,11 +211,6 @@ void LeAudioTransport::SourceMetadataChanged(const source_metadata_v7_t& source_ void LeAudioTransport::SinkMetadataChanged(const sink_metadata_v7_t& sink_metadata) { auto track_count = sink_metadata.track_count; - if (track_count == 0) { - log::warn(", invalid number of metadata changed tracks"); - return; - } - if (stream_cb_.on_sink_metadata_update_) { stream_cb_.on_sink_metadata_update_(sink_metadata); } @@ -547,6 +539,8 @@ bool hal_ucast_capability_to_stack_format(const UnicastCapability& hal_capabilit auto sample_rate_hz = hal_lc3_capability.samplingFrequencyHz[0]; auto frame_duration_us = hal_lc3_capability.frameDurationUs[0]; auto octets_per_frame = hal_lc3_capability.octetsPerFrame[0]; + auto codec_frame_blocks_per_sdu = + hal_lc3_capability.blocksPerSdu.size() ? hal_lc3_capability.blocksPerSdu[0] : 1; auto channel_count = hal_capability.channelCountPerDevice; if (sampling_freq_map.find(sample_rate_hz) == sampling_freq_map.end() || @@ -576,6 +570,9 @@ bool hal_ucast_capability_to_stack_format(const UnicastCapability& hal_capabilit stack_capability.params.Add( ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeOctetsPerCodecFrame, octets_per_frame_map[octets_per_frame]); + stack_capability.params.Add( + ::bluetooth::le_audio::codec_spec_conf::kLeAudioLtvTypeCodecFrameBlocksPerSdu, + uint8_t(codec_frame_blocks_per_sdu)); return true; } @@ -707,20 +704,31 @@ AudioConfiguration stream_config_to_hal_audio_config( return AudioConfiguration(ucast_config); } - // In the legacy configuration we use the first ASE configuration as the source of truth. - if (offload_config.stream_map.at(0).codec_config.id == - ::bluetooth::le_audio::types::LeAudioCodecIdLc3) { - Lc3Configuration lc3_config{ - .pcmBitDepth = static_cast<int8_t>(offload_config.bits_per_sample), - .samplingFrequencyHz = static_cast<int32_t>(offload_config.sampling_frequency_hz), - .frameDurationUs = static_cast<int32_t>(offload_config.frame_duration_us), - .octetsPerFrame = static_cast<int32_t>(offload_config.octets_per_codec_frame), - .blocksPerSdu = static_cast<int8_t>(offload_config.codec_frames_blocks_per_sdu), - }; - ucast_config.leAudioCodecConfig = LeAudioCodecConfiguration(lc3_config); - } - + bool lc3_codec_config_found = false; for (auto& info : offload_config.stream_map) { + if (!lc3_codec_config_found && + info.codec_config.id == ::bluetooth::le_audio::types::LeAudioCodecIdLc3) { + /* For now we have single configuration per directions, so this is enought to use + * configuration from the streaming cis. Find configuration and copy it. + */ + log::verbose( + "Found LC3 config: bits_per_sample: {}, sampling_frequency_hz: {}, " + "frame_duration_us: {}, octets_per_codec_frame: {}, codec_frames_blocks_per_sdu: {}", + offload_config.bits_per_sample, offload_config.sampling_frequency_hz, + offload_config.frame_duration_us, offload_config.octets_per_codec_frame, + offload_config.codec_frames_blocks_per_sdu); + + Lc3Configuration lc3_config{ + .pcmBitDepth = static_cast<int8_t>(offload_config.bits_per_sample), + .samplingFrequencyHz = static_cast<int32_t>(offload_config.sampling_frequency_hz), + .frameDurationUs = static_cast<int32_t>(offload_config.frame_duration_us), + .octetsPerFrame = static_cast<int32_t>(offload_config.octets_per_codec_frame), + .blocksPerSdu = static_cast<int8_t>(offload_config.codec_frames_blocks_per_sdu), + }; + ucast_config.leAudioCodecConfig = LeAudioCodecConfiguration(lc3_config); + lc3_codec_config_found = true; + } + LeAudioConfiguration::StreamMap::BluetoothDeviceAddress aidl_device_address; // The address should be set only if stream is active if (info.is_stream_active) { @@ -743,6 +751,11 @@ AudioConfiguration stream_config_to_hal_audio_config( }); } + if (!lc3_codec_config_found) { + auto id = offload_config.stream_map.at(0).codec_config.id; + log::info("Non LC3 Codec config is used. Format: {}, Vendor: {}, Company: {}", id.coding_format, + id.vendor_codec_id, id.vendor_company_id); + } return AudioConfiguration(ucast_config); } diff --git a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc index b745914999..a129917f8f 100644 --- a/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc +++ b/system/audio_hal_interface/hidl/hearing_aid_software_encoding_hidl.cc @@ -20,10 +20,11 @@ #include <bluetooth/log.h> -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" #include "client_interface_hidl.h" #include "osi/include/properties.h" +#define AUDIO_STREAM_OUTPUT_BUFFER_SZ (28 * 512) + namespace std { template <> struct formatter<audio_usage_t> : enum_formatter<audio_usage_t> {}; diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc index d3e65d63b8..2352981e76 100644 --- a/system/audio_hal_interface/le_audio_software.cc +++ b/system/audio_hal_interface/le_audio_software.cc @@ -280,6 +280,17 @@ void LeAudioClientInterface::Sink::StopSession() { get_aidl_client_interface(is_broadcaster_)->EndSession(); } +static inline void dumpOffloadConfig( + const char* msg, const ::bluetooth::audio::aidl::AudioConfiguration& offload_hal_config) { + const auto offload_cfg_str = offload_hal_config.toString(); + + constexpr size_t linelimit = 940; + std::string_view str_view(offload_cfg_str); + for (size_t offset = 0; offset < offload_cfg_str.length(); offset += linelimit) { + log::debug("{} {}", offset ? " > " : msg, str_view.substr(offset, linelimit)); + } +} + void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( const ::bluetooth::le_audio::stream_config& offload_config) { if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) { @@ -290,8 +301,10 @@ void LeAudioClientInterface::Sink::UpdateAudioConfigToHal( return; } - get_aidl_client_interface(is_broadcaster_) - ->UpdateAudioConfig(aidl::le_audio::stream_config_to_hal_audio_config(offload_config)); + auto offload_hal_config = aidl::le_audio::stream_config_to_hal_audio_config(offload_config); + dumpOffloadConfig("Encoding config:", offload_hal_config); + + get_aidl_client_interface(is_broadcaster_)->UpdateAudioConfig(offload_hal_config); } std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration> @@ -591,8 +604,11 @@ void LeAudioClientInterface::Source::UpdateAudioConfigToHal( aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) { return; } - aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig( - aidl::le_audio::stream_config_to_hal_audio_config(offload_config)); + + auto offload_hal_config = aidl::le_audio::stream_config_to_hal_audio_config(offload_config); + dumpOffloadConfig("Decoding config:", offload_hal_config); + + aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig(offload_hal_config); } size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, uint32_t len) { diff --git a/system/audio_hal_interface/le_audio_software_unittest.cc b/system/audio_hal_interface/le_audio_software_unittest.cc index 21db531e07..607b5d8df9 100644 --- a/system/audio_hal_interface/le_audio_software_unittest.cc +++ b/system/audio_hal_interface/le_audio_software_unittest.cc @@ -635,6 +635,56 @@ TEST_F(LeAudioSoftwareUnicastTestAidl, AcquireAndRelease) { ASSERT_NE(nullptr, source_); } +TEST_F(LeAudioSoftwareUnicastTestAidl, TrackListUpdate) { + ASSERT_NE(nullptr, sink_); + ASSERT_NE(nullptr, source_); + + // Recording tracks updates twice - with a valid track and with an empty track list + auto& sink_transport = + ::bluetooth::audio::aidl::le_audio::LeAudioSinkTransport::interface_unicast_; + ASSERT_NE(sink_transport, nullptr); + record_track_metadata_v7 recording_tracks[] = { + { + .base = + { + .source = AUDIO_SOURCE_MIC, + .gain = 1.0f, + .dest_device = AUDIO_DEVICE_IN_DEFAULT, + }, + .channel_mask = + audio_channel_mask_t(AUDIO_CHANNEL_IN_LEFT | AUDIO_CHANNEL_IN_RIGHT), + .tags = {'t', 'a', 'g'}, + }, + }; + EXPECT_CALL(sink_stream_callbacks_, OnSinkMetadataUpdate(testing::_)).Times(2); + sink_transport->GetTransportInstance()->SinkMetadataChanged( + sink_metadata_v7_t({.track_count = 1, .tracks = recording_tracks})); + sink_transport->GetTransportInstance()->SinkMetadataChanged( + sink_metadata_v7_t({.track_count = 0, .tracks = nullptr})); + + // Playback tracks updates twice - with a valid track and with an empty track list + auto& source_transport = ::bluetooth::audio::aidl::le_audio::LeAudioSourceTransport::interface; + ASSERT_NE(source_transport, nullptr); + playback_track_metadata_v7 playback_tracks[] = { + { + .base = + { + .usage = AUDIO_USAGE_MEDIA, + .content_type = AUDIO_CONTENT_TYPE_MOVIE, + .gain = 1.0f, + }, + .channel_mask = + audio_channel_mask_t(AUDIO_CHANNEL_IN_LEFT | AUDIO_CHANNEL_IN_RIGHT), + .tags = {'t', 'a', 'g'}, + }, + }; + EXPECT_CALL(source_stream_callbacks_, OnSourceMetadataUpdate(testing::_, testing::_)).Times(2); + source_transport->GetTransportInstance()->SourceMetadataChanged( + source_metadata_v7_t({.track_count = 1, .tracks = playback_tracks})); + source_transport->GetTransportInstance()->SourceMetadataChanged( + source_metadata_v7_t({.track_count = 0, .tracks = nullptr})); +} + class LeAudioSoftwareUnicastTestHidl : public LeAudioSoftwareUnicastTest { protected: virtual void SetUp() override { diff --git a/system/audio_hearing_aid_hw/Android.bp b/system/audio_hearing_aid_hw/Android.bp deleted file mode 100644 index afc160d599..0000000000 --- a/system/audio_hearing_aid_hw/Android.bp +++ /dev/null @@ -1,63 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "system_bt_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["system_bt_license"], -} - -cc_defaults { - name: "audio_hearing_aid_hw_defaults", - defaults: ["bluetooth_cflags"], - shared_libs: ["libchrome"], - include_dirs: [ - "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/gd", - "packages/modules/Bluetooth/system/include", - ], -} - -// Audio A2DP shared library for target -cc_library { - name: "audio.hearing_aid.default", - defaults: ["audio_hearing_aid_hw_defaults"], - relative_install_path: "hw", - srcs: [ - "src/audio_hearing_aid_hw.cc", - "src/audio_hearing_aid_hw_utils.cc", - ], - apex_available: ["com.android.bt"], - shared_libs: [ - "libbase", - "liblog", - ], - static_libs: [ - "libbluetooth_log", - "libosi", - ], -} - -// Audio A2DP library unit tests for target and host -cc_test { - name: "net_test_audio_hearing_aid_hw", - test_suites: ["general-tests"], - defaults: [ - "audio_hearing_aid_hw_defaults", - "mts_defaults", - ], - srcs: [ - "test/audio_hearing_aid_hw_test.cc", - ], - shared_libs: [ - "libbase", - "liblog", - ], - static_libs: [ - "audio.hearing_aid.default", - "libbluetooth_log", - "libcom.android.sysprop.bluetooth.wrapped", - "libosi", - ], - min_sdk_version: "29", -} diff --git a/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h b/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h deleted file mode 100644 index 7283079b33..0000000000 --- a/system/audio_hearing_aid_hw/include/audio_hearing_aid_hw.h +++ /dev/null @@ -1,146 +0,0 @@ -/****************************************************************************** - * - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/***************************************************************************** - * - * Filename: audio_hearing_aid_hw.h - * - * Description: - * - *****************************************************************************/ - -#ifndef AUDIO_HEARING_AID_HW_H -#define AUDIO_HEARING_AID_HW_H - -#include <hardware/bt_av.h> -#include <stdint.h> - -/***************************************************************************** - * Constants & Macros - *****************************************************************************/ - -#define HEARING_AID_AUDIO_HARDWARE_INTERFACE "audio.hearing_aid" -#define HEARING_AID_CTRL_PATH "/data/misc/bluedroid/.hearing_aid_ctrl" -#define HEARING_AID_DATA_PATH "/data/misc/bluedroid/.hearing_aid_data" - -// AUDIO_STREAM_OUTPUT_BUFFER_SZ controls the size of the audio socket buffer. -// If one assumes the write buffer is always full during normal BT playback, -// then increasing this value increases our playback latency. -// -// FIXME: The BT HAL should consume data at a constant rate. -// AudioFlinger assumes that the HAL draws data at a constant rate, which is -// true for most audio devices; however, the BT engine reads data at a variable -// rate (over the short term), which confuses both AudioFlinger as well as -// applications which deliver data at a (generally) fixed rate. -// -// 20 * 512 is not sufficient to smooth the variability for some BT devices, -// resulting in mixer sleep and throttling. We increase this to 28 * 512 to help -// reduce the effect of variable data consumption. -#define AUDIO_STREAM_OUTPUT_BUFFER_SZ (28 * 512) -#define AUDIO_STREAM_CONTROL_OUTPUT_BUFFER_SZ 256 - -// AUDIO_STREAM_OUTPUT_BUFFER_PERIODS controls how the socket buffer is divided -// for AudioFlinger data delivery. The AudioFlinger mixer delivers data in -// chunks of AUDIO_STREAM_OUTPUT_BUFFER_SZ / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS. -// If the number of periods is 2, the socket buffer represents "double -// buffering" of the AudioFlinger mixer buffer. -// -// In general, AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * 4 should be a divisor -// of AUDIO_STREAM_OUTPUT_BUFFER_SZ. -// -// These values should be chosen such that -// -// AUDIO_STREAM_BUFFER_SIZE * 1000 / (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS -// * AUDIO_STREAM_DEFAULT_RATE * 4) > 20 (ms) -// -// to avoid introducing the FastMixer in AudioFlinger. Using the FastMixer -// results in unnecessary latency and CPU overhead for Bluetooth. -#define AUDIO_STREAM_OUTPUT_BUFFER_PERIODS 2 - -#define AUDIO_SKT_DISCONNECTED (-1) - -typedef enum { - HEARING_AID_CTRL_CMD_NONE, - HEARING_AID_CTRL_CMD_CHECK_READY, - HEARING_AID_CTRL_CMD_START, - HEARING_AID_CTRL_CMD_STOP, - HEARING_AID_CTRL_CMD_SUSPEND, - HEARING_AID_CTRL_GET_INPUT_AUDIO_CONFIG, - HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG, - HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG, - HEARING_AID_CTRL_CMD_OFFLOAD_START, -} tHEARING_AID_CTRL_CMD; - -typedef enum { - HEARING_AID_CTRL_ACK_SUCCESS, - HEARING_AID_CTRL_ACK_FAILURE, - HEARING_AID_CTRL_ACK_INCALL_FAILURE, /* Failure when in Call*/ - HEARING_AID_CTRL_ACK_UNSUPPORTED -} tHEARING_AID_CTRL_ACK; - -typedef uint32_t tHA_SAMPLE_RATE; -typedef uint8_t tHA_CHANNEL_COUNT; - -/***************************************************************************** - * Type definitions for callback functions - *****************************************************************************/ - -/***************************************************************************** - * Type definitions and return values - *****************************************************************************/ - -/***************************************************************************** - * Extern variables and functions - *****************************************************************************/ - -/***************************************************************************** - * Functions - *****************************************************************************/ - -// Computes the Audio Hearing Aid HAL output buffer size. -// |codec_sample_rate| is the sample rate of the output stream. -// |codec_bits_per_sample| is the number of bits per sample of the output -// stream. -// |codec_channel_mode| is the channel mode of the output stream. -// -// The buffer size is computed by using the following formula: -// -// AUDIO_STREAM_OUTPUT_BUFFER_SIZE = -// (TIME_PERIOD_MS * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * -// SAMPLE_RATE_HZ * NUMBER_OF_CHANNELS * (BITS_PER_SAMPLE / 8)) / 1000 -// -// AUDIO_STREAM_OUTPUT_BUFFER_PERIODS controls how the socket buffer is -// divided for AudioFlinger data delivery. The AudioFlinger mixer delivers -// data in chunks of -// (AUDIO_STREAM_OUTPUT_BUFFER_SIZE / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS) . -// If the number of periods is 2, the socket buffer represents "double -// buffering" of the AudioFlinger mixer buffer. -// -// Furthermore, the AudioFlinger expects the buffer size to be a multiple -// of 16 frames. -// -// NOTE: Currently, the computation uses the conservative 20ms time period. -// -// Returns the computed buffer size. If any of the input parameters is -// invalid, the return value is the default |AUDIO_STREAM_OUTPUT_BUFFER_SZ|. -size_t audio_ha_hw_stream_compute_buffer_size( - btav_a2dp_codec_sample_rate_t codec_sample_rate, - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, - btav_a2dp_codec_channel_mode_t codec_channel_mode); - -#endif /* AUDIO_HEARING_AID_HW_H */ diff --git a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc b/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc deleted file mode 100644 index ac63105662..0000000000 --- a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw.cc +++ /dev/null @@ -1,1925 +0,0 @@ -/****************************************************************************** - * - * Copyright 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -/* Implements hal for bluedroid ha audio device */ - -#define LOG_TAG "bt_hearing_aid_hw" - -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" - -#include <fcntl.h> -#include <hardware/audio.h> -#include <hardware/hardware.h> -#include <inttypes.h> -#include <log/log.h> -#include <stdint.h> -#include <sys/socket.h> -#include <sys/stat.h> -#include <sys/time.h> -#include <sys/un.h> -#include <system/audio.h> -#include <unistd.h> - -#include <cerrno> -#include <mutex> - -#include "osi/include/hash_map_utils.h" -#include "osi/include/osi.h" -#include "osi/include/socket_utils/sockets.h" - -/***************************************************************************** - * Constants & Macros - *****************************************************************************/ - -#define CTRL_CHAN_RETRY_COUNT 3 -#define USEC_PER_SEC 1000000L -#define SOCK_SEND_TIMEOUT_MS 2000 /* Timeout for sending */ -#define SOCK_RECV_TIMEOUT_MS 5000 /* Timeout for receiving */ - -// set WRITE_POLL_MS to 0 for blocking sockets, nonzero for polled non-blocking -// sockets -#define WRITE_POLL_MS 20 - -#define FNLOG() ALOGV("%s:%d %s: ", __FILE__, __LINE__, __func__) -#define DEBUG(fmt, args...) ALOGD("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define INFO(fmt, args...) ALOGI("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define WARN(fmt, args...) ALOGW("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) -#define ERROR(fmt, args...) ALOGE("%s:%d %s: " fmt, __FILE__, __LINE__, __func__, ##args) - -#define ASSERTC(cond, msg, val) \ - if (!(cond)) { \ - ERROR("### ASSERT : %s line %d %s (%d) ###", __FILE__, __LINE__, msg, val); \ - } - -#define CASE_RETURN_STR(const) \ - case const: \ - return #const; - -static const char* audio_ha_hw_dump_ctrl_event(tHEARING_AID_CTRL_CMD event) { - switch (event) { - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_NONE) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_CHECK_READY) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_START) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_STOP) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_SUSPEND) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_INPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_OFFLOAD_START) - default: - break; - } - - return "UNKNOWN HEARING_AID_CTRL_CMD"; -} - -/***************************************************************************** - * Local type definitions - *****************************************************************************/ - -typedef enum { - AUDIO_HA_STATE_STARTING, - AUDIO_HA_STATE_STARTED, - AUDIO_HA_STATE_STOPPING, - AUDIO_HA_STATE_STOPPED, - /* need explicit set param call to resume (suspend=false) */ - AUDIO_HA_STATE_SUSPENDED, - AUDIO_HA_STATE_STANDBY /* allows write to autoresume */ -} ha_state_t; - -struct ha_stream_in; -struct ha_stream_out; - -struct ha_audio_device { - // Important: device must be first as an audio_hw_device* may be cast to - // ha_audio_device* when the type is implicitly known. - struct audio_hw_device device; - std::recursive_mutex* mutex; // See note below on mutex acquisition order. - struct ha_stream_in* input; - struct ha_stream_out* output; -}; - -struct ha_config { - uint32_t rate; - uint32_t channel_mask; - bool is_stereo_to_mono; // True if fetching Stereo and mixing into Mono - int format; -}; - -/* move ctrl_fd outside output stream and keep open until HAL unloaded ? */ - -struct ha_stream_common { - std::recursive_mutex* mutex; // See note below on mutex acquisition order. - int ctrl_fd; - int audio_fd; - size_t buffer_sz; - struct ha_config cfg; - ha_state_t state; -}; - -struct ha_stream_out { - struct audio_stream_out stream; - struct ha_stream_common common; - uint64_t frames_presented; // frames written, never reset - uint64_t frames_rendered; // frames written, reset on standby -}; - -struct ha_stream_in { - struct audio_stream_in stream; - struct ha_stream_common common; -}; - -/* - * Mutex acquisition order: - * - * The ha_audio_device (adev) mutex must be acquired before - * the ha_stream_common (out or in) mutex. - * - * This may differ from other audio HALs. - */ - -/***************************************************************************** - * Static variables - *****************************************************************************/ - -/***************************************************************************** - * Static functions - *****************************************************************************/ -static void hash_map_utils_dump_string_keys_string_values( - std::unordered_map<std::string, std::string>& map) { - for (const auto& ptr : map) { - INFO("key: '%s' value: '%s'\n", ptr.first.c_str(), ptr.second.c_str()); - } -} - -static size_t out_get_buffer_size(const struct audio_stream* stream); - -/***************************************************************************** - * Externs - *****************************************************************************/ - -/***************************************************************************** - * Functions - *****************************************************************************/ -static void ha_open_ctrl_path(struct ha_stream_common* common); - -/***************************************************************************** - * Miscellaneous helper functions - *****************************************************************************/ - -/* logs timestamp with microsec precision - pprev is optional in case a dedicated diff is required */ -static void ts_log(UNUSED_ATTR const char* tag, UNUSED_ATTR int val, struct timespec* pprev_opt) { - struct timespec now; - static struct timespec prev = {0, 0}; - unsigned long long now_us; - unsigned long long diff_us; - - clock_gettime(CLOCK_MONOTONIC, &now); - - now_us = now.tv_sec * USEC_PER_SEC + now.tv_nsec / 1000; - - if (pprev_opt) { - diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec) / 1000; - *pprev_opt = now; - DEBUG("[%s] ts %08lld, *diff %08lld, val %d", tag, now_us, diff_us, val); - } else { - diff_us = (now.tv_sec - prev.tv_sec) * USEC_PER_SEC + (now.tv_nsec - prev.tv_nsec) / 1000; - prev = now; - DEBUG("[%s] ts %08lld, diff %08lld, val %d", tag, now_us, diff_us, val); - } -} - -static int calc_audiotime_usec(struct ha_config cfg, int bytes) { - int chan_count = audio_channel_count_from_out_mask(cfg.channel_mask); - int bytes_per_sample; - - switch (cfg.format) { - case AUDIO_FORMAT_PCM_8_BIT: - bytes_per_sample = 1; - break; - case AUDIO_FORMAT_PCM_16_BIT: - bytes_per_sample = 2; - break; - case AUDIO_FORMAT_PCM_24_BIT_PACKED: - bytes_per_sample = 3; - break; - case AUDIO_FORMAT_PCM_8_24_BIT: - bytes_per_sample = 4; - break; - case AUDIO_FORMAT_PCM_32_BIT: - bytes_per_sample = 4; - break; - default: - ASSERTC(false, "unsupported sample format", cfg.format); - bytes_per_sample = 2; - break; - } - - return (int)(((int64_t)bytes * (USEC_PER_SEC / (chan_count * bytes_per_sample))) / cfg.rate); -} - -/***************************************************************************** - * - * bluedroid stack adaptation - * - ****************************************************************************/ - -static int skt_connect(const char* path, size_t buffer_sz) { - int ret; - int skt_fd; - int len; - - INFO("connect to %s (sz %zu)", path, buffer_sz); - - skt_fd = socket(AF_LOCAL, SOCK_STREAM, 0); - - if (osi_socket_local_client_connect(skt_fd, path, ANDROID_SOCKET_NAMESPACE_ABSTRACT, - SOCK_STREAM) < 0) { - ERROR("failed to connect (%s)", strerror(errno)); - close(skt_fd); - return -1; - } - - len = buffer_sz; - ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDBUF, (char*)&len, (int)sizeof(len)); - if (ret < 0) { - ERROR("setsockopt failed (%s)", strerror(errno)); - } - - ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVBUF, (char*)&len, (int)sizeof(len)); - if (ret < 0) { - ERROR("setsockopt failed (%s)", strerror(errno)); - } - - /* Socket send/receive timeout value */ - struct timeval tv; - tv.tv_sec = SOCK_SEND_TIMEOUT_MS / 1000; - tv.tv_usec = (SOCK_SEND_TIMEOUT_MS % 1000) * 1000; - - ret = setsockopt(skt_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); - if (ret < 0) { - ERROR("setsockopt failed (%s)", strerror(errno)); - } - - tv.tv_sec = SOCK_RECV_TIMEOUT_MS / 1000; - tv.tv_usec = (SOCK_RECV_TIMEOUT_MS % 1000) * 1000; - - ret = setsockopt(skt_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); - if (ret < 0) { - ERROR("setsockopt failed (%s)", strerror(errno)); - } - - INFO("connected to stack fd = %d", skt_fd); - - return skt_fd; -} - -static int skt_read(int fd, void* p, size_t len) { - ssize_t read; - - FNLOG(); - - ts_log("skt_read recv", len, NULL); - - OSI_NO_INTR(read = recv(fd, p, len, MSG_NOSIGNAL)); - if (read == -1) { - ERROR("read failed with errno=%d\n", errno); - } - - return (int)read; -} - -static int skt_write(int fd, const void* p, size_t len) { - ssize_t sent; - FNLOG(); - - ts_log("skt_write", len, NULL); - - if (WRITE_POLL_MS == 0) { - // do not poll, use blocking send - OSI_NO_INTR(sent = send(fd, p, len, MSG_NOSIGNAL)); - if (sent == -1) { - ERROR("write failed with error(%s)", strerror(errno)); - } - - return (int)sent; - } - - // use non-blocking send, poll - int ms_timeout = SOCK_SEND_TIMEOUT_MS; - size_t count = 0; - while (count < len) { - OSI_NO_INTR(sent = send(fd, p, len - count, MSG_NOSIGNAL | MSG_DONTWAIT)); - if (sent == -1) { - if (errno != EAGAIN && errno != EWOULDBLOCK) { - ERROR("write failed with error(%s)", strerror(errno)); - return -1; - } - if (ms_timeout >= WRITE_POLL_MS) { - usleep(WRITE_POLL_MS * 1000); - ms_timeout -= WRITE_POLL_MS; - continue; - } - WARN("write timeout exceeded, sent %zu bytes", count); - return -1; - } - count += sent; - p = (const uint8_t*)p + sent; - } - return (int)count; -} - -static int skt_disconnect(int fd) { - INFO("fd %d", fd); - - if (fd != AUDIO_SKT_DISCONNECTED) { - shutdown(fd, SHUT_RDWR); - close(fd); - } - return 0; -} - -/***************************************************************************** - * - * AUDIO CONTROL PATH - * - ****************************************************************************/ - -static int ha_ctrl_receive(struct ha_stream_common* common, void* buffer, size_t length) { - ssize_t ret; - int i; - - for (i = 0;; i++) { - OSI_NO_INTR(ret = recv(common->ctrl_fd, buffer, length, MSG_NOSIGNAL)); - if (ret > 0) { - break; - } - if (ret == 0) { - ERROR("receive control data failed: peer closed"); - break; - } - if (errno != EWOULDBLOCK && errno != EAGAIN) { - ERROR("receive control data failed: error(%s)", strerror(errno)); - break; - } - if (i == (CTRL_CHAN_RETRY_COUNT - 1)) { - ERROR("receive control data failed: max retry count"); - break; - } - INFO("receive control data failed (%s), retrying", strerror(errno)); - } - if (ret <= 0) { - skt_disconnect(common->ctrl_fd); - common->ctrl_fd = AUDIO_SKT_DISCONNECTED; - } - return ret; -} - -// Sends control info for stream |common|. The data to send is stored in -// |buffer| and has size |length|. -// On success, returns the number of octets sent, otherwise -1. -static int ha_ctrl_send(struct ha_stream_common* common, const void* buffer, size_t length) { - ssize_t sent; - size_t remaining = length; - int i; - - if (length == 0) { - return 0; // Nothing to do - } - - for (i = 0;; i++) { - OSI_NO_INTR(sent = send(common->ctrl_fd, buffer, remaining, MSG_NOSIGNAL)); - if (sent == static_cast<ssize_t>(remaining)) { - remaining = 0; - break; - } - if (sent > 0) { - buffer = (static_cast<const char*>(buffer) + sent); - remaining -= sent; - continue; - } - if (sent < 0) { - if (errno != EWOULDBLOCK && errno != EAGAIN) { - ERROR("send control data failed: error(%s)", strerror(errno)); - break; - } - INFO("send control data failed (%s), retrying", strerror(errno)); - } - if (i >= (CTRL_CHAN_RETRY_COUNT - 1)) { - ERROR("send control data failed: max retry count"); - break; - } - } - if (remaining > 0) { - skt_disconnect(common->ctrl_fd); - common->ctrl_fd = AUDIO_SKT_DISCONNECTED; - return -1; - } - return length; -} - -static int ha_command(struct ha_stream_common* common, tHEARING_AID_CTRL_CMD cmd) { - char ack; - - DEBUG("HEARING_AID COMMAND %s", audio_ha_hw_dump_ctrl_event(cmd)); - - if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED) { - INFO("starting up or recovering from previous error"); - ha_open_ctrl_path(common); - if (common->ctrl_fd == AUDIO_SKT_DISCONNECTED) { - ERROR("failure to open ctrl path"); - return -1; - } - } - - /* send command */ - ssize_t sent; - OSI_NO_INTR(sent = send(common->ctrl_fd, &cmd, 1, MSG_NOSIGNAL)); - if (sent == -1) { - ERROR("cmd failed (%s)", strerror(errno)); - skt_disconnect(common->ctrl_fd); - common->ctrl_fd = AUDIO_SKT_DISCONNECTED; - return -1; - } - - /* wait for ack byte */ - if (ha_ctrl_receive(common, &ack, 1) < 0) { - ERROR("HEARING_AID COMMAND %s: no ACK", audio_ha_hw_dump_ctrl_event(cmd)); - return -1; - } - - DEBUG("HEARING_AID COMMAND %s DONE STATUS %d", audio_ha_hw_dump_ctrl_event(cmd), ack); - - if (ack == HEARING_AID_CTRL_ACK_INCALL_FAILURE) { - return ack; - } - if (ack != HEARING_AID_CTRL_ACK_SUCCESS) { - ERROR("HEARING_AID COMMAND %s error %d", audio_ha_hw_dump_ctrl_event(cmd), ack); - return -1; - } - - return 0; -} - -static int check_ha_ready(struct ha_stream_common* common) { - if (ha_command(common, HEARING_AID_CTRL_CMD_CHECK_READY) < 0) { - ERROR("check ha ready failed"); - return -1; - } - return 0; -} - -static int ha_read_input_audio_config(struct ha_stream_common* common) { - tHA_SAMPLE_RATE sample_rate; - tHA_CHANNEL_COUNT channel_count; - - if (ha_command(common, HEARING_AID_CTRL_GET_INPUT_AUDIO_CONFIG) < 0) { - ERROR("get ha input audio config failed"); - return -1; - } - - if (ha_ctrl_receive(common, &sample_rate, sizeof(tHA_SAMPLE_RATE)) < 0) { - return -1; - } - if (ha_ctrl_receive(common, &channel_count, sizeof(tHA_CHANNEL_COUNT)) < 0) { - return -1; - } - - switch (sample_rate) { - case 16000: - case 24000: - case 44100: - case 48000: - common->cfg.rate = sample_rate; - break; - default: - ERROR("Invalid sample rate: %" PRIu32, sample_rate); - return -1; - } - - switch (channel_count) { - case 1: - common->cfg.channel_mask = AUDIO_CHANNEL_IN_MONO; - break; - case 2: - common->cfg.channel_mask = AUDIO_CHANNEL_IN_STEREO; - break; - default: - ERROR("Invalid channel count: %" PRIu32, channel_count); - return -1; - } - - // TODO: For now input audio format is always hard-coded as PCM 16-bit - common->cfg.format = AUDIO_FORMAT_PCM_16_BIT; - - INFO("got input audio config %d %d", common->cfg.format, common->cfg.rate); - - return 0; -} - -static int ha_read_output_audio_config(struct ha_stream_common* common, - btav_a2dp_codec_config_t* codec_config, - btav_a2dp_codec_config_t* codec_capability, - bool update_stream_config) { - struct ha_config stream_config; - - if (ha_command(common, HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG) < 0) { - ERROR("get ha output audio config failed"); - return -1; - } - - // Receive the current codec config - if (ha_ctrl_receive(common, &codec_config->sample_rate, sizeof(btav_a2dp_codec_sample_rate_t)) < - 0) { - return -1; - } - if (ha_ctrl_receive(common, &codec_config->bits_per_sample, - sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) { - return -1; - } - if (ha_ctrl_receive(common, &codec_config->channel_mode, sizeof(btav_a2dp_codec_channel_mode_t)) < - 0) { - return -1; - } - - // Receive the current codec capability - if (ha_ctrl_receive(common, &codec_capability->sample_rate, - sizeof(btav_a2dp_codec_sample_rate_t)) < 0) { - return -1; - } - if (ha_ctrl_receive(common, &codec_capability->bits_per_sample, - sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) { - return -1; - } - if (ha_ctrl_receive(common, &codec_capability->channel_mode, - sizeof(btav_a2dp_codec_channel_mode_t)) < 0) { - return -1; - } - - // Check the codec config sample rate - switch (codec_config->sample_rate) { - case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: - stream_config.rate = 44100; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: - stream_config.rate = 48000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_88200: - stream_config.rate = 88200; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_96000: - stream_config.rate = 96000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_176400: - stream_config.rate = 176400; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_192000: - stream_config.rate = 192000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: - stream_config.rate = 16000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: - stream_config.rate = 24000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - default: - ERROR("Invalid sample rate: 0x%x", codec_config->sample_rate); - return -1; - } - - // Check the codec config bits per sample - switch (codec_config->bits_per_sample) { - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: - stream_config.format = AUDIO_FORMAT_PCM_16_BIT; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: - stream_config.format = AUDIO_FORMAT_PCM_24_BIT_PACKED; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: - stream_config.format = AUDIO_FORMAT_PCM_32_BIT; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - default: - ERROR("Invalid bits per sample: 0x%x", codec_config->bits_per_sample); - return -1; - } - - // Check the codec config channel mode - switch (codec_config->channel_mode) { - case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: - stream_config.channel_mask = AUDIO_CHANNEL_OUT_MONO; - stream_config.is_stereo_to_mono = true; - break; - case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: - stream_config.channel_mask = AUDIO_CHANNEL_OUT_STEREO; - stream_config.is_stereo_to_mono = false; - break; - case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - default: - ERROR("Invalid channel mode: 0x%x", codec_config->channel_mode); - return -1; - } - if (stream_config.is_stereo_to_mono) { - stream_config.channel_mask = AUDIO_CHANNEL_OUT_STEREO; - } - - // Update the output stream configuration - if (update_stream_config) { - common->cfg.rate = stream_config.rate; - common->cfg.channel_mask = stream_config.channel_mask; - common->cfg.is_stereo_to_mono = stream_config.is_stereo_to_mono; - common->cfg.format = stream_config.format; - common->buffer_sz = audio_ha_hw_stream_compute_buffer_size( - codec_config->sample_rate, codec_config->bits_per_sample, codec_config->channel_mode); - if (common->cfg.is_stereo_to_mono) { - // We need to fetch twice as much data from the Audio framework - common->buffer_sz *= 2; - } - } - - INFO("got output codec config (update_stream_config=%s): " - "sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", - update_stream_config ? "true" : "false", codec_config->sample_rate, - codec_config->bits_per_sample, codec_config->channel_mode); - - INFO("got output codec capability: sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", - codec_capability->sample_rate, codec_capability->bits_per_sample, - codec_capability->channel_mode); - - return 0; -} - -static int ha_write_output_audio_config(struct ha_stream_common* common) { - btav_a2dp_codec_config_t codec_config; - - if (ha_command(common, HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG) < 0) { - ERROR("set ha output audio config failed"); - return -1; - } - - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; - - switch (common->cfg.rate) { - case 44100: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - break; - case 48000: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - break; - case 88200: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - break; - case 96000: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_96000; - break; - case 176400: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_176400; - break; - case 192000: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_192000; - break; - case 16000: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_16000; - break; - case 24000: - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_24000; - break; - default: - ERROR("Invalid sample rate: %" PRIu32, common->cfg.rate); - return -1; - } - - switch (common->cfg.format) { - case AUDIO_FORMAT_PCM_16_BIT: - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; - break; - case AUDIO_FORMAT_PCM_24_BIT_PACKED: - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; - break; - case AUDIO_FORMAT_PCM_32_BIT: - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32; - break; - case AUDIO_FORMAT_PCM_8_24_BIT: - // All 24-bit audio is expected in AUDIO_FORMAT_PCM_24_BIT_PACKED format - FALLTHROUGH_INTENDED; /* FALLTHROUGH */ - default: - ERROR("Invalid audio format: 0x%x", common->cfg.format); - return -1; - } - - switch (common->cfg.channel_mask) { - case AUDIO_CHANNEL_OUT_MONO: - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - break; - case AUDIO_CHANNEL_OUT_STEREO: - if (common->cfg.is_stereo_to_mono) { - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } else { - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - break; - default: - ERROR("Invalid channel mask: 0x%x", common->cfg.channel_mask); - return -1; - } - - // Send the current codec config that has been selected by us - if (ha_ctrl_send(common, &codec_config.sample_rate, sizeof(btav_a2dp_codec_sample_rate_t)) < 0) { - return -1; - } - if (ha_ctrl_send(common, &codec_config.bits_per_sample, - sizeof(btav_a2dp_codec_bits_per_sample_t)) < 0) { - return -1; - } - if (ha_ctrl_send(common, &codec_config.channel_mode, sizeof(btav_a2dp_codec_channel_mode_t)) < - 0) { - return -1; - } - - INFO("sent output codec config: sample_rate=0x%x bits_per_sample=0x%x channel_mode=0x%x", - codec_config.sample_rate, codec_config.bits_per_sample, codec_config.channel_mode); - - return 0; -} - -static void ha_open_ctrl_path(struct ha_stream_common* common) { - int i; - - if (common->ctrl_fd != AUDIO_SKT_DISCONNECTED) { - return; // already connected - } - - /* retry logic to catch any timing variations on control channel */ - for (i = 0; i < CTRL_CHAN_RETRY_COUNT; i++) { - /* connect control channel if not already connected */ - if ((common->ctrl_fd = - skt_connect(HEARING_AID_CTRL_PATH, AUDIO_STREAM_CONTROL_OUTPUT_BUFFER_SZ)) >= 0) { - /* success, now check if stack is ready */ - if (check_ha_ready(common) == 0) { - break; - } - - ERROR("error : ha not ready, wait 250 ms and retry"); - usleep(250000); - skt_disconnect(common->ctrl_fd); - common->ctrl_fd = AUDIO_SKT_DISCONNECTED; - } - - /* ctrl channel not ready, wait a bit */ - usleep(250000); - } -} - -/***************************************************************************** - * - * AUDIO DATA PATH - * - ****************************************************************************/ - -static void ha_stream_common_init(struct ha_stream_common* common) { - FNLOG(); - - common->mutex = new std::recursive_mutex; - - common->ctrl_fd = AUDIO_SKT_DISCONNECTED; - common->audio_fd = AUDIO_SKT_DISCONNECTED; - common->state = AUDIO_HA_STATE_STOPPED; - - /* manages max capacity of socket pipe */ - common->buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ; -} - -static void ha_stream_common_destroy(struct ha_stream_common* common) { - FNLOG(); - - delete common->mutex; - common->mutex = NULL; -} - -static int start_audio_datapath(struct ha_stream_common* common) { - INFO("state %d", common->state); - - int oldstate = common->state; - common->state = AUDIO_HA_STATE_STARTING; - - int ha_status = ha_command(common, HEARING_AID_CTRL_CMD_START); - if (ha_status < 0) { - ERROR("Audiopath start failed (status %d)", ha_status); - goto error; - } else if (ha_status == HEARING_AID_CTRL_ACK_INCALL_FAILURE) { - ERROR("Audiopath start failed - in call, move to suspended"); - goto error; - } - - /* connect socket if not yet connected */ - if (common->audio_fd == AUDIO_SKT_DISCONNECTED) { - common->audio_fd = skt_connect(HEARING_AID_DATA_PATH, common->buffer_sz); - if (common->audio_fd < 0) { - ERROR("Audiopath start failed - error opening data socket"); - goto error; - } - } - common->state = (ha_state_t)AUDIO_HA_STATE_STARTED; - return 0; - -error: - common->state = (ha_state_t)oldstate; - return -1; -} - -static int stop_audio_datapath(struct ha_stream_common* common) { - int oldstate = common->state; - - INFO("state %d", common->state); - - /* prevent any stray output writes from autostarting the stream - while stopping audiopath */ - common->state = AUDIO_HA_STATE_STOPPING; - - if (ha_command(common, HEARING_AID_CTRL_CMD_STOP) < 0) { - ERROR("audiopath stop failed"); - common->state = (ha_state_t)oldstate; - return -1; - } - - common->state = (ha_state_t)AUDIO_HA_STATE_STOPPED; - - /* disconnect audio path */ - skt_disconnect(common->audio_fd); - common->audio_fd = AUDIO_SKT_DISCONNECTED; - - return 0; -} - -static int suspend_audio_datapath(struct ha_stream_common* common, bool standby) { - INFO("state %d", common->state); - - if (common->state == AUDIO_HA_STATE_STOPPING) { - return -1; - } - - if (ha_command(common, HEARING_AID_CTRL_CMD_SUSPEND) < 0) { - return -1; - } - - if (standby) { - common->state = AUDIO_HA_STATE_STANDBY; - } else { - common->state = AUDIO_HA_STATE_SUSPENDED; - } - - /* disconnect audio path */ - skt_disconnect(common->audio_fd); - - common->audio_fd = AUDIO_SKT_DISCONNECTED; - - return 0; -} - -/***************************************************************************** - * - * audio output callbacks - * - ****************************************************************************/ - -static ssize_t out_write(struct audio_stream_out* stream, const void* buffer, size_t bytes) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - int sent = -1; - size_t write_bytes = bytes; - - DEBUG("write %zu bytes (fd %d)", bytes, out->common.audio_fd); - - std::unique_lock<std::recursive_mutex> lock(*out->common.mutex); - if (out->common.state == AUDIO_HA_STATE_SUSPENDED || - out->common.state == AUDIO_HA_STATE_STOPPING) { - DEBUG("stream suspended or closing"); - goto finish; - } - - /* only allow autostarting if we are in stopped or standby */ - if ((out->common.state == AUDIO_HA_STATE_STOPPED) || - (out->common.state == AUDIO_HA_STATE_STANDBY)) { - if (start_audio_datapath(&out->common) < 0) { - goto finish; - } - } else if (out->common.state != AUDIO_HA_STATE_STARTED) { - ERROR("stream not in stopped or standby"); - goto finish; - } - - // Mix the stereo into mono if necessary - if (out->common.cfg.is_stereo_to_mono) { - const size_t frames = bytes / audio_stream_out_frame_size(stream); - int16_t* src = (int16_t*)buffer; - int16_t* dst = (int16_t*)buffer; - for (size_t i = 0; i < frames; i++, dst++, src += 2) { - *dst = (int16_t)(((int32_t)src[0] + (int32_t)src[1]) >> 1); - } - write_bytes /= 2; - DEBUG("stereo-to-mono mixing: write %zu bytes (fd %d)", write_bytes, out->common.audio_fd); - } - - lock.unlock(); - sent = skt_write(out->common.audio_fd, buffer, write_bytes); - lock.lock(); - - if (sent == -1) { - skt_disconnect(out->common.audio_fd); - out->common.audio_fd = AUDIO_SKT_DISCONNECTED; - if ((out->common.state != AUDIO_HA_STATE_SUSPENDED) && - (out->common.state != AUDIO_HA_STATE_STOPPING)) { - out->common.state = AUDIO_HA_STATE_STOPPED; - } else { - ERROR("write failed : stream suspended, avoid resetting state"); - } - goto finish; - } - -finish:; - const size_t frames = bytes / audio_stream_out_frame_size(stream); - out->frames_rendered += frames; - out->frames_presented += frames; - lock.unlock(); - - // If send didn't work out, sleep to emulate write delay. - if (sent == -1) { - const int us_delay = calc_audiotime_usec(out->common.cfg, bytes); - DEBUG("emulate ha write delay (%d us)", us_delay); - usleep(us_delay); - } - return bytes; -} - -static uint32_t out_get_sample_rate(const struct audio_stream* stream) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - DEBUG("rate %" PRIu32, out->common.cfg.rate); - - return out->common.cfg.rate; -} - -static int out_set_sample_rate(struct audio_stream* stream, uint32_t rate) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - DEBUG("out_set_sample_rate : %" PRIu32, rate); - - out->common.cfg.rate = rate; - - return 0; -} - -static size_t out_get_buffer_size(const struct audio_stream* stream) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - // period_size is the AudioFlinger mixer buffer size. - const size_t period_size = out->common.buffer_sz / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS; - - DEBUG("socket buffer size: %zu period size: %zu", out->common.buffer_sz, period_size); - - return period_size; -} - -size_t audio_ha_hw_stream_compute_buffer_size( - btav_a2dp_codec_sample_rate_t codec_sample_rate, - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample, - btav_a2dp_codec_channel_mode_t codec_channel_mode) { - size_t buffer_sz = AUDIO_STREAM_OUTPUT_BUFFER_SZ; // Default value - const uint64_t time_period_ms = 20; // Conservative 20ms - uint32_t sample_rate; - uint32_t bits_per_sample; - uint32_t number_of_channels; - - // Check the codec config sample rate - switch (codec_sample_rate) { - case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: - sample_rate = 44100; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: - sample_rate = 48000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_88200: - sample_rate = 88200; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_96000: - sample_rate = 96000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_176400: - sample_rate = 176400; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_192000: - sample_rate = 192000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: - sample_rate = 16000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: - sample_rate = 24000; - break; - case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - default: - ERROR("Invalid sample rate: 0x%x", codec_sample_rate); - return buffer_sz; - } - - // Check the codec config bits per sample - switch (codec_bits_per_sample) { - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: - bits_per_sample = 16; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: - bits_per_sample = 24; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: - bits_per_sample = 32; - break; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - default: - ERROR("Invalid bits per sample: 0x%x", codec_bits_per_sample); - return buffer_sz; - } - - // Check the codec config channel mode - switch (codec_channel_mode) { - case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: - number_of_channels = 1; - break; - case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: - number_of_channels = 2; - break; - case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - default: - ERROR("Invalid channel mode: 0x%x", codec_channel_mode); - return buffer_sz; - } - - // - // The buffer size is computed by using the following formula: - // - // AUDIO_STREAM_OUTPUT_BUFFER_SIZE = - // (TIME_PERIOD_MS * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * - // SAMPLE_RATE_HZ * NUMBER_OF_CHANNELS * (BITS_PER_SAMPLE / 8)) / 1000 - // - // AUDIO_STREAM_OUTPUT_BUFFER_PERIODS controls how the socket buffer is - // divided for AudioFlinger data delivery. The AudioFlinger mixer delivers - // data in chunks of - // (AUDIO_STREAM_OUTPUT_BUFFER_SIZE / AUDIO_STREAM_OUTPUT_BUFFER_PERIODS) . - // If the number of periods is 2, the socket buffer represents "double - // buffering" of the AudioFlinger mixer buffer. - // - // Furthermore, the AudioFlinger expects the buffer size to be a multiple - // of 16 frames. - const size_t divisor = - (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * number_of_channels * bits_per_sample) / 8; - - buffer_sz = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * sample_rate * - number_of_channels * (bits_per_sample / 8)) / - 1000; - - // Adjust the buffer size so it can be divided by the divisor - const size_t remainder = buffer_sz % divisor; - if (remainder != 0) { - buffer_sz += divisor - remainder; - } - - return buffer_sz; -} - -static audio_channel_mask_t out_get_channels(const struct audio_stream* stream) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - DEBUG("channels 0x%" PRIx32, out->common.cfg.channel_mask); - - return (audio_channel_mask_t)out->common.cfg.channel_mask; -} - -static audio_format_t out_get_format(const struct audio_stream* stream) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - DEBUG("format 0x%x", out->common.cfg.format); - return (audio_format_t)out->common.cfg.format; -} - -static int out_set_format(UNUSED_ATTR struct audio_stream* stream, - UNUSED_ATTR audio_format_t format) { - DEBUG("setting format not yet supported (0x%x)", format); - return -ENOSYS; -} - -static int out_standby(struct audio_stream* stream) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - int retVal = 0; - - FNLOG(); - - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - // Do nothing in SUSPENDED state. - if (out->common.state != AUDIO_HA_STATE_SUSPENDED) { - retVal = suspend_audio_datapath(&out->common, true); - } - out->frames_rendered = 0; // rendered is reset, presented is not - - return retVal; -} - -static int out_dump(UNUSED_ATTR const struct audio_stream* stream, UNUSED_ATTR int fd) { - FNLOG(); - return 0; -} - -static int out_set_parameters(struct audio_stream* stream, const char* kvpairs) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - INFO("state %d kvpairs %s", out->common.state, kvpairs); - - std::unordered_map<std::string, std::string> params = - hash_map_utils_new_from_string_params(kvpairs); - int status = 0; - - if (params.empty()) { - return status; - } - - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - - /* dump params */ - hash_map_utils_dump_string_keys_string_values(params); - - if (params[AUDIO_PARAMETER_KEY_CLOSING].compare("true") == 0) { - DEBUG("stream closing, disallow any writes"); - out->common.state = AUDIO_HA_STATE_STOPPING; - } - - if (params["HearingAidSuspended"].compare("true") == 0) { - if (out->common.state == AUDIO_HA_STATE_STARTED) { - status = suspend_audio_datapath(&out->common, false); - } - } else { - /* Do not start the streaming automatically. If the phone was streaming - * prior to being suspended, the next out_write shall trigger the - * AVDTP start procedure */ - if (out->common.state == AUDIO_HA_STATE_SUSPENDED) { - out->common.state = AUDIO_HA_STATE_STANDBY; - } - /* Irrespective of the state, return 0 */ - } - - return status; -} - -static char* out_get_parameters(const struct audio_stream* stream, const char* keys) { - FNLOG(); - - btav_a2dp_codec_config_t codec_config; - btav_a2dp_codec_config_t codec_capability; - - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - std::unordered_map<std::string, std::string> params = hash_map_utils_new_from_string_params(keys); - std::unordered_map<std::string, std::string> return_params; - - if (params.empty()) { - return strdup(""); - } - - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - - if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, - false /* update_stream_config */) < 0) { - ERROR("ha_read_output_audio_config failed"); - goto done; - } - - // Add the format - if (params.find(AUDIO_PARAMETER_STREAM_SUP_FORMATS) != params.end()) { - std::string param; - if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { - if (!param.empty()) { - param += "|"; - } - param += "AUDIO_FORMAT_PCM_16_BIT"; - } - if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { - if (!param.empty()) { - param += "|"; - } - param += "AUDIO_FORMAT_PCM_24_BIT_PACKED"; - } - if (codec_capability.bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { - if (!param.empty()) { - param += "|"; - } - param += "AUDIO_FORMAT_PCM_32_BIT"; - } - if (param.empty()) { - ERROR("Invalid codec capability bits_per_sample=0x%x", codec_capability.bits_per_sample); - goto done; - } else { - return_params[AUDIO_PARAMETER_STREAM_SUP_FORMATS] = param; - } - } - - // Add the sample rate - if (params.find(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES) != params.end()) { - std::string param; - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_44100) { - if (!param.empty()) { - param += "|"; - } - param += "44100"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_48000) { - if (!param.empty()) { - param += "|"; - } - param += "48000"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_88200) { - if (!param.empty()) { - param += "|"; - } - param += "88200"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_96000) { - if (!param.empty()) { - param += "|"; - } - param += "96000"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_176400) { - if (!param.empty()) { - param += "|"; - } - param += "176400"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_192000) { - if (!param.empty()) { - param += "|"; - } - param += "192000"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_16000) { - if (!param.empty()) { - param += "|"; - } - param += "16000"; - } - if (codec_capability.sample_rate & BTAV_A2DP_CODEC_SAMPLE_RATE_24000) { - if (!param.empty()) { - param += "|"; - } - param += "24000"; - } - if (param.empty()) { - ERROR("Invalid codec capability sample_rate=0x%x", codec_capability.sample_rate); - goto done; - } else { - return_params[AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES] = param; - } - } - - // Add the channel mask - if (params.find(AUDIO_PARAMETER_STREAM_SUP_CHANNELS) != params.end()) { - std::string param; - if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_MONO) { - if (!param.empty()) { - param += "|"; - } - param += "AUDIO_CHANNEL_OUT_MONO"; - } - if (codec_capability.channel_mode & BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO) { - if (!param.empty()) { - param += "|"; - } - param += "AUDIO_CHANNEL_OUT_STEREO"; - } - if (param.empty()) { - ERROR("Invalid codec capability channel_mode=0x%x", codec_capability.channel_mode); - goto done; - } else { - return_params[AUDIO_PARAMETER_STREAM_SUP_CHANNELS] = param; - } - } - -done: - std::string result; - for (const auto& ptr : return_params) { - result += ptr.first + "=" + ptr.second + ";"; - } - - INFO("get parameters result = %s", result.c_str()); - - return strdup(result.c_str()); -} - -static uint32_t out_get_latency(const struct audio_stream_out* stream) { - int latency_us; - - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - FNLOG(); - - latency_us = ((out->common.buffer_sz * 1000) / audio_stream_out_frame_size(&out->stream) / - out->common.cfg.rate) * - 1000; - - return (latency_us / 1000) + 200; -} - -static int out_set_volume(UNUSED_ATTR struct audio_stream_out* stream, UNUSED_ATTR float left, - UNUSED_ATTR float right) { - FNLOG(); - - /* volume controlled in audioflinger mixer (digital) */ - - return -ENOSYS; -} - -static int out_get_presentation_position(const struct audio_stream_out* stream, uint64_t* frames, - struct timespec* timestamp) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - FNLOG(); - if (stream == NULL || frames == NULL || timestamp == NULL) { - return -EINVAL; - } - - int ret = -EWOULDBLOCK; - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; - if (out->frames_presented >= latency_frames) { - *frames = out->frames_presented - latency_frames; - clock_gettime(CLOCK_MONOTONIC, - timestamp); // could also be associated with out_write(). - ret = 0; - } - return ret; -} - -static int out_get_render_position(const struct audio_stream_out* stream, uint32_t* dsp_frames) { - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - FNLOG(); - if (stream == NULL || dsp_frames == NULL) { - return -EINVAL; - } - - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - uint64_t latency_frames = (uint64_t)out_get_latency(stream) * out->common.cfg.rate / 1000; - if (out->frames_rendered >= latency_frames) { - *dsp_frames = (uint32_t)(out->frames_rendered - latency_frames); - } else { - *dsp_frames = 0; - } - return 0; -} - -static int out_add_audio_effect(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR effect_handle_t effect) { - FNLOG(); - return 0; -} - -static int out_remove_audio_effect(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR effect_handle_t effect) { - FNLOG(); - return 0; -} - -/* - * AUDIO INPUT STREAM - */ - -static uint32_t in_get_sample_rate(const struct audio_stream* stream) { - struct ha_stream_in* in = (struct ha_stream_in*)stream; - - FNLOG(); - return in->common.cfg.rate; -} - -static int in_set_sample_rate(struct audio_stream* stream, uint32_t rate) { - struct ha_stream_in* in = (struct ha_stream_in*)stream; - - FNLOG(); - - if (in->common.cfg.rate > 0 && in->common.cfg.rate == rate) { - return 0; - } else { - return -1; - } -} - -static size_t in_get_buffer_size(UNUSED_ATTR const struct audio_stream* stream) { - FNLOG(); - return 320; -} - -static audio_channel_mask_t in_get_channels(const struct audio_stream* stream) { - struct ha_stream_in* in = (struct ha_stream_in*)stream; - - FNLOG(); - return (audio_channel_mask_t)in->common.cfg.channel_mask; -} - -static audio_format_t in_get_format(UNUSED_ATTR const struct audio_stream* stream) { - FNLOG(); - return AUDIO_FORMAT_PCM_16_BIT; -} - -static int in_set_format(UNUSED_ATTR struct audio_stream* stream, - UNUSED_ATTR audio_format_t format) { - FNLOG(); - if (format == AUDIO_FORMAT_PCM_16_BIT) { - return 0; - } else { - return -1; - } -} - -static int in_standby(UNUSED_ATTR struct audio_stream* stream) { - FNLOG(); - return 0; -} - -static int in_dump(UNUSED_ATTR const struct audio_stream* stream, UNUSED_ATTR int fd) { - FNLOG(); - return 0; -} - -static int in_set_parameters(UNUSED_ATTR struct audio_stream* stream, - UNUSED_ATTR const char* kvpairs) { - FNLOG(); - return 0; -} - -static char* in_get_parameters(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR const char* keys) { - FNLOG(); - return strdup(""); -} - -static int in_set_gain(UNUSED_ATTR struct audio_stream_in* stream, UNUSED_ATTR float gain) { - FNLOG(); - return 0; -} - -static ssize_t in_read(struct audio_stream_in* stream, void* buffer, size_t bytes) { - struct ha_stream_in* in = (struct ha_stream_in*)stream; - int read; - int us_delay; - - DEBUG("read %zu bytes, state: %d", bytes, in->common.state); - - std::unique_lock<std::recursive_mutex> lock(*in->common.mutex); - if (in->common.state == AUDIO_HA_STATE_SUSPENDED || in->common.state == AUDIO_HA_STATE_STOPPING) { - DEBUG("stream suspended"); - goto error; - } - - /* only allow autostarting if we are in stopped or standby */ - if ((in->common.state == AUDIO_HA_STATE_STOPPED) || - (in->common.state == AUDIO_HA_STATE_STANDBY)) { - if (start_audio_datapath(&in->common) < 0) { - goto error; - } - } else if (in->common.state != AUDIO_HA_STATE_STARTED) { - ERROR("stream not in stopped or standby"); - goto error; - } - - lock.unlock(); - read = skt_read(in->common.audio_fd, buffer, bytes); - lock.lock(); - if (read == -1) { - skt_disconnect(in->common.audio_fd); - in->common.audio_fd = AUDIO_SKT_DISCONNECTED; - if ((in->common.state != AUDIO_HA_STATE_SUSPENDED) && - (in->common.state != AUDIO_HA_STATE_STOPPING)) { - in->common.state = AUDIO_HA_STATE_STOPPED; - } else { - ERROR("read failed : stream suspended, avoid resetting state"); - } - goto error; - } else if (read == 0) { - DEBUG("read time out - return zeros"); - memset(buffer, 0, bytes); - read = bytes; - } - lock.unlock(); - - DEBUG("read %d bytes out of %zu bytes", read, bytes); - return read; - -error: - memset(buffer, 0, bytes); - us_delay = calc_audiotime_usec(in->common.cfg, bytes); - DEBUG("emulate ha read delay (%d us)", us_delay); - - usleep(us_delay); - return bytes; -} - -static uint32_t in_get_input_frames_lost(UNUSED_ATTR struct audio_stream_in* stream) { - FNLOG(); - return 0; -} - -static int in_add_audio_effect(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR effect_handle_t effect) { - FNLOG(); - return 0; -} - -static int in_remove_audio_effect(UNUSED_ATTR const struct audio_stream* stream, - UNUSED_ATTR effect_handle_t effect) { - FNLOG(); - - return 0; -} - -static int adev_open_output_stream(struct audio_hw_device* dev, - UNUSED_ATTR audio_io_handle_t handle, - UNUSED_ATTR audio_devices_t devices, - UNUSED_ATTR audio_output_flags_t flags, - struct audio_config* config, - struct audio_stream_out** stream_out, - UNUSED_ATTR const char* address) - -{ - struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; - struct ha_stream_out* out; - int ret = 0; - - INFO("opening output"); - // protect against adev->output and stream_out from being inconsistent - std::lock_guard<std::recursive_mutex> lock(*ha_dev->mutex); - out = (struct ha_stream_out*)calloc(1, sizeof(struct ha_stream_out)); - - if (!out) { - return -ENOMEM; - } - - out->stream.common.get_sample_rate = out_get_sample_rate; - out->stream.common.set_sample_rate = out_set_sample_rate; - out->stream.common.get_buffer_size = out_get_buffer_size; - out->stream.common.get_channels = out_get_channels; - out->stream.common.get_format = out_get_format; - out->stream.common.set_format = out_set_format; - out->stream.common.standby = out_standby; - out->stream.common.dump = out_dump; - out->stream.common.set_parameters = out_set_parameters; - out->stream.common.get_parameters = out_get_parameters; - out->stream.common.add_audio_effect = out_add_audio_effect; - out->stream.common.remove_audio_effect = out_remove_audio_effect; - out->stream.get_latency = out_get_latency; - out->stream.set_volume = out_set_volume; - out->stream.write = out_write; - out->stream.get_render_position = out_get_render_position; - out->stream.get_presentation_position = out_get_presentation_position; - - /* initialize ha specifics */ - ha_stream_common_init(&out->common); - - // Make sure we always have the feeding parameters configured - btav_a2dp_codec_config_t codec_config; - btav_a2dp_codec_config_t codec_capability; - if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, - true /* update_stream_config */) < 0) { - ERROR("ha_read_output_audio_config failed"); - ret = -1; - goto err_open; - } - // ha_read_output_audio_config() opens the socket control path (or fails) - - /* set output config values */ - if (config != nullptr) { - // Try to use the config parameters and send it to the remote side - // TODO: Shall we use out_set_format() and similar? - if (config->format != 0) { - out->common.cfg.format = config->format; - } - if (config->sample_rate != 0) { - out->common.cfg.rate = config->sample_rate; - } - if (config->channel_mask != 0) { - out->common.cfg.channel_mask = config->channel_mask; - } - if ((out->common.cfg.format != 0) || (out->common.cfg.rate != 0) || - (out->common.cfg.channel_mask != 0)) { - if (ha_write_output_audio_config(&out->common) < 0) { - ERROR("ha_write_output_audio_config failed"); - ret = -1; - goto err_open; - } - // Read again and make sure we use the same parameters as the remote side - if (ha_read_output_audio_config(&out->common, &codec_config, &codec_capability, - true /* update_stream_config */) < 0) { - ERROR("ha_read_output_audio_config failed"); - ret = -1; - goto err_open; - } - } - config->format = out_get_format((const struct audio_stream*)&out->stream); - config->sample_rate = out_get_sample_rate((const struct audio_stream*)&out->stream); - config->channel_mask = out_get_channels((const struct audio_stream*)&out->stream); - - INFO("Output stream config: format=0x%x sample_rate=%d channel_mask=0x%x buffer_sz=%zu", - config->format, config->sample_rate, config->channel_mask, out->common.buffer_sz); - } - *stream_out = &out->stream; - ha_dev->output = out; - - DEBUG("success"); - /* Delay to ensure Headset is in proper state when START is initiated from - * DUT immediately after the connection due to ongoing music playback. */ - usleep(250000); - return 0; - -err_open: - ha_stream_common_destroy(&out->common); - free(out); - *stream_out = NULL; - ha_dev->output = NULL; - ERROR("failed"); - return ret; -} - -static void adev_close_output_stream(struct audio_hw_device* dev, struct audio_stream_out* stream) { - struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; - struct ha_stream_out* out = (struct ha_stream_out*)stream; - - // prevent interference with adev_set_parameters. - std::lock_guard<std::recursive_mutex> lock(*ha_dev->mutex); - { - std::lock_guard<std::recursive_mutex> lock(*out->common.mutex); - const ha_state_t state = out->common.state; - INFO("closing output (state %d)", (int)state); - if ((state == AUDIO_HA_STATE_STARTED) || (state == AUDIO_HA_STATE_STOPPING)) { - stop_audio_datapath(&out->common); - } - - skt_disconnect(out->common.ctrl_fd); - out->common.ctrl_fd = AUDIO_SKT_DISCONNECTED; - } - - ha_stream_common_destroy(&out->common); - free(stream); - ha_dev->output = NULL; - - DEBUG("done"); -} - -static int adev_set_parameters(struct audio_hw_device* dev, const char* kvpairs) { - struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; - int retval = 0; - - // prevent interference with adev_close_output_stream - std::lock_guard<std::recursive_mutex> lock(*ha_dev->mutex); - struct ha_stream_out* out = ha_dev->output; - - if (out == NULL) { - return retval; - } - - INFO("state %d", out->common.state); - - retval = out->stream.common.set_parameters((struct audio_stream*)out, kvpairs); - - return retval; -} - -static char* adev_get_parameters(UNUSED_ATTR const struct audio_hw_device* dev, const char* keys) { - FNLOG(); - - std::unordered_map<std::string, std::string> params = hash_map_utils_new_from_string_params(keys); - hash_map_utils_dump_string_keys_string_values(params); - - return strdup(""); -} - -static int adev_init_check(UNUSED_ATTR const struct audio_hw_device* dev) { - FNLOG(); - - return 0; -} - -static int adev_set_voice_volume(UNUSED_ATTR struct audio_hw_device* dev, - UNUSED_ATTR float volume) { - FNLOG(); - - return -ENOSYS; -} - -static int adev_set_master_volume(UNUSED_ATTR struct audio_hw_device* dev, - UNUSED_ATTR float volume) { - FNLOG(); - - return -ENOSYS; -} - -static int adev_set_mode(UNUSED_ATTR struct audio_hw_device* dev, UNUSED_ATTR audio_mode_t mode) { - FNLOG(); - - return 0; -} - -static int adev_set_mic_mute(UNUSED_ATTR struct audio_hw_device* dev, UNUSED_ATTR bool state) { - FNLOG(); - - return -ENOSYS; -} - -static int adev_get_mic_mute(UNUSED_ATTR const struct audio_hw_device* dev, - UNUSED_ATTR bool* state) { - FNLOG(); - - return -ENOSYS; -} - -static size_t adev_get_input_buffer_size(UNUSED_ATTR const struct audio_hw_device* dev, - UNUSED_ATTR const struct audio_config* config) { - FNLOG(); - - return 320; -} - -static int adev_open_input_stream(struct audio_hw_device* dev, UNUSED_ATTR audio_io_handle_t handle, - UNUSED_ATTR audio_devices_t devices, - UNUSED_ATTR struct audio_config* config, - struct audio_stream_in** stream_in, - UNUSED_ATTR audio_input_flags_t flags, - UNUSED_ATTR const char* address, - UNUSED_ATTR audio_source_t source) { - struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; - struct ha_stream_in* in; - int ret; - - FNLOG(); - - // protect against adev->input and stream_in from being inconsistent - std::lock_guard<std::recursive_mutex> lock(*ha_dev->mutex); - in = (struct ha_stream_in*)calloc(1, sizeof(struct ha_stream_in)); - - if (!in) { - return -ENOMEM; - } - - in->stream.common.get_sample_rate = in_get_sample_rate; - in->stream.common.set_sample_rate = in_set_sample_rate; - in->stream.common.get_buffer_size = in_get_buffer_size; - in->stream.common.get_channels = in_get_channels; - in->stream.common.get_format = in_get_format; - in->stream.common.set_format = in_set_format; - in->stream.common.standby = in_standby; - in->stream.common.dump = in_dump; - in->stream.common.set_parameters = in_set_parameters; - in->stream.common.get_parameters = in_get_parameters; - in->stream.common.add_audio_effect = in_add_audio_effect; - in->stream.common.remove_audio_effect = in_remove_audio_effect; - in->stream.set_gain = in_set_gain; - in->stream.read = in_read; - in->stream.get_input_frames_lost = in_get_input_frames_lost; - - /* initialize ha specifics */ - ha_stream_common_init(&in->common); - - *stream_in = &in->stream; - ha_dev->input = in; - - if (ha_read_input_audio_config(&in->common) < 0) { - ERROR("ha_read_input_audio_config failed (%s)", strerror(errno)); - ret = -1; - goto err_open; - } - // ha_read_input_audio_config() opens socket control path (or fails) - - DEBUG("success"); - return 0; - -err_open: - ha_stream_common_destroy(&in->common); - free(in); - *stream_in = NULL; - ha_dev->input = NULL; - ERROR("failed"); - return ret; -} - -static void adev_close_input_stream(struct audio_hw_device* dev, struct audio_stream_in* stream) { - struct ha_audio_device* ha_dev = (struct ha_audio_device*)dev; - struct ha_stream_in* in = (struct ha_stream_in*)stream; - - std::lock_guard<std::recursive_mutex> lock(*ha_dev->mutex); - { - std::lock_guard<std::recursive_mutex> lock(*in->common.mutex); - const ha_state_t state = in->common.state; - INFO("closing input (state %d)", (int)state); - - if ((state == AUDIO_HA_STATE_STARTED) || (state == AUDIO_HA_STATE_STOPPING)) { - stop_audio_datapath(&in->common); - } - - skt_disconnect(in->common.ctrl_fd); - in->common.ctrl_fd = AUDIO_SKT_DISCONNECTED; - } - ha_stream_common_destroy(&in->common); - free(stream); - ha_dev->input = NULL; - - DEBUG("done"); -} - -static int adev_dump(UNUSED_ATTR const audio_hw_device_t* device, UNUSED_ATTR int fd) { - FNLOG(); - - return 0; -} - -static int adev_close(hw_device_t* device) { - struct ha_audio_device* ha_dev = (struct ha_audio_device*)device; - FNLOG(); - - delete ha_dev->mutex; - ha_dev->mutex = nullptr; - free(device); - return 0; -} - -static int adev_open(const hw_module_t* module, const char* name, hw_device_t** device) { - struct ha_audio_device* adev; - - INFO(" adev_open in ha_hw module"); - FNLOG(); - - if (strcmp(name, AUDIO_HARDWARE_INTERFACE) != 0) { - ERROR("interface %s not matching [%s]", name, AUDIO_HARDWARE_INTERFACE); - return -EINVAL; - } - - adev = (struct ha_audio_device*)calloc(1, sizeof(struct ha_audio_device)); - - if (!adev) { - return -ENOMEM; - } - - adev->mutex = new std::recursive_mutex; - - adev->device.common.tag = HARDWARE_DEVICE_TAG; - adev->device.common.version = AUDIO_DEVICE_API_VERSION_2_0; - adev->device.common.module = (struct hw_module_t*)module; - adev->device.common.close = adev_close; - - adev->device.init_check = adev_init_check; - adev->device.set_voice_volume = adev_set_voice_volume; - adev->device.set_master_volume = adev_set_master_volume; - adev->device.set_mode = adev_set_mode; - adev->device.set_mic_mute = adev_set_mic_mute; - adev->device.get_mic_mute = adev_get_mic_mute; - adev->device.set_parameters = adev_set_parameters; - adev->device.get_parameters = adev_get_parameters; - adev->device.get_input_buffer_size = adev_get_input_buffer_size; - adev->device.open_output_stream = adev_open_output_stream; - adev->device.close_output_stream = adev_close_output_stream; - adev->device.open_input_stream = adev_open_input_stream; - adev->device.close_input_stream = adev_close_input_stream; - adev->device.dump = adev_dump; - - adev->output = NULL; - - *device = &adev->device.common; - - return 0; -} - -static struct hw_module_methods_t hal_module_methods = { - .open = adev_open, -}; - -__attribute__((visibility("default"))) struct audio_module HAL_MODULE_INFO_SYM = { - .common = - { - .tag = HARDWARE_MODULE_TAG, - .version_major = 1, - .version_minor = 0, - .id = AUDIO_HARDWARE_MODULE_ID, - .name = "Hearing Aid Audio HW HAL", - .author = "The Android Open Source Project", - .methods = &hal_module_methods, - }, -}; diff --git a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw_utils.cc b/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw_utils.cc deleted file mode 100644 index 1553b05d3e..0000000000 --- a/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw_utils.cc +++ /dev/null @@ -1,44 +0,0 @@ -/****************************************************************************** - * - * Copyright 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" - -#define CASE_RETURN_STR(const) \ - case const: \ - return #const; - -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - -const char* audio_ha_hw_dump_ctrl_event(tHEARING_AID_CTRL_CMD event) { - switch (event) { - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_NONE) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_CHECK_READY) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_START) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_STOP) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_SUSPEND) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_INPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_OFFLOAD_START) - default: - break; - } - - return "UNKNOWN HEARING_AID_CTRL_CMD"; -} diff --git a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc b/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc deleted file mode 100644 index 95f3dc6288..0000000000 --- a/system/audio_hearing_aid_hw/test/audio_hearing_aid_hw_test.cc +++ /dev/null @@ -1,140 +0,0 @@ -/****************************************************************************** - * - * Copyright 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" - -#include <gtest/gtest.h> - -namespace { -static uint32_t codec_sample_rate2value(btav_a2dp_codec_sample_rate_t codec_sample_rate) { - switch (codec_sample_rate) { - case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: - return 44100; - case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: - return 48000; - case BTAV_A2DP_CODEC_SAMPLE_RATE_88200: - return 88200; - case BTAV_A2DP_CODEC_SAMPLE_RATE_96000: - return 96000; - case BTAV_A2DP_CODEC_SAMPLE_RATE_176400: - return 176400; - case BTAV_A2DP_CODEC_SAMPLE_RATE_192000: - return 192000; - case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: - return 16000; - case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: - return 24000; - case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - break; - } - return 0; -} - -static uint32_t codec_bits_per_sample2value( - btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample) { - switch (codec_bits_per_sample) { - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: - return 16; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: - return 24; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: - return 32; - case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - break; - } - return 0; -} - -static uint32_t codec_channel_mode2value(btav_a2dp_codec_channel_mode_t codec_channel_mode) { - switch (codec_channel_mode) { - case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: - return 1; - case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: - return 2; - case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - break; - } - return 0; -} - -} // namespace - -class AudioA2dpHwTest : public ::testing::Test { -protected: - AudioA2dpHwTest() {} - -private: -}; - -TEST_F(AudioA2dpHwTest, test_compute_buffer_size) { - const btav_a2dp_codec_sample_rate_t codec_sample_rate_array[] = { - BTAV_A2DP_CODEC_SAMPLE_RATE_NONE, BTAV_A2DP_CODEC_SAMPLE_RATE_44100, - BTAV_A2DP_CODEC_SAMPLE_RATE_48000, BTAV_A2DP_CODEC_SAMPLE_RATE_88200, - BTAV_A2DP_CODEC_SAMPLE_RATE_96000, BTAV_A2DP_CODEC_SAMPLE_RATE_176400, - BTAV_A2DP_CODEC_SAMPLE_RATE_192000}; - - const btav_a2dp_codec_bits_per_sample_t codec_bits_per_sample_array[] = { - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16, - BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24, BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32}; - - const btav_a2dp_codec_channel_mode_t codec_channel_mode_array[] = { - BTAV_A2DP_CODEC_CHANNEL_MODE_NONE, BTAV_A2DP_CODEC_CHANNEL_MODE_MONO, - BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO}; - - for (const auto codec_sample_rate : codec_sample_rate_array) { - for (const auto codec_bits_per_sample : codec_bits_per_sample_array) { - for (const auto codec_channel_mode : codec_channel_mode_array) { - size_t buffer_size = audio_ha_hw_stream_compute_buffer_size( - codec_sample_rate, codec_bits_per_sample, codec_channel_mode); - - // Check for invalid input - if ((codec_sample_rate == BTAV_A2DP_CODEC_SAMPLE_RATE_NONE) || - (codec_bits_per_sample == BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE) || - (codec_channel_mode == BTAV_A2DP_CODEC_CHANNEL_MODE_NONE)) { - EXPECT_EQ(buffer_size, static_cast<size_t>(AUDIO_STREAM_OUTPUT_BUFFER_SZ)); - continue; - } - - uint32_t sample_rate = codec_sample_rate2value(codec_sample_rate); - EXPECT_NE(0u, sample_rate); - - uint32_t bits_per_sample = codec_bits_per_sample2value(codec_bits_per_sample); - EXPECT_NE(0u, bits_per_sample); - - uint32_t number_of_channels = codec_channel_mode2value(codec_channel_mode); - EXPECT_NE(0u, number_of_channels); - - const uint64_t time_period_ms = 20; // TODO: Must be a parameter - size_t expected_buffer_size = (time_period_ms * AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * - sample_rate * number_of_channels * (bits_per_sample / 8)) / - 1000; - - // Compute the divisor and adjust the buffer size - const size_t divisor = - (AUDIO_STREAM_OUTPUT_BUFFER_PERIODS * 16 * number_of_channels * bits_per_sample) / - 8; - const size_t remainder = expected_buffer_size % divisor; - if (remainder != 0) { - expected_buffer_size += divisor - remainder; - } - - EXPECT_EQ(buffer_size, expected_buffer_size); - } - } - } -} diff --git a/system/bta/ag/bta_ag_act.cc b/system/bta/ag/bta_ag_act.cc index 559df238a2..b64fd333fe 100644 --- a/system/bta/ag/bta_ag_act.cc +++ b/system/bta/ag/bta_ag_act.cc @@ -402,7 +402,6 @@ void bta_ag_rfc_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { p_scb->codec_updated = false; p_scb->codec_fallback = false; p_scb->trying_cvsd_safe_settings = false; - p_scb->retransmission_effort_retries = 0; p_scb->codec_msbc_settings = BTA_AG_SCO_MSBC_SETTINGS_T2; p_scb->codec_cvsd_settings = BTA_AG_SCO_CVSD_SETTINGS_S4; p_scb->codec_aptx_settings = BTA_AG_SCO_APTX_SWB_SETTINGS_Q0; diff --git a/system/bta/ag/bta_ag_cmd.cc b/system/bta/ag/bta_ag_cmd.cc index 461971439f..22d291e054 100644 --- a/system/bta/ag/bta_ag_cmd.cc +++ b/system/bta/ag/bta_ag_cmd.cc @@ -47,11 +47,14 @@ #include "bta/include/bta_hfp_api.h" #include "device/include/interop.h" #include "internal_include/bt_target.h" +#include "main/shim/helpers.h" +#include "main/shim/metrics_api.h" #include "osi/include/compat.h" #include "stack/btm/btm_sco_hfp_hal.h" #include "stack/include/port_api.h" using namespace bluetooth; +using namespace bluetooth::shim; /***************************************************************************** * Constants @@ -1143,6 +1146,7 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, cha } } + LogMetricHfpAgVersion(ToGdAddress(p_scb->peer_addr), p_scb->peer_version); log::verbose("BRSF HF: 0x{:x}, phone: 0x{:x}", p_scb->peer_features, p_scb->masked_features); /* send BRSF, send OK */ diff --git a/system/bta/ag/bta_ag_int.h b/system/bta/ag/bta_ag_int.h index 9545bb6038..4faeb614c1 100644 --- a/system/bta/ag/bta_ag_int.h +++ b/system/bta/ag/bta_ag_int.h @@ -332,8 +332,6 @@ struct tBTA_AG_SCB { bool codec_fallback; /* If sco nego fails for mSBC, fallback to CVSD */ bool trying_cvsd_safe_settings; /* set to true whenever we are trying CVSD safe settings */ - uint8_t retransmission_effort_retries; /* Retry eSCO - with retransmission_effort value*/ tBTA_AG_SCO_MSBC_SETTINGS codec_msbc_settings; /* settings to be used for the impending eSCO on WB */ tBTA_AG_SCO_LC3_SETTINGS codec_lc3_settings; /* settings to be used for the diff --git a/system/bta/ag/bta_ag_main.cc b/system/bta/ag/bta_ag_main.cc index 2b95b5de39..3a0b8eb70a 100644 --- a/system/bta/ag/bta_ag_main.cc +++ b/system/bta/ag/bta_ag_main.cc @@ -152,7 +152,6 @@ static tBTA_AG_SCB* bta_ag_scb_alloc(void) { p_scb->codec_updated = false; p_scb->codec_fallback = false; p_scb->trying_cvsd_safe_settings = false; - p_scb->retransmission_effort_retries = 0; p_scb->peer_codecs = BTM_SCO_CODEC_CVSD; p_scb->sco_codec = BTM_SCO_CODEC_CVSD; p_scb->peer_version = HFP_HSP_VERSION_UNKNOWN; diff --git a/system/bta/ag/bta_ag_sco.cc b/system/bta/ag/bta_ag_sco.cc index a8e38c24a7..34102d1dd6 100644 --- a/system/bta/ag/bta_ag_sco.cc +++ b/system/bta/ag/bta_ag_sco.cc @@ -284,24 +284,15 @@ static void bta_ag_sco_disc_cback(uint16_t sco_idx) { } } else if (bta_ag_sco_is_opening(bta_ag_cb.sco.p_curr_scb) && (!com::android::bluetooth::flags::fix_hfp_qual_1_9() || bta_ag_cb.sco.is_local)) { - if (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && - bta_ag_cb.sco.p_curr_scb->retransmission_effort_retries == 0) { - bta_ag_cb.sco.p_curr_scb->retransmission_effort_retries++; - if (!com::android::bluetooth::flags::fix_hfp_qual_1_9()) { - bta_ag_cb.sco.p_curr_scb->state = (tBTA_AG_STATE)BTA_AG_SCO_CODEC_ST; - } - log::warn("eSCO/SCO failed to open, retry with retransmission_effort"); - } else { - log::error("eSCO/SCO failed to open, no more fall back"); - if (bta_ag_is_sco_managed_by_audio()) { - if (hfp_software_datapath_enabled) { - if (hfp_encode_interface) { - hfp_encode_interface->CancelStreamingRequest(); - hfp_decode_interface->CancelStreamingRequest(); - } - } else { - hfp_offload_interface->CancelStreamingRequest(); + log::error("eSCO/SCO failed to open, no more fall back"); + if (bta_ag_is_sco_managed_by_audio()) { + if (hfp_software_datapath_enabled) { + if (hfp_encode_interface) { + hfp_encode_interface->CancelStreamingRequest(); + hfp_decode_interface->CancelStreamingRequest(); } + } else { + hfp_offload_interface->CancelStreamingRequest(); } } } @@ -534,13 +525,6 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) { updateCodecParametersFromProviderInfo(esco_codec, params); - if (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && - p_scb->retransmission_effort_retries == 1) { - log::info("change retransmission_effort to 0, retry"); - p_scb->retransmission_effort_retries++; - params.retransmission_effort = ESCO_RETRANSMISSION_OFF; - } - /* Configure input/output data path based on HAL settings. */ hfp_hal_interface::set_codec_datapath(esco_codec); hfp_hal_interface::update_esco_parameters(¶ms); @@ -1484,8 +1468,6 @@ void bta_ag_sco_conn_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* call app callback */ bta_ag_cback_sco(p_scb, BTA_AG_AUDIO_OPEN_EVT); - /* reset retransmission_effort_retries*/ - p_scb->retransmission_effort_retries = 0; /* reset to mSBC T2 settings as the preferred */ p_scb->codec_msbc_settings = BTA_AG_SCO_MSBC_SETTINGS_T2; /* reset to LC3 T2 settings as the preferred */ @@ -1516,19 +1498,16 @@ void bta_ag_sco_conn_close(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& /* data */) { /* codec_fallback is set when AG is initiator and connection failed for mSBC. * OR if codec is msbc and T2 settings failed, then retry Safe T1 settings * same operations for LC3 settings */ - if (p_scb->svc_conn && - (p_scb->codec_fallback || - (p_scb->sco_codec == BTM_SCO_CODEC_MSBC && - p_scb->codec_msbc_settings == BTA_AG_SCO_MSBC_SETTINGS_T1) || - (p_scb->sco_codec == BTM_SCO_CODEC_LC3 && - p_scb->codec_lc3_settings == BTA_AG_SCO_LC3_SETTINGS_T1) || - (com::android::bluetooth::flags::retry_esco_with_zero_retransmission_effort() && - p_scb->retransmission_effort_retries == 1) || - aptx_voice || - (com::android::bluetooth::flags::fix_hfp_qual_1_9() && - p_scb->sco_codec == BTM_SCO_CODEC_CVSD && - p_scb->codec_cvsd_settings == BTA_AG_SCO_CVSD_SETTINGS_S1 && - p_scb->trying_cvsd_safe_settings))) { + if (p_scb->svc_conn && (p_scb->codec_fallback || + (p_scb->sco_codec == BTM_SCO_CODEC_MSBC && + p_scb->codec_msbc_settings == BTA_AG_SCO_MSBC_SETTINGS_T1) || + (p_scb->sco_codec == BTM_SCO_CODEC_LC3 && + p_scb->codec_lc3_settings == BTA_AG_SCO_LC3_SETTINGS_T1) || + aptx_voice || + (com::android::bluetooth::flags::fix_hfp_qual_1_9() && + p_scb->sco_codec == BTM_SCO_CODEC_CVSD && + p_scb->codec_cvsd_settings == BTA_AG_SCO_CVSD_SETTINGS_S1 && + p_scb->trying_cvsd_safe_settings))) { bta_ag_sco_event(p_scb, BTA_AG_SCO_REOPEN_E); } else { /* Indicate if the closing of audio is because of transfer */ diff --git a/system/bta/ag/bta_ag_sdp.cc b/system/bta/ag/bta_ag_sdp.cc index 3870e01c4e..9f41d2339f 100644 --- a/system/bta/ag/bta_ag_sdp.cc +++ b/system/bta/ag/bta_ag_sdp.cc @@ -43,6 +43,8 @@ #include "device/include/interop.h" #include "device/include/interop_config.h" #include "internal_include/bt_target.h" +#include "main/shim/helpers.h" +#include "main/shim/metrics_api.h" #include "osi/include/allocator.h" #include "sdp_callback.h" #include "sdp_status.h" @@ -59,6 +61,7 @@ using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; +using namespace bluetooth::shim; using bluetooth::Uuid; /* Number of protocol elements in protocol element list. */ @@ -388,6 +391,8 @@ bool bta_ag_sdp_find_attr(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { peer_version = p_scb->peer_version; } + LogMetricHfpHfVersion(ToGdAddress(p_scb->peer_addr), p_scb->peer_version); + if (service & BTA_HFP_SERVICE_MASK) { /* Update cached peer version if the new one is different */ if (peer_version != p_scb->peer_version) { diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc index adc66066f2..a9a2480849 100644 --- a/system/bta/csis/csis_client_test.cc +++ b/system/bta/csis/csis_client_test.cc @@ -33,12 +33,10 @@ #include "csis_types.h" #include "gatt/database_builder.h" #include "hardware/bt_gatt_types.h" +#include "stack/gatt/gatt_int.h" #include "stack/include/bt_uuid16.h" #include "test/common/mock_functions.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - bool gatt_cl_read_sirk_req(const RawAddress& /*peer_bda*/, base::OnceCallback<void(tGATT_STATUS status, const RawAddress&, uint8_t sirk_type, Octet16& sirk)> @@ -75,6 +73,7 @@ using testing::SetArgPointee; using testing::WithArg; // Disables most likely false-positives from base::SplitString() +extern "C" const char* __asan_default_options(); extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } RawAddress GetTestAddress(int index) { diff --git a/system/bta/gatt/bta_gattc_act.cc b/system/bta/gatt/bta_gattc_act.cc index cca68b8c0d..4825da22b7 100644 --- a/system/bta/gatt/bta_gattc_act.cc +++ b/system/bta/gatt/bta_gattc_act.cc @@ -45,9 +45,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::Uuid; using namespace bluetooth; @@ -110,8 +107,6 @@ static const char* bta_gattc_op_code_name[] = { * Action Functions ****************************************************************************/ -void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status); - /** Enables GATTC module */ static void bta_gattc_enable() { log::verbose(""); diff --git a/system/bta/gatt/bta_gattc_cache.cc b/system/bta/gatt/bta_gattc_cache.cc index ce7deeeb9e..491a29a035 100644 --- a/system/bta/gatt/bta_gattc_cache.cc +++ b/system/bta/gatt/bta_gattc_cache.cc @@ -48,9 +48,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; @@ -63,8 +60,6 @@ using gatt::IncludedService; using gatt::Service; static tGATT_STATUS bta_gattc_sdp_service_disc(tCONN_ID conn_id, tBTA_GATTC_SERV* p_server_cb); -const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle); -const Characteristic* bta_gattc_get_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle); static void bta_gattc_explore_srvc_finished(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb); static void bta_gattc_read_db_hash_cmpl(tBTA_GATTC_CLCB* p_clcb, const tBTA_GATTC_OP_CMPL* p_data, @@ -117,8 +112,8 @@ void bta_gattc_init_cache(tBTA_GATTC_SERV* p_srvc_cb) { p_srvc_cb->pending_discovery.Clear(); } -const Service* bta_gattc_find_matching_service(const std::list<Service>& services, - uint16_t handle) { +static const Service* bta_gattc_find_matching_service(const std::list<Service>& services, + uint16_t handle) { for (const Service& service : services) { if (handle >= service.handle && handle <= service.end_handle) { return &service; @@ -316,7 +311,7 @@ static void bta_gattc_explore_srvc_finished(tCONN_ID conn_id, tBTA_GATTC_SERV* p } /** Start discovery for characteristic descriptor */ -void bta_gattc_start_disc_char_dscp(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb) { +static void bta_gattc_start_disc_char_dscp(tCONN_ID conn_id, tBTA_GATTC_SERV* p_srvc_cb) { log::verbose("starting discover characteristics descriptor"); std::pair<uint16_t, uint16_t> range = p_srvc_cb->pending_discovery.NextDescriptorRangeToExplore(); @@ -336,8 +331,8 @@ descriptor_discovery_done: } /* Process the discovery result from sdp */ -void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, const RawAddress& /* bd_addr */, - tSDP_STATUS sdp_status) { +static void bta_gattc_sdp_callback(tBTA_GATTC_CB_DATA* cb_data, const RawAddress& /* bd_addr */, + tSDP_STATUS sdp_status) { tBTA_GATTC_SERV* p_srvc_cb = bta_gattc_find_scb_by_cid(cb_data->sdp_conn_id); if (p_srvc_cb == nullptr) { @@ -591,7 +586,7 @@ void bta_gattc_search_service(tBTA_GATTC_CLCB* p_clcb, Uuid* p_uuid) { } } -const std::list<Service>* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) { +static const std::list<Service>* bta_gattc_get_services_srcb(tBTA_GATTC_SERV* p_srcb) { if (!p_srcb || p_srcb->gatt_database.IsEmpty()) { return NULL; } @@ -655,7 +650,7 @@ const Characteristic* bta_gattc_get_characteristic(tCONN_ID conn_id, uint16_t ha return bta_gattc_get_characteristic_srcb(p_srcb, handle); } -const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) { +static const Descriptor* bta_gattc_get_descriptor_srcb(tBTA_GATTC_SERV* p_srcb, uint16_t handle) { const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle); if (!service) { @@ -684,8 +679,8 @@ const Descriptor* bta_gattc_get_descriptor(tCONN_ID conn_id, uint16_t handle) { return bta_gattc_get_descriptor_srcb(p_srcb, handle); } -const Characteristic* bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, - uint16_t handle) { +static const Characteristic* bta_gattc_get_owning_characteristic_srcb(tBTA_GATTC_SERV* p_srcb, + uint16_t handle) { const Service* service = bta_gattc_get_service_for_handle_srcb(p_srcb, handle); if (!service) { @@ -882,9 +877,9 @@ static void bta_gattc_read_ext_prop_desc_cmpl(tBTA_GATTC_CLCB* p_clcb, * Returns None. * ******************************************************************************/ -void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, bt_gatt_db_attribute_type_t type, - uint16_t att_handle, uint16_t s_handle, uint16_t e_handle, - uint16_t id, const Uuid& uuid, uint8_t prop) { +static void bta_gattc_fill_gatt_db_el(btgatt_db_element_t* p_attr, bt_gatt_db_attribute_type_t type, + uint16_t att_handle, uint16_t s_handle, uint16_t e_handle, + uint16_t id, const Uuid& uuid, uint8_t prop) { p_attr->type = type; p_attr->attribute_handle = att_handle; p_attr->start_handle = s_handle; diff --git a/system/bta/gatt/bta_gattc_int.h b/system/bta/gatt/bta_gattc_int.h index ef029100f9..c578da63cf 100644 --- a/system/bta/gatt/bta_gattc_int.h +++ b/system/bta/gatt/bta_gattc_int.h @@ -482,6 +482,7 @@ enum class RobustCachingSupport { UNSUPPORTED, SUPPORTED, UNKNOWN, W4_REMOTE_VER RobustCachingSupport GetRobustCachingSupport(const tBTA_GATTC_CLCB* p_clcb, const gatt::Database& db); +void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, uint16_t acl_handle); void bta_gattc_reset_discover_st(tBTA_GATTC_SERV* p_srcb, tGATT_STATUS status); tBTA_GATTC_CONN* bta_gattc_conn_alloc(const RawAddress& remote_bda); diff --git a/system/bta/gatt/bta_gattc_utils.cc b/system/bta/gatt/bta_gattc_utils.cc index f1cbab7aee..23b150b829 100644 --- a/system/bta/gatt/bta_gattc_utils.cc +++ b/system/bta/gatt/bta_gattc_utils.cc @@ -39,9 +39,6 @@ #include "types/hci_role.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; static uint8_t ble_acceptlist_size() { diff --git a/system/bta/gatt/bta_gatts_act.cc b/system/bta/gatt/bta_gatts_act.cc index b48b0cb5d1..049899fcc7 100644 --- a/system/bta/gatt/bta_gatts_act.cc +++ b/system/bta/gatt/bta_gatts_act.cc @@ -38,9 +38,6 @@ #include "stack/include/gatt_api.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; static void bta_gatts_nv_save_cback(bool is_saved, tGATTS_HNDL_RANGE* p_hndl_range); @@ -114,7 +111,7 @@ static bool bta_gatts_nv_srv_chg_cback(tGATTS_SRV_CHG_CMD /*cmd*/, tGATTS_SRV_CH * Returns none. * ******************************************************************************/ -void bta_gatts_enable(tBTA_GATTS_CB* p_cb) { +static void bta_gatts_enable(tBTA_GATTS_CB* p_cb) { if (p_cb->enabled) { log::verbose("GATTS already enabled."); } else { diff --git a/system/bta/gatt/bta_gatts_api.cc b/system/bta/gatt/bta_gatts_api.cc index 5b34fb047a..79b2b5d66e 100644 --- a/system/bta/gatt/bta_gatts_api.cc +++ b/system/bta/gatt/bta_gatts_api.cc @@ -39,9 +39,6 @@ #include "types/bt_transport.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; /***************************************************************************** @@ -123,8 +120,8 @@ void BTA_GATTS_AppDeregister(tGATT_IF server_if) { bta_sys_sendmsg(p_buf); } -void bta_gatts_add_service_impl(tGATT_IF server_if, std::vector<btgatt_db_element_t> service, - BTA_GATTS_AddServiceCb cb) { +static void bta_gatts_add_service_impl(tGATT_IF server_if, std::vector<btgatt_db_element_t> service, + BTA_GATTS_AddServiceCb cb) { uint8_t rcb_idx = bta_gatts_find_app_rcb_idx_by_app_if(&bta_gatts_cb, server_if); log::info("rcb_idx={}", rcb_idx); diff --git a/system/bta/gatt/database_builder.cc b/system/bta/gatt/database_builder.cc index bda546c9d9..ef9e5017ab 100644 --- a/system/bta/gatt/database_builder.cc +++ b/system/bta/gatt/database_builder.cc @@ -33,9 +33,6 @@ #include "stack/include/gattdefs.h" #include "types/bluetooth/uuid.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::Uuid; using namespace bluetooth; @@ -198,7 +195,7 @@ std::pair<uint16_t, uint16_t> DatabaseBuilder::NextDescriptorRangeToExplore() { return {HANDLE_MAX, HANDLE_MAX}; } -Descriptor* FindDescriptorByHandle(std::list<Service>& services, uint16_t handle) { +static Descriptor* FindDescriptorByHandle(std::list<Service>& services, uint16_t handle) { Service* service = FindService(services, handle); if (!service) { return nullptr; diff --git a/system/bta/groups/groups_test.cc b/system/bta/groups/groups_test.cc index 469da52a5d..ae64880033 100644 --- a/system/bta/groups/groups_test.cc +++ b/system/bta/groups/groups_test.cc @@ -24,9 +24,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace groups { @@ -44,7 +41,7 @@ using bluetooth::groups::DeviceGroupsCallbacks; DeviceGroupsCallbacks* dev_callbacks; -RawAddress GetTestAddress(int index) { +static RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast<uint8_t>(index)}}; return result; diff --git a/system/bta/has/has_client_test.cc b/system/bta/has/has_client_test.cc index ddaed634a0..cf0e63f1cc 100644 --- a/system/bta/has/has_client_test.cc +++ b/system/bta/has/has_client_test.cc @@ -39,14 +39,12 @@ #include "hardware/bt_gatt_types.h" #include "has_types.h" #include "mock_csis_client.h" +#include "stack/gatt/gatt_int.h" #include "stack/include/bt_uuid16.h" #include "stack/include/btm_status.h" #include "test/common/mock_functions.h" #include "types/bt_transport.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - bool gatt_profile_get_eatt_support(const RawAddress& /*addr*/) { return true; } void osi_property_set_bool(const char* key, bool value); diff --git a/system/bta/hearing_aid/hearing_aid_audio_source.cc b/system/bta/hearing_aid/hearing_aid_audio_source.cc index c8b3b92942..51714a5f70 100644 --- a/system/bta/hearing_aid/hearing_aid_audio_source.cc +++ b/system/bta/hearing_aid/hearing_aid_audio_source.cc @@ -31,7 +31,6 @@ #include <vector> #include "audio_hal_interface/hearing_aid_software_encoding.h" -#include "audio_hearing_aid_hw/include/audio_hearing_aid_hw.h" #include "bta/include/bta_hearing_aid_api.h" #include "common/message_loop_thread.h" #include "common/repeating_timer.h" @@ -40,41 +39,10 @@ #include "hardware/bt_av.h" #include "osi/include/wakelock.h" #include "stack/include/main_thread.h" -#include "udrv/include/uipc.h" using namespace bluetooth; -namespace std { -template <> -struct formatter<tUIPC_EVENT> : enum_formatter<tUIPC_EVENT> {}; -template <> -struct formatter<tHEARING_AID_CTRL_ACK> : enum_formatter<tHEARING_AID_CTRL_ACK> {}; -template <> -struct formatter<tHEARING_AID_CTRL_CMD> : enum_formatter<tHEARING_AID_CTRL_CMD> {}; -} // namespace std - namespace { -#define CASE_RETURN_STR(const) \ - case const: \ - return #const; - -const char* audio_ha_hw_dump_ctrl_event(tHEARING_AID_CTRL_CMD event) { - switch (event) { - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_NONE) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_CHECK_READY) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_START) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_STOP) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_SUSPEND) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_INPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG) - CASE_RETURN_STR(HEARING_AID_CTRL_CMD_OFFLOAD_START) - default: - break; - } - - return "UNKNOWN HEARING_AID_CTRL_CMD"; -} int bit_rate = -1; int sample_rate = -1; @@ -82,7 +50,6 @@ int data_interval_ms = -1; int num_channels = 2; bluetooth::common::RepeatingTimer audio_timer; HearingAidAudioReceiver* localAudioReceiver = nullptr; -std::unique_ptr<tUIPC_STATE> uipc_hearing_aid = nullptr; struct AudioHalStats { size_t media_read_total_underflow_bytes; @@ -108,11 +75,9 @@ void send_audio_data() { uint8_t p_buf[bytes_per_tick]; - uint32_t bytes_read; + uint32_t bytes_read = 0; if (bluetooth::audio::hearing_aid::is_hal_enabled()) { bytes_read = bluetooth::audio::hearing_aid::read(p_buf, bytes_per_tick); - } else { - bytes_read = UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, p_buf, bytes_per_tick); } log::debug("bytes_read: {}", bytes_read); @@ -129,12 +94,6 @@ void send_audio_data() { } } -void hearing_aid_send_ack(tHEARING_AID_CTRL_ACK status) { - uint8_t ack = status; - log::debug("Hearing Aid audio ctrl ack: {}", status); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, &ack, sizeof(ack)); -} - void start_audio_ticks() { if (data_interval_ms != HA_INTERVAL_10_MS && data_interval_ms != HA_INTERVAL_20_MS) { log::fatal("Unsupported data interval: {}", data_interval_ms); @@ -153,193 +112,6 @@ void stop_audio_ticks() { wakelock_release(); } -void hearing_aid_data_cb(tUIPC_CH_ID, tUIPC_EVENT event) { - log::debug("Hearing Aid audio data event: {}", event); - switch (event) { - case UIPC_OPEN_EVT: - log::info("UIPC_OPEN_EVT"); - /* - * Read directly from media task from here on (keep callback for - * connection events. - */ - UIPC_Ioctl(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, UIPC_REG_REMOVE_ACTIVE_READSET, NULL); - UIPC_Ioctl(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, UIPC_SET_READ_POLL_TMO, - reinterpret_cast<void*>(0)); - - do_in_main_thread(base::BindOnce(start_audio_ticks)); - break; - case UIPC_CLOSE_EVT: - log::info("UIPC_CLOSE_EVT"); - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); - do_in_main_thread(base::BindOnce(stop_audio_ticks)); - break; - default: - log::error("Hearing Aid audio data event not recognized: {}", event); - } -} - -void hearing_aid_recv_ctrl_data() { - tHEARING_AID_CTRL_CMD cmd = HEARING_AID_CTRL_CMD_NONE; - int n; - - uint8_t read_cmd = 0; /* The read command size is one octet */ - n = UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, &read_cmd, 1); - cmd = static_cast<tHEARING_AID_CTRL_CMD>(read_cmd); - - /* detach on ctrl channel means audioflinger process was terminated */ - if (n == 0) { - log::warn("CTRL CH DETACHED"); - UIPC_Close(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL); - return; - } - - log::info("{}", audio_ha_hw_dump_ctrl_event(cmd)); - // a2dp_cmd_pending = cmd; - - tHEARING_AID_CTRL_ACK ctrl_ack_status; - - switch (cmd) { - case HEARING_AID_CTRL_CMD_CHECK_READY: - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); - break; - - case HEARING_AID_CTRL_CMD_START: - ctrl_ack_status = HEARING_AID_CTRL_ACK_SUCCESS; - // timer is restarted in UIPC_Open - if (!hearing_aid_on_resume_req(false)) { - ctrl_ack_status = HEARING_AID_CTRL_ACK_FAILURE; - } else { - UIPC_Open(*uipc_hearing_aid, UIPC_CH_ID_AV_AUDIO, hearing_aid_data_cb, - HEARING_AID_DATA_PATH); - } - hearing_aid_send_ack(ctrl_ack_status); - break; - - case HEARING_AID_CTRL_CMD_STOP: - if (!hearing_aid_on_suspend_req()) { - log::info("HEARING_AID_CTRL_CMD_STOP: hearing_aid_on_suspend_req() errs, but ignored."); - } - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); - break; - - case HEARING_AID_CTRL_CMD_SUSPEND: - ctrl_ack_status = HEARING_AID_CTRL_ACK_SUCCESS; - if (!hearing_aid_on_suspend_req()) { - ctrl_ack_status = HEARING_AID_CTRL_ACK_FAILURE; - } - hearing_aid_send_ack(ctrl_ack_status); - break; - - case HEARING_AID_CTRL_GET_OUTPUT_AUDIO_CONFIG: { - btav_a2dp_codec_config_t codec_config; - btav_a2dp_codec_config_t codec_capability; - if (sample_rate == 16000) { - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_16000; - codec_capability.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_16000; - } else if (sample_rate == 24000) { - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_24000; - codec_capability.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_24000; - } else { - log::fatal("unsupported sample rate: {}", sample_rate); - } - - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; - codec_capability.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; - - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - codec_capability.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); - // Send the current codec config - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_config.sample_rate), - sizeof(btav_a2dp_codec_sample_rate_t)); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_config.bits_per_sample), - sizeof(btav_a2dp_codec_bits_per_sample_t)); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_config.channel_mode), - sizeof(btav_a2dp_codec_channel_mode_t)); - // Send the current codec capability - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_capability.sample_rate), - sizeof(btav_a2dp_codec_sample_rate_t)); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_capability.bits_per_sample), - sizeof(btav_a2dp_codec_bits_per_sample_t)); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, - reinterpret_cast<const uint8_t*>(&codec_capability.channel_mode), - sizeof(btav_a2dp_codec_channel_mode_t)); - break; - } - - case HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG: { - // TODO: we only support one config for now! - btav_a2dp_codec_config_t codec_config; - codec_config.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; - codec_config.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; - codec_config.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; - - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_SUCCESS); - // Send the current codec config - if (UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, - reinterpret_cast<uint8_t*>(&codec_config.sample_rate), - sizeof(btav_a2dp_codec_sample_rate_t)) != - sizeof(btav_a2dp_codec_sample_rate_t)) { - log::error("Error reading sample rate from audio HAL"); - break; - } - if (UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, - reinterpret_cast<uint8_t*>(&codec_config.bits_per_sample), - sizeof(btav_a2dp_codec_bits_per_sample_t)) != - sizeof(btav_a2dp_codec_bits_per_sample_t)) { - log::error("Error reading bits per sample from audio HAL"); - - break; - } - if (UIPC_Read(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, - reinterpret_cast<uint8_t*>(&codec_config.channel_mode), - sizeof(btav_a2dp_codec_channel_mode_t)) != - sizeof(btav_a2dp_codec_channel_mode_t)) { - log::error("Error reading channel mode from audio HAL"); - - break; - } - log::info( - "HEARING_AID_CTRL_SET_OUTPUT_AUDIO_CONFIG: sample_rate={}, " - "bits_per_sample={},channel_mode={}", - codec_config.sample_rate, codec_config.bits_per_sample, codec_config.channel_mode); - break; - } - - default: - log::error("UNSUPPORTED CMD: {}", cmd); - hearing_aid_send_ack(HEARING_AID_CTRL_ACK_FAILURE); - break; - } - log::info("a2dp-ctrl-cmd : {} DONE", audio_ha_hw_dump_ctrl_event(cmd)); -} - -void hearing_aid_ctrl_cb(tUIPC_CH_ID, tUIPC_EVENT event) { - log::debug("Hearing Aid audio ctrl event: {}", event); - switch (event) { - case UIPC_OPEN_EVT: - break; - case UIPC_CLOSE_EVT: - /* restart ctrl server unless we are shutting down */ - if (HearingAid::IsHearingAidRunning()) { - UIPC_Open(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, hearing_aid_ctrl_cb, - HEARING_AID_CTRL_PATH); - } - break; - case UIPC_RX_DATA_READY_EVT: - hearing_aid_recv_ctrl_data(); - break; - default: - log::error("Hearing Aid audio ctrl unrecognized event: {}", event); - } -} - bool hearing_aid_on_resume_req(bool start_media_task) { if (localAudioReceiver == nullptr) { log::error("HEARING_AID_CTRL_CMD_START: audio receiver not started"); @@ -414,18 +186,13 @@ void HearingAidAudioSource::Initialize() { .on_suspend_ = hearing_aid_on_suspend_req, }; if (!bluetooth::audio::hearing_aid::init(stream_cb, get_main_thread())) { - log::warn("Using legacy HAL"); - uipc_hearing_aid = UIPC_Init(); - UIPC_Open(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, hearing_aid_ctrl_cb, HEARING_AID_CTRL_PATH); + log::error("Hearing AID HAL failed to initialize"); } } void HearingAidAudioSource::CleanUp() { if (bluetooth::audio::hearing_aid::is_hal_enabled()) { bluetooth::audio::hearing_aid::cleanup(); - } else { - UIPC_Close(*uipc_hearing_aid, UIPC_CH_ID_ALL); - uipc_hearing_aid = nullptr; } } diff --git a/system/bta/hf_client/bta_hf_client_at.cc b/system/bta/hf_client/bta_hf_client_at.cc index 95d871c17c..d2344e06b4 100644 --- a/system/bta/hf_client/bta_hf_client_at.cc +++ b/system/bta/hf_client/bta_hf_client_at.cc @@ -57,9 +57,6 @@ /* timeout (in milliseconds) for AT hold timer */ #define BTA_HF_CLIENT_AT_HOLD_TIMEOUT 41 -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; static constexpr char kPropertyEnhancedDrivingIndicatorEnabled[] = @@ -120,8 +117,8 @@ static const tBTA_HF_CLIENT_INDICATOR #define BTA_HF_CLIENT_VGM_MIN 0 #define BTA_HF_CLIENT_VGM_MAX 15 -uint32_t service_index = 0; -bool service_availability = true; +static uint32_t service_index = 0; +static bool service_availability = true; /* helper functions for handling AT commands queueing */ static void bta_hf_client_handle_ok(tBTA_HF_CLIENT_CB* client_cb); @@ -792,7 +789,7 @@ void bta_hf_client_cnum(tBTA_HF_CLIENT_CB* client_cb, char* number, uint16_t ser bta_hf_client_app_callback(BTA_HF_CLIENT_CNUM_EVT, &evt); } -void bta_hf_client_unknown_response(tBTA_HF_CLIENT_CB* client_cb, const char* evt_buffer) { +static void bta_hf_client_unknown_response(tBTA_HF_CLIENT_CB* client_cb, const char* evt_buffer) { tBTA_HF_CLIENT evt = {}; osi_strlcpy(evt.unknown.event_string, evt_buffer, BTA_HF_CLIENT_UNKNOWN_EVENT_LEN + 1); @@ -2164,7 +2161,8 @@ void bta_hf_client_send_at_bia(tBTA_HF_CLIENT_CB* client_cb) { bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_BIA, buf, at_len); } -void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, const char* str) { +static void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, + const char* str) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; log::verbose(""); @@ -2181,7 +2179,7 @@ void bta_hf_client_send_at_vendor_specific_cmd(tBTA_HF_CLIENT_CB* client_cb, con bta_hf_client_send_at(client_cb, BTA_HF_CLIENT_AT_VENDOR_SPECIFIC, buf, at_len); } -void bta_hf_client_send_at_android(tBTA_HF_CLIENT_CB* client_cb, const char* str) { +static void bta_hf_client_send_at_android(tBTA_HF_CLIENT_CB* client_cb, const char* str) { char buf[BTA_HF_CLIENT_AT_MAX_LEN]; int at_len; diff --git a/system/bta/hh/bta_hh_main.cc b/system/bta/hh/bta_hh_main.cc index 7c15be0ac7..919a4eafe6 100644 --- a/system/bta/hh/bta_hh_main.cc +++ b/system/bta/hh/bta_hh_main.cc @@ -35,9 +35,6 @@ #include "osi/include/allocator.h" #include "stack/include/bt_hdr.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; /***************************************************************************** @@ -332,7 +329,7 @@ void bta_hh_sm_execute(tBTA_HH_DEV_CB* p_cb, tBTA_HH_INT_EVT event, const tBTA_H * Returns void * ******************************************************************************/ -void bta_hh_hdl_failure(tBTA_HH_INT_EVT event, const tBTA_HH_DATA* p_data) { +static void bta_hh_hdl_failure(tBTA_HH_INT_EVT event, const tBTA_HH_DATA* p_data) { if (bta_hh_cb.p_cback == nullptr) { log::error("No callback handler"); return; diff --git a/system/bta/include/bta_le_audio_api.h b/system/bta/include/bta_le_audio_api.h index 52a3f7d83c..db541799c7 100644 --- a/system/bta/include/bta_le_audio_api.h +++ b/system/bta/include/bta_le_audio_api.h @@ -80,9 +80,10 @@ public: static bool RegisterIsoDataConsumer(LeAudioIsoDataCallback callback); - static void AddFromStorage(const RawAddress& addr, bool autoconnect, int sink_audio_location, - int source_audio_location, int sink_supported_context_types, - int source_supported_context_types, + static void AddFromStorage(const RawAddress& addr, bool autoconnect, + std::optional<int> sink_audio_location, + std::optional<int> source_audio_location, + int sink_supported_context_types, int source_supported_context_types, const std::vector<uint8_t>& handles, const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs, diff --git a/system/bta/jv/bta_jv_act.cc b/system/bta/jv/bta_jv_act.cc index f0ccf28cf0..d9eb9d0bbc 100644 --- a/system/bta/jv/bta_jv_act.cc +++ b/system/bta/jv/bta_jv_act.cc @@ -53,9 +53,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; @@ -105,7 +102,7 @@ tBTA_JV_CFG* p_bta_jv_cfg = &bta_jv_cfg; * Returns * ******************************************************************************/ -uint8_t bta_jv_alloc_sec_id(void) { +static uint8_t bta_jv_alloc_sec_id(void) { uint8_t ret = 0; int i; for (i = 0; i < BTA_JV_NUM_SERVICE_ID; i++) { @@ -218,7 +215,7 @@ static tBTA_JV_L2CAP_REASON bta_jv_from_gap_l2cap_err(const tL2CAP_CONN& l2cap_r * Returns * ******************************************************************************/ -tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, tBTA_JV_PCB** pp_pcb) { +static tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, tBTA_JV_PCB** pp_pcb) { tBTA_JV_RFC_CB* p_cb = NULL; tBTA_JV_PCB* p_pcb; int i, j; @@ -260,7 +257,7 @@ tBTA_JV_RFC_CB* bta_jv_alloc_rfc_cb(uint16_t port_handle, tBTA_JV_PCB** pp_pcb) * Returns * ******************************************************************************/ -tBTA_JV_PCB* bta_jv_rfc_port_to_pcb(uint16_t port_handle) { +static tBTA_JV_PCB* bta_jv_rfc_port_to_pcb(uint16_t port_handle) { tBTA_JV_PCB* p_pcb = NULL; if ((port_handle > 0) && (port_handle <= MAX_RFC_PORTS) && @@ -281,7 +278,7 @@ tBTA_JV_PCB* bta_jv_rfc_port_to_pcb(uint16_t port_handle) { * Returns * ******************************************************************************/ -tBTA_JV_RFC_CB* bta_jv_rfc_port_to_cb(uint16_t port_handle) { +static tBTA_JV_RFC_CB* bta_jv_rfc_port_to_cb(uint16_t port_handle) { tBTA_JV_RFC_CB* p_cb = NULL; uint32_t handle; @@ -397,7 +394,7 @@ static tBTA_JV_STATUS bta_jv_free_rfc_cb(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pc * Returns * ******************************************************************************/ -tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB* p_cb) { +static tBTA_JV_STATUS bta_jv_free_l2c_cb(tBTA_JV_L2C_CB* p_cb) { tBTA_JV_STATUS status = tBTA_JV_STATUS::SUCCESS; if (BTA_JV_ST_NONE != p_cb->state) { @@ -587,7 +584,7 @@ static tBTA_JV_PM_CB* bta_jv_alloc_set_pm_profile_cb(uint32_t jv_handle, tBTA_JV * Returns true, if allowed * ******************************************************************************/ -bool bta_jv_check_psm(uint16_t psm) { +static bool bta_jv_check_psm(uint16_t psm) { bool ret = false; if (L2C_IS_VALID_PSM(psm)) { diff --git a/system/bta/jv/bta_jv_int.h b/system/bta/jv/bta_jv_int.h index dc3c2ac3ba..d7b5007797 100644 --- a/system/bta/jv/bta_jv_int.h +++ b/system/bta/jv/bta_jv_int.h @@ -32,6 +32,7 @@ #include "internal_include/bt_target.h" #include "stack/include/bt_hdr.h" #include "stack/include/rfcdefs.h" +#include "stack/include/sdp_status.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -178,4 +179,9 @@ void bta_jv_set_pm_profile(uint32_t handle, tBTA_JV_PM_ID app_id, tBTA_JV_CONN_S void bta_jv_l2cap_stop_server_le(uint16_t local_chan); +namespace bluetooth::legacy::testing { +void bta_jv_start_discovery_cback(uint32_t rfcomm_slot_id, const RawAddress& bd_addr, + tSDP_RESULT result); +} // namespace bluetooth::legacy::testing + #endif /* BTA_JV_INT_H */ diff --git a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc index 1ca832afb3..8618670c0e 100644 --- a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc +++ b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc @@ -30,9 +30,7 @@ #include "common/message_loop_thread.h" #include "hardware/bluetooth.h" #include "osi/include/wakelock.h" - -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" +#include "stack/include/main_thread.h" using ::testing::_; using ::testing::Assign; @@ -64,9 +62,6 @@ bt_status_t do_in_main_thread(base::OnceClosure task) { return BT_STATUS_SUCCESS; } -static base::MessageLoop* message_loop_; -base::MessageLoop* get_main_message_loop() { return message_loop_; } - static void init_message_loop_thread() { message_loop_thread.StartUp(); if (!message_loop_thread.IsRunning()) { @@ -76,17 +71,9 @@ static void init_message_loop_thread() { if (!message_loop_thread.EnableRealTimeScheduling()) { log::error("Unable to set real time scheduling"); } - - message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) { - FAIL() << "unable to get message loop."; - } } -static void cleanup_message_loop_thread() { - message_loop_ = nullptr; - message_loop_thread.ShutDown(); -} +static void cleanup_message_loop_thread() { message_loop_thread.ShutDown(); } using bluetooth::audio::le_audio::LeAudioClientInterface; diff --git a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc index 88fb4f51ad..33af17284b 100644 --- a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc +++ b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc @@ -310,8 +310,11 @@ bool SourceImpl::OnMetadataUpdateReq(const source_metadata_v7_t& source_metadata return false; } - std::vector<struct playback_track_metadata_v7> metadata( - source_metadata.tracks, source_metadata.tracks + source_metadata.track_count); + std::vector<struct playback_track_metadata_v7> metadata; + if (source_metadata.tracks != nullptr) { + metadata = std::vector<struct playback_track_metadata_v7>( + source_metadata.tracks, source_metadata.tracks + source_metadata.track_count); + } bt_status_t status = do_in_main_thread(base::BindOnce( &LeAudioSourceAudioHalClient::Callbacks::OnAudioMetadataUpdate, diff --git a/system/bta/le_audio/audio_set_scenarios.json b/system/bta/le_audio/audio_set_scenarios.json index 52857f3356..93cd811a61 100644 --- a/system/bta/le_audio/audio_set_scenarios.json +++ b/system/bta/le_audio/audio_set_scenarios.json @@ -161,7 +161,25 @@ "One-TwoChan-SnkAse-Lc3_24_2_Low_Latency", "One-TwoChan-SnkAse-Lc3_24_1_Low_Latency", "One-TwoChan-SnkAse-Lc3_16_2_Low_Latency", - "One-TwoChan-SnkAse-Lc3_16_1_Low_Latency" + "One-TwoChan-SnkAse-Lc3_16_1_Low_Latency", + "Two-OneChan-SrcAse-Lc3_32_2_Low_Latency", + "Two-OneChan-SrcAse-Lc3_32_1_Low_Latency", + "Two-OneChan-SrcAse-Lc3_24_2_Low_Latency", + "Two-OneChan-SrcAse-Lc3_24_1_Low_Latency", + "Two-OneChan-SrcAse-Lc3_16_2_Low_Latency", + "Two-OneChan-SrcAse-Lc3_16_1_Low_Latency", + "One-TwoChan-SrcAse-Lc3_32_2_Low_Latency", + "One-TwoChan-SrcAse-Lc3_32_1_Low_Latency", + "One-TwoChan-SrcAse-Lc3_24_2_Low_Latency", + "One-TwoChan-SrcAse-Lc3_24_1_Low_Latency", + "One-TwoChan-SrcAse-Lc3_16_2_Low_Latency", + "One-TwoChan-SrcAse-Lc3_16_1_Low_Latency", + "One-OneChan-SrcAse-Lc3_32_2_Low_Latency", + "One-OneChan-SrcAse-Lc3_32_1_Low_Latency", + "One-OneChan-SrcAse-Lc3_24_2_Low_Latency", + "One-OneChan-SrcAse-Lc3_24_1_Low_Latency", + "One-OneChan-SrcAse-Lc3_16_2_Low_Latency", + "One-OneChan-SrcAse-Lc3_16_1_Low_Latency" ] }, { diff --git a/system/bta/le_audio/broadcaster/broadcaster_test.cc b/system/bta/le_audio/broadcaster/broadcaster_test.cc index 2b3462866c..28bfcfb24c 100644 --- a/system/bta/le_audio/broadcaster/broadcaster_test.cc +++ b/system/bta/le_audio/broadcaster/broadcaster_test.cc @@ -32,8 +32,10 @@ #include "bta/le_audio/content_control_id_keeper.h" #include "bta/le_audio/le_audio_types.h" #include "bta/le_audio/mock_codec_manager.h" +#include "btif/include/btif_common.h" #include "hci/controller_interface_mock.h" #include "stack/include/btm_iso_api.h" +#include "stack/include/main_thread.h" #include "test/common/mock_functions.h" #include "test/mock/mock_main_shim_entry.h" #include "test/mock/mock_osi_alarm.h" @@ -41,9 +43,6 @@ #define TEST_BT com::android::bluetooth::flags -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace std::chrono_literals; using bluetooth::le_audio::types::AudioContexts; @@ -72,6 +71,7 @@ using bluetooth::le_audio::broadcaster::BroadcastStateMachine; using bluetooth::le_audio::broadcaster::BroadcastSubgroupCodecConfig; // Disables most likely false-positives from base::SplitString() +extern "C" const char* __asan_default_options(); extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } struct alarm_t { @@ -109,9 +109,6 @@ bt_status_t do_in_main_thread(base::OnceClosure task) { return BT_STATUS_SUCCESS; } -static base::MessageLoop* message_loop_; -base::MessageLoop* get_main_message_loop() { return message_loop_; } - static void init_message_loop_thread() { num_async_tasks = 0; message_loop_thread.StartUp(); @@ -122,17 +119,9 @@ static void init_message_loop_thread() { if (!message_loop_thread.EnableRealTimeScheduling()) { log::error("Unable to set real time scheduling"); } - - message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) { - FAIL() << "unable to get message loop."; - } } -static void cleanup_message_loop_thread() { - message_loop_ = nullptr; - message_loop_thread.ShutDown(); -} +static void cleanup_message_loop_thread() { message_loop_thread.ShutDown(); } bool LeAudioClient::IsLeAudioClientRunning(void) { return false; } diff --git a/system/bta/le_audio/broadcaster/state_machine_test.cc b/system/bta/le_audio/broadcaster/state_machine_test.cc index 15d8ba0565..70a74ea510 100644 --- a/system/bta/le_audio/broadcaster/state_machine_test.cc +++ b/system/bta/le_audio/broadcaster/state_machine_test.cc @@ -35,9 +35,6 @@ #define TEST_BT com::android::bluetooth::flags -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth::hci::iso_manager; using bluetooth::hci::IsoManager; @@ -49,6 +46,7 @@ using testing::SaveArg; using testing::Test; // Disables most likely false-positives from base::SplitString() +extern "C" const char* __asan_default_options(); extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } void btsnd_hcic_ble_rand(base::Callback<void(BT_OCTET8)> /*cb*/) {} diff --git a/system/bta/le_audio/client.cc b/system/bta/le_audio/client.cc index 7c1c6d7f96..18f5f501da 100644 --- a/system/bta/le_audio/client.cc +++ b/system/bta/le_audio/client.cc @@ -104,9 +104,6 @@ #include <hardware/audio.h> #endif // TARGET_FLOSS -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Closure; using bluetooth::Uuid; using bluetooth::common::ToString; @@ -148,6 +145,7 @@ using bluetooth::le_audio::types::AudioLocations; using bluetooth::le_audio::types::BidirectionalPair; using bluetooth::le_audio::types::DataPathState; using bluetooth::le_audio::types::hdl_pair; +using bluetooth::le_audio::types::hdl_pair_wrapper; using bluetooth::le_audio::types::kLeAudioContextAllRemoteSource; using bluetooth::le_audio::types::kLeAudioContextAllTypesArray; using bluetooth::le_audio::types::LeAudioContextType; @@ -172,7 +170,7 @@ enum class AudioState { RELEASING, }; -std::ostream& operator<<(std::ostream& os, const AudioReconfigurationResult& state) { +static std::ostream& operator<<(std::ostream& os, const AudioReconfigurationResult& state) { switch (state) { case AudioReconfigurationResult::RECONFIGURATION_NEEDED: os << "RECONFIGURATION_NEEDED"; @@ -190,7 +188,7 @@ std::ostream& operator<<(std::ostream& os, const AudioReconfigurationResult& sta return os; } -std::ostream& operator<<(std::ostream& os, const AudioState& audio_state) { +static std::ostream& operator<<(std::ostream& os, const AudioState& audio_state) { switch (audio_state) { case AudioState::IDLE: os << "IDLE"; @@ -848,9 +846,9 @@ public: /* All the configurations should be recalculated for the new conditions */ group->InvalidateCachedConfigurations(); group->InvalidateGroupStrategy(); - callbacks_->OnAudioConf( - group->audio_directions_, group->group_id_, group->snk_audio_locations_.to_ulong(), - group->src_audio_locations_.to_ulong(), group->GetAvailableContexts().value()); + callbacks_->OnAudioConf(group->audio_directions_, group->group_id_, + group->audio_locations_.sink, group->audio_locations_.source, + group->GetAvailableContexts().value()); } } @@ -1115,32 +1113,26 @@ public: } /* Return true if stream is started */ - bool GroupStream(int group_id, LeAudioContextType configuration_context_type, + bool GroupStream(LeAudioDeviceGroup* group, LeAudioContextType configuration_context_type, BidirectionalPair<AudioContexts> remote_contexts) { - LeAudioDeviceGroup* group = aseGroups_.FindById(group_id); + log::assert_that(group != nullptr, "Group shall not be null"); log::debug( "configuration_context_type= {}, remote sink contexts= {}, remote source contexts= {}", ToString(configuration_context_type), ToString(remote_contexts.sink), ToString(remote_contexts.source)); - log::debug(""); if (configuration_context_type >= LeAudioContextType::RFU) { log::error("stream context type is not supported: {}", ToHexString(configuration_context_type)); return false; } - if (!group) { - log::error("unknown group id: {}", group_id); - return false; - } - log::debug("group state={}, target_state={}", ToString(group->GetState()), ToString(group->GetTargetState())); if (!group->IsAnyDeviceConnected()) { - log::error("group {} is not connected", group_id); + log::error("group {} is not connected", group->group_id_); return false; } @@ -1200,7 +1192,13 @@ public: void GroupStream(const int group_id, uint16_t context_type) override { BidirectionalPair<AudioContexts> initial_contexts = {AudioContexts(context_type), AudioContexts(context_type)}; - GroupStream(group_id, LeAudioContextType(context_type), initial_contexts); + auto group = aseGroups_.FindById(group_id); + if (!group) { + log::error("unknown group id: {}", group_id); + return; + } + + GroupStream(group, LeAudioContextType(context_type), initial_contexts); } void GroupSuspend(const int group_id) override { @@ -1371,6 +1369,11 @@ public: // Preemptively remove conversational context for reconfiguration speed up in_call_metadata_context_types_.sink.unset(LeAudioContextType::CONVERSATIONAL); in_call_metadata_context_types_.source.unset(LeAudioContextType::CONVERSATIONAL); + if (in_call_metadata_context_types_.sink.none() && + in_call_metadata_context_types_.source.none()) { + log::debug("No metadata, set default Media"); + in_call_metadata_context_types_.source.set(LeAudioContextType::MEDIA); + } local_metadata_context_types_ = in_call_metadata_context_types_; log::debug("restored local_metadata_context_types_ sink: {} source: {}", local_metadata_context_types_.sink.to_string(), @@ -1931,8 +1934,9 @@ public: } /* Restore paired device from storage to recreate groups */ - void AddFromStorage(const RawAddress& address, bool autoconnect, int sink_audio_location, - int source_audio_location, int sink_supported_context_types, + void AddFromStorage(const RawAddress& address, bool autoconnect, + std::optional<int> sink_audio_location, + std::optional<int> source_audio_location, int sink_supported_context_types, int source_supported_context_types, const std::vector<uint8_t>& handles, const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs, const std::vector<uint8_t>& ases, @@ -1948,7 +1952,9 @@ public: "restoring: {}, autoconnect {}, sink_audio_location: {}, " "source_audio_location: {}, sink_supported_context_types : 0x{:04x}, " "source_supported_context_types 0x{:04x}", - address, autoconnect, sink_audio_location, source_audio_location, + address, autoconnect, + sink_audio_location ? std::to_string(sink_audio_location.value()) : "none", + source_audio_location ? std::to_string(source_audio_location.value()) : "none", sink_supported_context_types, source_supported_context_types); leAudioDevices_.Add(address, DeviceConnectState::DISCONNECTED); @@ -1960,11 +1966,6 @@ public: group_add_node(group_id, address); } - leAudioDevice->src_audio_locations_ = source_audio_location; - leAudioDevice->snk_audio_locations_ = sink_audio_location; - callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong()); - BidirectionalPair<AudioContexts> supported_contexts = { .sink = AudioContexts(sink_supported_context_types), .source = AudioContexts(source_supported_context_types), @@ -1979,12 +1980,22 @@ public: log::warn("Could not load Handles"); } + if (sink_audio_location) { + leAudioDevice->audio_locations_.sink->value = sink_audio_location.value(); + } + + if (source_audio_location) { + leAudioDevice->audio_locations_.source->value = source_audio_location.value(); + } + /* Presence of PAC characteristic for a direction means support for that direction */ - if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.source) { leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource; } - if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.sink) { leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink; + callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, + leAudioDevice->audio_locations_.sink->value); } if (!DeserializeSinkPacs(leAudioDevice, sink_pacs)) { @@ -2196,13 +2207,13 @@ public: std::get<0>(pac_tuple).val_hdl); } - if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.sink) { BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_.val_hdl); + leAudioDevice->audio_locations_.sink->handles.val_hdl); } - if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.source) { BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_.val_hdl); + leAudioDevice->audio_locations_.source->handles.val_hdl); } if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) { BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_, @@ -2324,15 +2335,15 @@ public: return; } - if (hdl == leAudioDevice->snk_audio_locations_hdls_.val_hdl) { + if (leAudioDevice->audio_locations_.sink && + hdl == leAudioDevice->audio_locations_.sink->handles.val_hdl) { AudioLocations snk_audio_locations; - bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(snk_audio_locations, len, value); /* Value may not change */ - if ((leAudioDevice->audio_directions_ & bluetooth::le_audio::types::kLeAudioDirectionSink) && - (leAudioDevice->snk_audio_locations_ ^ snk_audio_locations).none()) { + if (!leAudioDevice->audio_locations_.sink || + (leAudioDevice->audio_locations_.sink->value ^ snk_audio_locations).none()) { return; } @@ -2340,29 +2351,26 @@ public: * audio location. Value of 0x00000000 means mono/unspecified */ leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink; - leAudioDevice->snk_audio_locations_ = snk_audio_locations; + leAudioDevice->audio_locations_.sink->value = snk_audio_locations; - callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, - snk_audio_locations.to_ulong()); + callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, snk_audio_locations); if (notify) { - btif_storage_set_leaudio_audio_location(leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + btif_storage_set_leaudio_sink_audio_location( + leAudioDevice->address_, leAudioDevice->audio_locations_.sink->value.to_ulong()); if (group && group->IsReleasingOrIdle()) { UpdateLocationsAndContextsAvailability(group); } } - } else if (hdl == leAudioDevice->src_audio_locations_hdls_.val_hdl) { + } else if (leAudioDevice->audio_locations_.source && + hdl == leAudioDevice->audio_locations_.source->handles.val_hdl) { AudioLocations src_audio_locations; - bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(src_audio_locations, len, value); /* Value may not change */ - if ((leAudioDevice->audio_directions_ & - bluetooth::le_audio::types::kLeAudioDirectionSource) && - (leAudioDevice->src_audio_locations_ ^ src_audio_locations).none()) { + if (!leAudioDevice->audio_locations_.source || + (leAudioDevice->audio_locations_.source->value ^ src_audio_locations).none()) { return; } @@ -2370,12 +2378,11 @@ public: * audio location. Value of 0x00000000 means mono/unspecified */ leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource; - leAudioDevice->src_audio_locations_ = src_audio_locations; + leAudioDevice->audio_locations_.source->value = src_audio_locations; if (notify) { - btif_storage_set_leaudio_audio_location(leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + btif_storage_set_leaudio_source_audio_location( + leAudioDevice->address_, leAudioDevice->audio_locations_.source->value.to_ulong()); if (group && group->IsReleasingOrIdle()) { UpdateLocationsAndContextsAvailability(group); } @@ -2622,14 +2629,14 @@ public: std::get<0>(pac_tuple), gatt_register, write_ccc); } - if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.sink) { subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_, gatt_register, + leAudioDevice->audio_locations_.sink->handles, gatt_register, write_ccc); } - if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) { + if (leAudioDevice->audio_locations_.source) { subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_, gatt_register, + leAudioDevice->audio_locations_.source->handles, gatt_register, write_ccc); } @@ -2970,7 +2977,7 @@ public: } bool subscribe_for_notification(tCONN_ID conn_id, const RawAddress& address, - struct bluetooth::le_audio::types::hdl_pair handle_pair, + const struct bluetooth::le_audio::types::hdl_pair& handle_pair, bool gatt_register = true, bool write_ccc = true) { std::vector<uint8_t> value(2); uint8_t* ptr = value.data(); @@ -3280,55 +3287,51 @@ public: "Found Source PAC characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, addr: {}", charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_); } else if (charac.uuid == bluetooth::le_audio::uuid::kSinkAudioLocationCharacteristicUuid) { - leAudioDevice->snk_audio_locations_hdls_.val_hdl = charac.value_handle; - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac); + auto ccc_hdl = find_ccc_handle(charac); + leAudioDevice->audio_locations_.sink.emplace(hdl_pair(charac.value_handle, ccc_hdl), + AudioLocations(0)); - if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl == 0) { + if (ccc_hdl == 0) { log::info(", snk audio locations char doesn't have ccc"); - } - - if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl != 0 && - !subscribe_for_notification(conn_id, leAudioDevice->address_, - leAudioDevice->snk_audio_locations_hdls_)) { + } else if (!subscribe_for_notification(conn_id, leAudioDevice->address_, + leAudioDevice->audio_locations_.sink->handles)) { disconnectInvalidDevice(leAudioDevice, ", could not subscribe for snk locations char", LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of sink audio locations */ - BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->snk_audio_locations_hdls_.val_hdl, + BtaGattQueue::ReadCharacteristic(conn_id, + leAudioDevice->audio_locations_.sink->handles.val_hdl, OnGattReadRspStatic, NULL); log::info( - "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc " - "handle: 0x{:04x}, addr: {}", - charac.value_handle, leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, - leAudioDevice->address_); + "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc handle: " + "0x{:04x}, addr: {}", + charac.value_handle, ccc_hdl, leAudioDevice->address_); } else if (charac.uuid == bluetooth::le_audio::uuid::kSourceAudioLocationCharacteristicUuid) { - leAudioDevice->src_audio_locations_hdls_.val_hdl = charac.value_handle; - leAudioDevice->src_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac); + auto ccc_hdl = find_ccc_handle(charac); + leAudioDevice->audio_locations_.source.emplace(hdl_pair(charac.value_handle, ccc_hdl), + AudioLocations(0)); - if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl == 0) { + if (ccc_hdl == 0) { log::info(", src audio locations char doesn't have ccc"); - } - - if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl != 0 && - !subscribe_for_notification(conn_id, leAudioDevice->address_, - leAudioDevice->src_audio_locations_hdls_)) { + } else if (!subscribe_for_notification(conn_id, leAudioDevice->address_, + leAudioDevice->audio_locations_.source->handles)) { disconnectInvalidDevice(leAudioDevice, ", could not subscribe for src locations char", LeAudioHealthDeviceStatType::INVALID_DB); return; } /* Obtain initial state of source audio locations */ - BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->src_audio_locations_hdls_.val_hdl, + BtaGattQueue::ReadCharacteristic(conn_id, + leAudioDevice->audio_locations_.source->handles.val_hdl, OnGattReadRspStatic, NULL); log::info( - "Found Source audio locations characteristic, handle: 0x{:04x}, " - "ccc handle: 0x{:04x}, addr: {}", - charac.value_handle, leAudioDevice->src_audio_locations_hdls_.ccc_hdl, - leAudioDevice->address_); + "Found Source audio locations characteristic, handle: 0x{:04x}, ccc handle: " + "0x{:04x}, addr: {}", + charac.value_handle, ccc_hdl, leAudioDevice->address_); } else if (charac.uuid == bluetooth::le_audio::uuid::kAudioContextAvailabilityCharacteristicUuid) { leAudioDevice->audio_avail_hdls_.val_hdl = charac.value_handle; @@ -3946,8 +3949,11 @@ public: uint16_t left_cis_handle = 0; uint16_t right_cis_handle = 0; for (auto const& info : group->stream_conf.stream_params.source.stream_config.stream_map) { - if (info.audio_channel_allocation & - bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) { + // Use the left channel decoder for the Mono Audio microphone + auto is_mono = info.audio_channel_allocation == + bluetooth::le_audio::codec_spec_conf::kLeAudioLocationMonoAudio; + if (is_mono || (info.audio_channel_allocation & + bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft)) { left_cis_handle = info.stream_handle; } if (info.audio_channel_allocation & @@ -4136,15 +4142,29 @@ public: } le_audio_source_hal_client_->UpdateRemoteDelay(remote_delay_ms); + + /* We update the target audio allocation before streamStarted so that the CodecManager would + * already know how to configure the encoder once we confirm the streaming request. */ + CodecManager::GetInstance()->UpdateActiveAudioConfig( + group->stream_conf.stream_params, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2), + ::bluetooth::le_audio::types::kLeAudioDirectionSink); + ConfirmLocalAudioSourceStreamingRequest(); + /* After confirming the streaming request, if no Stream Active API is available, we need to + * send an additional update with the currently active audio channel configuration (in case one + * of the earbuds is not yet connected) so that the offloader would know if any channel mixing + * (and sending joint-stereo to one CIS) is required until the other bud joins the stream. + * NOTE: With the Stream Active API available, both information is passed with the initial call. + */ if (!LeAudioHalVerifier::SupportsStreamActiveApi()) { - /* We update the target audio allocation before streamStarted so that the - * CodecManager would know how to configure the encoder. */ CodecManager::GetInstance()->UpdateActiveAudioConfig( group->stream_conf.stream_params, std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), - std::placeholders::_1, std::placeholders::_2)); + std::placeholders::_1, std::placeholders::_2), + bluetooth::le_audio::types::kLeAudioDirectionSink); } } @@ -4200,16 +4220,31 @@ public: return; } } + le_audio_sink_hal_client_->UpdateRemoteDelay(remote_delay_ms); + + /* We update the target audio allocation before streamStarted so that the CodecManager would + * already know how to configure the encoder once we confirm the streaming request. */ + CodecManager::GetInstance()->UpdateActiveAudioConfig( + group->stream_conf.stream_params, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2), + ::bluetooth::le_audio::types::kLeAudioDirectionSource); + ConfirmLocalAudioSinkStreamingRequest(); + /* After confirming the streaming request, if no Stream Active API is available, we need to + * send an additional update with the currently active audio channel configuration (in case one + * of the earbuds is not yet connected) so that the offloader would know if any channel mixing + * (and sending joint-stereo to one CIS) is required until the other bud joins the stream. + * NOTE: With the Stream Active API available, both information is passed with the initial call. + */ if (!LeAudioHalVerifier::SupportsStreamActiveApi()) { - /* We update the target audio allocation before streamStarted so that the - * CodecManager would know how to configure the encoder. */ CodecManager::GetInstance()->UpdateActiveAudioConfig( group->stream_conf.stream_params, std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), - std::placeholders::_1, std::placeholders::_2)); + std::placeholders::_1, std::placeholders::_2), + bluetooth::le_audio::types::kLeAudioDirectionSource); } } @@ -4408,7 +4443,7 @@ public: return false; } - return GroupStream(active_group_id_, configuration_context_type_, remote_contexts); + return GroupStream(group, configuration_context_type_, remote_contexts); } void OnAudioSuspend() { @@ -5356,11 +5391,17 @@ public: * no incoming call to accept or reject on TBS could confuse the remote * device and interrupt the stream establish procedure. */ - if (!IsInCall()) { + if (!IsInCall() && !IsInVoipCall()) { SetInVoipCall(true); } } else if (IsInVoipCall()) { - SetInVoipCall(false); + /* When determining whether the VoIP has ended or not make sure + * we check the just updated direction metadata for CONVERSATIONAL + */ + auto const local_direction_contexts = local_metadata_context_types_.get(local_direction); + if (!local_direction_contexts.test_any(possible_voip_contexts)) { + SetInVoipCall(false); + } } BidirectionalPair<AudioContexts> remote_metadata = { @@ -5370,6 +5411,24 @@ public: auto all_bidirectional_contexts = group->GetAllSupportedBidirectionalContextTypes(); log::debug("all_bidirectional_contexts {}", ToString(all_bidirectional_contexts)); + /* + * Detect the gaming scenario and mirror the context to the other direction. + * Thanks to this, we will be able to configure even Microphone only devices, for the GAME + * audio context detected on the local audio source, which never gets resumed for such devices. + */ + if (remote_metadata.sink.test(LeAudioContextType::GAME)) { + auto ctxs = group->GetSupportedContexts(bluetooth::le_audio::types::kLeAudioDirectionSource) & + AudioContexts(LeAudioContextType::GAME) & + bluetooth::le_audio::types::kLeAudioContextAllBidir; + if (ctxs.any()) { + log::debug( + "Gaming scenario detected. Use this audio context for the other direction if " + "supported"); + remote_metadata.source.clear(); + remote_metadata.source.set_all(ctxs); + } + } + /* Make sure we have CONVERSATIONAL when in a call and it is not mixed * with any other bidirectional context */ @@ -5409,10 +5468,26 @@ public: log::debug("is_ongoing_call_on_other_direction={}", is_ongoing_call_on_other_direction ? "True" : "False"); - if (remote_metadata.get(remote_other_direction).test_any(all_bidirectional_contexts) && - !(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction)) { - log::debug("The other direction is not streaming bidirectional, ignore that context."); - remote_metadata.get(remote_other_direction).clear(); + /* If the other direction is a bidir scenario we might want to take it into the account, but + * not always. Look below for details. + */ + auto is_other_direction_bidir = + remote_metadata.get(remote_other_direction).test_any(all_bidirectional_contexts); + + /* If the not-resumed direction is local source, we might need to take it's metadata, + * (this way we detect GAME scenario), but local sink metadata is unreliable. + */ + bool take_unresumed_local_source_metadata_for_mic_only_devices = + (group->audio_locations_.sink == std::nullopt) && + (local_other_direction == bluetooth::le_audio::types::kLeAudioDirectionSource); + if (is_other_direction_bidir) { + if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction) && + !take_unresumed_local_source_metadata_for_mic_only_devices) { + log::debug( + "The other direction is not streaming bidirectional or is not a reliable source of " + "metadata, ignore that context."); + remote_metadata.get(remote_other_direction).clear(); + } } auto single_direction_only_context_types = @@ -5437,7 +5512,8 @@ public: remote_metadata.get(remote_direction).unset_all(all_bidirectional_contexts); remote_metadata.get(remote_direction).set(LeAudioContextType::CONVERSATIONAL); } else { - if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction)) { + if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction) && + !take_unresumed_local_source_metadata_for_mic_only_devices) { // Do not take the obsolete metadata remote_metadata.get(remote_other_direction).clear(); } else { @@ -5530,7 +5606,7 @@ public: log::info("new_configuration_context= {}.", ToString(new_configuration_context)); BidirectionalPair<AudioContexts> remote_contexts = {.sink = override_contexts, .source = override_contexts}; - return GroupStream(active_group_id_, new_configuration_context, remote_contexts); + return GroupStream(group, new_configuration_context, remote_contexts); } /* Return true if stream is started */ @@ -5545,6 +5621,10 @@ public: * or source metadata update event. */ auto remote_metadata = DirectionalRealignMetadataAudioContexts(group, remote_direction); + if (!remote_metadata.sink.any() && !remote_metadata.source.any()) { + log::warn("No valid metadata to update or reconfigure to."); + return false; + } /* Choose the right configuration context */ auto config_context_candids = get_bidirectional(remote_metadata); @@ -5655,7 +5735,7 @@ public: "Sink: " + ToString(remote_contexts.sink) + "Source: " + ToString(remote_contexts.source)); - return GroupStream(group->group_id_, configuration_context_type_, remote_contexts); + return GroupStream(group, configuration_context_type_, remote_contexts); } return false; } @@ -5688,9 +5768,14 @@ public: btif_storage_leaudio_update_pacs_bin(leAudioDevice->address_); btif_storage_leaudio_update_ase_bin(leAudioDevice->address_); - btif_storage_set_leaudio_audio_location(leAudioDevice->address_, - leAudioDevice->snk_audio_locations_.to_ulong(), - leAudioDevice->src_audio_locations_.to_ulong()); + if (leAudioDevice->audio_locations_.sink) { + btif_storage_set_leaudio_sink_audio_location( + leAudioDevice->address_, leAudioDevice->audio_locations_.sink->value.to_ulong()); + } + if (leAudioDevice->audio_locations_.source) { + btif_storage_set_leaudio_source_audio_location( + leAudioDevice->address_, leAudioDevice->audio_locations_.source->value.to_ulong()); + } instance->connectionReady(leAudioDevice); } @@ -6061,7 +6146,8 @@ public: log::info( "status: {}, group_id: {}, audio_sender_state {}, audio_receiver_state {}, " "is_active_group_operation {}", - static_cast<int>(status), group_id, bluetooth::common::ToString(audio_sender_state_), + bluetooth::common::ToString(status), group_id, + bluetooth::common::ToString(audio_sender_state_), bluetooth::common::ToString(audio_receiver_state_), is_active_group_operation); LeAudioDeviceGroup* group = aseGroups_.FindById(group_id); @@ -6117,17 +6203,30 @@ public: return; } - CodecManager::GetInstance()->UpdateActiveAudioConfig( - group->stream_conf.stream_params, - std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), - std::placeholders::_1, std::placeholders::_2)); - if (audio_sender_state_ == AudioState::READY_TO_START) { StartSendingAudio(group_id); + } else if (audio_sender_state_ == AudioState::STARTED) { + /* If we are already sending, the initial configuration was already sent and + * we might need to just update the current channel mixing information. + */ + CodecManager::GetInstance()->UpdateActiveAudioConfig( + group->stream_conf.stream_params, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2), + ::bluetooth::le_audio::types::kLeAudioDirectionSink); } if (audio_receiver_state_ == AudioState::READY_TO_START) { StartReceivingAudio(group_id); + } else if (audio_receiver_state_ == AudioState::STARTED) { + /* If we are already receiving, the initial configuration was already sent and + * we might need to just update the current channel mixing information. + */ + CodecManager::GetInstance()->UpdateActiveAudioConfig( + group->stream_conf.stream_params, + std::bind(&LeAudioClientImpl::UpdateAudioConfigToHal, weak_factory_.GetWeakPtr(), + std::placeholders::_1, std::placeholders::_2), + bluetooth::le_audio::types::kLeAudioDirectionSource); } speed_stop_setup(group_id); @@ -6172,47 +6271,54 @@ public: if (group) { handleAsymmetricPhyForUnicast(group); UpdateLocationsAndContextsAvailability(group); - if (group->IsPendingConfiguration()) { - log::debug( - "Pending configuration for group_id: {} pre_configuration_context_type_ : {} " - "-> " - "configuration_context_type_ {}", - group->group_id_, ToString(pre_configuration_context_type_), - ToString(configuration_context_type_)); - auto remote_direction = kLeAudioContextAllRemoteSource.test(configuration_context_type_) - ? bluetooth::le_audio::types::kLeAudioDirectionSource - : bluetooth::le_audio::types::kLeAudioDirectionSink; - - /* Reconfiguration to non requiring source scenario */ - if (sink_monitor_mode_ && - (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink)) { - notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); - } - - auto remote_contexts = DirectionalRealignMetadataAudioContexts(group, remote_direction); - ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, remote_direction); - log::verbose( - "Pending configuration 2 pre_configuration_context_type_ : {} -> " - "configuration_context_type_ {}", - ToString(pre_configuration_context_type_), - ToString(configuration_context_type_)); - if ((configuration_context_type_ != pre_configuration_context_type_) && - GroupStream(group->group_id_, configuration_context_type_, remote_contexts)) { - /* If configuration succeed wait for new status. */ - return; - } - log::info("Clear pending configuration flag for group {}", group->group_id_); - group->ClearPendingConfiguration(); + if (!group->IsPendingConfiguration()) { if (is_active_group_operation) { - reconfigurationComplete(); - } - } else if (is_active_group_operation) { - if (sink_monitor_mode_) { - notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); + if (sink_monitor_mode_) { + notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); + } + + if (source_monitor_mode_) { + notifyAudioLocalSource(UnicastMonitorModeStatus::STREAMING_SUSPENDED); + } } + } else { + if (!is_active_group_operation) { + log::info("Clear pending configuration flag for group {}", group->group_id_); + group->ClearPendingConfiguration(); + } else { + log::debug( + "Pending configuration for group_id: {} pre_configuration_context_type_ : {} " + "-> " + "configuration_context_type_ {}", + group->group_id_, ToString(pre_configuration_context_type_), + ToString(configuration_context_type_)); + auto remote_direction = + kLeAudioContextAllRemoteSource.test(configuration_context_type_) + ? bluetooth::le_audio::types::kLeAudioDirectionSource + : bluetooth::le_audio::types::kLeAudioDirectionSink; + + /* Reconfiguration to non requiring source scenario */ + if (sink_monitor_mode_ && + (remote_direction == bluetooth::le_audio::types::kLeAudioDirectionSink)) { + notifyAudioLocalSink(UnicastMonitorModeStatus::STREAMING_SUSPENDED); + } - if (source_monitor_mode_) { - notifyAudioLocalSource(UnicastMonitorModeStatus::STREAMING_SUSPENDED); + auto remote_contexts = + DirectionalRealignMetadataAudioContexts(group, remote_direction); + ApplyRemoteMetadataAudioContextPolicy(group, remote_contexts, remote_direction); + log::verbose( + "Pending configuration 2 pre_configuration_context_type_ : {} -> " + "configuration_context_type_ {}", + ToString(pre_configuration_context_type_), + ToString(configuration_context_type_)); + if ((configuration_context_type_ != pre_configuration_context_type_) && + GroupStream(group, configuration_context_type_, remote_contexts)) { + /* If configuration succeed wait for new status. */ + return; + } + log::info("Clear pending configuration flag for group {}", group->group_id_); + group->ClearPendingConfiguration(); + reconfigurationComplete(); } } } @@ -6732,8 +6838,8 @@ DeviceGroupsCallbacksImpl deviceGroupsCallbacksImpl; } // namespace void LeAudioClient::AddFromStorage( - const RawAddress& addr, bool autoconnect, int sink_audio_location, - int source_audio_location, int sink_supported_context_types, + const RawAddress& addr, bool autoconnect, std::optional<int> sink_audio_location, + std::optional<int> source_audio_location, int sink_supported_context_types, int source_supported_context_types, const std::vector<uint8_t>& handles, const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs, const std::vector<uint8_t>& ases, const std::vector<uint8_t>& gmap) { @@ -6847,15 +6953,25 @@ void LeAudioClient::Initialize( cm->GetLocalAudioOutputCodecCapa()); if (GmapServer::IsGmapServerEnabled()) { - auto capabilities = cm->GetLocalAudioOutputCodecCapa(); std::bitset<8> UGG_feature = GmapServer::GetUGGFeature(); - for (auto& capa : capabilities) { + + auto input_capabilities = cm->GetLocalAudioOutputCodecCapa(); + for (auto& capa : input_capabilities) { if (capa.sample_rate == bluetooth::le_audio::LE_AUDIO_SAMPLE_RATE_INDEX_48000HZ) { UGG_feature |= static_cast<uint8_t>( bluetooth::gmap::UGGFeatureBitMask::NinetySixKbpsSourceFeatureSupport); break; } } + + auto output_capabilities = cm->GetLocalAudioOutputCodecCapa(); + for (auto& capa : output_capabilities) { + if (capa.channel_count > bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_1) { + UGG_feature |= + static_cast<uint8_t>(bluetooth::gmap::UGGFeatureBitMask::MultiplexFeatureSupport); + break; + } + } GmapServer::Initialize(UGG_feature); } } @@ -6874,7 +6990,6 @@ void LeAudioClient::DebugDump(int fd) { LeAudioSinkAudioHalClient::DebugDump(fd); LeAudioSourceAudioHalClient::DebugDump(fd); - bluetooth::le_audio::AudioSetConfigurationProvider::DebugDump(fd); IsoManager::GetInstance()->Dump(fd); LeAudioLogHistory::DebugDump(fd); dprintf(fd, "\n"); diff --git a/system/bta/le_audio/client_linux.cc b/system/bta/le_audio/client_linux.cc index 9908ef0a61..abf6a8faad 100644 --- a/system/bta/le_audio/client_linux.cc +++ b/system/bta/le_audio/client_linux.cc @@ -49,8 +49,8 @@ void LeAudioClient::Cleanup(void) {} LeAudioClient* LeAudioClient::Get(void) { return nullptr; } void LeAudioClient::DebugDump(int fd) {} void LeAudioClient::AddFromStorage( - const RawAddress& addr, bool autoconnect, int sink_audio_location, - int source_audio_location, int sink_supported_context_types, + const RawAddress& addr, bool autoconnect, std::optional<int> sink_audio_location, + std::optional<int> source_audio_location, int sink_supported_context_types, int source_supported_context_types, const std::vector<uint8_t>& handles, const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs, const std::vector<uint8_t>& ases, const std::vector<uint8_t>& gmap) {} diff --git a/system/bta/le_audio/codec_manager.cc b/system/bta/le_audio/codec_manager.cc index 8ad59b449d..9452218c5d 100644 --- a/system/bta/le_audio/codec_manager.cc +++ b/system/bta/le_audio/codec_manager.cc @@ -191,13 +191,19 @@ public: void UpdateActiveAudioConfig( const types::BidirectionalPair<stream_parameters>& stream_params, - std::function<void(const stream_config& config, uint8_t direction)> update_receiver) { + std::function<void(const stream_config& config, uint8_t direction)> update_receiver, + uint8_t remote_directions_to_update) { if (GetCodecLocation() != bluetooth::le_audio::types::CodecLocation::ADSP) { return; } for (auto direction : {bluetooth::le_audio::types::kLeAudioDirectionSink, bluetooth::le_audio::types::kLeAudioDirectionSource}) { + /* Update only the requested directions */ + if ((remote_directions_to_update & direction) != direction) { + continue; + } + auto& stream_map = offloader_stream_maps.get(direction); if (!stream_map.has_changed && !stream_map.is_initial) { log::warn("unexpected call for direction {}, stream_map.has_changed {}", direction, @@ -1053,7 +1059,7 @@ private: } void storeLocalCapa( - std::vector<::bluetooth::le_audio::types::AudioSetConfiguration>& adsp_capabilities, + const std::vector<::bluetooth::le_audio::types::AudioSetConfiguration>& adsp_capabilities, const std::vector<btle_audio_codec_config_t>& offload_preference_set) { log::debug("Print adsp_capabilities:"); @@ -1082,6 +1088,7 @@ private: conf.codec.GetChannelCountPerIsoStream()), .frame_duration = utils::translateToBtLeAudioCodecConfigFrameDuration( conf.codec.GetDataIntervalUs()), + .codec_frame_blocks_per_sdu = conf.codec.GetCodecFrameBlocksPerSdu(), }; auto& capa_container = (direction == types::kLeAudioDirectionSink) ? codec_output_capa @@ -1306,7 +1313,7 @@ CodecManager::GetLocalAudioOutputCodecCapa() { std::vector<bluetooth::le_audio::btle_audio_codec_config_t> CodecManager::GetLocalAudioInputCodecCapa() { if (pimpl_->IsRunning()) { - return pimpl_->codec_manager_impl_->GetLocalAudioOutputCodecCapa(); + return pimpl_->codec_manager_impl_->GetLocalAudioInputCodecCapa(); } std::vector<bluetooth::le_audio::btle_audio_codec_config_t> empty{}; return empty; @@ -1314,9 +1321,11 @@ CodecManager::GetLocalAudioInputCodecCapa() { void CodecManager::UpdateActiveAudioConfig( const types::BidirectionalPair<stream_parameters>& stream_params, - std::function<void(const stream_config& config, uint8_t direction)> update_receiver) { + std::function<void(const stream_config& config, uint8_t direction)> update_receiver, + uint8_t remote_directions_to_update) { if (pimpl_->IsRunning()) { - pimpl_->codec_manager_impl_->UpdateActiveAudioConfig(stream_params, update_receiver); + pimpl_->codec_manager_impl_->UpdateActiveAudioConfig(stream_params, update_receiver, + remote_directions_to_update); } } diff --git a/system/bta/le_audio/codec_manager.h b/system/bta/le_audio/codec_manager.h index 7aa9231bea..e5aeb9a27a 100644 --- a/system/bta/le_audio/codec_manager.h +++ b/system/bta/le_audio/codec_manager.h @@ -118,7 +118,9 @@ public: LeAudioSourceAudioHalClient* source_broadcast_client, bool is_active); virtual void UpdateActiveAudioConfig( const types::BidirectionalPair<stream_parameters>& stream_params, - std::function<void(const stream_config& config, uint8_t direction)> update_receiver); + std::function<void(const stream_config& config, uint8_t direction)> update_receiver, + uint8_t directions_to_update = (bluetooth::le_audio::types::kLeAudioDirectionSink | + bluetooth::le_audio::types::kLeAudioDirectionSource)); virtual std::unique_ptr<::bluetooth::le_audio::types::AudioSetConfiguration> GetCodecConfig( const UnicastConfigurationRequirements& requirements, UnicastConfigurationProvider provider); diff --git a/system/bta/le_audio/codec_manager_test.cc b/system/bta/le_audio/codec_manager_test.cc index 6511a5e2a6..f7474bd1c3 100644 --- a/system/bta/le_audio/codec_manager_test.cc +++ b/system/bta/le_audio/codec_manager_test.cc @@ -32,9 +32,6 @@ #include "test/mock/mock_legacy_hci_interface.h" #include "test/mock/mock_main_shim_entry.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using ::testing::_; using ::testing::Mock; using ::testing::NiceMock; @@ -56,20 +53,20 @@ static const std::vector<AudioSetConfiguration> offload_capabilities_none(0); const std::vector<AudioSetConfiguration>* offload_capabilities = &offload_capabilities_none; const std::string kSmpOptions("mock smp options"); -bool get_pts_avrcp_test(void) { return false; } -bool get_pts_secure_only_mode(void) { return false; } -bool get_pts_conn_updates_disabled(void) { return false; } -bool get_pts_crosskey_sdp_disable(void) { return false; } -const std::string* get_pts_smp_options(void) { return &kSmpOptions; } -int get_pts_smp_failure_case(void) { return 123; } -bool get_pts_force_eatt_for_notifications(void) { return false; } -bool get_pts_connect_eatt_unconditionally(void) { return false; } -bool get_pts_connect_eatt_before_encryption(void) { return false; } -bool get_pts_unencrypt_broadcast(void) { return false; } -bool get_pts_eatt_peripheral_collision_support(void) { return false; } -bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } -bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } -config_t* get_all(void) { return nullptr; } +static bool get_pts_avrcp_test(void) { return false; } +static bool get_pts_secure_only_mode(void) { return false; } +static bool get_pts_conn_updates_disabled(void) { return false; } +static bool get_pts_crosskey_sdp_disable(void) { return false; } +static const std::string* get_pts_smp_options(void) { return &kSmpOptions; } +static int get_pts_smp_failure_case(void) { return 123; } +static bool get_pts_force_eatt_for_notifications(void) { return false; } +static bool get_pts_connect_eatt_unconditionally(void) { return false; } +static bool get_pts_connect_eatt_before_encryption(void) { return false; } +static bool get_pts_unencrypt_broadcast(void) { return false; } +static bool get_pts_eatt_peripheral_collision_support(void) { return false; } +static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } +static bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } +static config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ .get_pts_avrcp_test = get_pts_avrcp_test, @@ -278,7 +275,7 @@ static const types::CodecConfigSetting vendor_code_48_2 = { .channel_count_per_iso_stream = 1, }; -void set_mock_offload_capabilities(const std::vector<AudioSetConfiguration>& caps) { +static void set_mock_offload_capabilities(const std::vector<AudioSetConfiguration>& caps) { offload_capabilities = ∩︀ } @@ -289,7 +286,7 @@ static constexpr char kPropLeAudioOffloadDisabled[] = "persist.bluetooth.leaudio static constexpr char kPropLeAudioBidirSwbSupported[] = "bluetooth.leaudio.dual_bidirection_swb.supported"; -RawAddress GetTestAddress(uint8_t index) { +static RawAddress GetTestAddress(uint8_t index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; return result; @@ -729,6 +726,17 @@ TEST_F(CodecManagerTestAdsp, test_capabilities) { {.codec_type = bluetooth::le_audio::LE_AUDIO_CODEC_INDEX_SOURCE_LC3}}; codec_manager->Start(offloading_preference); + auto output_capabilities = codec_manager->GetLocalAudioOutputCodecCapa(); + bool is_multiplex_supported = false; + for (auto& capa : output_capabilities) { + if (capa.channel_count > bluetooth::le_audio::LE_AUDIO_CHANNEL_COUNT_INDEX_1) { + is_multiplex_supported = true; + break; + } + } + + ASSERT_TRUE(is_multiplex_supported); + size_t available_configs_size = 0; auto match_first_config = [&available_configs_size]( diff --git a/system/bta/le_audio/device_groups.cc b/system/bta/le_audio/device_groups.cc index bfd6bba80a..733f9e71ec 100644 --- a/system/bta/le_audio/device_groups.cc +++ b/system/bta/le_audio/device_groups.cc @@ -57,9 +57,6 @@ #include "stack/include/btm_client_interface.h" #include "types/bt_transport.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth::le_audio { using bluetooth::le_audio::types::ase; @@ -842,6 +839,12 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy BidirectionalPair<bool> has_location = {false, false}; for (auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) { + if (!device->audio_locations_.get(direction)) { + log::debug("Device {} has no audio allocation for direction: {}", device->address_, + (int)direction); + continue; + } + // Do not put any requirements on the Source if Sink only scenario is used // Note: With the RINGTONE we should already prepare for a call. if ((direction == types::kLeAudioDirectionSource) && @@ -873,10 +876,8 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy } } - auto& dev_locations = (direction == types::kLeAudioDirectionSink) - ? device->snk_audio_locations_ - : device->src_audio_locations_; - if (dev_locations.none()) { + auto const& dev_locations = device->audio_locations_.get(direction); + if (dev_locations == std::nullopt) { log::warn("Device {} has no specified locations for direction: {}", device->address_, (int)direction); } @@ -891,8 +892,9 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy } // Pass the audio channel allocation requirement according to TMAP - auto locations = dev_locations.to_ulong() & (codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight); + auto locations = + dev_locations->value.to_ulong() & (codec_spec_conf::kLeAudioLocationFrontLeft | + codec_spec_conf::kLeAudioLocationFrontRight); CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements config_req; config_req.params.Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, (uint32_t)locations); @@ -1059,27 +1061,29 @@ types::BidirectionalPair<AudioContexts> LeAudioDeviceGroup::GetLatestAvailableCo } bool LeAudioDeviceGroup::ReloadAudioLocations(void) { - AudioLocations updated_snk_audio_locations_ = codec_spec_conf::kLeAudioLocationMonoAudio; - AudioLocations updated_src_audio_locations_ = codec_spec_conf::kLeAudioLocationMonoAudio; - - for (const auto& device : leAudioDevices_) { - if (device.expired() || - (device.lock().get()->GetConnectionState() != DeviceConnectState::CONNECTED)) { - continue; + types::BidirectionalPair<std::optional<AudioLocations>> updated_audio_locations = { + .sink = std::nullopt, .source = std::nullopt}; + + for (const auto& device_locked : leAudioDevices_) { + auto device = device_locked.lock(); + if (device && device->GetConnectionState() == DeviceConnectState::CONNECTED) { + if (device->audio_locations_.sink) { + updated_audio_locations.sink = + updated_audio_locations.sink.value_or(0) | device->audio_locations_.sink->value; + } + if (device->audio_locations_.source) { + updated_audio_locations.source = + updated_audio_locations.source.value_or(0) | device->audio_locations_.source->value; + } } - updated_snk_audio_locations_ |= device.lock().get()->snk_audio_locations_; - updated_src_audio_locations_ |= device.lock().get()->src_audio_locations_; } /* Nothing has changed */ - if ((updated_snk_audio_locations_ == snk_audio_locations_) && - (updated_src_audio_locations_ == src_audio_locations_)) { + if (updated_audio_locations == audio_locations_) { return false; } - snk_audio_locations_ = updated_snk_audio_locations_; - src_audio_locations_ = updated_src_audio_locations_; - + audio_locations_ = updated_audio_locations; return true; } @@ -1104,7 +1108,7 @@ bool LeAudioDeviceGroup::ReloadAudioDirections(void) { return true; } -AudioContexts LeAudioDeviceGroup::GetAllSupportedBidirectionalContextTypes(void) { +AudioContexts LeAudioDeviceGroup::GetAllSupportedBidirectionalContextTypes(void) const { auto result = GetSupportedContexts(types::kLeAudioDirectionSink) & GetSupportedContexts(types::kLeAudioDirectionSource); @@ -1114,7 +1118,7 @@ AudioContexts LeAudioDeviceGroup::GetAllSupportedBidirectionalContextTypes(void) } AudioContexts LeAudioDeviceGroup::GetAllSupportedSingleDirectionOnlyContextTypes( - uint8_t remote_direction) { + uint8_t remote_direction) const { AudioContexts result; /* Remote device present supported context types on the different directions. @@ -1215,27 +1219,33 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() c /* Update the strategy if not set yet or was invalidated */ if (!strategy_) { /* Choose the group configuration strategy based on PAC records */ - strategy_ = [this]() { + auto strategy_selector = [&, this](uint8_t direction) { int expected_group_size = Size(); + if (!audio_locations_.get(direction)) { + log::error("No audio locations for direction: {} available in the group", +direction); + return types::LeAudioConfigurationStrategy::RFU; + } + /* Simple strategy picker */ log::debug("Group {} size {}", group_id_, expected_group_size); if (expected_group_size > 1) { return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE; } - log::debug("audio location 0x{:04x}", snk_audio_locations_.to_ulong()); - if (!(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) || - !(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight) || - snk_audio_locations_.none()) { + /* Check supported audio locations */ + auto const& locations = audio_locations_.get(direction).value(); + + log::verbose("audio location 0x{:04x}", locations.to_ulong()); + if (!(locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) || + !(locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight) || locations.none()) { return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE; } auto device = GetFirstDevice(); /* Note: Currently, the audio channel counts LTV is only mandatory for * LC3. */ - auto channel_count_bitmap = - device->GetSupportedAudioChannelCounts(types::kLeAudioDirectionSink); + auto channel_count_bitmap = device->GetSupportedAudioChannelCounts(direction); log::debug("Supported channel counts for group {} (device {}) is {}", group_id_, device->address_, channel_count_bitmap); if (channel_count_bitmap == 1) { @@ -1243,7 +1253,12 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() c } return types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE; - }(); + }; + strategy_ = strategy_selector(types::kLeAudioDirectionSink); + if (strategy_ == types::LeAudioConfigurationStrategy::RFU) { + log::warn("Unable to find the proper remote sink strategy. Trying source direction instead"); + strategy_ = strategy_selector(types::kLeAudioDirectionSource); + } log::info("Group strategy set to: {}", [](types::LeAudioConfigurationStrategy strategy) { switch (strategy) { @@ -1270,6 +1285,94 @@ int LeAudioDeviceGroup::GetAseCount(uint8_t direction) const { return result; } +/* Calculate the total number of sink, source and bidirectional CISes required by the CIG, + * for the given configuration audio context. + */ +void LeAudioDeviceGroup::CigConfiguration::GetCisCount(LeAudioContextType context_type, + uint8_t& out_cis_count_bidir, + uint8_t& out_cis_count_unidir_sink, + uint8_t& out_cis_count_unidir_source) const { + auto expected_device_cnt = group_->DesiredSize(); + auto avail_group_ase_snk_cnt = group_->GetAseCount(types::kLeAudioDirectionSink); + auto avail_group_ase_src_count = group_->GetAseCount(types::kLeAudioDirectionSource); + auto strategy = group_->GetGroupSinkStrategy(); + + bool is_bidirectional = group_->GetAllSupportedBidirectionalContextTypes().test(context_type); + bool is_source_only = !is_bidirectional && group_->GetAllSupportedSingleDirectionOnlyContextTypes( + types::kLeAudioDirectionSource) + .test(context_type); + log::debug( + "{} {}, strategy {}, group avail sink ases: {}, " + "group avail source ases {} " + "expected_device_count {}", + bluetooth::common::ToString(context_type), + is_bidirectional ? "is bidirectional" + : (is_source_only ? "is source only" : "is sink only"), + static_cast<int>(strategy), avail_group_ase_snk_cnt, avail_group_ase_src_count, + expected_device_cnt); + + switch (strategy) { + case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: + /* This strategy is for the CSIS topology, e.g. two earbuds which are both + * connected with a Phone + */ + case types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE: + /* This strategy is for e.g. the banded headphones */ + if (is_bidirectional) { + if ((avail_group_ase_snk_cnt > 0) && (avail_group_ase_src_count) > 0) { + /* Prepare CIG to enable all microphones */ + out_cis_count_bidir = expected_device_cnt; + } else { + if (avail_group_ase_snk_cnt > 0) { + out_cis_count_unidir_sink = expected_device_cnt; + } else if (avail_group_ase_src_count > 0) { + out_cis_count_unidir_source = expected_device_cnt; + } + } + } else if (is_source_only) { + out_cis_count_unidir_source = expected_device_cnt; + } else { + out_cis_count_unidir_sink = expected_device_cnt; + } + + break; + case types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE: + /* This strategy is for the old TWS topology. e.g. one earbud connected to + * the Phone but each channel is carried in separate CIS + */ + if (is_bidirectional) { + if ((avail_group_ase_snk_cnt > 0) && (avail_group_ase_src_count) > 0) { + /* Prepare CIG to enable all microphones per device */ + out_cis_count_bidir = expected_device_cnt; + if (avail_group_ase_src_count > 1) { + out_cis_count_bidir++; + } else { + out_cis_count_unidir_sink = expected_device_cnt; + } + } else { + if (avail_group_ase_snk_cnt > 0) { + out_cis_count_unidir_sink = 2 * expected_device_cnt; + } else if (avail_group_ase_src_count > 0) { + out_cis_count_unidir_source = 2 * expected_device_cnt; + } + } + } else if (is_source_only) { + out_cis_count_unidir_source = 2 * expected_device_cnt; + } else { + out_cis_count_unidir_sink = 2 * expected_device_cnt; + } + break; + case types::LeAudioConfigurationStrategy::RFU: + log::error("Should not happen;"); + break; + } + + log::info( + "Required cis count: Bi-Directional: {}, Uni-Directional Sink: {}, " + "Uni-Directional Source: {}", + out_cis_count_bidir, out_cis_count_unidir_sink, out_cis_count_unidir_source); +} + void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds(LeAudioContextType context_type) { log::info("Group {}, group_id: {}, context_type: {}", std::format_ptr(group_), group_->group_id_, bluetooth::common::ToString(context_type)); @@ -1282,23 +1385,7 @@ void LeAudioDeviceGroup::CigConfiguration::GenerateCisIds(LeAudioContextType con uint8_t cis_count_bidir = 0; uint8_t cis_count_unidir_sink = 0; uint8_t cis_count_unidir_source = 0; - int group_size = group_->DesiredSize(); - - uint8_t expected_remote_directions; - if (group_->GetAllSupportedBidirectionalContextTypes().test(context_type)) { - expected_remote_directions = types::kLeAudioDirectionBoth; - } else if (group_->GetAllSupportedSingleDirectionOnlyContextTypes(types::kLeAudioDirectionSource) - .test(context_type)) { - expected_remote_directions = types::kLeAudioDirectionSource; - } else { - expected_remote_directions = types::kLeAudioDirectionSink; - } - - types::get_cis_count(context_type, expected_remote_directions, group_size, - group_->GetGroupSinkStrategy(), - group_->GetAseCount(types::kLeAudioDirectionSink), - group_->GetAseCount(types::kLeAudioDirectionSource), cis_count_bidir, - cis_count_unidir_sink, cis_count_unidir_source); + GetCisCount(context_type, cis_count_bidir, cis_count_unidir_sink, cis_count_unidir_source); uint8_t idx = 0; while (cis_count_bidir > 0) { @@ -1520,17 +1607,26 @@ void LeAudioDeviceGroup::CigConfiguration::UnassignCis(LeAudioDevice* leAudioDev } } -bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy, - const types::AseConfiguration& conf, uint8_t direction, - const LeAudioDevice& device) { +static bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy, + const types::AseConfiguration& conf, uint8_t direction, + const LeAudioDevice& device) { + if (strategy == types::LeAudioConfigurationStrategy::RFU) { + log::error("Device {}: No valid strategy for direction: {}", device.address_, +direction); + return false; + } + + if (!device.audio_locations_.get(direction)) { + log::error("Device {}: No valid audio locations for direction: {}", device.address_, + +direction); + return false; + } + /* Check direction and if audio location allows to create more cises to a * single device. */ - types::AudioLocations audio_locations = (direction == types::kLeAudioDirectionSink) - ? device.snk_audio_locations_ - : device.src_audio_locations_; - - log::debug("strategy: {}, locations: {}", (int)strategy, audio_locations.to_ulong()); + auto const& audio_locations = device.audio_locations_.get(direction)->value; + log::debug("Device {}: strategy: {}, locations: {}", device.address_, (int)strategy, + audio_locations.to_ulong()); switch (strategy) { case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: @@ -2194,10 +2290,8 @@ bool LeAudioDeviceGroup::Configure( types::BidirectionalPair<std::vector<uint8_t>> ccid_lists) { auto conf = GetConfiguration(context_type); if (!conf) { - log::error( - ", requested context type: {} , is in mismatch with cached available " - "contexts", - bluetooth::common::ToString(context_type)); + log::error("Requested context type: {} , is in mismatch with cached available contexts", + bluetooth::common::ToString(context_type)); return false; } diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h index 73d537ce0e..421eacf28b 100644 --- a/system/bta/le_audio/device_groups.h +++ b/system/bta/le_audio/device_groups.h @@ -62,7 +62,9 @@ public: bluetooth::common::ToString(state)); state_ = state; } - + void GetCisCount(types::LeAudioContextType context_type, uint8_t& out_cis_count_bidir, + uint8_t& out_cis_count_unidir_sink, + uint8_t& out_cis_count_unidir_source) const; void GenerateCisIds(types::LeAudioContextType context_type); bool AssignCisIds(LeAudioDevice* leAudioDevice); void AssignCisConnHandles(const std::vector<uint16_t>& conn_handles); @@ -92,8 +94,7 @@ public: bool notify_streaming_when_cises_are_ready_; uint8_t audio_directions_; - types::AudioLocations snk_audio_locations_; - types::AudioLocations src_audio_locations_; + types::BidirectionalPair<std::optional<types::AudioLocations>> audio_locations_; /* Whether LE Audio is preferred for OUTPUT_ONLY and DUPLEX cases */ bool is_output_preference_le_audio; @@ -217,8 +218,8 @@ public: void ResetPreferredAudioSetConfiguration(void) const; bool ReloadAudioLocations(void); bool ReloadAudioDirections(void); - types::AudioContexts GetAllSupportedBidirectionalContextTypes(void); - types::AudioContexts GetAllSupportedSingleDirectionOnlyContextTypes(uint8_t direction); + types::AudioContexts GetAllSupportedBidirectionalContextTypes(void) const; + types::AudioContexts GetAllSupportedSingleDirectionOnlyContextTypes(uint8_t direction) const; std::shared_ptr<const types::AudioSetConfiguration> GetActiveConfiguration(void) const; bool IsPendingConfiguration(void) const; std::shared_ptr<const types::AudioSetConfiguration> GetConfiguration( diff --git a/system/bta/le_audio/devices.cc b/system/bta/le_audio/devices.cc index 59849628af..1d23d93d5e 100644 --- a/system/bta/le_audio/devices.cc +++ b/system/bta/le_audio/devices.cc @@ -59,9 +59,6 @@ #include "types/bt_transport.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::hci::kIsoCigPhy1M; using bluetooth::hci::kIsoCigPhy2M; using bluetooth::le_audio::DeviceConnectState; @@ -205,9 +202,18 @@ static uint32_t GetFirstRight(const AudioLocations& audio_locations) { return 0; } -uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, - const AudioLocations& device_locations, - AudioLocations& group_locations) { +static uint32_t PickAudioLocation( + types::LeAudioConfigurationStrategy strategy, uint8_t direction, + const types::BidirectionalPair< + std::optional<types::hdl_pair_wrapper<types::AudioLocations>>>& + device_audio_locations, + AudioLocations& group_locations) { + if (!device_audio_locations.get(direction)) { + log::error("No valid location is available for direction {}", +direction); + return 0; + } + auto const device_locations = device_audio_locations.get(direction)->value; + log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}", (int)strategy, device_locations.to_ulong(), group_locations.to_ulong()); @@ -218,7 +224,9 @@ uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, uint32_t left_device_loc = GetFirstLeft(device_locations); uint32_t right_device_loc = GetFirstRight(device_locations); - if (left_device_loc == 0 && right_device_loc == 0) { + /* Sink locations should be either Left or Right - TMAP 1.0 Sec. 3.5.1.2.1 */ + if (direction == le_audio::types::kLeAudioDirectionSink && left_device_loc == 0 && + right_device_loc == 0) { log::warn("Can't find device able to render left and right audio channel"); } @@ -247,15 +255,23 @@ uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy, return 0; } - log::error( - "Can't find device for left/right channel. Strategy: {}, " - "device_locations: {:x}, output group_locations: {:x}.", - strategy, device_locations.to_ulong(), group_locations.to_ulong()); - /* Return either any left or any right audio location. It might result with * multiple devices within the group having the same location. */ - return left_device_loc ? left_device_loc : right_device_loc; + auto location = left_device_loc ? left_device_loc : right_device_loc; + + if (direction == le_audio::types::kLeAudioDirectionSink) { + log::error( + "Can't find device for left/right channel. Strategy: {}, device_locations: {:x}, " + "output group_locations: {:x}, chosen location: {}.", + strategy, device_locations.to_ulong(), group_locations.to_ulong(), location); + } else { + log::debug( + "No left or right audio location available. Strategy: {}, device_locations: {:x}, " + "output group_locations: {:x}, chosen location: {}.", + strategy, device_locations.to_ulong(), group_locations.to_ulong(), location); + } + return location; } bool LeAudioDevice::IsAudioSetConfigurationSupported( @@ -290,6 +306,11 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_ AudioLocations& group_audio_locations_memo, const AudioContexts& metadata_context_types, const std::vector<uint8_t>& ccid_lists, bool reuse_cis_id) { + if (num_of_devices == 0) { + log::error("No devices available for configuration."); + return false; + } + auto direction_str = (direction == types::kLeAudioDirectionSink ? "Sink" : "Source"); /* First try to use the already configured ASE */ auto ase = GetFirstActiveAseByDirection(direction); @@ -305,9 +326,12 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_ return false; } - auto audio_locations = - (direction == types::kLeAudioDirectionSink) ? snk_audio_locations_ : src_audio_locations_; + if (!audio_locations_.get(direction)) { + log::error("{}, unable to find a {} audio allocation", address_, direction_str); + return false; + } + auto const& audio_locations = audio_locations_.get(direction)->value; auto const& group_ase_configs = audio_set_conf->confs.get(direction); std::vector<types::AseConfiguration> ase_configs; std::copy_if(group_ase_configs.cbegin(), group_ase_configs.cend(), @@ -409,7 +433,7 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_ /* Let's choose audio channel allocation if not set */ ase->codec_config.params.Add( codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation, - PickAudioLocation(strategy, audio_locations, group_audio_locations_memo)); + PickAudioLocation(strategy, direction, audio_locations_, group_audio_locations_memo)); /* Get default value if no requirement for specific frame blocks per sdu */ @@ -1046,8 +1070,12 @@ static std::string locationToString(uint32_t location) { void LeAudioDevice::Dump(std::stringstream& stream) { uint16_t acl_handle = get_btm_client_interface().peer.BTM_GetHCIConnHandle(address_, BT_TRANSPORT_LE); - std::string snk_location = locationToString(snk_audio_locations_.to_ulong()); - std::string src_location = locationToString(src_audio_locations_.to_ulong()); + std::string snk_location = audio_locations_.sink + ? locationToString(audio_locations_.sink->value.to_ulong()) + : "None"; + std::string src_location = audio_locations_.source + ? locationToString(audio_locations_.source->value.to_ulong()) + : "None"; stream << " ● Device address: " << address_.ToRedactedStringForLogging() << ", " << connection_state_ diff --git a/system/bta/le_audio/devices.h b/system/bta/le_audio/devices.h index a176caaf4a..ed1f7621c1 100644 --- a/system/bta/le_audio/devices.h +++ b/system/bta/le_audio/devices.h @@ -93,14 +93,12 @@ public: std::bitset<16> tmap_role_; uint8_t audio_directions_; - types::AudioLocations snk_audio_locations_; - types::AudioLocations src_audio_locations_; + types::BidirectionalPair<std::optional<types::hdl_pair_wrapper<types::AudioLocations>>> + audio_locations_; types::PublishedAudioCapabilities snk_pacs_; types::PublishedAudioCapabilities src_pacs_; - struct types::hdl_pair snk_audio_locations_hdls_; - struct types::hdl_pair src_audio_locations_hdls_; struct types::hdl_pair audio_avail_hdls_; struct types::hdl_pair audio_supp_cont_hdls_; std::vector<struct types::ase> ases_; diff --git a/system/bta/le_audio/devices_test.cc b/system/bta/le_audio/devices_test.cc index 07c9cab819..9abeb6c82e 100644 --- a/system/bta/le_audio/devices_test.cc +++ b/system/bta/le_audio/devices_test.cc @@ -35,13 +35,6 @@ #include "stack/btm/btm_int_types.h" #include "test/mock/mock_main_shim_entry.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - -tACL_CONN* btm_bda_to_acl(const RawAddress& /*bda*/, tBT_TRANSPORT /*transport*/) { - return nullptr; -} - const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { return tBLE_BD_ADDR{.type = BLE_ADDR_PUBLIC, .bda = bd_addr}; } @@ -317,19 +310,19 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) { switch (id) { case Lc3SettingId::LC3_8_1: case Lc3SettingId::LC3_8_2: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq8000Hz; + return codec_spec_conf::kLeAudioSamplingFreq8000Hz; case Lc3SettingId::LC3_16_1: case Lc3SettingId::LC3_16_2: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq16000Hz; + return codec_spec_conf::kLeAudioSamplingFreq16000Hz; case Lc3SettingId::LC3_24_1: case Lc3SettingId::LC3_24_2: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz; + return codec_spec_conf::kLeAudioSamplingFreq24000Hz; case Lc3SettingId::LC3_32_1: case Lc3SettingId::LC3_32_2: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz; + return codec_spec_conf::kLeAudioSamplingFreq32000Hz; case Lc3SettingId::LC3_441_1: case Lc3SettingId::LC3_441_2: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq44100Hz; + return codec_spec_conf::kLeAudioSamplingFreq44100Hz; case Lc3SettingId::LC3_48_1: case Lc3SettingId::LC3_48_2: case Lc3SettingId::LC3_48_3: @@ -337,7 +330,7 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) { case Lc3SettingId::LC3_48_5: case Lc3SettingId::LC3_48_6: case Lc3SettingId::LC3_VND_1: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz; + return codec_spec_conf::kLeAudioSamplingFreq48000Hz; case Lc3SettingId::UNSUPPORTED: return kLeAudioSamplingFreqRfu; } @@ -354,7 +347,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) { case Lc3SettingId::LC3_48_1: case Lc3SettingId::LC3_48_3: case Lc3SettingId::LC3_48_5: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us; + return codec_spec_conf::kLeAudioCodecFrameDur7500us; case Lc3SettingId::LC3_8_2: case Lc3SettingId::LC3_16_2: case Lc3SettingId::LC3_24_2: @@ -364,7 +357,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) { case Lc3SettingId::LC3_48_4: case Lc3SettingId::LC3_48_6: case Lc3SettingId::LC3_VND_1: - return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us; + return codec_spec_conf::kLeAudioCodecFrameDur10000us; case Lc3SettingId::UNSUPPORTED: return kLeAudioCodecFrameDurRfu; } @@ -662,8 +655,8 @@ protected: kLeAudioDirectionSource); } - log::debug("snk confs size: {}", cfg.confs.sink.size()); - log::debug("src confs size: {}", cfg.confs.source.size()); + log::debug("{}: snk confs size: {}", cfg.name, cfg.confs.sink.size()); + log::debug("{}: src confs size: {}", cfg.name, cfg.confs.source.size()); return (!cfg.confs.sink.empty() || !cfg.confs.source.empty()) ? std::make_unique<AudioSetConfiguration>(cfg) : nullptr; @@ -748,13 +741,11 @@ protected: } } - LeAudioDevice* AddTestDevice( - int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0, int src_ase_num_cached = 0, - bool invert_ases_emplacement = false, bool out_of_range_device = false, - uint8_t snk_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight, - uint8_t src_allocation = codec_spec_conf::kLeAudioLocationFrontLeft | - codec_spec_conf::kLeAudioLocationFrontRight) { + LeAudioDevice* AddTestDevice(int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0, + int src_ase_num_cached = 0, bool invert_ases_emplacement = false, + bool out_of_range_device = false, + std::optional<uint32_t> snk_allocation = kChannelAllocationStereo, + std::optional<uint32_t> src_allocation = kChannelAllocationStereo) { int index = group_->Size() + 1; auto device = (std::make_shared<LeAudioDevice>(GetTestAddress(index), DeviceConnectState::DISCONNECTED)); @@ -799,8 +790,16 @@ protected: .source = AudioContexts(kLeAudioContextAllTypes)}); device->SetAvailableContexts({.sink = AudioContexts(kLeAudioContextAllTypes), .source = AudioContexts(kLeAudioContextAllTypes)}); - device->snk_audio_locations_ = snk_allocation; - device->src_audio_locations_ = src_allocation; + + if (snk_allocation) { + device->audio_locations_.sink.emplace(hdl_pair(0x00ea, 0x0eb), + types::AudioLocations(snk_allocation.value())); + } + + if (src_allocation) { + device->audio_locations_.source.emplace(hdl_pair(0x00fa, 0x00fb), + types::AudioLocations(src_allocation.value())); + } device->conn_id_ = index; device->SetConnectionState(out_of_range_device ? DeviceConnectState::DISCONNECTED @@ -810,6 +809,12 @@ protected: return device.get(); } + LeAudioDevice* AddTestDevice(std::optional<std::pair<int, uint32_t>> sink, + std::optional<std::pair<int, uint32_t>> source = std::nullopt) { + return AddTestDevice(sink ? sink->first : 0, source ? source->first : 0, 0, 0, false, false, + sink ? sink->second : 0, source ? source->second : 0); + } + bool TestGroupAseConfigurationVerdict(const TestGroupAseConfigurationData& data, uint8_t directions_to_verify) { BidirectionalPair<uint8_t> active_channel_num = {0, 0}; @@ -975,16 +980,11 @@ protected: ::bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations( context_type); - bool success_expected = directions_to_verify != 0; + bool is_expected_to_match_config = directions_to_verify != 0; int num_of_matching_configurations = 0; for (const auto& audio_set_conf : *configurations) { bool interesting_configuration = true; - uint8_t configuration_directions = 0; - - // the configuration should fail if there are no active ases expected - PublishedAudioCapabilitiesBuilder snk_pac_builder, src_pac_builder; - snk_pac_builder.Reset(); - src_pac_builder.Reset(); + uint8_t expected_configuration_directions = 0; /* Let's go thru devices in the group and configure them*/ for (int i = 0; i < data_size; i++) { @@ -993,43 +993,46 @@ protected: /* Prepare PAC's for each device. Also make sure configuration is in our * interest to test */ for (auto direction : {kLeAudioDirectionSink, kLeAudioDirectionSource}) { - auto const& ase_confs = audio_set_conf->confs.get(direction); - auto strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig(ase_confs, data_size); - auto const ase_cnt = ase_confs.size(); - - if (ase_cnt == 0) { + auto const& ase_confs = audio_set_conf->confs; + if (ase_confs.get(direction).size() == 0) { // Skip the direction if not available continue; } /* Make sure the strategy is the expected one */ - if (direction == kLeAudioDirectionSink && group_->GetGroupSinkStrategy() != strategy) { + auto ase_config_strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig( + ase_confs.get(direction), data_size); + if (group_->GetGroupSinkStrategy() != ase_config_strategy) { log::debug("Sink strategy mismatch group!=cfg.entry ({}!={})", static_cast<int>(group_->GetGroupSinkStrategy()), - static_cast<int>(strategy)); + static_cast<int>(ase_config_strategy)); interesting_configuration = false; } - configuration_directions |= direction; - - auto& pac_builder = - (direction == kLeAudioDirectionSink) ? snk_pac_builder : src_pac_builder; auto& dest_pacs = (direction == kLeAudioDirectionSink) ? data[i].device->snk_pacs_ : data[i].device->src_pacs_; - auto const& data_channel_counts = (direction == kLeAudioDirectionSink) - ? data[i].audio_channel_counts_snk - : data[i].audio_channel_counts_src; + auto const& pacs_data_channel_counts = (direction == kLeAudioDirectionSink) + ? data[i].audio_channel_counts_snk + : data[i].audio_channel_counts_src; + + if (((direction == kLeAudioDirectionSink) + ? data[i].expected_active_channel_num_snk + : data[i].expected_active_channel_num_src) > 0) { + expected_configuration_directions |= direction; + } - for (const auto& entry : ase_confs) { - num_of_ase.get(direction)++; - pac_builder.Add(entry.codec, data_channel_counts); + /* Add PAC records */ + PublishedAudioCapabilitiesBuilder pac_builder; + for (const auto& entry : ase_confs.get(direction)) { + pac_builder.Add(entry.codec, pacs_data_channel_counts); if (preferred_codec_config && should_use_preferred_codec) { const auto customized_codec_config = PreparePreferredCodecConfig(entry.codec, *preferred_codec_config); - pac_builder.Add(customized_codec_config, data_channel_counts); + pac_builder.Add(customized_codec_config, pacs_data_channel_counts); } dest_pacs = pac_builder.Get(); } + num_of_ase.get(direction) += ase_confs.get(direction).size(); num_of_ase.get(direction) /= data_size; } @@ -1043,9 +1046,6 @@ protected: } } - BidirectionalPair<AudioContexts> group_audio_locations = { - .sink = AudioContexts(context_type), .source = AudioContexts(context_type)}; - /* Set preferred codec*/ if (preferred_codec_config) { group_->SetPreferredAudioSetConfiguration(*preferred_codec_config, *preferred_codec_config); @@ -1055,11 +1055,18 @@ protected: group_->UpdateAudioContextAvailability(); group_->UpdateAudioSetConfigurationCache(context_type); + BidirectionalPair<AudioContexts> group_audio_locations = { + .sink = AudioContexts(context_type), .source = AudioContexts(context_type)}; auto configuration_result = group_->Configure(context_type, group_audio_locations); /* In case of configuration #ase is same as the one we expected to be * activated verify, ASEs are actually active */ - if (interesting_configuration && (directions_to_verify == configuration_directions)) { + uint8_t configuration_directions = + (audio_set_conf->confs.sink.size() ? kLeAudioDirectionSink : 0) | + (audio_set_conf->confs.source.size() ? kLeAudioDirectionSource : 0); + + if (interesting_configuration && + (expected_configuration_directions == configuration_directions)) { ASSERT_TRUE(configuration_result); ASSERT_EQ(group_->GetPreferredConfiguration(context_type) != nullptr, should_use_preferred_codec); @@ -1080,13 +1087,23 @@ protected: TestAsesInactive(); } - if (success_expected) { + if (is_expected_to_match_config) { ASSERT_GT(num_of_matching_configurations, 0); } else { ASSERT_EQ(0, num_of_matching_configurations); } } + auto TestGroupAseConfiguration(LeAudioContextType context_type, + std::vector<TestGroupAseConfigurationData> data, + uint8_t directions_to_verify = kLeAudioDirectionSink | + kLeAudioDirectionSource, + btle_audio_codec_config_t* preferred_codec_config = nullptr, + bool should_use_preferred_codec = false) { + return TestGroupAseConfiguration(context_type, data.data(), data.size(), directions_to_verify, + preferred_codec_config, should_use_preferred_codec); + } + void TestAsesActive(LeAudioCodecId codec_id, uint8_t sampling_frequency, uint8_t frame_duration, uint16_t octets_per_frame, uint8_t codec_frame_blocks_per_sdu = 1) { bool active_ase = false; @@ -1369,12 +1386,10 @@ protected: } /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; + left->audio_locations_.sink->value = codec_spec_conf::kLeAudioLocationFrontLeft; + left->audio_locations_.source->value = codec_spec_conf::kLeAudioLocationFrontLeft; + right->audio_locations_.sink->value = codec_spec_conf::kLeAudioLocationFrontRight; + right->audio_locations_.source->value = codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); ASSERT_TRUE(group_->Configure(context_type, {.sink = AudioContexts(context_type), @@ -1415,16 +1430,12 @@ protected: }; TEST_P(LeAudioAseConfigurationTest, test_context_update) { - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); - ASSERT_EQ(2, group_->Size()); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); - /* Change locations */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); + ASSERT_EQ(2, group_->Size()); /* Put the PACS */ auto conversational_configuration = getSpecificConfiguration( @@ -1560,45 +1571,65 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) { ASSERT_TRUE(group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS)); } -TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone) { - LeAudioDevice* mono_speaker = AddTestDevice(1, 0); +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone_loc0) { + /* mono location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}}); TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}); - /* mono, change location as by default it is stereo */ - mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); + uint8_t direction_to_verify = kLeAudioDirectionSink; + + TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify); +} + +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone) { + /* left only location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountSingleChannel, 1, 0}); uint8_t direction_to_verify = kLeAudioDirectionSink; TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify); } -TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational) { - LeAudioDevice* mono_speaker = AddTestDevice(1, 0); +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational_loc0) { + /* mono location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}}); TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountNone, 1, 0}); - /* mono, change location as by default it is stereo */ - mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); + /* Microphone should be used on the phone */ + uint8_t direction_to_verify = kLeAudioDirectionSink; + TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify); +} + +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational) { + /* left only location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountNone, 1, 0}); /* Microphone should be used on the phone */ uint8_t direction_to_verify = kLeAudioDirectionSink; TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify); } -TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media) { - LeAudioDevice* mono_speaker = AddTestDevice(1, 0); +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media_loc0) { + /* mono location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}}); TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountNone, 1, 0}); - /* mono, change location as by default it is stereo */ - mono_speaker->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); + uint8_t direction_to_verify = kLeAudioDirectionSink; + TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify); +} + +TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media) { + /* left only location */ + LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel, + kLeAudioCodecChannelCountNone, 1, 0}); uint8_t direction_to_verify = kLeAudioDirectionSink; TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify); @@ -1632,24 +1663,19 @@ TEST_P(LeAudioAseConfigurationTest, test_banded_headphones_media) { } TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_mono_microphone) { - LeAudioDevice* banded_headset = - AddTestDevice(2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationFrontLeft); + /* mono source */ + LeAudioDevice* banded_headset = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationStereo}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel, kLeAudioCodecChannelCountSingleChannel, 2, 1}); - /* mono, change location as by default it is stereo */ - banded_headset->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); - TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_mono_microphone_loc0) { - LeAudioDevice* banded_headset = - AddTestDevice(2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo, - codec_spec_conf::kLeAudioLocationMonoAudio); + /* mono source */ + LeAudioDevice* banded_headset = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationStereo}}, + {{1, codec_spec_conf::kLeAudioLocationMonoAudio}}); TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel, kLeAudioCodecChannelCountSingleChannel, 2, 1}); @@ -1760,79 +1786,59 @@ TEST_P(LeAudioAseConfigurationTest, test_banded_headset_media) { } TEST_P(LeAudioAseConfigurationTest, test_earbuds_ringtone) { - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - TestGroupAseConfiguration(LeAudioContextType::RINGTONE, data, 2); } TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational) { - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; group_->ReloadAudioLocations(); TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, data, 2); } TEST_P(LeAudioAseConfigurationTest, test_earbuds_media) { - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - uint8_t directions_to_verify = kLeAudioDirectionSink; TestGroupAseConfiguration(LeAudioContextType::MEDIA, data, 2, directions_to_verify); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_ringtone) { - LeAudioDevice* handsfree = AddTestDevice(1, 1); + LeAudioDevice* handsfree = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}); - handsfree->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - handsfree->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); - TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1); } TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_ringtone) { - LeAudioDevice* handsfree = AddTestDevice( - 1, 1, 0, 0, false, false, - codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight, - codec_spec_conf::kLeAudioLocationFrontLeft); + LeAudioDevice* handsfree = AddTestDevice({{1, kChannelAllocationStereo}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); TestGroupAseConfigurationData data( {handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel, kLeAudioCodecChannelCountSingleChannel, 2, 1}); @@ -1841,16 +1847,11 @@ TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_ringtone) { } TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_conversational) { - LeAudioDevice* handsfree = AddTestDevice(1, 1); + LeAudioDevice* handsfree = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}); - handsfree->snk_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - handsfree->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); - TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1); } @@ -1924,20 +1925,15 @@ TEST_P(LeAudioAseConfigurationTest, test_lc3_config_media) { TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_media) { com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true); - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - // this would be also built into pac record btle_audio_codec_config_t preferred_codec_config = { .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, @@ -1957,20 +1953,15 @@ TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_media) { TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_media) { com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true); - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - // this would be also built into pac record btle_audio_codec_config_t preferred_codec_config = { .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, @@ -1990,20 +1981,15 @@ TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_media) TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_conv) { com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true); - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - // this would be also built into pac record btle_audio_codec_config_t preferred_codec_config = { .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, @@ -2023,20 +2009,15 @@ TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_conv) { TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_conv) { com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true); - LeAudioDevice* left = AddTestDevice(1, 1); - LeAudioDevice* right = AddTestDevice(1, 1); + LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}, {right, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 1}}; - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - // this would be also built into pac record btle_audio_codec_config_t preferred_codec_config = { .codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3, @@ -2170,16 +2151,10 @@ static auto PrepareStackMetadataLtvBase() { } TEST_P(LeAudioAseConfigurationTest, test_reconnection_media) { - LeAudioDevice* left = AddTestDevice(2, 1); - LeAudioDevice* right = AddTestDevice(2, 1); - - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); - + LeAudioDevice* left = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel, kLeAudioCodecChannelCountSingleChannel, 1, 0}, {right, kLeAudioCodecChannelCountSingleChannel, @@ -2267,10 +2242,6 @@ TEST_P(LeAudioAseConfigurationTest, test_ase_metadata) { LeAudioDevice* headphones = AddTestDevice(2, 1); - /* Change location as by default it is stereo */ - headphones->snk_audio_locations_ = kChannelAllocationStereo; - group_->ReloadAudioLocations(); - AudioSetConfiguration media_configuration = *getSpecificConfiguration( "One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA); @@ -2355,13 +2326,8 @@ TEST_P(LeAudioAseConfigurationTest, test_ase_metadata) { * not assigned) or assigned to the same CIS ID as the opposite direction. */ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) { - LeAudioDevice* tws_headset = AddTestDevice(0, 0, 2, 1, true); - - /* Change location as by default it is stereo */ - tws_headset->snk_audio_locations_ = kChannelAllocationStereo; - tws_headset->src_audio_locations_ = - ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - group_->ReloadAudioLocations(); + LeAudioDevice* tws_headset = AddTestDevice(0, 0, 2, 1, true, false, kChannelAllocationStereo, + codec_spec_conf::kLeAudioLocationFrontLeft); auto conversational_configuration = getSpecificConfiguration( "Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency", @@ -2436,10 +2402,14 @@ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) { group_->Activate(LeAudioContextType::CONVERSATIONAL, audio_contexts, ccid_lists); TestActiveAses(); + ASSERT_NE(this->group_->cig.cises.size(), 0lu); /* Verify ASEs assigned CISes by counting assigned to bi-directional CISes */ int bi_dir_ases_count = std::count_if(tws_headset->ases_.begin(), tws_headset->ases_.end(), [this](auto& ase) { + if (ase.cis_id == kInvalidCisId) { + return false; + } return this->group_->cig.cises[ase.cis_id].type == CisType::CIS_TYPE_BIDIRECTIONAL; }); @@ -2476,14 +2446,10 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { /* Set desired size to 2 */ desired_group_size_ = 2; - LeAudioDevice* left = AddTestDevice(2, 1); + LeAudioDevice* left = + AddTestDevice({{2, kChannelAllocationStereo}}, {{1, kChannelAllocationStereo}}); LeAudioDevice* right = AddTestDevice(0, 0, 0, 0, false, true); - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = kChannelAllocationStereo; - right->snk_audio_locations_ = kChannelAllocationStereo; - group_->ReloadAudioLocations(); - auto media_configuration = getSpecificConfiguration( "One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA); ASSERT_NE(nullptr, media_configuration); @@ -2535,14 +2501,10 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) { } TEST_P(LeAudioAseConfigurationTest, test_config_support) { - LeAudioDevice* left = AddTestDevice(2, 1); + LeAudioDevice* left = + AddTestDevice({{2, kChannelAllocationStereo}}, {{1, kChannelAllocationStereo}}); LeAudioDevice* right = AddTestDevice(0, 0, 0, 0, false, true); - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = kChannelAllocationStereo; - right->snk_audio_locations_ = kChannelAllocationStereo; - group_->ReloadAudioLocations(); - auto test_config = getSpecificConfiguration( "One-OneChan-SnkAse-Lc3_48_4-One-OneChan-SrcAse-Lc3_16_2_Balanced_Reliability", LeAudioContextType::VOICEASSISTANTS); @@ -2575,15 +2537,10 @@ TEST_P(LeAudioAseConfigurationTest, test_config_support) { TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group) { // A group of two earbuds - LeAudioDevice* left = AddTestDevice(2, 1); - LeAudioDevice* right = AddTestDevice(2, 1); - - /* Change location as by default it is stereo */ - left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft; - right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight; - group_->ReloadAudioLocations(); + LeAudioDevice* left = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontLeft}}, + {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + LeAudioDevice* right = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontRight}}, + {{1, codec_spec_conf::kLeAudioLocationFrontRight}}); // The Right earbud is currently disconnected right->SetConnectionState(DeviceConnectState::DISCONNECTED); @@ -2599,6 +2556,32 @@ TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group direction_to_verify); } +TEST_P(LeAudioAseConfigurationTest, test_mono_microphone_conversational_loc0) { + /* Mono microphone - Speaker should be used on the phone */ + auto mono_microphone = + AddTestDevice(std::nullopt, {{1, codec_spec_conf::kLeAudioLocationMonoAudio}}); + TestGroupAseConfigurationData data( + {.device = mono_microphone, + .audio_channel_counts_snk = kLeAudioCodecChannelCountNone, + .audio_channel_counts_src = kLeAudioCodecChannelCountSingleChannel, + .expected_active_channel_num_snk = 0, + .expected_active_channel_num_src = 1}); + TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, {data}); +} + +TEST_P(LeAudioAseConfigurationTest, test_mono_microphone_conversational) { + /* Mono microphone - Speaker should be used on the phone */ + auto mono_microphone = + AddTestDevice(std::nullopt, {{1, codec_spec_conf::kLeAudioLocationFrontLeft}}); + TestGroupAseConfigurationData data( + {.device = mono_microphone, + .audio_channel_counts_snk = kLeAudioCodecChannelCountNone, + .audio_channel_counts_src = kLeAudioCodecChannelCountSingleChannel, + .expected_active_channel_num_snk = 0, + .expected_active_channel_num_src = 1}); + TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, {data}); +} + TEST_P(LeAudioAseConfigurationTest, test_get_metadata_no_ccid) { auto mono_microphone = AddTestDevice(1, 0); auto metadata = mono_microphone->GetMetadata( diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc index f7ae688b37..a8fdad50ca 100644 --- a/system/bta/le_audio/le_audio_client_test.cc +++ b/system/bta/le_audio/le_audio_client_test.cc @@ -30,6 +30,7 @@ #include "bta_groups.h" #include "bta_le_audio_api.h" #include "bta_le_audio_broadcaster_api.h" +#include "btif/include/btif_common.h" #include "btif/include/mock_core_callbacks.h" #include "btif_storage_mock.h" #include "btm_api_mock.h" @@ -51,15 +52,13 @@ #include "mock_device_groups.h" #include "mock_state_machine.h" #include "stack/include/btm_status.h" +#include "stack/include/main_thread.h" #include "test/common/mock_functions.h" #include "test/mock/mock_main_shim_entry.h" #include "test/mock/mock_stack_btm_iso.h" #define TEST_BT com::android::bluetooth::flags -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using testing::_; using testing::AnyNumber; using testing::AtLeast; @@ -107,18 +106,14 @@ static constexpr char kNotifyUpperLayerAboutGroupBeingInIdleDuringCall[] = void osi_property_set_bool(const char* key, bool value); // Disables most likely false-positives from base::SplitString() +extern "C" const char* __asan_default_options(); extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } std::atomic<int> num_async_tasks; -static base::MessageLoop* message_loop_; bluetooth::common::MessageLoopThread message_loop_thread("test message loop"); bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } bt_status_t do_in_main_thread(base::OnceClosure task) { - if (!message_loop_) { - return BT_STATUS_FAIL; - } - // Wrap the task with task counter so we could later know if there are // any callbacks scheduled and we should wait before performing some actions if (!message_loop_thread.DoInThread(base::BindOnce( @@ -139,8 +134,6 @@ bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::micro return do_in_main_thread(std::move(task)); } -base::MessageLoop* get_main_message_loop() { return message_loop_; } - static void init_message_loop_thread() { num_async_tasks = 0; message_loop_thread.StartUp(); @@ -151,17 +144,9 @@ static void init_message_loop_thread() { if (!message_loop_thread.EnableRealTimeScheduling()) { bluetooth::log::error("Unable to set real time scheduling"); } - - message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) { - FAIL() << "unable to get message loop."; - } } -static void cleanup_message_loop_thread() { - message_loop_ = nullptr; - message_loop_thread.ShutDown(); -} +static void cleanup_message_loop_thread() { message_loop_thread.ShutDown(); } const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { return tBLE_BD_ADDR{.type = BLE_ADDR_PUBLIC, .bda = bd_addr}; @@ -171,20 +156,20 @@ void invoke_switch_codec_cb(bool /*is_low_latency_buffer_size*/) {} void invoke_switch_buffer_size_cb(bool /*is_low_latency_buffer_size*/) {} const std::string kSmpOptions("mock smp options"); -bool get_pts_avrcp_test(void) { return false; } -bool get_pts_secure_only_mode(void) { return false; } -bool get_pts_conn_updates_disabled(void) { return false; } -bool get_pts_crosskey_sdp_disable(void) { return false; } -const std::string* get_pts_smp_options(void) { return &kSmpOptions; } -int get_pts_smp_failure_case(void) { return 123; } -bool get_pts_force_eatt_for_notifications(void) { return false; } -bool get_pts_connect_eatt_unconditionally(void) { return false; } -bool get_pts_connect_eatt_before_encryption(void) { return false; } -bool get_pts_unencrypt_broadcast(void) { return false; } -bool get_pts_eatt_peripheral_collision_support(void) { return false; } -bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } -bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } -config_t* get_all(void) { return nullptr; } +static bool get_pts_avrcp_test(void) { return false; } +static bool get_pts_secure_only_mode(void) { return false; } +static bool get_pts_conn_updates_disabled(void) { return false; } +static bool get_pts_crosskey_sdp_disable(void) { return false; } +static const std::string* get_pts_smp_options(void) { return &kSmpOptions; } +static int get_pts_smp_failure_case(void) { return 123; } +static bool get_pts_force_eatt_for_notifications(void) { return false; } +static bool get_pts_connect_eatt_unconditionally(void) { return false; } +static bool get_pts_connect_eatt_before_encryption(void) { return false; } +static bool get_pts_unencrypt_broadcast(void) { return false; } +static bool get_pts_eatt_peripheral_collision_support(void) { return false; } +static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } +static bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } +static config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ .get_pts_avrcp_test = get_pts_avrcp_test, @@ -239,7 +224,7 @@ std::unique_ptr<LeAudioSinkAudioHalClient> LeAudioSinkAudioHalClient::AcquireUni void LeAudioSinkAudioHalClient::DebugDump(int /*fd*/) {} -RawAddress GetTestAddress(uint8_t index) { +static RawAddress GetTestAddress(uint8_t index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; return result; @@ -256,11 +241,12 @@ public: MOCK_METHOD((void), OnGroupNodeStatus, (const RawAddress& bd_addr, int group_id, GroupNodeStatus node_status), (override)); MOCK_METHOD((void), OnAudioConf, - (uint8_t direction, int group_id, uint32_t snk_audio_location, - uint32_t src_audio_location, uint16_t avail_cont), + (uint8_t direction, int group_id, std::optional<std::bitset<32>> snk_audio_location, + std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont), + (override)); + MOCK_METHOD(void, OnSinkAudioLocationAvailable, + (const RawAddress& bd_addr, std::optional<std::bitset<32>> snk_audio_location), (override)); - MOCK_METHOD((void), OnSinkAudioLocationAvailable, - (const RawAddress& bd_addr, uint32_t snk_audio_location), (override)); MOCK_METHOD((void), OnAudioLocalCodecCapabilities, (std::vector<btle_audio_codec_config_t> local_input_capa_codec_conf, std::vector<btle_audio_codec_config_t> local_output_capa_codec_conf), @@ -1043,6 +1029,21 @@ protected: } } + // When the device attaches to the stream we send again the state machine state to + // stimulate the stream map update + // see LeAudioGroupStateMachineImpl::SendStreamingStatusCbIfNeeded(group); + if (!group->HaveAllCisesDisconnected() && + (group->GetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) && + (group->GetTargetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { + do_in_main_thread(base::BindOnce( + [](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb(group_id, + GroupStreamStatus::STREAMING); + }, + group->group_id_, base::Unretained(this->state_machine_callbacks_))); + } + return true; }); @@ -1334,8 +1335,8 @@ protected: }); ON_CALL(mock_state_machine_, ProcessHciNotifCisDisconnected(_, _, _)) - .WillByDefault([](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, - const bluetooth::hci::iso_manager::cis_disconnected_evt* event) { + .WillByDefault([this](LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice, + const bluetooth::hci::iso_manager::cis_disconnected_evt* event) { if (!group) { return; } @@ -1407,6 +1408,21 @@ protected: } group->cig.UnassignCis(leAudioDevice, event->cis_conn_hdl); + + // When the device detaches from the stream we send again the state machine state to + // stimulate the stream map update + // see LeAudioGroupStateMachineImpl::SendStreamingStatusCbIfNeeded(group); + if (!group->HaveAllCisesDisconnected() && + (group->GetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) && + (group->GetTargetState() == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) { + do_in_main_thread(base::BindOnce( + [](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks* + state_machine_callbacks) { + state_machine_callbacks->StatusReportCb(group_id, + GroupStreamStatus::STREAMING); + }, + group->group_id_, base::Unretained(this->state_machine_callbacks_))); + } }); ON_CALL(mock_state_machine_, StopStream(_)).WillByDefault([this](LeAudioDeviceGroup* group) { @@ -1946,31 +1962,44 @@ protected: UpdateLocalSourceMetadata(tracks, reconfigure_existing_stream); } - void UpdateLocalSinkMetadata(audio_source_t audio_source) { + void UpdateLocalSinkMetadata( + std::optional<audio_source_t> audio_source, + std::optional<audio_source_t> additional_audio_source = std::nullopt) { std::vector<struct record_track_metadata> tracks = { - {{AUDIO_SOURCE_INVALID, 0.5, AUDIO_DEVICE_NONE, "00:11:22:33:44:55"}, - {AUDIO_SOURCE_MIC, 0.7, AUDIO_DEVICE_OUT_BLE_HEADSET, "AA:BB:CC:DD:EE:FF"}}}; + {{AUDIO_SOURCE_INVALID, 0.5, AUDIO_DEVICE_NONE, "00:11:22:33:44:55"}}}; - tracks[1].source = audio_source; + if (audio_source.has_value() && (audio_source.value() != AUDIO_SOURCE_INVALID)) { + tracks.push_back( + {audio_source.value(), 0.7, AUDIO_DEVICE_OUT_BLE_HEADSET, "AA:BB:CC:DD:EE:FF"}); + } + if (additional_audio_source.has_value() && + (additional_audio_source.value() != AUDIO_SOURCE_INVALID)) { + tracks.push_back({additional_audio_source.value(), 0.7, AUDIO_DEVICE_OUT_BLE_HEADSET, + "AA:BB:CC:DD:EE:FF"}); + } - std::vector<record_track_metadata_v7> tracks_vec; - tracks_vec.reserve(tracks.size()); - for (const auto& track : tracks) { - record_track_metadata_v7 desc_track = { - .base = - { - .source = static_cast<audio_source_t>(track.source), - .gain = track.gain, - .dest_device = static_cast<audio_devices_t>(track.dest_device), - }, - }; + // Call the callback if we have added a valid track or we explicitly want to send no tracks + if (!audio_source.has_value() || tracks.size() > 1) { + std::vector<record_track_metadata_v7> tracks_vec; + tracks_vec.reserve(tracks.size()); + for (const auto& track : tracks) { + record_track_metadata_v7 desc_track = { + .base = + { + .source = static_cast<audio_source_t>(track.source), + .gain = track.gain, + .dest_device = static_cast<audio_devices_t>(track.dest_device), + }, + }; - strcpy(desc_track.base.dest_device_address, track.dest_device_address); - tracks_vec.push_back(desc_track); - } + snprintf(desc_track.base.dest_device_address, AUDIO_DEVICE_MAX_ADDRESS_LEN, "%s", + track.dest_device_address); + tracks_vec.push_back(desc_track); + } - ASSERT_NE(nullptr, unicast_sink_hal_cb_); - unicast_sink_hal_cb_->OnAudioMetadataUpdate(std::move(tracks_vec)); + ASSERT_NE(nullptr, unicast_sink_hal_cb_); + unicast_sink_hal_cb_->OnAudioMetadataUpdate(std::move(tracks_vec)); + } } void LocalAudioSourceSuspend(void) { @@ -2026,9 +2055,7 @@ protected: ASSERT_NE(unicast_source_hal_cb_, nullptr); UpdateLocalSourceMetadata(usage, content_type, reconfigure_existing_stream); - if (audio_source != AUDIO_SOURCE_INVALID) { - UpdateLocalSinkMetadata(audio_source); - } + UpdateLocalSinkMetadata(audio_source); /* Stream has been automatically restarted on UpdateLocalSourceMetadata */ if (reconfigure_existing_stream) { @@ -2247,8 +2274,8 @@ protected: uint16_t conn_id; RawAddress addr; - uint32_t sink_audio_allocation = codec_spec_conf::kLeAudioLocationStereo; - uint32_t source_audio_allocation = codec_spec_conf::kLeAudioLocationStereo; + std::optional<uint32_t> sink_audio_allocation = std::nullopt; + std::optional<uint32_t> source_audio_allocation = std::nullopt; uint8_t sink_channel_cnt = 0x03; uint8_t source_channel_cnt = 0x03; uint16_t sample_freq_mask = 0x0004; @@ -2336,14 +2363,18 @@ protected: if (add_pacs) { // attribute handles pacs->start = 0x0060; - pacs->sink_pac_char = 0x0061; - pacs->sink_pac_ccc = 0x0063; - pacs->sink_audio_loc_char = 0x0064; - pacs->sink_audio_loc_ccc = 0x0066; - pacs->source_pac_char = 0x0067; - pacs->source_pac_ccc = 0x0069; - pacs->source_audio_loc_char = 0x0070; - pacs->source_audio_loc_ccc = 0x0072; + if (sink_audio_allocation.has_value()) { + pacs->sink_pac_char = 0x0061; + pacs->sink_pac_ccc = 0x0063; + pacs->sink_audio_loc_char = 0x0064; + pacs->sink_audio_loc_ccc = 0x0066; + } + if (source_audio_allocation.has_value()) { + pacs->source_pac_char = 0x0067; + pacs->source_pac_ccc = 0x0069; + pacs->source_audio_loc_char = 0x0070; + pacs->source_audio_loc_ccc = 0x0072; + } pacs->avail_contexts_char = 0x0073; pacs->avail_contexts_ccc = 0x0075; pacs->supp_contexts_char = 0x0076; @@ -2358,14 +2389,14 @@ protected: ascs->start = 0x0090; uint16_t handle = 0x0091; for (int i = 0; i < add_ascs_cnt; i++) { - if (sink_audio_allocation != 0) { + if (sink_audio_allocation.has_value()) { ascs->sink_ase_char[i] = handle; handle += 2; ascs->sink_ase_ccc[i] = handle; handle++; } - if (source_audio_allocation != 0) { + if (source_audio_allocation.has_value()) { ascs->source_ase_char[i] = handle; handle += 2; ascs->source_ase_ccc[i] = handle; @@ -2384,19 +2415,6 @@ protected: std::move(pacs)); if (add_pacs) { - uint8_t snk_allocation[4]; - uint8_t src_allocation[4]; - - snk_allocation[0] = (uint8_t)(sink_audio_allocation); - snk_allocation[1] = (uint8_t)(sink_audio_allocation >> 8); - snk_allocation[2] = (uint8_t)(sink_audio_allocation >> 16); - snk_allocation[3] = (uint8_t)(sink_audio_allocation >> 24); - - src_allocation[0] = (uint8_t)(source_audio_allocation); - src_allocation[1] = (uint8_t)(source_audio_allocation >> 8); - src_allocation[2] = (uint8_t)(source_audio_allocation >> 16); - src_allocation[3] = (uint8_t)(source_audio_allocation >> 24); - uint8_t sample_freq[2]; sample_freq[0] = (uint8_t)(sample_freq_mask); sample_freq[1] = (uint8_t)(sample_freq_mask >> 8); @@ -2473,11 +2491,10 @@ protected: } } else if (handle == pacs->sink_audio_loc_char + 1) { value = { - // Audio Locations - snk_allocation[0], - snk_allocation[1], - snk_allocation[2], - snk_allocation[3], + (uint8_t)(sink_audio_allocation.value_or(0)), + (uint8_t)(sink_audio_allocation.value_or(0) >> 8), + (uint8_t)(sink_audio_allocation.value_or(0) >> 16), + (uint8_t)(sink_audio_allocation.value_or(0) >> 24), }; } else if (handle == pacs->source_pac_char + 1) { if (empty_source_pack_) { @@ -2542,11 +2559,10 @@ protected: } } else if (handle == pacs->source_audio_loc_char + 1) { value = { - // Audio Locations - src_allocation[0], - src_allocation[1], - src_allocation[2], - src_allocation[3], + (uint8_t)(source_audio_allocation.value_or(0)), + (uint8_t)(source_audio_allocation.value_or(0) >> 8), + (uint8_t)(source_audio_allocation.value_or(0) >> 16), + (uint8_t)(source_audio_allocation.value_or(0) >> 24), }; } else if (handle == pacs->avail_contexts_char + 1) { value = { @@ -6691,6 +6707,110 @@ TEST_F(UnicastTest, TestUnidirectionalGameAndLiveRecording) { Mock::VerifyAndClearExpectations(&mock_state_machine_); } +TEST_F(UnicastTest, TestUnidirectionalGameAndLiveRecordingMicOnlyDev) { + const RawAddress test_address0 = GetTestAddress(0); + int group_id = bluetooth::groups::kGroupUnknown; + + /** + * Scenario test steps + * 1. Configure group to support GAME | LIVE | CONVERSATIONAL | VOICEASSISTANTS only on Source + * 2. Start a GAME + * 3. Start recording during the GAME + */ + + // No sink at all + available_snk_context_types_ = 0; + supported_snk_context_types_ = 0; + + // Source available for + available_src_context_types_ = + (types::LeAudioContextType::CONVERSATIONAL | types::LeAudioContextType::GAME | + types::LeAudioContextType::LIVE | types::LeAudioContextType::VOICEASSISTANTS | + types::LeAudioContextType::UNSPECIFIED) + .value(); + supported_src_context_types_ = available_src_context_types_; + + // Setup a single mic-only device + empty_sink_pack_ = true; + default_channel_cnt = 1; + SampleDatabaseParameters db_params{ + .conn_id = 1, + .addr = test_address0, + .sink_audio_allocation = std::nullopt, + .source_audio_allocation = codec_spec_conf::kLeAudioLocationMonoAudio, + .sink_channel_cnt = 0, + .source_channel_cnt = default_channel_cnt, + .sample_freq_mask = le_audio::codec_spec_caps::kLeAudioSamplingFreq32000Hz, + .add_csis = false, + .add_cas = false, + .add_pacs = true, + .add_ascs_cnt = 1, + .set_size = 0, + .rank = 0, + .gatt_status = GATT_SUCCESS, + .max_supported_codec_frames_per_sdu = 1, + }; + SetSampleDatabaseEarbudsValid(db_params); + + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnConnectionState(ConnectionState::CONNECTED, test_address0)) + .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) + .WillOnce(DoAll(SaveArg<1>(&group_id))); + + types::BidirectionalPair<types::AudioContexts> expected_metadata_contexts = { + .sink = types::AudioContexts(), + .source = types::AudioContexts(types::LeAudioContextType::GAME)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::GAME, expected_metadata_contexts, _)) + .Times(1); + + log::info("Connecting LeAudio to {}", test_address0); + ConnectLeAudio(test_address0); + ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); + + // Both audio sessions are always started to monitor the metadata (even for mic only devices) + EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); + + EXPECT_CALL(*mock_codec_manager_, + UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_, + mock_le_audio_sink_hal_client_, true)) + .Times(1); + + LeAudioClient::Get()->GroupSetActive(group_id); + SyncOnMainLoop(); + + // Configure a bidirectional GAME scenario (on a mic-only device) + UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN); + UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); + LocalAudioSinkResume(); + SyncOnMainLoop(); + + Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(mock_codec_manager_); + Mock::VerifyAndClearExpectations(&mock_state_machine_); + SyncOnMainLoop(); + + // We do expect only unidirectional CIS + uint8_t cis_count_out = 0; + uint8_t cis_count_in = 1; + + // Verify Data transfer on one local audio sink + TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 0, 40); + SyncOnMainLoop(); + + // Expect no reconfiguration triggered by the GAME updates + EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0); + UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN); + LocalAudioSinkSuspend(); + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(&mock_state_machine_); +} + TEST_F(UnicastTest, TestUnidirectionalVoiceAssistant_Sink) { com::android::bluetooth::flags::provider_->le_audio_support_unidirectional_voice_assistant(true); const RawAddress test_address0 = GetTestAddress(0); @@ -8387,23 +8507,99 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSource) { LeAudioClient::Get()->GroupSetActive(group_id); Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); - // Start streaming + // Start streaming - expect HAL being notified by both directions config change EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(1); EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _)) - .Times(1) - .WillOnce([](const types::BidirectionalPair<stream_parameters>& stream_params, - std::function<void(const stream_config& config, uint8_t direction)> - update_receiver) { + + /* Expect one update per direction - 2 in total for voice communication usage */ + EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _, _)) + .WillRepeatedly([&](const types::BidirectionalPair<stream_parameters>& stream_params, + std::function<void(const stream_config& config, uint8_t direction)> + update_receiver, + uint8_t directions_to_update) { + bluetooth::le_audio::stream_config unicast_cfg; + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSink) && + stream_params.sink.stream_config.peer_delay_ms != 0) { + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSink); + } + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSource) && + stream_params.source.stream_config.peer_delay_ms != 0) { + update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSource); + } + }); + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); + + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + Mock::VerifyAndClearExpectations(&mock_codec_manager_); + + // Verify Data transfer on two peer sinks and two sources + uint8_t cis_count_out = 2; + uint8_t cis_count_in = 2; + TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 40); + + // Suspend + LeAudioClient::Get()->GroupSuspend(group_id); + SyncOnMainLoop(); +} + +TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSourceLateJoin) { + uint8_t group_size = 2; + int group_id = 2; + + // Report working CSIS + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); + + ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) + .WillByDefault(Invoke([&](int /*group_id*/) { return group_size; })); + + // First earbud + const RawAddress test_address0 = GetTestAddress(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); + + // Set group as active + EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); + LeAudioClient::Get()->GroupSetActive(group_id); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + + // Start streaming - expect HAL being notified by both directions config change + EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + + /* Expect one update per direction - 2 in total for voice communication usage */ + EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _, _)) + .WillRepeatedly([&](const types::BidirectionalPair<stream_parameters>& stream_params, + std::function<void(const stream_config& config, uint8_t direction)> + update_receiver, + uint8_t directions_to_update) { bluetooth::le_audio::stream_config unicast_cfg; - if (stream_params.sink.stream_config.peer_delay_ms != 0) { + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSink) && + stream_params.sink.stream_config.peer_delay_ms != 0) { update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSink); } - if (stream_params.source.stream_config.peer_delay_ms != 0) { + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSource) && + stream_params.source.stream_config.peer_delay_ms != 0) { update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSource); } }); StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, group_id); + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + + // Second earbud join should trigger audio config update to HAL + EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + + const RawAddress test_address1 = GetTestAddress(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); SyncOnMainLoop(); Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); @@ -8415,6 +8611,38 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSource) { uint8_t cis_count_in = 2; TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 40); + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + + // Second earbud disconnect should trigger audio config update to HAL + EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); + + /* Simulate ASE releasing and CIS Disconnection */ + ASSERT_NE(0lu, streaming_groups.count(group_id)); + auto group = streaming_groups.at(group_id); + ASSERT_NE(group, nullptr); + auto device = group->GetFirstDevice(); + for (auto& ase : device->ases_) { + /* Releasing state */ + if (!ase.active) { + continue; + } + + std::vector<uint8_t> releasing_state = { + ase.id, static_cast<uint8_t>(types::AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)}; + InjectNotificationEvent(device->address_, device->conn_id_, ase.hdls.val_hdl, releasing_state); + SyncOnMainLoop(); + InjectCisDisconnected(group_id, ase.cis_conn_hdl); + SyncOnMainLoop(); + } + + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + Mock::VerifyAndClearExpectations(&mock_codec_manager_); + // Suspend LeAudioClient::Get()->GroupSuspend(group_id); SyncOnMainLoop(); @@ -8451,16 +8679,19 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSource) { // Start streaming EXPECT_CALL(*mock_le_audio_source_hal_client_, UpdateAudioConfigToHal(_)).Times(1); EXPECT_CALL(*mock_le_audio_sink_hal_client_, UpdateAudioConfigToHal(_)).Times(0); - EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _)) + EXPECT_CALL(*mock_codec_manager_, UpdateActiveAudioConfig(_, _, _)) .Times(1) .WillOnce([](const types::BidirectionalPair<stream_parameters>& stream_params, std::function<void(const stream_config& config, uint8_t direction)> - update_receiver) { + update_receiver, + uint8_t directions_to_update) { bluetooth::le_audio::stream_config unicast_cfg; - if (stream_params.sink.stream_config.peer_delay_ms != 0) { + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSink) && + stream_params.sink.stream_config.peer_delay_ms != 0) { update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSink); } - if (stream_params.source.stream_config.peer_delay_ms != 0) { + if ((directions_to_update & bluetooth::le_audio::types::kLeAudioDirectionSource) && + stream_params.source.stream_config.peer_delay_ms != 0) { update_receiver(unicast_cfg, bluetooth::le_audio::types::kLeAudioDirectionSource); } }); @@ -8729,6 +8960,8 @@ TEST_F(UnicastTest, TwoEarbudsStreamingContextSwitchReconfigure) { log::info("End call"); LeAudioClient::Get()->SetInCall(false); + UpdateLocalSourceMetadata(AUDIO_USAGE_UNKNOWN, AUDIO_CONTENT_TYPE_UNKNOWN, false); + UpdateLocalSinkMetadata(std::nullopt); // Stop StopStreaming(group_id, true); @@ -8945,6 +9178,76 @@ TEST_F(UnicastTest, TwoEarbudsVoipStreamingVerifyMetadataUpdate) { Mock::VerifyAndClearExpectations(&mock_state_machine_); } +TEST_F(UnicastTest, TwoEarbudsVoipDuringLiveVerifyMetadataUpdate) { + uint8_t group_size = 2; + int group_id = 2; + + /* + * Scenario + * 1. Configure stream for the mixed CONVERSATIONAL and MEDIA + * 2. Start and Stop streaming + * 3. Update CONVERSATIONAL metadata with additional LIVE usage for the mixed contexts + * 4. Resume LocalSink and LocalSource + * 5. Make sure there is only the leading CONVERSATIONAL context in the metadata and + * LIVE is not mixed in, as the remote devices often are confused when any other + * bidirectional audio context is mixed with CONVERSATIONAL + */ + + // Report working CSIS + ON_CALL(mock_csis_client_module_, IsCsisClientRunning()).WillByDefault(Return(true)); + + ON_CALL(mock_csis_client_module_, GetDesiredSize(group_id)) + .WillByDefault(Invoke([&](int /*group_id*/) { return group_size; })); + + available_snk_context_types_ = + (types::LeAudioContextType::CONVERSATIONAL | types::LeAudioContextType::MEDIA | + types::LeAudioContextType::LIVE) + .value(); + available_src_context_types_ = available_snk_context_types_; + + // First earbud + const RawAddress test_address0 = GetTestAddress(0); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address0, true)).Times(1); + ConnectCsisDevice(test_address0, 1 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontLeft, + codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/); + + // Second earbud + const RawAddress test_address1 = GetTestAddress(1); + EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); + ConnectCsisDevice(test_address1, 2 /*conn_id*/, codec_spec_conf::kLeAudioLocationFrontRight, + codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/, + true /*connect_through_csis*/); + + constexpr int gtbs_ccid = 2; + + LeAudioClient::Get()->SetCcidInformation(gtbs_ccid, 2 /* Phone */); + LeAudioClient::Get()->GroupSetActive(group_id); + SyncOnMainLoop(); + + StartStreaming(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_MUSIC, group_id); + StopStreaming(group_id); + + // Add LIVE into the mix but expect staying with CONVERSATIONAL for the configuration and the + // metadata + types::BidirectionalPair<types::AudioContexts> meta_contexts = { + .sink = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL), + .source = types::AudioContexts(types::LeAudioContextType::CONVERSATIONAL)}; + EXPECT_CALL(mock_state_machine_, + StartStream(_, types::LeAudioContextType::CONVERSATIONAL, meta_contexts, _)) + .Times(AtLeast(1)); + + UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC, AUDIO_SOURCE_VOICE_COMMUNICATION); + UpdateLocalSourceMetadata(AUDIO_USAGE_VOICE_COMMUNICATION, AUDIO_CONTENT_TYPE_SPEECH, false); + SyncOnMainLoop(); + + LocalAudioSourceResume(); + LocalAudioSinkResume(); + + Mock::VerifyAndClearExpectations(&mock_state_machine_); + Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); +} + TEST_F(UnicastTest, TwoReconfigureAndVerifyEnableContextType) { uint8_t group_size = 2; int group_id = 2; @@ -8985,9 +9288,6 @@ TEST_F(UnicastTest, TwoReconfigureAndVerifyEnableContextType) { LeAudioClient::Get()->GroupSetActive(group_id); SyncOnMainLoop(); - // Update metadata on local audio sink - UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); - types::BidirectionalPair<std::vector<uint8_t>> ccids = {.sink = {gmcs_ccid}, .source = {}}; EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, ccids)).Times(1); StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id); @@ -10542,6 +10842,77 @@ TEST_F(UnicastTest, SwitchBetweenMicrophoneAndSoundEffectScenario) { TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 60); } +TEST_F(UnicastTest, SwitchBetweenSoundEffectAndMicrophoneScenario) { + const RawAddress test_address0 = GetTestAddress(0); + int group_id = bluetooth::groups::kGroupUnknown; + + /* Scenario: + * 1. User starts Recording which first triggers SoundEffect + * 2. Just after that LIVE metadata arrives and this creates bidiretional CISes + */ + SetSampleDatabaseEarbudsValid(1, test_address0, codec_spec_conf::kLeAudioLocationStereo, + codec_spec_conf::kLeAudioLocationFrontLeft, default_channel_cnt, + default_channel_cnt, 0x0024, false /*add_csis*/, true /*add_cas*/, + true /*add_pacs*/, default_ase_cnt /*add_ascs_cnt*/, 1 /*set_size*/, + 0 /*rank*/); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnConnectionState(ConnectionState::CONNECTED, test_address0)) + .Times(1); + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED)) + .WillOnce(DoAll(SaveArg<1>(&group_id))); + + ConnectLeAudio(test_address0); + ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown); + + // Audio sessions are started only when device gets active + EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1); + LeAudioClient::Get()->GroupSetActive(group_id); + SyncOnMainLoop(); + + // When the local audio source resumes we have no knowledge of recording + EXPECT_CALL(mock_state_machine_, + StartStream(_, bluetooth::le_audio::types::LeAudioContextType::SOUNDEFFECTS, _, _)) + .Times(1); + + StartStreaming(AUDIO_USAGE_ASSISTANCE_SONIFICATION, AUDIO_CONTENT_TYPE_SONIFICATION, group_id); + SyncOnMainLoop(); + + Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + Mock::VerifyAndClearExpectations(&mock_state_machine_); + + auto group = streaming_groups.at(group_id); + group->PrintDebugState(); + + log::info("Start Microphone recording - reconfiguration is expected"); + EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(1); + EXPECT_CALL(*mock_le_audio_source_hal_client_, CancelStreamingRequest()).Times(1); + EXPECT_CALL(*mock_le_audio_sink_hal_client_, CancelStreamingRequest()).Times(1); + + UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC); + LocalAudioSinkResume(); + + SyncOnMainLoop(); + Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_); + Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_); + group->PrintDebugState(); + + log::info("Resume after reconfiguration - bidirectional CISes are expected"); + LocalAudioSourceResume(); + LocalAudioSinkResume(); + + // Verify Data transfer on one audio source cis + uint8_t cis_count_out = 0; + uint8_t cis_count_in = 1; + TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920, 60); + + ASSERT_EQ(1, get_func_call_count("alarm_set_on_mloop")); + ASSERT_EQ(0, get_func_call_count("alarm_cancel")); +} + /* When a certain context is unavailable and not supported we should stream * as UNSPECIFIED for the backwards compatibility. * Since UNSPECIFIED is available, put the UNSPECIFIED into the metadata instead @@ -10603,6 +10974,7 @@ TEST_F(UnicastTest, UpdateNotSupportedContextTypeUnspecifiedAvailable) { LeAudioClient::Get()->SetInCall(false); LocalAudioSinkSuspend(); + UpdateLocalSinkMetadata(std::nullopt); /* We should use GAME configuration, but do not send the GAME context type, as * it is not available on the remote device. @@ -11161,6 +11533,7 @@ TEST_F(UnicastTest, MusicDuringCallContextTypes) { // --------------------------------------- // Suspend should stop the stream EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(1); + UpdateLocalSinkMetadata(std::nullopt); LocalAudioSourceSuspend(); LocalAudioSinkSuspend(); // simulate suspend timeout passed, alarm executing @@ -12050,9 +12423,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) .Times(0); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address0, + std::make_optional<std::bitset<32>>( + codec_spec_conf::kLeAudioLocationFrontLeft))) .Times(0); // First earbud initial connection @@ -12088,9 +12462,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { InjectGroupDeviceAdded(test_address0, group_id); // Second earbud initial connection - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable(test_address1, codec_spec_conf::kLeAudioLocationFrontRight)) + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address1, + std::make_optional<std::bitset<32>>( + codec_spec_conf::kLeAudioLocationFrontRight))) .Times(1); EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1); @@ -12126,9 +12501,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) { EXPECT_CALL(mock_audio_hal_client_callbacks_, OnConnectionState(ConnectionState::CONNECTED, test_address0)) .Times(1); - EXPECT_CALL( - mock_audio_hal_client_callbacks_, - OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft)) + EXPECT_CALL(mock_audio_hal_client_callbacks_, + OnSinkAudioLocationAvailable(test_address0, + std::make_optional<std::bitset<32>>( + codec_spec_conf::kLeAudioLocationFrontLeft))) .Times(1); /* Prepare valid GATT status responsing attributes */ @@ -13260,7 +13636,10 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { .WillByDefault( Invoke([&](const types::BidirectionalPair<stream_parameters>& stream_params, std::function<void(const stream_config& config, uint8_t direction)> - /*updater*/) { codec_manager_stream_params = stream_params; })); + /*updater*/, + uint8_t /*directions_to_update*/) { + codec_manager_stream_params = stream_params; + })); const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; @@ -13268,9 +13647,18 @@ TEST_F(UnicastTest, CodecFrameBlocks2) { SampleDatabaseParameters remote_params{ .conn_id = 1, .addr = test_address0, + .sink_audio_allocation = codec_spec_conf::kLeAudioLocationStereo, + .source_audio_allocation = codec_spec_conf::kLeAudioLocationStereo, + .sink_channel_cnt = default_channel_cnt, + .source_channel_cnt = default_channel_cnt, + .sample_freq_mask = le_audio::codec_spec_caps::kLeAudioSamplingFreq32000Hz, .add_csis = false, + .add_cas = true, + .add_pacs = true, + .add_ascs_cnt = 1, .set_size = 0, .rank = 0, + .gatt_status = GATT_SUCCESS, .max_supported_codec_frames_per_sdu = 2, }; SetSampleDatabaseEarbudsValid(remote_params); diff --git a/system/bta/le_audio/le_audio_health_status_test.cc b/system/bta/le_audio/le_audio_health_status_test.cc index 0ec96d2f37..1e1be60eed 100644 --- a/system/bta/le_audio/le_audio_health_status_test.cc +++ b/system/bta/le_audio/le_audio_health_status_test.cc @@ -27,9 +27,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::groups::kGroupUnknown; using bluetooth::le_audio::DeviceConnectState; using bluetooth::le_audio::LeAudioDevice; @@ -71,7 +68,7 @@ protected: LeAudioDeviceGroup* group_ = nullptr; }; -RawAddress GetTestAddress(uint8_t index) { +static RawAddress GetTestAddress(uint8_t index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; return result; diff --git a/system/bta/le_audio/le_audio_types.cc b/system/bta/le_audio/le_audio_types.cc index 2f2e3420a9..d92eca54a0 100644 --- a/system/bta/le_audio/le_audio_types.cc +++ b/system/bta/le_audio/le_audio_types.cc @@ -48,9 +48,6 @@ #include "le_audio_utils.h" #include "stack/include/bt_types.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth::le_audio { using types::acs_ac_record; using types::LeAudioContextType; @@ -60,84 +57,6 @@ using types::CodecConfigSetting; using types::kLeAudioCodingFormatLC3; using types::LeAudioCoreCodecConfig; -void get_cis_count(LeAudioContextType context_type, uint8_t expected_remote_direction, - int expected_device_cnt, types::LeAudioConfigurationStrategy strategy, - int avail_group_ase_snk_cnt, int avail_group_ase_src_count, - uint8_t& out_cis_count_bidir, uint8_t& out_cis_count_unidir_sink, - uint8_t& out_cis_count_unidir_source) { - log::info( - "{} expected_remote_direction {}, strategy {}, group avail sink ases: {}, " - "group avail source ases {} " - "expected_device_count {}", - bluetooth::common::ToString(context_type), expected_remote_direction, - static_cast<int>(strategy), avail_group_ase_snk_cnt, avail_group_ase_src_count, - expected_device_cnt); - - bool is_bidirectional = expected_remote_direction == types::kLeAudioDirectionBoth; - bool is_source_only = expected_remote_direction == types::kLeAudioDirectionSource; - - switch (strategy) { - case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE: - /* This strategy is for the CSIS topology, e.g. two earbuds which are both - * connected with a Phone - */ - case types::LeAudioConfigurationStrategy::STEREO_ONE_CIS_PER_DEVICE: - /* This strategy is for e.g. the banded headphones */ - if (is_bidirectional) { - if ((avail_group_ase_snk_cnt > 0) && (avail_group_ase_src_count) > 0) { - /* Prepare CIG to enable all microphones */ - out_cis_count_bidir = expected_device_cnt; - } else { - if (avail_group_ase_snk_cnt > 0) { - out_cis_count_unidir_sink = expected_device_cnt; - } else if (avail_group_ase_src_count > 0) { - out_cis_count_unidir_source = expected_device_cnt; - } - } - } else if (is_source_only) { - out_cis_count_unidir_source = expected_device_cnt; - } else { - out_cis_count_unidir_sink = expected_device_cnt; - } - - break; - case types::LeAudioConfigurationStrategy::STEREO_TWO_CISES_PER_DEVICE: - /* This strategy is for the old TWS topology. e.g. one earbud connected to - * the Phone but each channel is carried in separate CIS - */ - if (is_bidirectional) { - if ((avail_group_ase_snk_cnt > 0) && (avail_group_ase_src_count) > 0) { - /* Prepare CIG to enable all microphones per device */ - out_cis_count_bidir = expected_device_cnt; - if (avail_group_ase_src_count > 1) { - out_cis_count_bidir++; - } else { - out_cis_count_unidir_sink = expected_device_cnt; - } - } else { - if (avail_group_ase_snk_cnt > 0) { - out_cis_count_unidir_sink = 2 * expected_device_cnt; - } else if (avail_group_ase_src_count > 0) { - out_cis_count_unidir_source = 2 * expected_device_cnt; - } - } - } else if (is_source_only) { - out_cis_count_unidir_source = 2 * expected_device_cnt; - } else { - out_cis_count_unidir_sink = 2 * expected_device_cnt; - } - break; - case types::LeAudioConfigurationStrategy::RFU: - log::error("Should not happen;"); - break; - } - - log::info( - "Required cis count: Bi-Directional: {}, Uni-Directional Sink: {}, " - "Uni-Directional Source: {}", - out_cis_count_bidir, out_cis_count_unidir_sink, out_cis_count_unidir_source); -} - uint16_t CodecConfigSetting::GetOctetsPerFrame() const { switch (id.coding_format) { case kLeAudioCodingFormatLC3: @@ -260,7 +179,7 @@ const std::map<uint32_t, uint8_t> LeAudioCoreCodecConfig::data_interval_map = { codec_spec_conf::kLeAudioCodecFrameDur10000us}, }; -std::string CapabilityTypeToStr(const uint8_t& type) { +static std::string CapabilityTypeToStr(const uint8_t& type) { switch (type) { case codec_spec_caps::kLeAudioLtvTypeSupportedSamplingFrequencies: return "Supported Sampling Frequencies"; @@ -277,7 +196,7 @@ std::string CapabilityTypeToStr(const uint8_t& type) { } } -std::string CapabilityValueToStr(const uint8_t& type, const std::vector<uint8_t>& value) { +static std::string CapabilityValueToStr(const uint8_t& type, const std::vector<uint8_t>& value) { std::string string = ""; switch (type) { diff --git a/system/bta/le_audio/le_audio_types.h b/system/bta/le_audio/le_audio_types.h index b388c0c424..a0a3afc777 100644 --- a/system/bta/le_audio/le_audio_types.h +++ b/system/bta/le_audio/le_audio_types.h @@ -617,6 +617,10 @@ struct LeAudioCoreCodecConfig { /** Returns the audio channel allocation bitmask */ inline uint32_t GetAudioChannelAllocation() const { return audio_channel_allocation.value_or(0); } + /** Returns the number of codec frame blocks */ + inline uint8_t GetCodecFrameBlocksPerSdu() const { + return codec_frames_blocks_per_sdu.value_or(0); + } }; struct LeAudioCoreCodecCapabilities { @@ -1098,6 +1102,12 @@ struct hdl_pair { uint16_t ccc_hdl = 0; }; +template <typename T> +struct hdl_pair_wrapper { + hdl_pair handles; + T value; +}; + struct AseQosConfiguration { uint32_t presentation_delay = 0; uint32_t sdu_interval = 0; @@ -1142,6 +1152,10 @@ struct CodecConfigSetting { inline uint32_t GetAudioChannelAllocation() const { return params.GetAsCoreCodecConfig().GetAudioChannelAllocation(); } + inline uint8_t GetCodecFrameBlocksPerSdu() const { + return params.GetAsCoreCodecConfig().GetCodecFrameBlocksPerSdu(); + } + /* Audio channels number for a device */ uint8_t GetChannelCountPerIsoStream() const { return channel_count_per_iso_stream; } @@ -1285,12 +1299,6 @@ const types::LeAudioCodecId LeAudioCodecIdLc3 = { static constexpr uint32_t kChannelAllocationStereo = codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight; - -/* Declarations */ -void get_cis_count(types::LeAudioContextType context_type, uint8_t expected_direction, - int expected_device_cnt, types::LeAudioConfigurationStrategy strategy, - int group_ase_snk_cnt, int group_ase_src_count, uint8_t& cis_count_bidir, - uint8_t& cis_count_unidir_sink, uint8_t& cis_count_unidir_source); } // namespace types struct stream_map_info { diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc index 6f8d3ed42e..2d2c0da641 100644 --- a/system/bta/le_audio/le_audio_utils.cc +++ b/system/bta/le_audio/le_audio_utils.cc @@ -247,14 +247,6 @@ AudioContexts GetAudioContextsFromSinkMetadata( all_track_contexts.set(track_context); } - if (all_track_contexts.none()) { - all_track_contexts = AudioContexts(static_cast<std::underlying_type<LeAudioContextType>::type>( - LeAudioContextType::UNSPECIFIED)); - log::debug( - "Unable to find supported audio source context for the remote audio " - "sink device. This may result in voice back channel malfunction."); - } - log::info("Allowed contexts from sink metadata: {} (0x{:08x})", bluetooth::common::ToString(all_track_contexts), all_track_contexts.value()); return all_track_contexts; @@ -608,6 +600,8 @@ const struct types::acs_ac_record* GetConfigurationSupportedPac( /* Doesn't match required configuration with any PAC */ if (pacs.size() == 0) { log::error("No PAC records"); + } else { + log::error("No matching PAC record"); } return nullptr; } diff --git a/system/bta/le_audio/metrics_collector_test.cc b/system/bta/le_audio/metrics_collector_test.cc index 6110f82fdc..c94db90ad6 100644 --- a/system/bta/le_audio/metrics_collector_test.cc +++ b/system/bta/le_audio/metrics_collector_test.cc @@ -23,11 +23,9 @@ #include <cstdint> #include <vector> +#include "common/metrics.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using testing::_; using testing::AnyNumber; using testing::AtLeast; diff --git a/system/bta/le_audio/mock_codec_manager.cc b/system/bta/le_audio/mock_codec_manager.cc index 8612e1d11d..a704fe7b7b 100644 --- a/system/bta/le_audio/mock_codec_manager.cc +++ b/system/bta/le_audio/mock_codec_manager.cc @@ -78,9 +78,10 @@ bool CodecManager::UpdateActiveBroadcastAudioHalClient( void CodecManager::UpdateActiveAudioConfig( const types::BidirectionalPair<stream_parameters>& stream_params, std::function<void(const ::bluetooth::le_audio::stream_config& config, uint8_t direction)> - update_receiver) { + update_receiver, + uint8_t directions_to_update) { if (pimpl_) { - return pimpl_->UpdateActiveAudioConfig(stream_params, update_receiver); + return pimpl_->UpdateActiveAudioConfig(stream_params, update_receiver, directions_to_update); } } diff --git a/system/bta/le_audio/mock_codec_manager.h b/system/bta/le_audio/mock_codec_manager.h index b5e20910ee..7f901c54d0 100644 --- a/system/bta/le_audio/mock_codec_manager.h +++ b/system/bta/le_audio/mock_codec_manager.h @@ -56,7 +56,8 @@ public: bluetooth::le_audio::stream_parameters>& stream_params, std::function<void(const ::bluetooth::le_audio::stream_config& config, uint8_t direction)> - update_receiver)); + update_receiver, + uint8_t directions_to_update)); MOCK_METHOD( (std::unique_ptr<bluetooth::le_audio::types::AudioSetConfiguration>), GetCodecConfig, (const bluetooth::le_audio::CodecManager::UnicastConfigurationRequirements& requirements, diff --git a/system/bta/le_audio/state_machine_test.cc b/system/bta/le_audio/state_machine_test.cc index 284b498c63..2a318c16f1 100644 --- a/system/bta/le_audio/state_machine_test.cc +++ b/system/bta/le_audio/state_machine_test.cc @@ -42,9 +42,6 @@ #include "test/mock/mock_stack_btm_iso.h" #include "types/bt_transport.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using ::bluetooth::le_audio::DeviceConnectState; using ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecChannelCountSingleChannel; using ::bluetooth::le_audio::codec_spec_caps::kLeAudioCodecChannelCountTwoChannel; @@ -70,20 +67,20 @@ constexpr uint8_t call_ccid = 0xD0; constexpr auto call_context = LeAudioContextType::CONVERSATIONAL; const std::string kSmpOptions("mock smp options"); -bool get_pts_avrcp_test(void) { return false; } -bool get_pts_secure_only_mode(void) { return false; } -bool get_pts_conn_updates_disabled(void) { return false; } -bool get_pts_crosskey_sdp_disable(void) { return false; } -const std::string* get_pts_smp_options(void) { return &kSmpOptions; } -int get_pts_smp_failure_case(void) { return 123; } -bool get_pts_force_eatt_for_notifications(void) { return false; } -bool get_pts_connect_eatt_unconditionally(void) { return false; } -bool get_pts_connect_eatt_before_encryption(void) { return false; } -bool get_pts_unencrypt_broadcast(void) { return false; } -bool get_pts_eatt_peripheral_collision_support(void) { return false; } -bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } -bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } -config_t* get_all(void) { return nullptr; } +static bool get_pts_avrcp_test(void) { return false; } +static bool get_pts_secure_only_mode(void) { return false; } +static bool get_pts_conn_updates_disabled(void) { return false; } +static bool get_pts_crosskey_sdp_disable(void) { return false; } +static const std::string* get_pts_smp_options(void) { return &kSmpOptions; } +static int get_pts_smp_failure_case(void) { return 123; } +static bool get_pts_force_eatt_for_notifications(void) { return false; } +static bool get_pts_connect_eatt_unconditionally(void) { return false; } +static bool get_pts_connect_eatt_before_encryption(void) { return false; } +static bool get_pts_unencrypt_broadcast(void) { return false; } +static bool get_pts_eatt_peripheral_collision_support(void) { return false; } +static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; } +static bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; } +static config_t* get_all(void) { return nullptr; } stack_config_t mock_stack_config{ .get_pts_avrcp_test = get_pts_avrcp_test, @@ -251,6 +248,7 @@ protected: /* Use for single test to simulate late ASE notifications */ bool stop_inject_configured_ase_after_first_ase_configured_; + uint16_t attr_handle = ATTR_HANDLE_ASCS_POOL_START; uint16_t pacs_attr_handle_next = ATTR_HANDLE_PACS_POOL_START; virtual void SetUp() override { @@ -646,11 +644,6 @@ protected: leAudioDevice->conn_id_ = id; leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED); - uint16_t attr_handle = ATTR_HANDLE_ASCS_POOL_START; - leAudioDevice->snk_audio_locations_hdls_.val_hdl = attr_handle++; - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = attr_handle++; - leAudioDevice->src_audio_locations_hdls_.val_hdl = attr_handle++; - leAudioDevice->src_audio_locations_hdls_.ccc_hdl = attr_handle++; leAudioDevice->audio_avail_hdls_.val_hdl = attr_handle++; leAudioDevice->audio_avail_hdls_.ccc_hdl = attr_handle++; leAudioDevice->audio_supp_cont_hdls_.val_hdl = attr_handle++; @@ -1087,7 +1080,10 @@ protected: leAudioDevice->snk_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs)); - leAudioDevice->snk_audio_locations_ = audio_locations; + auto val_hdl = attr_handle++; + auto ccc_hdl = attr_handle++; + leAudioDevice->audio_locations_.sink.emplace(types::hdl_pair(val_hdl, ccc_hdl), + types::AudioLocations(audio_locations)); } if ((direction & types::kLeAudioDirectionSource) > 0) { @@ -1108,7 +1104,10 @@ protected: leAudioDevice->src_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs)); - leAudioDevice->src_audio_locations_ = audio_locations; + auto val_hdl = attr_handle++; + auto ccc_hdl = attr_handle++; + leAudioDevice->audio_locations_.source.emplace(types::hdl_pair(val_hdl, ccc_hdl), + types::AudioLocations(audio_locations)); } DeviceContextsUpdate(leAudioDevice, direction, contexts_available, contexts_supported); @@ -9235,7 +9234,7 @@ TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisDisc /* Now lets try to attach the device back to the stream (Enabling and Receiver * Start ready to be called)*/ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) .Times(2); @@ -9344,7 +9343,7 @@ TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisConn /* Now lets try to attach the device back to the stream (Enabling and Receiver * Start ready to be called)*/ - EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl, + EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl, _, GATT_WRITE_NO_RSP, _, _)) .Times(2); diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc index 021b3fa811..95c308ff15 100644 --- a/system/bta/le_audio/storage_helper.cc +++ b/system/bta/le_audio/storage_helper.cc @@ -32,9 +32,6 @@ #include "le_audio_types.h" #include "stack/include/bt_types.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::le_audio::types::hdl_pair; namespace bluetooth::le_audio { @@ -68,8 +65,8 @@ static constexpr size_t LEAUDIO_STORAGE_HANDLES_ENTRIES_SZ = sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /*available context type handle*/ + sizeof(uint16_t) /*ccc handle*/ + sizeof(uint16_t) /* tmas handle */; -bool serializePacs(const bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, - std::vector<uint8_t>& out) { +static bool serializePacs(const bluetooth::le_audio::types::PublishedAudioCapabilities& pacs, + std::vector<uint8_t>& out) { auto num_of_pacs = pacs.size(); if (num_of_pacs == 0 || (num_of_pacs > std::numeric_limits<uint8_t>::max())) { log::warn("No pacs available"); @@ -162,8 +159,9 @@ bool SerializeSourcePacs(const bluetooth::le_audio::LeAudioDevice* leAudioDevice return serializePacs(leAudioDevice->src_pacs_, out); } -bool deserializePacs(LeAudioDevice* leAudioDevice, types::PublishedAudioCapabilities& pacs_db, - const std::vector<uint8_t>& in) { +static bool deserializePacs(LeAudioDevice* leAudioDevice, + types::PublishedAudioCapabilities& pacs_db, + const std::vector<uint8_t>& in) { if (in.size() < LEAUDIO_STORAGE_HEADER_WITH_ENTRIES_SZ + LEAUDIO_PACS_ENTRY_SZ) { log::warn("There is not single PACS stored"); return false; @@ -362,11 +360,19 @@ bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector<uint8_t>& UINT16_TO_STREAM(ptr, leAudioDevice->ctp_hdls_.val_hdl); UINT16_TO_STREAM(ptr, leAudioDevice->ctp_hdls_.ccc_hdl); - UINT16_TO_STREAM(ptr, leAudioDevice->snk_audio_locations_hdls_.val_hdl); - UINT16_TO_STREAM(ptr, leAudioDevice->snk_audio_locations_hdls_.ccc_hdl); + UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.sink + ? leAudioDevice->audio_locations_.sink->handles.val_hdl + : 0); + UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.sink + ? leAudioDevice->audio_locations_.sink->handles.ccc_hdl + : 0); - UINT16_TO_STREAM(ptr, leAudioDevice->src_audio_locations_hdls_.val_hdl); - UINT16_TO_STREAM(ptr, leAudioDevice->src_audio_locations_hdls_.ccc_hdl); + UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.source + ? leAudioDevice->audio_locations_.source->handles.val_hdl + : 0); + UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.source + ? leAudioDevice->audio_locations_.source->handles.ccc_hdl + : 0); UINT16_TO_STREAM(ptr, leAudioDevice->audio_supp_cont_hdls_.val_hdl); UINT16_TO_STREAM(ptr, leAudioDevice->audio_supp_cont_hdls_.ccc_hdl); @@ -406,21 +412,26 @@ bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector<uint8_t> log::verbose("ctp.val_hdl: 0x{:04x}, ctp.ccc_hdl: 0x{:04x}", leAudioDevice->ctp_hdls_.val_hdl, leAudioDevice->ctp_hdls_.ccc_hdl); - STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.val_hdl, ptr); - STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, ptr); + uint16_t val_hdl, ccc_hdl; + STREAM_TO_UINT16(val_hdl, ptr); + STREAM_TO_UINT16(ccc_hdl, ptr); log::verbose( - "snk_audio_locations_hdls_.val_hdl: " - "0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}", - leAudioDevice->snk_audio_locations_hdls_.val_hdl, - leAudioDevice->snk_audio_locations_hdls_.ccc_hdl); + "snk_audio_locations_hdls_.val_hdl: 0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}", + val_hdl, ccc_hdl); + if (val_hdl) { + leAudioDevice->audio_locations_.sink.emplace(hdl_pair(val_hdl, ccc_hdl), + types::AudioLocations(0)); + } - STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.val_hdl, ptr); - STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.ccc_hdl, ptr); + STREAM_TO_UINT16(val_hdl, ptr); + STREAM_TO_UINT16(ccc_hdl, ptr); log::verbose( - "src_audio_locations_hdls_.val_hdl: " - "0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}", - leAudioDevice->src_audio_locations_hdls_.val_hdl, - leAudioDevice->src_audio_locations_hdls_.ccc_hdl); + "src_audio_locations_hdls_.val_hdl: 0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}", + val_hdl, ccc_hdl); + if (val_hdl) { + leAudioDevice->audio_locations_.source.emplace(hdl_pair(val_hdl, ccc_hdl), + types::AudioLocations(0)); + } STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.val_hdl, ptr); STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, ptr); diff --git a/system/bta/le_audio/storage_helper.h b/system/bta/le_audio/storage_helper.h index 78868fa744..aa711dfaad 100644 --- a/system/bta/le_audio/storage_helper.h +++ b/system/bta/le_audio/storage_helper.h @@ -34,4 +34,5 @@ bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector<uint8_t>& bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector<uint8_t>& in); bool SerializeGmap(const GmapClient* gmap_server, std::vector<uint8_t>& out); bool DeserializeGmap(GmapClient* gmap_server, const std::vector<uint8_t>& in); +bool DeserializeGmapV1(GmapClient* gmapClient, const std::vector<uint8_t>& in); } // namespace bluetooth::le_audio diff --git a/system/bta/le_audio/storage_helper_test.cc b/system/bta/le_audio/storage_helper_test.cc index 9effb2b47f..8a56427607 100644 --- a/system/bta/le_audio/storage_helper_test.cc +++ b/system/bta/le_audio/storage_helper_test.cc @@ -18,13 +18,11 @@ #include <gtest/gtest.h> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::le_audio::LeAudioDevice; namespace bluetooth::le_audio { -RawAddress GetTestAddress(uint8_t index) { + +static RawAddress GetTestAddress(uint8_t index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, index}}; return result; diff --git a/system/bta/sdp/bta_sdp_act.cc b/system/bta/sdp/bta_sdp_act.cc index ab2f120d17..364930d8c5 100644 --- a/system/bta/sdp/bta_sdp_act.cc +++ b/system/bta/sdp/bta_sdp_act.cc @@ -39,9 +39,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; diff --git a/system/bta/sdp/bta_sdp_int.h b/system/bta/sdp/bta_sdp_int.h index 0416880a2e..703bdbf98c 100644 --- a/system/bta/sdp/bta_sdp_int.h +++ b/system/bta/sdp/bta_sdp_int.h @@ -28,6 +28,7 @@ #define BTA_SDP_INT_H #include "bta/include/bta_sdp_api.h" +#include "stack/include/sdp_status.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -53,4 +54,9 @@ void bta_sdp_search(const RawAddress bd_addr, const bluetooth::Uuid uuid); void bta_sdp_create_record(void* user_data); void bta_sdp_remove_record(void* user_data); +namespace bluetooth::testing { +void bta_create_dip_sdp_record(bluetooth_sdp_record* record, tSDP_DISC_REC* p_rec); +void bta_sdp_search_cback(Uuid uuid, const RawAddress& bd_addr, tSDP_RESULT result); +} // namespace bluetooth::testing + #endif /* BTA_SDP_INT_H */ diff --git a/system/bta/test/bta_ag_sco_test.cc b/system/bta/test/bta_ag_sco_test.cc index bbd5bd2430..cadf4a9919 100644 --- a/system/bta/test/bta_ag_sco_test.cc +++ b/system/bta/test/bta_ag_sco_test.cc @@ -24,13 +24,10 @@ #include "bta/include/bta_le_audio_api.h" #include "hci/controller_interface_mock.h" #include "stack/btm/btm_int_types.h" +#include "stack/btm/btm_sco.h" #include "test/mock/mock_device_esco_parameters.h" #include "test/mock/mock_main_shim_entry.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - -bool btm_peer_supports_esco_ev3(const RawAddress& /*remote_bda*/) { return true; } tBTM_CB btm_cb; LeAudioClient* LeAudioClient::Get() { return nullptr; } bool LeAudioClient::IsLeAudioClientInStreaming() { return false; } @@ -104,7 +101,7 @@ TEST_P(BtaAgScoParameterSelectionTest, create_pending_sco_cvsd) { } } -std::vector<std::tuple<tBTA_AG_FEAT, tBTA_AG_PEER_FEAT, bool>> +static std::vector<std::tuple<tBTA_AG_FEAT, tBTA_AG_PEER_FEAT, bool>> BtaAgScoParameterSelectionTestParameters() { tBTA_AG_FEAT features[] = {0, BTA_AG_FEAT_ESCO_S4}; tBTA_AG_PEER_FEAT peer_features[] = {0, BTA_AG_PEER_FEAT_ESCO_S4}; diff --git a/system/bta/test/bta_av_test.cc b/system/bta/test/bta_av_test.cc index 97bcbca6cb..06eabc3d6c 100644 --- a/system/bta/test/bta_av_test.cc +++ b/system/bta/test/bta_av_test.cc @@ -20,13 +20,11 @@ #include "bta/av/bta_av_int.h" #include "bta/hf_client/bta_hf_client_int.h" +#include "btif/include/btif_av.h" #include "test/common/mock_functions.h" #include "test/mock/mock_osi_alarm.h" #include "test/mock/mock_stack_acl.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace std::chrono_literals; bool btif_av_both_enable(void) { return true; } diff --git a/system/bta/test/bta_gatt_client_test.cc b/system/bta/test/bta_gatt_client_test.cc deleted file mode 100644 index c48dc02cf5..0000000000 --- a/system/bta/test/bta_gatt_client_test.cc +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include <gmock/gmock.h> -#include <gtest/gtest.h> -#include <sys/socket.h> - -#include <format> -#include <string> - -#include "bta/dm/bta_dm_gatt_client.h" -#include "common/circular_buffer.h" - -using namespace bluetooth::common; - -// Test hooks - -class BtaDiscTest : public testing::Test { -protected: - void SetUp() override {} - - void TearDown() override {} -}; - -TEST_F(BtaDiscTest, nop) {} - -TEST_F(BtaDiscTest, gatt_history_callback) { - std::array<std::string, 3> a = { - "ThisIsATest 0", - "ThisIsATest 1", - "ThisIsATest 2", - }; - - // C string - gatt_history_callback(std::format("{}", a[0].c_str())); - // Cpp string - gatt_history_callback(a[1]); - // Third entry for "fun" - gatt_history_callback(std::format("{}", a[2].c_str())); - - std::vector<bluetooth::common::TimestampedEntry<std::string>> history = - bluetooth::testing::PullCopyOfGattHistory(); - ASSERT_EQ(3UL, history.size()); - ASSERT_STREQ(a[0].c_str(), history[0].entry.c_str()); - ASSERT_STREQ(a[1].c_str(), history[1].entry.c_str()); - ASSERT_STREQ(a[2].c_str(), history[2].entry.c_str()); -} diff --git a/system/bta/test/bta_gatt_test.cc b/system/bta/test/bta_gatt_test.cc index 2a7909657c..7a31aaea34 100644 --- a/system/bta/test/bta_gatt_test.cc +++ b/system/bta/test/bta_gatt_test.cc @@ -28,9 +28,6 @@ #include "stack/gatt/gatt_int.h" #include "test/common/mock_functions.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace param { struct { uint16_t conn_id; @@ -41,8 +38,9 @@ struct { void* data; } bta_gatt_read_complete_callback; } // namespace param -void bta_gatt_read_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, uint8_t* value, void* data) { + +static void bta_gatt_read_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, uint8_t* value, void* data) { param::bta_gatt_read_complete_callback.conn_id = conn_id; param::bta_gatt_read_complete_callback.status = status; param::bta_gatt_read_complete_callback.handle = handle; @@ -62,8 +60,8 @@ struct { } bta_gatt_write_complete_callback; } // namespace param -void bta_gatt_write_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, - uint16_t len, const uint8_t* value, void* data) { +static void bta_gatt_write_complete_callback(uint16_t conn_id, tGATT_STATUS status, uint16_t handle, + uint16_t len, const uint8_t* value, void* data) { param::bta_gatt_write_complete_callback.conn_id = conn_id; param::bta_gatt_write_complete_callback.status = status; param::bta_gatt_write_complete_callback.handle = handle; @@ -80,7 +78,8 @@ struct { } bta_gatt_configure_mtu_complete_callback; } // namespace param -void bta_gatt_configure_mtu_complete_callback(uint16_t conn_id, tGATT_STATUS status, void* data) { +static void bta_gatt_configure_mtu_complete_callback(uint16_t conn_id, tGATT_STATUS status, + void* data) { param::bta_gatt_configure_mtu_complete_callback.conn_id = conn_id; param::bta_gatt_configure_mtu_complete_callback.status = status; param::bta_gatt_configure_mtu_complete_callback.data = data; @@ -93,7 +92,7 @@ struct { } bta_gattc_event_complete_callback; } // namespace param -void bta_gattc_event_complete_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { +static void bta_gattc_event_complete_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { param::bta_gattc_event_complete_callback.event = event; param::bta_gattc_event_complete_callback.p_data = p_data; } diff --git a/system/bta/test/common/btif_storage_mock.cc b/system/bta/test/common/btif_storage_mock.cc index 3b7ee7d06e..7e4a4e5118 100644 --- a/system/bta/test/common/btif_storage_mock.cc +++ b/system/bta/test/common/btif_storage_mock.cc @@ -19,8 +19,8 @@ #include <bluetooth/log.h> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" +#include "btif/include/btif_profile_storage.h" +#include "btif/include/btif_storage.h" using namespace bluetooth; @@ -57,10 +57,15 @@ void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) { btif_storage_interface->LeAudioUpdateHandles(addr); } -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location) { +void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) { log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); - btif_storage_interface->SetLeAudioLocations(addr, sink_location, source_location); + btif_storage_interface->SetLeAudioSinkLocations(addr, sink_location); +} + +void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr, + uint32_t source_location) { + log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!"); + btif_storage_interface->SetLeAudioSourceLocations(addr, source_location); } void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, diff --git a/system/bta/test/common/btif_storage_mock.h b/system/bta/test/common/btif_storage_mock.h index c756336dab..8809643f70 100644 --- a/system/bta/test/common/btif_storage_mock.h +++ b/system/bta/test/common/btif_storage_mock.h @@ -31,8 +31,8 @@ public: virtual void LeAudioUpdateGmap(RawAddress const& addr) = 0; virtual void LeAudioUpdateAses(RawAddress const& addr) = 0; virtual void LeAudioUpdateHandles(RawAddress const& addr) = 0; - virtual void SetLeAudioLocations(RawAddress const& addr, uint32_t sink_location, - uint32_t source_location) = 0; + virtual void SetLeAudioSinkLocations(RawAddress const& addr, uint32_t sink_location) = 0; + virtual void SetLeAudioSourceLocations(RawAddress const& addr, uint32_t source_location) = 0; virtual void SetLeAudioContexts(RawAddress const& addr, uint16_t sink_context, uint16_t source_context) = 0; virtual void ClearLeAudioServiceData(RawAddress const& addr) = 0; @@ -61,8 +61,9 @@ public: MOCK_METHOD((void), LeAudioUpdateGmap, (RawAddress const& addr), (override)); MOCK_METHOD((void), LeAudioUpdateAses, (RawAddress const& addr), (override)); MOCK_METHOD((void), LeAudioUpdateHandles, (RawAddress const& addr), (override)); - MOCK_METHOD((void), SetLeAudioLocations, - (RawAddress const& addr, uint32_t sink_location, uint32_t source_location), + MOCK_METHOD((void), SetLeAudioSinkLocations, (RawAddress const& addr, uint32_t sink_location), + (override)); + MOCK_METHOD((void), SetLeAudioSourceLocations, (RawAddress const& addr, uint32_t source_location), (override)); MOCK_METHOD((void), SetLeAudioContexts, (RawAddress const& addr, uint16_t sink_context, uint16_t source_context), (override)); diff --git a/system/bta/test/common/btm_api_mock.cc b/system/bta/test/common/btm_api_mock.cc index 10540aea65..87907f80f8 100644 --- a/system/bta/test/common/btm_api_mock.cc +++ b/system/bta/test/common/btm_api_mock.cc @@ -22,13 +22,13 @@ #include <optional> #include "bt_octets.h" +#include "stack/btm/btm_dev.h" +#include "stack/btm/btm_sec.h" +#include "stack/include/acl_api.h" #include "stack/include/btm_ble_sec_api.h" #include "test/mock/mock_stack_btm_interface.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; static bluetooth::manager::MockBtmInterface* btm_interface = nullptr; diff --git a/system/bta/vc/devices_test.cc b/system/bta/vc/devices_test.cc index 15dd527e2b..80c860e04e 100644 --- a/system/bta/vc/devices_test.cc +++ b/system/bta/vc/devices_test.cc @@ -33,9 +33,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace vc { namespace internal { @@ -50,7 +47,7 @@ using ::testing::SaveArg; using ::testing::SetArgPointee; using ::testing::Test; -RawAddress GetTestAddress(int index) { +static RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast<uint8_t>(index)}}; return result; diff --git a/system/bta/vc/vc_test.cc b/system/bta/vc/vc_test.cc index 71d291d1b1..4961a32399 100644 --- a/system/bta/vc/vc_test.cc +++ b/system/bta/vc/vc_test.cc @@ -38,11 +38,6 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - -void btif_storage_add_volume_control(const RawAddress& /*addr*/, bool /*auto_conn*/) {} - struct alarm_t { alarm_callback_t cb = nullptr; void* data = nullptr; @@ -75,7 +70,7 @@ using testing::SaveArg; using testing::SetArgPointee; using testing::WithArg; -RawAddress GetTestAddress(int index) { +static RawAddress GetTestAddress(int index) { EXPECT_LT(index, UINT8_MAX); RawAddress result = {{0xC0, 0xDE, 0xC0, 0xDE, 0x00, static_cast<uint8_t>(index)}}; return result; diff --git a/system/btcore/Android.bp b/system/btcore/Android.bp index 17d5c01905..7b95bd95ca 100644 --- a/system/btcore/Android.bp +++ b/system/btcore/Android.bp @@ -33,30 +33,6 @@ cc_defaults { } cc_library_static { - name: "libbthalutils", - defaults: ["fluoride_defaults"], - srcs: [ - "src/hal_util.cc", - ], - local_include_dirs: ["include"], - include_dirs: [ - "packages/modules/Bluetooth/system", - "packages/modules/Bluetooth/system/gd", - ], - header_libs: ["libbluetooth_headers"], - host_supported: true, - apex_available: ["com.android.bt"], - target: { - host_linux: { - cflags: ["-D_GNU_SOURCE"], - }, - }, - static_libs: [ - "libbluetooth_log", - ], -} - -cc_library_static { name: "libbtcore", visibility: [ "//packages/apps/Test/connectivity/sl4n", diff --git a/system/btif/BUILD.gn b/system/btif/BUILD.gn index 38b8fa9c6a..ea6a0f6fbc 100644 --- a/system/btif/BUILD.gn +++ b/system/btif/BUILD.gn @@ -16,9 +16,6 @@ static_library("btif") { sources = [ - # TODO(abps) - Do we need this? - "//bt/system/audio_hearing_aid_hw/src/audio_hearing_aid_hw_utils.cc", - # AVRCP Target Service "avrcp/avrcp_service.cc", @@ -94,7 +91,6 @@ static_library("btif") { "//bt/system/", "//bt/system/bta/dm", "//bt/system/linux_include", - "//bt/system/audio_hearing_aid_hw/include", "//bt/system/bta/aics/include", "//bt/system/bta/include", "//bt/system/bta/sys", diff --git a/system/btif/include/btif_hh.h b/system/btif/include/btif_hh.h index b20099d13e..38dfc7761d 100644 --- a/system/btif/include/btif_hh.h +++ b/system/btif/include/btif_hh.h @@ -133,7 +133,9 @@ typedef struct { bool service_dereg_active; std::list<tAclLinkSpec> new_connection_requests; - tBTA_HH_CONN pending_incoming_connection; // Early incoming connection request during pairing + + tBTA_HH_CONN pending_incoming_connection; // Unexpected incoming connection request + alarm_t* incoming_connection_timer; // Timer to handle unexpected incoming connection } btif_hh_cb_t; /******************************************************************************* diff --git a/system/btif/include/btif_profile_storage.h b/system/btif/include/btif_profile_storage.h index 681ea2b0af..d411a95e00 100644 --- a/system/btif/include/btif_profile_storage.h +++ b/system/btif/include/btif_profile_storage.h @@ -124,8 +124,11 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr); void btif_storage_leaudio_update_handles_bin(const RawAddress& addr); /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location); +void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location); + +/** Store Le Audio device audio locations */ +void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr, + uint32_t source_location); /** Store Le Audio device context types */ void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h index 2e81246bcd..083e27413d 100644 --- a/system/btif/include/btif_storage.h +++ b/system/btif/include/btif_storage.h @@ -296,8 +296,11 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr); void btif_storage_leaudio_update_handles_bin(const RawAddress& addr); /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location); +void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location); + +/** Store Le Audio device audio locations */ +void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr, + uint32_t source_location); /** Store Le Audio device context types */ void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr, diff --git a/system/btif/src/btif_hf.cc b/system/btif/src/btif_hf.cc index a8caa39452..49e183d06b 100644 --- a/system/btif/src/btif_hf.cc +++ b/system/btif/src/btif_hf.cc @@ -63,6 +63,8 @@ #include "include/hardware/bluetooth_headset_interface.h" #include "include/hardware/bt_hf.h" #include "internal_include/bt_target.h" +#include "main/shim/helpers.h" +#include "main/shim/metrics_api.h" #include "stack/btm/btm_sco_hfp_hal.h" #include "stack/include/bt_uuid16.h" #include "stack/include/btm_client_interface.h" @@ -75,6 +77,7 @@ (number.size() > 2) ? number.size() - 2 : 0, '*') \ .c_str()) +using namespace bluetooth::shim; namespace { constexpr char kBtmLogTag[] = "HFP"; } @@ -372,12 +375,14 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { // Check if the incoming open event and the outgoing connection are // for the same device. if (p_data->open.bd_addr == btif_hf_cb[idx].connected_bda) { + LogMetricHfpRfcommChannelFail(ToGdAddress(p_data->open.bd_addr)); log::warn( "btif_hf_cb state[{}] is not expected, possible connection " "collision, ignoring AG open failure event for the same device " "{}", p_data->open.status, p_data->open.bd_addr); } else { + LogMetricHfpRfcommCollisionFail(ToGdAddress(p_data->open.bd_addr)); log::warn( "btif_hf_cb state[{}] is not expected, possible connection " "collision, ignoring AG open failure event for the different " @@ -440,6 +445,7 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { p_data->open.bd_addr); break; } + LogMetricHfpRfcommAgOpenFail(ToGdAddress(p_data->open.bd_addr)); log::error("self initiated AG open failed for {}, status {}", btif_hf_cb[idx].connected_bda, p_data->open.status); RawAddress connected_bda = btif_hf_cb[idx].connected_bda; @@ -496,6 +502,7 @@ static void btif_hf_upstreams_evt(uint16_t event, char* p_param) { log_counter_metrics_btif(android::bluetooth::CodePathCounterKeyEnum::HFP_SLC_SETUP_FAILED, 1); btif_queue_advance(); + LogMetricHfpSlcFail(ToGdAddress(p_data->open.bd_addr)); DEVICE_IOT_CONFIG_ADDR_INT_ADD_ONE(btif_hf_cb[idx].connected_bda, IOT_CONF_KEY_HFP_SLC_CONN_FAIL_COUNT); } diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc index ecbca4c7c8..81f7b77e5e 100644 --- a/system/btif/src/btif_hh.cc +++ b/system/btif/src/btif_hh.cc @@ -88,6 +88,9 @@ static int btif_hh_keylockstates = 0; // The current key state of each key #define BTIF_TIMEOUT_VUP_MS (3 * 1000) +#define BTIF_HH_INCOMING_CONNECTION_DURING_BONDING_TIMEOUT_MS (4 * 1000) +#define BTIF_HH_UNEXPECTED_INCOMING_CONNECTION_TIMEOUT_MS (1 * 1000) + /* HH request events */ typedef enum { BTIF_HH_CONNECT_REQ_EVT = 0, @@ -454,6 +457,30 @@ static void btif_hh_start_vup_timer(const tAclLinkSpec& link_spec) { alarm_set_on_mloop(p_dev->vup_timer, BTIF_TIMEOUT_VUP_MS, btif_hh_timer_timeout, p_dev); } +static void btif_hh_incoming_connection_timeout(void* data) { + uint8_t handle = reinterpret_cast<size_t>(data) & 0xFF; + tBTA_HH_CONN& conn = btif_hh_cb.pending_incoming_connection; + if (conn.link_spec.addrt.bda.IsEmpty()) { + log::warn("Unknown incoming connection timeout, handle: {}", handle); + return; + } + + if (conn.handle != handle) { + log::error("Pending connection ({}) handle: {} does not match {}", conn.link_spec, conn.handle, + handle); + } + log::warn("Reject unexpected incoming HID Connection, device: {}", conn.link_spec); + log_counter_metrics_btif( + android::bluetooth::CodePathCounterKeyEnum::HIDH_COUNT_INCOMING_CONNECTION_REJECTED, 1); + + btif_hh_device_t* p_dev = btif_hh_find_dev_by_link_spec(conn.link_spec); + if (p_dev != nullptr) { + p_dev->dev_status = BTHH_CONN_STATE_DISCONNECTED; + } + BTA_HhRemoveDev(conn.handle); + btif_hh_cb.pending_incoming_connection = {}; +} + static bthh_connection_state_t hh_get_state_on_disconnect(tAclLinkSpec& link_spec) { btif_hh_added_device_t* added_dev = btif_hh_find_added_dev(link_spec); if (added_dev != nullptr) { @@ -576,18 +603,34 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { if (dev_status != BTHH_CONN_STATE_ACCEPTING && dev_status != BTHH_CONN_STATE_CONNECTING) { if (com::android::bluetooth::flags::early_incoming_hid_connection() && - btif_dm_is_pairing(conn.link_spec.addrt.bda) && - conn.link_spec.transport == BT_TRANSPORT_BR_EDR && conn.status == BTA_HH_OK) { - // Remote device is trying to connect while bonding is in progress. We should wait for locally - // initiated connect request to plumb the remote device to UHID. - log::warn("Awaiting local connect request to plumb the incoming connection {}, handle: {}", + conn.status == BTA_HH_OK && conn.link_spec.transport == BT_TRANSPORT_BR_EDR) { + uint64_t delay = 0; + if (btif_dm_is_pairing(conn.link_spec.addrt.bda)) { + // Remote device is trying to connect while bonding is in progress. We should wait for + // locally initiated connect request to plumb the remote device to UHID. + log::warn( + "Incoming HID connection during bonding, wait for local connect request {}, " + "handle: {}", + conn.link_spec, conn.handle); + delay = BTIF_HH_INCOMING_CONNECTION_DURING_BONDING_TIMEOUT_MS; + } else { + // Unexpected incoming connection, wait for a while before rejecting. + log::warn( + "Unexpected incoming HID connection, wait for local connect request {}, handle: {}", conn.link_spec, conn.handle); + delay = BTIF_HH_UNEXPECTED_INCOMING_CONNECTION_TIMEOUT_MS; + } + if (!btif_hh_cb.pending_incoming_connection.link_spec.addrt.bda.IsEmpty()) { log::error("Replacing existing pending connection {}", btif_hh_cb.pending_incoming_connection.link_spec); BTA_HhRemoveDev(btif_hh_cb.pending_incoming_connection.handle); } btif_hh_cb.pending_incoming_connection = conn; + alarm_cancel(btif_hh_cb.incoming_connection_timer); + alarm_set_on_mloop(btif_hh_cb.incoming_connection_timer, delay, + btif_hh_incoming_connection_timeout, reinterpret_cast<void*>(conn.handle)); + return; } @@ -666,7 +709,8 @@ static void hh_close_handler(tBTA_HH_CBDATA& dev_status) { !btif_hh_cb.pending_incoming_connection.link_spec.addrt.bda.IsEmpty()) { log::warn("Pending incoming connection {} closed, handle: {} ", btif_hh_cb.pending_incoming_connection.link_spec, dev_status.handle); - BTA_HhRemoveDev(dev_status.handle); + BTA_HhRemoveDev(btif_hh_cb.pending_incoming_connection.handle); + alarm_cancel(btif_hh_cb.incoming_connection_timer); btif_hh_cb.pending_incoming_connection = {}; return; } @@ -945,6 +989,7 @@ void btif_hh_disconnected(const RawAddress& addr, tBT_TRANSPORT transport) { btif_hh_cb.pending_incoming_connection.link_spec, btif_hh_cb.pending_incoming_connection.handle); BTA_HhRemoveDev(btif_hh_cb.pending_incoming_connection.handle); + alarm_cancel(btif_hh_cb.incoming_connection_timer); btif_hh_cb.pending_incoming_connection = {}; } @@ -980,6 +1025,7 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { btif_hh_cb.pending_incoming_connection.link_spec, btif_hh_cb.pending_incoming_connection.handle); BTA_HhRemoveDev(btif_hh_cb.pending_incoming_connection.handle); + alarm_cancel(btif_hh_cb.incoming_connection_timer); btif_hh_cb.pending_incoming_connection = {}; } @@ -1210,8 +1256,10 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { if (com::android::bluetooth::flags::early_incoming_hid_connection() && btif_hh_cb.pending_incoming_connection.link_spec == link_spec) { log::info("Resume pending incoming connection {}", link_spec); - hh_open_handler(btif_hh_cb.pending_incoming_connection); + tBTA_HH_CONN conn = btif_hh_cb.pending_incoming_connection; + alarm_cancel(btif_hh_cb.incoming_connection_timer); btif_hh_cb.pending_incoming_connection = {}; + hh_open_handler(conn); return BT_STATUS_SUCCESS; } @@ -1573,6 +1621,8 @@ static bt_status_t init(bthh_callbacks_t* callbacks) { for (i = 0; i < BTIF_HH_MAX_HID; i++) { btif_hh_cb.devices[i].dev_status = BTHH_CONN_STATE_UNKNOWN; } + btif_hh_cb.incoming_connection_timer = alarm_new("btif_hh.incoming_connection_timer"); + /* Invoke the enable service API to the core to set the appropriate service_id */ btif_enable_service(BTA_HID_SERVICE_ID); @@ -2179,6 +2229,9 @@ static void cleanup(void) { btif_hh_cb.service_dereg_active = FALSE; btif_disable_service(BTA_HID_SERVICE_ID); } + alarm_free(btif_hh_cb.incoming_connection_timer); + btif_hh_cb.incoming_connection_timer = nullptr; + btif_hh_cb.pending_incoming_connection = {}; btif_hh_cb.new_connection_requests.clear(); for (i = 0; i < BTIF_HH_MAX_HID; i++) { p_dev = &btif_hh_cb.devices[i]; diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc index 9b4fdc81fc..10eb8f99fb 100644 --- a/system/btif/src/btif_le_audio.cc +++ b/system/btif/src/btif_le_audio.cc @@ -71,14 +71,16 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, public LeAudio group_id, node_status)); } - void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, - uint32_t src_audio_location, uint16_t avail_cont) override { + void OnAudioConf(uint8_t direction, int group_id, + std::optional<std::bitset<32>> snk_audio_location, + std::optional<std::bitset<32>> src_audio_location, + uint16_t avail_cont) override { do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioConf, Unretained(callbacks), direction, group_id, snk_audio_location, src_audio_location, avail_cont)); } void OnSinkAudioLocationAvailable(const RawAddress& address, - uint32_t snk_audio_location) override { + std::optional<std::bitset<32>> snk_audio_location) override { do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnSinkAudioLocationAvailable, Unretained(callbacks), address, snk_audio_location)); } diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc index 4a8d13d59d..6051de1415 100644 --- a/system/btif/src/btif_profile_storage.cc +++ b/system/btif/src/btif_profile_storage.cc @@ -683,17 +683,27 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) { } /** Store Le Audio device audio locations */ -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location) { +void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) { do_in_jni_thread(Bind( - [](const RawAddress& addr, int sink_location, int source_location) { + [](const RawAddress& addr, int sink_location) { std::string bdstr = addr.ToString(); - log::debug("saving le audio device: {}", addr); + log::debug("saving le audio device: {} sink locations", addr); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, sink_location); + }, + addr, sink_location)); +} + +/** Store Le Audio device audio locations */ +void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr, + uint32_t source_location) { + do_in_jni_thread(Bind( + [](const RawAddress& addr, int source_location) { + std::string bdstr = addr.ToString(); + log::debug("saving le audio device: {} source locations", addr); btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, source_location); }, - addr, sink_location, source_location)); + addr, source_location)); } /** Store Le Audio device context types */ @@ -729,12 +739,12 @@ void btif_storage_load_bonded_leaudio() { autoconnect = !!value; } - int sink_audio_location = 0; + std::optional<int> sink_audio_location = std::nullopt; if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, &value)) { sink_audio_location = value; } - int source_audio_location = 0; + std::optional<int> source_audio_location = std::nullopt; if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, &value)) { source_audio_location = value; } diff --git a/system/btif/test/btif_keystore_test.cc b/system/btif/test/btif_keystore_test.cc deleted file mode 100644 index 0137e6fe3f..0000000000 --- a/system/btif/test/btif_keystore_test.cc +++ /dev/null @@ -1,63 +0,0 @@ -/****************************************************************************** - * - * Copyright 2019 Google, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "btif/include/btif_keystore.h" - -#include <binder/ProcessState.h> -#include <gtest/gtest.h> - -#include <fstream> - -using namespace bluetooth; - -class BtifKeystoreTest : public ::testing::Test { -protected: - std::unique_ptr<BtifKeystore> btif_keystore_; - void SetUp() override { - android::ProcessState::self()->startThreadPool(); - btif_keystore_ = std::make_unique<BtifKeystore>( - static_cast<keystore::KeystoreClient*>(new keystore::KeystoreClientImpl)); - } - void TearDown() override { btif_keystore_ = nullptr; } -}; - -TEST_F(BtifKeystoreTest, test_encrypt_decrypt) { - std::string hash = "test"; - - std::string encrypted_hash = btif_keystore_->Encrypt(hash, 0); - std::string decrypted_hash = btif_keystore_->Decrypt(encrypted_hash); - - EXPECT_FALSE(encrypted_hash.empty()); - EXPECT_EQ(hash, decrypted_hash); -} - -TEST_F(BtifKeystoreTest, test_encrypt_empty_hash) { - std::string hash = ""; - - std::string encrypted_hash = btif_keystore_->Encrypt(hash, 0); - - EXPECT_TRUE(encrypted_hash.empty()); -} - -TEST_F(BtifKeystoreTest, test_decrypt_empty_hash) { - std::string hash = ""; - - std::string decrypted_hash = btif_keystore_->Decrypt(hash); - - EXPECT_TRUE(decrypted_hash.empty()); -} diff --git a/system/common/benchmark/thread_performance_benchmark.cc b/system/common/benchmark/thread_performance_benchmark.cc index 8a6b34600a..b2b5e7fe5d 100644 --- a/system/common/benchmark/thread_performance_benchmark.cc +++ b/system/common/benchmark/thread_performance_benchmark.cc @@ -30,9 +30,6 @@ #include "osi/include/fixed_queue.h" #include "osi/include/thread.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using ::benchmark::State; using bluetooth::common::MessageLoopThread; @@ -41,7 +38,7 @@ using bluetooth::common::MessageLoopThread; static std::atomic<int> g_counter = 0; static std::unique_ptr<std::promise<void>> g_counter_promise = nullptr; -void pthread_callback_batch(void* context) { +static void pthread_callback_batch(void* context) { auto queue = static_cast<fixed_queue_t*>(context); bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); @@ -51,15 +48,15 @@ void pthread_callback_batch(void* context) { } } -void callback_sequential(void* /* context */) { g_counter_promise->set_value(); } +static void callback_sequential(void* /* context */) { g_counter_promise->set_value(); } -void callback_sequential_queue(fixed_queue_t* queue, void* /* context */) { +static void callback_sequential_queue(fixed_queue_t* queue, void* /* context */) { bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter_promise->set_value(); } -void callback_batch(fixed_queue_t* queue, void* /* data */) { +static void callback_batch(fixed_queue_t* queue, void* /* data */) { bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter++; diff --git a/system/common/metric_id_allocator_unittest.cc b/system/common/metric_id_allocator_unittest.cc index 778163c62d..8172d57319 100644 --- a/system/common/metric_id_allocator_unittest.cc +++ b/system/common/metric_id_allocator_unittest.cc @@ -25,14 +25,11 @@ #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::MetricIdAllocator; -RawAddress kthAddress(uint32_t k) { +static RawAddress kthAddress(uint32_t k) { uint8_t array[6] = {0, 0, 0, 0, 0, 0}; for (int i = 5; i >= 2; i--) { array[i] = k % 256; @@ -42,7 +39,7 @@ RawAddress kthAddress(uint32_t k) { return addr; } -std::unordered_map<RawAddress, int> generateAddresses(const uint32_t num) { +static std::unordered_map<RawAddress, int> generateAddresses(const uint32_t num) { // generate first num of mac address -> id pairs // input may is always valid 256^6 = 2^48 > 2^32 std::unordered_map<RawAddress, int> device_map; diff --git a/system/common/metrics_linux.cc b/system/common/metrics_linux.cc index bbd411b11e..009d16878e 100644 --- a/system/common/metrics_linux.cc +++ b/system/common/metrics_linux.cc @@ -21,9 +21,6 @@ #include "common/metrics.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace common { @@ -134,10 +131,11 @@ void LogLinkLayerConnectionEvent(const RawAddress* /* address */, uint32_t /* co uint16_t /* cmd_status */, uint16_t /* reason_code */) {} void LogManufacturerInfo(const RawAddress& /* address */, + android::bluetooth::AddressTypeEnum /* address_type */, android::bluetooth::DeviceInfoSrcEnum /* source_type */, const std::string& /* source_name */, - /* const */ std::string& /* manufacturer */, - const std::string& /* model */, const std::string& /* hardware_version */, + const std::string& /* manufacturer */, const std::string& /* model */, + const std::string& /* hardware_version */, const std::string& /* software_version */) {} void LogSdpAttribute(const RawAddress& /* address */, uint16_t /* protocol_uuid */, diff --git a/system/common/metrics_unittest.cc b/system/common/metrics_unittest.cc index 86e2ec7a13..4bbabb242a 100644 --- a/system/common/metrics_unittest.cc +++ b/system/common/metrics_unittest.cc @@ -32,9 +32,6 @@ #define BTM_COD_MAJOR_AUDIO_TEST 0x04 -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::A2dpSessionMetrics; @@ -63,14 +60,15 @@ const size_t kMaxEventGenerationLimit = 5000; static void sleep_ms(int64_t t) { std::this_thread::sleep_for(std::chrono::milliseconds(t)); } -DeviceInfo* MakeDeviceInfo(int32_t device_class, DeviceInfo_DeviceType device_type) { +static DeviceInfo* MakeDeviceInfo(int32_t device_class, DeviceInfo_DeviceType device_type) { DeviceInfo* info = new DeviceInfo(); info->set_device_class(device_class); info->set_device_type(device_type); return info; } -PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, DeviceInfo* device_info) { +static PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, + DeviceInfo* device_info) { PairEvent* event = new PairEvent(); event->set_disconnect_reason(disconnect_reason); event->set_event_time_millis(timestamp_ms); @@ -80,8 +78,8 @@ PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, Device return event; } -WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& requestor, - const std::string& name, int64_t timestamp_ms) { +static WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& requestor, + const std::string& name, int64_t timestamp_ms) { WakeEvent* event = new WakeEvent(); event->set_wake_event_type(event_type); event->set_requestor(requestor); @@ -90,9 +88,9 @@ WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& return event; } -ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& initiator, - ScanEvent_ScanTechnologyType tech_type, int32_t num_results, - int64_t timestamp_ms) { +static ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& initiator, + ScanEvent_ScanTechnologyType tech_type, int32_t num_results, + int64_t timestamp_ms) { ScanEvent* event = new ScanEvent(); event->set_scan_event_type(event_type); event->set_initiator(initiator); @@ -102,7 +100,8 @@ ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& return event; } -A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, A2dpSourceCodec source_codec) { +static A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, + A2dpSourceCodec source_codec) { A2DPSession* session = new A2DPSession(); session->set_media_timer_min_millis(metrics.media_timer_min_ms); session->set_media_timer_max_millis(metrics.media_timer_max_ms); @@ -117,11 +116,10 @@ A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, A2dpSourceCodec return session; } -BluetoothSession* MakeBluetoothSession(int64_t session_duration_sec, - BluetoothSession_ConnectionTechnologyType conn_type, - BluetoothSession_DisconnectReasonType disconnect_reason, - DeviceInfo* device_info, RFCommSession* rfcomm_session, - A2DPSession* a2dp_session) { +static BluetoothSession* MakeBluetoothSession( + int64_t session_duration_sec, BluetoothSession_ConnectionTechnologyType conn_type, + BluetoothSession_DisconnectReasonType disconnect_reason, DeviceInfo* device_info, + RFCommSession* rfcomm_session, A2DPSession* a2dp_session) { BluetoothSession* session = new BluetoothSession(); if (a2dp_session) { session->set_allocated_a2dp_session(a2dp_session); @@ -138,31 +136,7 @@ BluetoothSession* MakeBluetoothSession(int64_t session_duration_sec, return session; } -BluetoothLog* MakeBluetoothLog(std::vector<BluetoothSession*> bt_sessions, - std::vector<PairEvent*> pair_events, - std::vector<WakeEvent*> wake_events, - std::vector<ScanEvent*> scan_events) { - BluetoothLog* bt_log = new BluetoothLog(); - for (BluetoothSession* session : bt_sessions) { - bt_log->mutable_session()->AddAllocated(session); - } - bt_sessions.clear(); - for (PairEvent* event : pair_events) { - bt_log->mutable_pair_event()->AddAllocated(event); - } - pair_events.clear(); - for (WakeEvent* event : wake_events) { - bt_log->mutable_wake_event()->AddAllocated(event); - } - wake_events.clear(); - for (ScanEvent* event : scan_events) { - bt_log->mutable_scan_event()->AddAllocated(event); - } - scan_events.clear(); - return bt_log; -} - -void GenerateWakeEvents(size_t start, size_t end, std::vector<WakeEvent*>* wake_events) { +static void GenerateWakeEvents(size_t start, size_t end, std::vector<WakeEvent*>* wake_events) { for (size_t i = start; i < end; ++i) { wake_events->push_back( MakeWakeEvent(i % 2 == 0 ? WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED diff --git a/system/common/os_utils.cc b/system/common/os_utils.cc index a4bf8ea314..cdd645bf6f 100644 --- a/system/common/os_utils.cc +++ b/system/common/os_utils.cc @@ -14,14 +14,13 @@ * limitations under the License. */ +#include "common/os_utils.h" + #ifdef __ANDROID__ #include <private/android_filesystem_config.h> #include <unistd.h> #endif -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - bool is_bluetooth_uid() { #ifdef __ANDROID__ return getuid() == AID_BLUETOOTH; diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc index 5dfd66d3e6..17ca715c4f 100644 --- a/system/common/test/thread_performance_test.cc +++ b/system/common/test/thread_performance_test.cc @@ -31,9 +31,6 @@ #include "osi/include/fixed_queue.h" #include "osi/include/thread.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::common::MessageLoopThread; using namespace bluetooth; @@ -42,7 +39,7 @@ using namespace bluetooth; static int g_counter = 0; static std::unique_ptr<std::promise<void>> g_counter_promise = nullptr; -void callback_batch(fixed_queue_t* queue, void* /* data */) { +static void callback_batch(fixed_queue_t* queue, void* /* data */) { if (queue != nullptr) { fixed_queue_dequeue(queue); } diff --git a/system/gd/Android.bp b/system/gd/Android.bp index dd70c9cf80..a57b83073d 100644 --- a/system/gd/Android.bp +++ b/system/gd/Android.bp @@ -535,6 +535,7 @@ cc_defaults { cflags: [ "-DFUZZ_TARGET", "-DUSE_FAKE_TIMERS", + "-Wno-missing-prototypes", ], target: { android: { diff --git a/system/gd/common/metric_id_manager_unittest.cc b/system/gd/common/metric_id_manager_unittest.cc index 6c36187a55..3caca10b4a 100644 --- a/system/gd/common/metric_id_manager_unittest.cc +++ b/system/gd/common/metric_id_manager_unittest.cc @@ -22,14 +22,11 @@ #include <thread> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::MetricIdManager; -bluetooth::hci::Address kthAddress(uint32_t k) { +static bluetooth::hci::Address kthAddress(uint32_t k) { uint8_t array[6] = {0, 0, 0, 0, 0, 0}; for (int i = 5; i >= 2; i--) { array[i] = k % 256; @@ -39,7 +36,7 @@ bluetooth::hci::Address kthAddress(uint32_t k) { return addr; } -std::unordered_map<bluetooth::hci::Address, int> generateAddresses(const uint32_t num) { +static std::unordered_map<bluetooth::hci::Address, int> generateAddresses(const uint32_t num) { // generate first num of mac address -> id pairs // input may is always valid 256^6 = 2^48 > 2^32 std::unordered_map<bluetooth::hci::Address, int> device_map; diff --git a/system/gd/common/strings_test.cc b/system/gd/common/strings_test.cc index 63a9804ab7..9188eae528 100644 --- a/system/gd/common/strings_test.cc +++ b/system/gd/common/strings_test.cc @@ -23,9 +23,6 @@ #include <array> #include <memory> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::BoolFromString; @@ -269,7 +266,7 @@ TEST(StringsTest, string_format_time_with_ms_test) { } class ExampleClass {}; -std::ostream& operator<<(std::ostream& os, const ExampleClass& /* obj */) { +static std::ostream& operator<<(std::ostream& os, const ExampleClass& /* obj */) { os << "ExampleClass"; return os; } diff --git a/system/gd/fuzz_test.cc b/system/gd/fuzz_test.cc index 8b4b2b9786..bdb007b295 100644 --- a/system/gd/fuzz_test.cc +++ b/system/gd/fuzz_test.cc @@ -17,9 +17,6 @@ #include <stddef.h> #include <stdint.h> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - void RunHciPacketFuzzTest(const uint8_t* data, size_t size); extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { diff --git a/system/gd/hal/snoop_logger.cc b/system/gd/hal/snoop_logger.cc index d650725df0..53f5509a0b 100644 --- a/system/gd/hal/snoop_logger.cc +++ b/system/gd/hal/snoop_logger.cc @@ -1305,17 +1305,21 @@ void SnoopLogger::Start() { EnableFilters(); } - auto snoop_logger_socket = std::make_unique<SnoopLoggerSocket>(&syscall_if); - snoop_logger_socket_thread_ = - std::make_unique<SnoopLoggerSocketThread>(std::move(snoop_logger_socket)); - auto thread_started_future = snoop_logger_socket_thread_->Start(); - thread_started_future.wait(); - if (thread_started_future.get()) { - RegisterSocket(snoop_logger_socket_thread_.get()); - } else { - snoop_logger_socket_thread_->Stop(); - snoop_logger_socket_thread_.reset(); - snoop_logger_socket_thread_ = nullptr; + if (os::GetSystemPropertyBool(kIsDebuggableProperty, false)) { + // Cf b/375056207: The implementation must pass a security review + // in order to enable the snoop logger socket in user builds. + auto snoop_logger_socket = std::make_unique<SnoopLoggerSocket>(&syscall_if); + snoop_logger_socket_thread_ = + std::make_unique<SnoopLoggerSocketThread>(std::move(snoop_logger_socket)); + auto thread_started_future = snoop_logger_socket_thread_->Start(); + thread_started_future.wait(); + if (thread_started_future.get()) { + RegisterSocket(snoop_logger_socket_thread_.get()); + } else { + snoop_logger_socket_thread_->Stop(); + snoop_logger_socket_thread_.reset(); + snoop_logger_socket_thread_ = nullptr; + } } } diff --git a/system/gd/hal/snoop_logger_test.cc b/system/gd/hal/snoop_logger_test.cc index 1f4d2daa64..4681f82f30 100644 --- a/system/gd/hal/snoop_logger_test.cc +++ b/system/gd/hal/snoop_logger_test.cc @@ -34,9 +34,6 @@ #include "os/system_properties.h" #include "os/utils.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::hal::SnoopLoggerCommon; @@ -368,7 +365,7 @@ TEST_F(SnoopLoggerModuleTest, snoop_log_persists) { ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_)); } -void sync_handler(bluetooth::os::Handler* handler) { +static void sync_handler(bluetooth::os::Handler* handler) { std::promise<void> promise; auto future = promise.get_future(); handler->Post(bluetooth::common::BindOnce(&std::promise<void>::set_value, diff --git a/system/gd/hci/BUILD.gn b/system/gd/hci/BUILD.gn index 8f65671fd7..a287f60d2d 100644 --- a/system/gd/hci/BUILD.gn +++ b/system/gd/hci/BUILD.gn @@ -22,8 +22,6 @@ source_set("BluetoothHciSources") { "acl_manager/classic_acl_connection.cc", "acl_manager/le_acl_connection.cc", "acl_manager/round_robin_scheduler.cc", - "address.cc", - "class_of_device.cc", "controller.cc", "distance_measurement_manager.cc", "hci_layer.cc", diff --git a/system/gd/hci/acl_manager/classic_impl_test.cc b/system/gd/hci/acl_manager/classic_impl_test.cc index e5aa6d61ae..6b57eac662 100644 --- a/system/gd/hci/acl_manager/classic_impl_test.cc +++ b/system/gd/hci/acl_manager/classic_impl_test.cc @@ -33,9 +33,6 @@ #include "packet/bit_inserter.h" #include "packet/raw_builder.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; using namespace std::chrono_literals; @@ -143,14 +140,6 @@ public: } }; -PacketView<kLittleEndian> GetPacketView(std::unique_ptr<packet::BasePacketBuilder> packet) { - auto bytes = std::make_shared<std::vector<uint8_t>>(); - BitInserter i(*bytes); - bytes->reserve(packet->size()); - packet->Serialize(i); - return packet::PacketView<packet::kLittleEndian>(bytes); -} - class ClassicImplTest : public ::testing::Test { protected: void SetUp() override { diff --git a/system/gd/hci/address.cc b/system/gd/hci/address.cc deleted file mode 100644 index 6960c30c30..0000000000 --- a/system/gd/hci/address.cc +++ /dev/null @@ -1,132 +0,0 @@ -/****************************************************************************** - * - * Copyright 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "hci/address.h" - -#include <algorithm> -#include <cstdint> -#include <cstdio> -#include <iomanip> -#include <sstream> - -#include "common/strings.h" - -namespace bluetooth { -namespace hci { - -const Address Address::kAny{{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; -const Address Address::kEmpty{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}; - -// Address cannot initialize member variables as it is a POD type -// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) -Address::Address(const uint8_t (&addr)[6]) { std::copy(addr, addr + kLength, data()); } - -Address::Address(std::initializer_list<uint8_t> l) { - std::copy(l.begin(), std::min(l.begin() + kLength, l.end()), data()); -} - -std::string Address::_ToMaskedColonSepHexString(int bytes_to_mask) const { - std::stringstream ss; - int count = 0; - for (auto it = address.rbegin(); it != address.rend(); it++) { - if (count++ < bytes_to_mask) { - ss << "xx"; - } else { - ss << std::nouppercase << std::hex << std::setw(2) << std::setfill('0') << +*it; - } - if (std::next(it) != address.rend()) { - ss << ':'; - } - } - return ss.str(); -} - -std::string Address::ToString() const { return _ToMaskedColonSepHexString(0); } - -std::string Address::ToColonSepHexString() const { return _ToMaskedColonSepHexString(0); } - -std::string Address::ToStringForLogging() const { return _ToMaskedColonSepHexString(0); } - -std::string Address::ToRedactedStringForLogging() const { return _ToMaskedColonSepHexString(4); } - -std::string Address::ToLegacyConfigString() const { return ToString(); } - -std::optional<Address> Address::FromLegacyConfigString(const std::string& str) { - return FromString(str); -} - -std::optional<Address> Address::FromString(const std::string& from) { - if (from.length() != 17) { - return std::nullopt; - } - - Address addr{}; - std::istringstream stream(from); - std::string token; - int index = 0; - while (getline(stream, token, ':')) { - if (index >= 6) { - return std::nullopt; - } - - if (token.length() != 2) { - return std::nullopt; - } - - char* temp = nullptr; - addr.address.at(5 - index) = std::strtol(token.c_str(), &temp, 16); - if (temp == token.c_str()) { - // string token is empty or has wrong format - return std::nullopt; - } - if (temp != (token.c_str() + token.size())) { - // cannot parse whole string - return std::nullopt; - } - - index++; - } - - if (index != 6) { - return std::nullopt; - } - - return addr; -} - -bool Address::FromString(const std::string& from, Address& to) { - auto addr = FromString(from); - if (!addr) { - to = {}; - return false; - } - to = std::move(*addr); - return true; -} - -size_t Address::FromOctets(const uint8_t* from) { - std::copy(from, from + kLength, data()); - return kLength; -} - -bool Address::IsValidAddress(const std::string& address) { - return Address::FromString(address).has_value(); -} - -} // namespace hci -} // namespace bluetooth diff --git a/system/gd/hci/class_of_device.cc b/system/gd/hci/class_of_device.cc deleted file mode 100644 index 4ec755b6ed..0000000000 --- a/system/gd/hci/class_of_device.cc +++ /dev/null @@ -1,130 +0,0 @@ -/****************************************************************************** - * - * Copyright 2019 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at: - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ******************************************************************************/ - -#include "hci/class_of_device.h" - -#include <algorithm> -#include <cstdint> -#include <cstdio> -#include <cstdlib> -#include <sstream> - -namespace bluetooth { -namespace hci { - -// ClassOfDevice cannot initialize member variables as it is a POD type -// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) -ClassOfDevice::ClassOfDevice(const uint8_t (&class_of_device)[kLength]) { - std::copy(class_of_device, class_of_device + kLength, cod.data()); -} - -std::string ClassOfDevice::ToString() const { - char buffer[] = "000-0-00"; - std::snprintf(&buffer[0], sizeof(buffer), "%03x-%01x-%02x", - (static_cast<uint16_t>(cod[2]) << 4) | cod[1] >> 4, cod[1] & 0x0f, cod[0]); - std::string str(buffer); - return str; -} - -std::string ClassOfDevice::ToLegacyConfigString() const { return std::to_string(ToUint32Legacy()); } - -std::optional<ClassOfDevice> ClassOfDevice::FromString(const std::string& str) { - if (str.length() != 8) { - return std::nullopt; - } - - std::istringstream stream(str); - std::string token; - int index = 0; - uint16_t values[3]; - - ClassOfDevice new_cod{}; - while (getline(stream, token, '-')) { - if (index >= 3) { - return std::nullopt; - } - - if (index == 0 && token.length() != 3) { - return std::nullopt; - } else if (index == 1 && token.length() != 1) { - return std::nullopt; - } else if (index == 2 && token.length() != 2) { - return std::nullopt; - } - char* temp = nullptr; - values[index] = std::strtol(token.c_str(), &temp, 16); - if (*temp != '\0') { - return std::nullopt; - } - - index++; - } - - if (index != 3) { - return std::nullopt; - } - - new_cod.cod[0] = values[2]; - new_cod.cod[1] = values[1] | ((values[0] & 0xf) << 4); - new_cod.cod[2] = values[0] >> 4; - - return new_cod; -} - -bool ClassOfDevice::FromString(const std::string& from, ClassOfDevice& to) { - auto new_cod = FromString(from); - if (!new_cod) { - to = {}; - return false; - } - to = std::move(*new_cod); - return true; -} - -std::optional<ClassOfDevice> ClassOfDevice::FromUint32Legacy(uint32_t cod_int) { - if (cod_int != 0 && (cod_int >> 24) != 0) { - return std::nullopt; - } - ClassOfDevice result = {}; - result.cod[2] = static_cast<uint8_t>(cod_int); - result.cod[1] = static_cast<uint8_t>(cod_int >> 8); - result.cod[0] = static_cast<uint8_t>(cod_int >> 16); - return result; -} - -std::optional<ClassOfDevice> ClassOfDevice::FromLegacyConfigString(const std::string& str) { - char* ptr = nullptr; - auto num = std::strtoull(str.data(), &ptr, 10); - if (num > 0xffffff) { - return std::nullopt; - } - return FromUint32Legacy(static_cast<uint32_t>(num)); -} - -uint32_t ClassOfDevice::ToUint32Legacy() const { return (cod[2]) | (cod[1] << 8) | (cod[0] << 16); } - -size_t ClassOfDevice::FromOctets(const uint8_t* from) { - std::copy(from, from + kLength, data()); - return kLength; -} - -bool ClassOfDevice::IsValid(const std::string& cod) { - return ClassOfDevice::FromString(cod).has_value(); -} -} // namespace hci -} // namespace bluetooth diff --git a/system/gd/hci/controller_test.cc b/system/gd/hci/controller_test.cc index 05dcaf9d7e..0743204ffd 100644 --- a/system/gd/hci/controller_test.cc +++ b/system/gd/hci/controller_test.cc @@ -32,9 +32,6 @@ #include "os/thread.h" #include "packet/raw_builder.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; using namespace std::chrono_literals; @@ -580,7 +577,7 @@ TEST_F(Controller104Test, feature_spec_version_104_test) { std::promise<void> credits1_set; std::promise<void> credits2_set; -void CheckReceivedCredits(uint16_t handle, uint16_t credits) { +static void CheckReceivedCredits(uint16_t handle, uint16_t credits) { switch (handle) { case (kHandle1): ASSERT_EQ(kCredits1, credits); @@ -624,7 +621,7 @@ TEST_F(ControllerTest, aclCreditCallbackListenerUnregistered) { std::promise<uint64_t> le_rand_set; -void le_rand_callback(uint64_t random) { le_rand_set.set_value(random); } +static void le_rand_callback(uint64_t random) { le_rand_set.set_value(random); } TEST_F(ControllerTest, leRandTest) { le_rand_set = std::promise<uint64_t>(); diff --git a/system/gd/hci/fuzz/acl_manager_fuzz_test.cc b/system/gd/hci/fuzz/acl_manager_fuzz_test.cc index 06544789b7..d9c039415c 100644 --- a/system/gd/hci/fuzz/acl_manager_fuzz_test.cc +++ b/system/gd/hci/fuzz/acl_manager_fuzz_test.cc @@ -25,9 +25,6 @@ #include "module.h" #include "os/fake_timer/fake_timerfd.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::FuzzTestModuleRegistry; using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::hci::AclManager; diff --git a/system/gd/hci/fuzz/hci_layer_fuzz_test.cc b/system/gd/hci/fuzz/hci_layer_fuzz_test.cc index 392ffdd3e6..1fed31e882 100644 --- a/system/gd/hci/fuzz/hci_layer_fuzz_test.cc +++ b/system/gd/hci/fuzz/hci_layer_fuzz_test.cc @@ -25,9 +25,6 @@ #include "module.h" #include "os/fake_timer/fake_timerfd.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::FuzzTestModuleRegistry; using bluetooth::fuzz::GetArbitraryBytes; using bluetooth::hal::HciHal; diff --git a/system/gd/hci/hci_layer_unittest.cc b/system/gd/hci/hci_layer_unittest.cc index 1f2526e46d..5abc0c74fc 100644 --- a/system/gd/hci/hci_layer_unittest.cc +++ b/system/gd/hci/hci_layer_unittest.cc @@ -34,9 +34,6 @@ #include "os/thread.h" #include "packet/raw_builder.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace std::chrono_literals; namespace { @@ -72,14 +69,6 @@ using packet::kLittleEndian; using packet::PacketView; using packet::RawBuilder; -std::vector<uint8_t> GetPacketBytes(std::unique_ptr<packet::BasePacketBuilder> packet) { - std::vector<uint8_t> bytes; - BitInserter i(bytes); - bytes.reserve(packet->size()); - packet->Serialize(i); - return bytes; -} - static std::chrono::milliseconds getHciTimeoutMs() { static auto sHciTimeoutMs = std::chrono::milliseconds(bluetooth::os::GetSystemPropertyUint32Base( "bluetooth.hci.timeout_milliseconds", HciLayer::kHciTimeoutMs.count())); diff --git a/system/gd/hci/hci_packets_fuzz_test.cc b/system/gd/hci/hci_packets_fuzz_test.cc index 2868477c46..00a053273c 100644 --- a/system/gd/hci/hci_packets_fuzz_test.cc +++ b/system/gd/hci/hci_packets_fuzz_test.cc @@ -21,9 +21,6 @@ #include "packet/bit_inserter.h" #include "packet/raw_builder.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::packet::BitInserter; using bluetooth::packet::RawBuilder; using std::vector; diff --git a/system/gd/hci/le_address_manager.cc b/system/gd/hci/le_address_manager.cc index bddbcaf4d1..034f251b0e 100644 --- a/system/gd/hci/le_address_manager.cc +++ b/system/gd/hci/le_address_manager.cc @@ -28,9 +28,6 @@ // TODO(b/378143579) For peer address not in resolving list -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace hci { @@ -53,7 +50,7 @@ std::string LeAddressManager::ClientStateText(const ClientState cs) { RETURN_UNKNOWN_TYPE_STRING(ClientState, cs); } -std::string AddressPolicyText(const LeAddressManager::AddressPolicy policy) { +static std::string AddressPolicyText(const LeAddressManager::AddressPolicy policy) { switch (policy) { CASE_RETURN_STRING(LeAddressManager::AddressPolicy::POLICY_NOT_SET); CASE_RETURN_STRING(LeAddressManager::AddressPolicy::USE_PUBLIC_ADDRESS); diff --git a/system/gd/hci/le_advertising_manager.cc b/system/gd/hci/le_advertising_manager.cc index acf3da1188..afa8fd300b 100644 --- a/system/gd/hci/le_advertising_manager.cc +++ b/system/gd/hci/le_advertising_manager.cc @@ -35,9 +35,6 @@ #include "os/system_properties.h" #include "packet/fragmenting_inserter.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace hci { @@ -102,7 +99,7 @@ struct Advertiser { * (2) if the host supports only non-resolvable addresses, then advertisements will never use RPA * (3) if the host supports RPAs, then the requested type will always be honored */ -AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( +static AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( AdvertiserAddressType requested_address_type, LeAddressManager::AddressPolicy address_policy) { switch (address_policy) { @@ -127,7 +124,7 @@ AdvertiserAddressType GetAdvertiserAddressTypeFromRequestedTypeAndPolicy( * can use both Public and NRPA if requested. Use NRPA if RPA is requested. * (2) in other cases, based on the requested type and the address manager policy. */ -AdvertiserAddressType GetAdvertiserAddressTypeNonConnectable( +static AdvertiserAddressType GetAdvertiserAddressTypeNonConnectable( AdvertiserAddressType requested_address_type, LeAddressManager::AddressPolicy address_policy) { switch (address_policy) { diff --git a/system/gd/hci/msft.cc b/system/gd/hci/msft.cc index b27bcf23d5..1c5a700030 100644 --- a/system/gd/hci/msft.cc +++ b/system/gd/hci/msft.cc @@ -56,10 +56,13 @@ struct MsftExtensionManager::impl { * Query the kernel/drivers to derive the MSFT opcode so that * we can issue MSFT vendor specific commands. */ - if (!supports_msft_extensions()) { + uint16_t opcode = hal_->getMsftOpcode(); + if (opcode == 0) { log::info("MSFT extension is not supported."); return; } + msft_.opcode = opcode; + log::info("MSFT opcode 0x{:04x}", msft_.opcode.value()); /* * The vendor prefix is required to distinguish among the vendor events @@ -121,20 +124,7 @@ struct MsftExtensionManager::impl { } } - bool supports_msft_extensions() { - if (msft_.opcode.has_value()) { - return true; - } - - uint16_t opcode = hal_->getMsftOpcode(); - if (opcode == 0) { - return false; - } - - msft_.opcode = opcode; - log::info("MSFT opcode 0x{:04x}", msft_.opcode.value()); - return true; - } + bool supports_msft_extensions() { return msft_.opcode.has_value(); } void msft_adv_monitor_add(const MsftAdvMonitor& monitor, MsftAdvMonitorAddCallback cb) { if (!supports_msft_extensions()) { @@ -225,7 +215,11 @@ struct MsftExtensionManager::impl { log::assert_that(view.IsValid(), "assert failed: view.IsValid()"); auto status_view = MsftReadSupportedFeaturesCommandCompleteView::Create( MsftCommandCompleteView::Create(view)); - log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()"); + if (!status_view.IsValid()) { + log::error("MSFT Read supported features failed"); + msft_.opcode = std::nullopt; + return; + } if (status_view.GetStatus() != ErrorCode::SUCCESS) { log::warn("MSFT Command complete status {}", ErrorCodeText(status_view.GetStatus())); diff --git a/system/gd/metrics/bluetooth_event.cc b/system/gd/metrics/bluetooth_event.cc index ce83747978..26ce918099 100644 --- a/system/gd/metrics/bluetooth_event.cc +++ b/system/gd/metrics/bluetooth_event.cc @@ -17,12 +17,10 @@ #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h> +#include "bta/include/bta_hfp_api.h" #include "main/shim/helpers.h" #include "os/metrics.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace metrics { @@ -169,7 +167,7 @@ State MapErrorCodeToState(ErrorCode reason) { } } -State MapHCIStatusToState(tHCI_STATUS status) { +static State MapHCIStatusToState(tHCI_STATUS status) { switch (status) { case tHCI_STATUS::HCI_SUCCESS: return State::SUCCESS; @@ -260,7 +258,7 @@ State MapHCIStatusToState(tHCI_STATUS status) { } } -State MapSmpStatusCodeToState(tSMP_STATUS status) { +static State MapSmpStatusCodeToState(tSMP_STATUS status) { switch (status) { case tSMP_STATUS::SMP_SUCCESS: return State::SUCCESS; @@ -317,6 +315,29 @@ State MapSmpStatusCodeToState(tSMP_STATUS status) { } } +State MapHfpVersionToState(uint16_t version) { + switch (version) { + case HSP_VERSION_1_0: + return State::VERSION_1_0; + case HFP_VERSION_1_1: + return State::VERSION_1_1; + case HSP_VERSION_1_2: + return State::VERSION_1_2; + case HFP_VERSION_1_5: + return State::VERSION_1_5; + case HFP_VERSION_1_6: + return State::VERSION_1_6; + case HFP_VERSION_1_7: + return State::VERSION_1_7; + case HFP_VERSION_1_8: + return State::VERSION_1_8; + case HFP_VERSION_1_9: + return State::VERSION_1_9; + default: + return State::VERSION_UNKNOWN; + } +} + void LogIncomingAclStartEvent(const hci::Address& address) { bluetooth::os::LogMetricBluetoothEvent(address, EventType::ACL_CONNECTION_RESPONDER, State::START); diff --git a/system/gd/metrics/bluetooth_event.h b/system/gd/metrics/bluetooth_event.h index acdb7a84f6..12a122c442 100644 --- a/system/gd/metrics/bluetooth_event.h +++ b/system/gd/metrics/bluetooth_event.h @@ -50,5 +50,7 @@ void LogLePairingFail(const RawAddress& raw_address, uint8_t failure_reason, boo android::bluetooth::State MapErrorCodeToState(hci::ErrorCode reason); +android::bluetooth::State MapHfpVersionToState(uint16_t version); + } // namespace metrics } // namespace bluetooth diff --git a/system/gd/os/linux_generic/alarm_timerfd_unittest.cc b/system/gd/os/linux_generic/alarm_timerfd_unittest.cc index 03d99bb476..bcf802b86d 100644 --- a/system/gd/os/linux_generic/alarm_timerfd_unittest.cc +++ b/system/gd/os/linux_generic/alarm_timerfd_unittest.cc @@ -23,22 +23,6 @@ #include "gtest/gtest.h" #include "os/alarm.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - -namespace bluetooth::common { - -struct IsSpace { - bool operator()(std::string::value_type v) { return isspace(static_cast<int>(v)); } -}; - -std::string StringTrim(std::string str) { - str.erase(str.begin(), std::find_if_not(str.begin(), str.end(), IsSpace{})); - str.erase(std::find_if_not(str.rbegin(), str.rend(), IsSpace{}).base(), str.end()); - return str; -} -} // namespace bluetooth::common - namespace bluetooth::os { using common::BindOnce; diff --git a/system/gd/os/linux_generic/wakelock_manager.cc b/system/gd/os/linux_generic/wakelock_manager.cc index 7cca56201a..ad31b82063 100644 --- a/system/gd/os/linux_generic/wakelock_manager.cc +++ b/system/gd/os/linux_generic/wakelock_manager.cc @@ -27,16 +27,13 @@ #include "os/internal/wakelock_native.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace os { using internal::WakelockNative; using StatusCode = WakelockNative::StatusCode; -uint64_t now_ms() { +static uint64_t now_ms() { struct timespec ts = {}; if (clock_gettime(CLOCK_BOOTTIME, &ts) == -1) { log::error("unable to get current time: {}", strerror(errno)); diff --git a/system/gd/rust/linux/client/src/callbacks.rs b/system/gd/rust/linux/client/src/callbacks.rs index 32fdd7f55d..603716376e 100644 --- a/system/gd/rust/linux/client/src/callbacks.rs +++ b/system/gd/rust/linux/client/src/callbacks.rs @@ -1473,8 +1473,8 @@ impl IBluetoothMediaCallback for MediaCallback { &mut self, _direction: u8, _group_id: i32, - _snk_audio_location: u32, - _src_audio_location: u32, + _snk_audio_location: i64, + _src_audio_location: i64, _avail_cont: u16, ) { } diff --git a/system/gd/rust/linux/client/src/dbus_iface.rs b/system/gd/rust/linux/client/src/dbus_iface.rs index ba31286cf0..9e0f2818d1 100644 --- a/system/gd/rust/linux/client/src/dbus_iface.rs +++ b/system/gd/rust/linux/client/src/dbus_iface.rs @@ -2989,8 +2989,8 @@ impl IBluetoothMediaCallback for IBluetoothMediaCallbackDBus { &mut self, direction: u8, group_id: i32, - snk_audio_location: u32, - src_audio_location: u32, + snk_audio_location: i64, + src_audio_location: i64, avail_cont: u16, ) { } diff --git a/system/gd/rust/linux/service/src/iface_bluetooth_media.rs b/system/gd/rust/linux/service/src/iface_bluetooth_media.rs index 88d6b200a5..8da5e60683 100644 --- a/system/gd/rust/linux/service/src/iface_bluetooth_media.rs +++ b/system/gd/rust/linux/service/src/iface_bluetooth_media.rs @@ -155,8 +155,8 @@ impl IBluetoothMediaCallback for BluetoothMediaCallbackDBus { &mut self, direction: u8, group_id: i32, - snk_audio_location: u32, - src_audio_location: u32, + snk_audio_location: i64, + src_audio_location: i64, avail_cont: u16, ) { dbus_generated!() diff --git a/system/gd/rust/linux/stack/src/bluetooth_media.rs b/system/gd/rust/linux/stack/src/bluetooth_media.rs index e87d3d9086..c8ea9bcb7e 100644 --- a/system/gd/rust/linux/stack/src/bluetooth_media.rs +++ b/system/gd/rust/linux/stack/src/bluetooth_media.rs @@ -296,8 +296,8 @@ pub trait IBluetoothMediaCallback: RPCProxy { &mut self, direction: u8, group_id: i32, - snk_audio_location: u32, - src_audio_location: u32, + snk_audio_location: i64, + src_audio_location: i64, avail_cont: u16, ); @@ -420,8 +420,8 @@ struct UHid { struct LEAAudioConf { pub direction: u8, pub group_id: i32, - pub snk_audio_location: u32, - pub src_audio_location: u32, + pub snk_audio_location: i64, + pub src_audio_location: i64, pub avail_cont: u16, } diff --git a/system/gd/rust/topshim/le_audio/le_audio_shim.cc b/system/gd/rust/topshim/le_audio/le_audio_shim.cc index 53a0f7d98f..96ecfba464 100644 --- a/system/gd/rust/topshim/le_audio/le_audio_shim.cc +++ b/system/gd/rust/topshim/le_audio/le_audio_shim.cc @@ -207,15 +207,19 @@ static void group_stream_status_cb(int group_id, le_audio::GroupStreamStatus sta le_audio_group_stream_status_callback(group_id, to_rust_btle_audio_group_stream_status(status)); } -static void audio_conf_cb(uint8_t direction, int group_id, uint32_t snk_audio_location, - uint32_t src_audio_location, uint16_t avail_cont) { - le_audio_audio_conf_callback(direction, group_id, snk_audio_location, src_audio_location, +static void audio_conf_cb(uint8_t direction, int group_id, + std::optional<std::bitset<32>> snk_audio_location, + std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont) { + int64_t rs_snk_audio_location = snk_audio_location ? snk_audio_location->to_ulong() : -1l; + int64_t rs_src_audio_location = src_audio_location ? src_audio_location->to_ulong() : -1l; + le_audio_audio_conf_callback(direction, group_id, rs_snk_audio_location, rs_src_audio_location, avail_cont); } static void sink_audio_location_available_cb(const RawAddress& address, - uint32_t snk_audio_locations) { - le_audio_sink_audio_location_available_callback(address, snk_audio_locations); + std::optional<std::bitset<32>> snk_audio_location) { + int64_t rs_snk_audio_location = snk_audio_location ? snk_audio_location->to_ulong() : -1l; + le_audio_sink_audio_location_available_callback(address, rs_snk_audio_location); } static void audio_local_codec_capabilities_cb( @@ -270,19 +274,24 @@ public: topshim::rust::internal::group_node_status_cb(bd_addr, group_id, node_status); } - void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, - uint32_t src_audio_location, uint16_t avail_cont) { + void OnAudioConf(uint8_t direction, int group_id, + std::optional<std::bitset<32>> snk_audio_location, + std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont) { log::info( "direction={}, group_id={}, snk_audio_location={}, src_audio_location={}, " "avail_cont={}", - direction, group_id, snk_audio_location, src_audio_location, avail_cont); + direction, group_id, + std::to_string(snk_audio_location ? snk_audio_location->to_ulong() : -1), + std::to_string(src_audio_location ? src_audio_location->to_ulong() : -1), avail_cont); topshim::rust::internal::audio_conf_cb(direction, group_id, snk_audio_location, src_audio_location, avail_cont); } - void OnSinkAudioLocationAvailable(const RawAddress& address, uint32_t snk_audio_locations) { - log::info("address={}, snk_audio_locations={}", address, snk_audio_locations); - topshim::rust::internal::sink_audio_location_available_cb(address, snk_audio_locations); + void OnSinkAudioLocationAvailable(const RawAddress& address, + std::optional<std::bitset<32>> snk_audio_location) { + log::info("address={}, snk_audio_locations={}", address, + std::to_string(snk_audio_location ? snk_audio_location->to_ulong() : -1)); + topshim::rust::internal::sink_audio_location_available_cb(address, snk_audio_location); } void OnAudioLocalCodecCapabilities( diff --git a/system/gd/rust/topshim/src/profiles/le_audio.rs b/system/gd/rust/topshim/src/profiles/le_audio.rs index 64e5ae4185..b7aa3ed7e3 100644 --- a/system/gd/rust/topshim/src/profiles/le_audio.rs +++ b/system/gd/rust/topshim/src/profiles/le_audio.rs @@ -194,13 +194,13 @@ pub mod ffi { fn le_audio_audio_conf_callback( direction: u8, group_id: i32, - snk_audio_location: u32, - src_audio_location: u32, + snk_audio_location: i64, + src_audio_location: i64, avail_cont: u16, ); fn le_audio_sink_audio_location_available_callback( addr: RawAddress, - snk_audio_locations: u32, + snk_audio_locations: i64, ); fn le_audio_audio_local_codec_capabilities_callback( local_input_capa_codec_conf: &Vec<BtLeAudioCodecConfig>, @@ -477,8 +477,8 @@ pub enum LeAudioClientCallbacks { ConnectionState(BtLeAudioConnectionState, RawAddress), GroupStatus(i32, BtLeAudioGroupStatus), GroupNodeStatus(RawAddress, i32, BtLeAudioGroupNodeStatus), - AudioConf(u8, i32, u32, u32, u16), - SinkAudioLocationAvailable(RawAddress, u32), + AudioConf(u8, i32, i64, i64, u16), + SinkAudioLocationAvailable(RawAddress, i64), AudioLocalCodecCapabilities(Vec<BtLeAudioCodecConfig>, Vec<BtLeAudioCodecConfig>), AudioGroupCodecConf( i32, @@ -520,11 +520,11 @@ cb_variant!(LeAudioClientCb, cb_variant!(LeAudioClientCb, le_audio_audio_conf_callback -> LeAudioClientCallbacks::AudioConf, - u8, i32, u32, u32, u16); + u8, i32, i64, i64, u16); cb_variant!(LeAudioClientCb, le_audio_sink_audio_location_available_callback -> LeAudioClientCallbacks::SinkAudioLocationAvailable, - RawAddress, u32); + RawAddress, i64); cb_variant!(LeAudioClientCb, le_audio_unicast_monitor_mode_status_callback -> LeAudioClientCallbacks::UnicastMonitorModeStatus, diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h index 94c3762596..a4ac245f2e 100644 --- a/system/include/hardware/bt_le_audio.h +++ b/system/include/hardware/bt_le_audio.h @@ -20,6 +20,7 @@ #include <bluetooth/log.h> #include <array> +#include <bitset> #include <map> #include <optional> #include <ostream> @@ -78,6 +79,42 @@ enum class GroupStreamStatus { DESTROYED, }; +inline std::ostream& operator<<(std::ostream& os, const GroupStreamStatus& state) { + switch (state) { + case GroupStreamStatus::IDLE: + os << "IDLE"; + break; + case GroupStreamStatus::STREAMING: + os << "STREAMING"; + break; + case GroupStreamStatus::RELEASING: + os << "RELEASING"; + break; + case GroupStreamStatus::RELEASING_AUTONOMOUS: + os << "RELEASING_AUTONOMOUS"; + break; + case GroupStreamStatus::SUSPENDING: + os << "SUSPENDING"; + break; + case GroupStreamStatus::SUSPENDED: + os << "SUSPENDED"; + break; + case GroupStreamStatus::CONFIGURED_AUTONOMOUS: + os << "CONFIGURED_AUTONOMOUS"; + break; + case GroupStreamStatus::CONFIGURED_BY_USER: + os << "CONFIGURED_BY_USER"; + break; + case GroupStreamStatus::DESTROYED: + os << "DESTROYED"; + break; + default: + os << "UNKNOWN"; + break; + } + return os; +} + enum class GroupNodeStatus { ADDED = 1, REMOVED, @@ -139,6 +176,7 @@ typedef struct btle_audio_codec_config { btle_audio_bits_per_sample_index_t bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE; btle_audio_channel_count_index_t channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_NONE; btle_audio_frame_duration_index_t frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_NONE; + uint8_t codec_frame_blocks_per_sdu = 0; uint16_t octets_per_frame = 0; int32_t codec_priority = 0; @@ -318,11 +356,13 @@ public: virtual void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id, GroupNodeStatus node_status) = 0; /* Callback for newly recognized or reconfigured existing le audio group */ - virtual void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location, - uint32_t src_audio_location, uint16_t avail_cont) = 0; + virtual void OnAudioConf(uint8_t direction, int group_id, + std::optional<std::bitset<32>> snk_audio_location, + std::optional<std::bitset<32>> src_audio_location, + uint16_t avail_cont) = 0; /* Callback for sink audio location recognized */ virtual void OnSinkAudioLocationAvailable(const RawAddress& address, - uint32_t snk_audio_locations) = 0; + std::optional<std::bitset<32>> snk_audio_location) = 0; /* Callback with local codec capabilities */ virtual void OnAudioLocalCodecCapabilities( std::vector<btle_audio_codec_config_t> local_input_capa_codec_conf, diff --git a/system/main/Android.bp b/system/main/Android.bp index 5fd82531fa..4bddd6a5ab 100644 --- a/system/main/Android.bp +++ b/system/main/Android.bp @@ -158,7 +158,6 @@ cc_test { ":TestMockBtif", ":TestMockBtu", ":TestMockJni", - ":TestMockLegacyHciCommands", ":TestMockLegacyHciInterface", ":TestMockMainShimEntry", ":TestMockStack", diff --git a/system/main/shim/BUILD.gn b/system/main/shim/BUILD.gn index ff7bdae78a..5021795e93 100644 --- a/system/main/shim/BUILD.gn +++ b/system/main/shim/BUILD.gn @@ -36,6 +36,7 @@ source_set("BluetoothStackManagerSources") { "//bt/system/gd/packet:BluetoothPacketSources", "//bt/system/gd/rust/topshim:libbluetooth_topshim", "//bt/system/osi", + "//bt/system/pdl:BluetoothHciPacketSources", "//bt/system/pdl:BluetoothGeneratedPackets_h", "//bt/system/stack", "//bt/system/types", @@ -81,6 +82,7 @@ source_set("LibBluetoothShimSources") { "//bt/system/gd/packet:BluetoothPacketSources", "//bt/system/gd/rust/topshim:libbluetooth_topshim", "//bt/system/osi", + "//bt/system/pdl:BluetoothHciPacketSources", "//bt/system/pdl:BluetoothGeneratedPackets_h", "//bt/system/stack", "//bt/system/types", diff --git a/system/main/shim/metrics_api.cc b/system/main/shim/metrics_api.cc index 69fcaab313..20c14191a9 100644 --- a/system/main/shim/metrics_api.cc +++ b/system/main/shim/metrics_api.cc @@ -23,6 +23,8 @@ #include "os/metrics.h" #include "types/raw_address.h" +using android::bluetooth::EventType; +using android::bluetooth::State; using bluetooth::hci::Address; namespace bluetooth { @@ -215,5 +217,35 @@ bool CountCounterMetrics(int32_t key, int64_t count) { return counter_metrics->Count(key, count); } +void LogMetricHfpAgVersion(hci::Address address, uint16_t version) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_AG_VERSION, + bluetooth::metrics::MapHfpVersionToState(version)); +} + +void LogMetricHfpHfVersion(hci::Address address, uint16_t version) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_HF_VERSION, + bluetooth::metrics::MapHfpVersionToState(version)); +} + +void LogMetricHfpRfcommChannelFail(hci::Address address) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_SESSION, + State::HFP_RFCOMM_CHANNEL_FAIL); +} + +void LogMetricHfpRfcommCollisionFail(hci::Address address) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_SESSION, + State::HFP_RFCOMM_COLLISION_FAIL); +} + +void LogMetricHfpRfcommAgOpenFail(hci::Address address) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_SESSION, + State::HFP_RFCOMM_AG_OPEN_FAIL); +} + +void LogMetricHfpSlcFail(hci::Address address) { + bluetooth::os::LogMetricBluetoothEvent(address, EventType::HFP_SESSION, + State::HFP_SLC_FAIL_CONNECTION); +} + } // namespace shim } // namespace bluetooth diff --git a/system/main/shim/metrics_api.h b/system/main/shim/metrics_api.h index ae37fddf61..43d89e5469 100644 --- a/system/main/shim/metrics_api.h +++ b/system/main/shim/metrics_api.h @@ -316,5 +316,43 @@ void LogMetricLeConnectionRejected(hci::Address address); bool CountCounterMetrics(int32_t key, int64_t count); +/** + * Logs the AG version in a HFP session + * @param address of a device + * @param version AG HFP version + */ +void LogMetricHfpAgVersion(hci::Address address, uint16_t version); + +/** + * Logs the HF version in a HFP session + * @param address of a device + * @param version HF HFP Version + */ +void LogMetricHfpHfVersion(hci::Address address, uint16_t version); + +/** + * Logs a RFCOMM channel failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommChannelFail(hci::Address address); + +/** + * Logs a RFCOMM collision failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommCollisionFail(hci::Address address); + +/** + * Logs a RFCOMM AG open failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommAgOpenFail(hci::Address address); + +/** + * Logs a SLC failure in a HFP Session + * @param address of a device + */ +void LogMetricHfpSlcFail(hci::Address address); + } // namespace shim } // namespace bluetooth diff --git a/system/pdl/BUILD.gn b/system/pdl/BUILD.gn index bf8885a5ea..c79976fdd7 100644 --- a/system/pdl/BUILD.gn +++ b/system/pdl/BUILD.gn @@ -15,6 +15,15 @@ import("//bt/system/gd/packet/parser/packetgen.gni") +source_set("BluetoothHciPacketSources") { + sources = [ + "hci/address.cc", + "hci/class_of_device.cc", + ] + + include_dirs = [ "//bt/system/gd" ] +} + packetgen_headers("BluetoothGeneratedPackets_h") { sources = [ "hci/hci_packets.pdl", diff --git a/system/stack/Android.bp b/system/stack/Android.bp index 13d7984359..fe027336d5 100644 --- a/system/stack/Android.bp +++ b/system/stack/Android.bp @@ -468,7 +468,6 @@ cc_fuzz { ":TestMockDevice", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackArbiter", @@ -520,7 +519,6 @@ cc_fuzz { ":TestMockDevice", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackArbiter", @@ -1141,7 +1139,6 @@ cc_test { srcs: [ ":TestCommonMockFunctions", ":TestMockMainShim", - ":TestMockRustFfi", ":TestMockStackArbiter", ":TestMockStackBtm", ":TestMockStackConnMgr", @@ -1476,7 +1473,6 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockMainShim", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackConnMgr", ":TestMockStackL2cap", @@ -1691,10 +1687,8 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockLegacyHciInterface", - ":TestMockMainBte", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtu", ":TestMockStackConnMgr", ":TestMockStackGap", @@ -1946,7 +1940,6 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", ":TestMockStackAcl", @@ -2024,10 +2017,8 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackBtm", @@ -2128,7 +2119,6 @@ cc_test { ":TestMockBtif", ":TestMockHci", ":TestMockJni", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", ":TestMockStackAcl", @@ -2227,11 +2217,9 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockLegacyHciInterface", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackBtu", ":TestMockStackConnMgr", @@ -2325,10 +2313,8 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockLegacyHciInterface", - ":TestMockMainBte", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackBtu", ":TestMockStackGap", diff --git a/system/stack/a2dp/a2dp_aac.cc b/system/stack/a2dp/a2dp_aac.cc index 8ae4d68ede..cb19031e62 100644 --- a/system/stack/a2dp/a2dp_aac.cc +++ b/system/stack/a2dp/a2dp_aac.cc @@ -951,7 +951,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -1017,28 +1016,24 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { result_config_cie.sampleRate = A2DP_AAC_SAMPLING_FREQ_44100; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { result_config_cie.sampleRate = A2DP_AAC_SAMPLING_FREQ_48000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_88200: if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { result_config_cie.sampleRate = A2DP_AAC_SAMPLING_FREQ_88200; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_96000: if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { result_config_cie.sampleRate = A2DP_AAC_SAMPLING_FREQ_96000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; @@ -1047,7 +1042,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -1072,20 +1066,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_44100) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - } - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_48000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - } - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_88200) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - } - if (sampleRate & A2DP_AAC_SAMPLING_FREQ_96000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; - } - // No user preference - try the codec audio config if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, &codec_config_)) { @@ -1123,27 +1103,23 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: result_config_cie.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -1157,9 +1133,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - codec_capability_.bits_per_sample = bits_per_sample; - // No user preference - the the codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_aac_caps->bits_per_sample, &result_config_cie, &codec_config_)) { @@ -1196,19 +1169,16 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { result_config_cie.channelMode = A2DP_AAC_CHANNEL_MODE_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { result_config_cie.channelMode = A2DP_AAC_CHANNEL_MODE_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -1227,14 +1197,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - if (channelMode & A2DP_AAC_CHANNEL_MODE_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (channelMode & A2DP_AAC_CHANNEL_MODE_STEREO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - try the codec audio config if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, &codec_config_)) { @@ -1325,7 +1287,6 @@ tA2DP_STATUS A2dpCodecConfigAacBase::setCodecConfig(const uint8_t* p_peer_codec_ fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/a2dp/a2dp_codec_config.cc b/system/stack/a2dp/a2dp_codec_config.cc index 65329b0d5c..135f4ee992 100644 --- a/system/stack/a2dp/a2dp_codec_config.cc +++ b/system/stack/a2dp/a2dp_codec_config.cc @@ -123,7 +123,6 @@ A2dpCodecConfig::A2dpCodecConfig(btav_a2dp_codec_index_t codec_index, a2dp::Code setCodecPriority(codec_priority); init_btav_a2dp_codec_config(&codec_config_, codec_index_, codecPriority()); - init_btav_a2dp_codec_config(&codec_capability_, codec_index_, codecPriority()); init_btav_a2dp_codec_config(&codec_local_capability_, codec_index_, codecPriority()); init_btav_a2dp_codec_config(&codec_selectable_capability_, codec_index_, codecPriority()); init_btav_a2dp_codec_config(&codec_user_config_, codec_index_, BTAV_A2DP_CODEC_PRIORITY_DEFAULT); @@ -321,13 +320,6 @@ btav_a2dp_codec_config_t A2dpCodecConfig::getCodecConfig() { return codec_config_; } -btav_a2dp_codec_config_t A2dpCodecConfig::getCodecCapability() { - std::lock_guard<std::recursive_mutex> lock(codec_mutex_); - - // TODO: We should check whether the codec capability is valid - return codec_capability_; -} - btav_a2dp_codec_config_t A2dpCodecConfig::getCodecLocalCapability() { std::lock_guard<std::recursive_mutex> lock(codec_mutex_); diff --git a/system/stack/a2dp/a2dp_ext.cc b/system/stack/a2dp/a2dp_ext.cc index fafb688613..b938c93cd9 100644 --- a/system/stack/a2dp/a2dp_ext.cc +++ b/system/stack/a2dp/a2dp_ext.cc @@ -46,9 +46,8 @@ A2dpCodecConfigExt::A2dpCodecConfigExt(btav_a2dp_codec_index_t codec_index, bool is_source_(is_source) { // Load the local capabilities from the provider info. auto result = ::bluetooth::audio::a2dp::provider::codec_info( - codec_index, nullptr, ota_codec_config_, &codec_capability_); + codec_index, nullptr, ota_codec_config_, &codec_local_capability_); log::assert_that(result, "provider::codec_info unexpectdly failed"); - codec_selectable_capability_ = codec_capability_; } tA2DP_STATUS A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info, @@ -59,9 +58,8 @@ tA2DP_STATUS A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info } // Call get_a2dp_config to recompute best capabilities. - // This method need to update codec_capability_, codec_config_, - // and ota_codec_config_ using the local codec_user_config_, and input - // peer_codec_info. + // This method need to update codec_config_, and ota_codec_config_ + // using the local codec_user_config_, and input peer_codec_info. using namespace bluetooth::audio::a2dp; provider::a2dp_remote_capabilities capabilities = { .seid = 0, // the SEID does not matter here. @@ -76,11 +74,15 @@ tA2DP_STATUS A2dpCodecConfigExt::setCodecConfig(const uint8_t* p_peer_codec_info return AVDTP_UNSUPPORTED_CONFIGURATION; } - memcpy(ota_codec_config_, result->codec_config, sizeof(ota_codec_config_)); - memcpy(p_result_codec_config, result->codec_config, sizeof(ota_codec_config_)); + // Use the local capabilities for the selectable capabilities: + // the provider AIDL HAL does not provide an interface to parse the + // peer capabilities and the selectable capabilities cannot be + // computed. + codec_selectable_capability_ = codec_local_capability_; codec_config_ = result->codec_parameters; - codec_capability_ = result->codec_parameters; vendor_specific_parameters_ = result->vendor_specific_parameters; + memcpy(ota_codec_config_, result->codec_config, sizeof(ota_codec_config_)); + memcpy(p_result_codec_config, result->codec_config, sizeof(ota_codec_config_)); return A2DP_SUCCESS; } @@ -92,6 +94,19 @@ bool A2dpCodecConfigExt::setPeerCodecCapabilities(const uint8_t* /* p_peer_codec return true; } +void A2dpCodecConfigExt::setCodecConfig(btav_a2dp_codec_config_t codec_parameters, + uint8_t const codec_config[AVDT_CODEC_SIZE], + std::vector<uint8_t> const& vendor_specific_parameters) { + // Use the local capabilities for the selectable capabilities: + // the provider AIDL HAL does not provide an interface to parse the + // peer capabilities and the selectable capabilities cannot be + // computed. + codec_selectable_capability_ = codec_local_capability_; + codec_config_ = codec_parameters; + memcpy(ota_codec_config_, codec_config, sizeof(ota_codec_config_)); + vendor_specific_parameters_ = vendor_specific_parameters; +} + tA2DP_ENCODER_INTERFACE const a2dp_encoder_interface_ext = { .encoder_init = [](const tA2DP_ENCODER_INIT_PEER_PARAMS*, A2dpCodecConfig*, a2dp_source_read_callback_t, a2dp_source_enqueue_callback_t) {}, diff --git a/system/stack/a2dp/a2dp_sbc.cc b/system/stack/a2dp/a2dp_sbc.cc index f04fe13134..6afdad4827 100644 --- a/system/stack/a2dp/a2dp_sbc.cc +++ b/system/stack/a2dp/a2dp_sbc.cc @@ -998,7 +998,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -1044,14 +1043,12 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { result_config_cie.samp_freq = A2DP_SBC_IE_SAMP_FREQ_44; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { result_config_cie.samp_freq = A2DP_SBC_IE_SAMP_FREQ_48; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; @@ -1062,7 +1059,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -1081,14 +1077,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_44) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - } - if (samp_freq & A2DP_SBC_IE_SAMP_FREQ_48) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - } - // No user preference - try the codec audio config if (select_audio_sample_rate(&codec_audio_config_, samp_freq, &result_config_cie, &codec_config_)) { @@ -1120,13 +1108,11 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; switch (codec_user_config_.bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -1140,9 +1126,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; - // No user preference - try the codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, &codec_config_)) { break; @@ -1174,32 +1157,27 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { result_config_cie.ch_mode = A2DP_SBC_IE_CH_MD_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (ch_mode & A2DP_SBC_IE_CH_MD_JOINT) { result_config_cie.ch_mode = A2DP_SBC_IE_CH_MD_JOINT; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; break; } if (ch_mode & A2DP_SBC_IE_CH_MD_STEREO) { result_config_cie.ch_mode = A2DP_SBC_IE_CH_MD_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; break; } if (ch_mode & A2DP_SBC_IE_CH_MD_DUAL) { result_config_cie.ch_mode = A2DP_SBC_IE_CH_MD_DUAL; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; break; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -1224,14 +1202,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ break; } - // Compute the common capability - if (ch_mode & A2DP_SBC_IE_CH_MD_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (ch_mode & (A2DP_SBC_IE_CH_MD_JOINT | A2DP_SBC_IE_CH_MD_STEREO | A2DP_SBC_IE_CH_MD_DUAL)) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - use the codec audio config if (select_audio_channel_mode(&codec_audio_config_, ch_mode, &result_config_cie, &codec_config_)) { @@ -1359,7 +1329,6 @@ tA2DP_STATUS A2dpCodecConfigSbcBase::setCodecConfig(const uint8_t* p_peer_codec_ fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/a2dp/a2dp_vendor_aptx.cc b/system/stack/a2dp/a2dp_vendor_aptx.cc index 203dd5e847..1be16a5203 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx.cc @@ -555,7 +555,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -589,14 +588,12 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { result_config_cie.sampleRate = A2DP_APTX_SAMPLERATE_44100; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { result_config_cie.sampleRate = A2DP_APTX_SAMPLERATE_48000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; @@ -607,7 +604,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -626,14 +622,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf break; } - // Compute the common capability - if (sampleRate & A2DP_APTX_SAMPLERATE_44100) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - } - if (sampleRate & A2DP_APTX_SAMPLERATE_48000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - } - // No user preference - try the codec audio config if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, &codec_config_)) { @@ -666,13 +654,11 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; switch (codec_user_config_.bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -686,9 +672,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf break; } - // Compute the common capability - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16; - // No user preference - try the codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, &codec_config_)) { break; @@ -721,19 +704,16 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_APTX_CHANNELS_MONO) { result_config_cie.channelMode = A2DP_APTX_CHANNELS_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (channelMode & A2DP_APTX_CHANNELS_STEREO) { result_config_cie.channelMode = A2DP_APTX_CHANNELS_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -752,14 +732,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf break; } - // Compute the common capability - if (channelMode & A2DP_APTX_CHANNELS_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (channelMode & A2DP_APTX_CHANNELS_STEREO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - try the codec audio config if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, &codec_config_)) { @@ -830,7 +802,6 @@ tA2DP_STATUS A2dpCodecConfigAptx::setCodecConfig(const uint8_t* p_peer_codec_inf fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc index 2f92aff69c..5624ba57c6 100644 --- a/system/stack/a2dp/a2dp_vendor_aptx_hd.cc +++ b/system/stack/a2dp/a2dp_vendor_aptx_hd.cc @@ -569,7 +569,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -603,14 +602,12 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { result_config_cie.sampleRate = A2DP_APTX_HD_SAMPLERATE_44100; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { result_config_cie.sampleRate = A2DP_APTX_HD_SAMPLERATE_48000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; @@ -621,7 +618,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -640,14 +636,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i break; } - // Compute the common capability - if (sampleRate & A2DP_APTX_HD_SAMPLERATE_44100) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - } - if (sampleRate & A2DP_APTX_HD_SAMPLERATE_48000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - } - // No user preference - try the codec audio config if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, &codec_config_)) { @@ -680,13 +668,11 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; switch (codec_user_config_.bits_per_sample) { case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -700,9 +686,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i break; } - // Compute the common capability - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24; - // No user preference - try the codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, &codec_config_)) { break; @@ -735,19 +718,16 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { result_config_cie.channelMode = A2DP_APTX_HD_CHANNELS_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { result_config_cie.channelMode = A2DP_APTX_HD_CHANNELS_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -766,14 +746,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i break; } - // Compute the common capability - if (channelMode & A2DP_APTX_HD_CHANNELS_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (channelMode & A2DP_APTX_HD_CHANNELS_STEREO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - try the codec audio config if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, &codec_config_)) { @@ -851,7 +823,6 @@ tA2DP_STATUS A2dpCodecConfigAptxHd::setCodecConfig(const uint8_t* p_peer_codec_i fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/a2dp/a2dp_vendor_ldac.cc b/system/stack/a2dp/a2dp_vendor_ldac.cc index ef7fea0be8..e73fb1f23a 100644 --- a/system/stack/a2dp/a2dp_vendor_ldac.cc +++ b/system/stack/a2dp/a2dp_vendor_ldac.cc @@ -820,7 +820,6 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -854,49 +853,42 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_SAMPLE_RATE_44100: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_44100; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_48000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_88200: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_88200; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_96000: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_96000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_176400: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_176400; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_192000: if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { result_config_cie.sampleRate = A2DP_LDAC_SAMPLING_FREQ_192000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -927,26 +919,6 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec break; } - // Compute the common capability - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_44100) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_44100; - } - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_48000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; - } - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_88200) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_88200; - } - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_96000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_96000; - } - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_176400) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_176400; - } - if (sampleRate & A2DP_LDAC_SAMPLING_FREQ_192000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_192000; - } - // No user preference - try the codec audio config if (select_audio_sample_rate(&codec_audio_config_, sampleRate, &result_config_cie, &codec_config_)) { @@ -982,27 +954,23 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: result_config_cie.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -1016,9 +984,6 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec break; } - // Compute the common capability - codec_capability_.bits_per_sample = bits_per_sample; - // No user preference - the the codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_ldac_caps->bits_per_sample, &result_config_cie, &codec_config_)) { @@ -1055,26 +1020,22 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { result_config_cie.channelMode = A2DP_LDAC_CHANNEL_MODE_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (channelMode & A2DP_LDAC_CHANNEL_MODE_STEREO) { result_config_cie.channelMode = A2DP_LDAC_CHANNEL_MODE_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; break; } if (channelMode & A2DP_LDAC_CHANNEL_MODE_DUAL) { result_config_cie.channelMode = A2DP_LDAC_CHANNEL_MODE_DUAL; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; break; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -1096,14 +1057,6 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec break; } - // Compute the common capability - if (channelMode & A2DP_LDAC_CHANNEL_MODE_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (channelMode & (A2DP_LDAC_CHANNEL_MODE_STEREO | A2DP_LDAC_CHANNEL_MODE_DUAL)) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - try the codec audio config if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, &codec_config_)) { @@ -1167,7 +1120,6 @@ tA2DP_STATUS A2dpCodecConfigLdacBase::setCodecConfig(const uint8_t* p_peer_codec fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/a2dp/a2dp_vendor_opus.cc b/system/stack/a2dp/a2dp_vendor_opus.cc index d7a5685706..9c5bf5cea3 100644 --- a/system/stack/a2dp/a2dp_vendor_opus.cc +++ b/system/stack/a2dp/a2dp_vendor_opus.cc @@ -847,7 +847,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec // Save the internal state btav_a2dp_codec_config_t saved_codec_config = codec_config_; - btav_a2dp_codec_config_t saved_codec_capability = codec_capability_; btav_a2dp_codec_config_t saved_codec_selectable_capability = codec_selectable_capability_; btav_a2dp_codec_config_t saved_codec_user_config = codec_user_config_; btav_a2dp_codec_config_t saved_codec_audio_config = codec_audio_config_; @@ -882,7 +881,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_SAMPLE_RATE_48000: if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { result_config_cie.sampleRate = A2DP_OPUS_SAMPLING_FREQ_48000; - codec_capability_.sample_rate = codec_user_config_.sample_rate; codec_config_.sample_rate = codec_user_config_.sample_rate; } break; @@ -894,7 +892,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_SAMPLE_RATE_16000: case BTAV_A2DP_CODEC_SAMPLE_RATE_24000: case BTAV_A2DP_CODEC_SAMPLE_RATE_NONE: - codec_capability_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; codec_config_.sample_rate = BTAV_A2DP_CODEC_SAMPLE_RATE_NONE; break; } @@ -912,7 +909,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec // Compute the common capability if (sampleRate & A2DP_OPUS_SAMPLING_FREQ_48000) { - codec_capability_.sample_rate |= BTAV_A2DP_CODEC_SAMPLE_RATE_48000; } // No user preference - try the codec audio config @@ -950,27 +946,23 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_16) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_24) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32: if (bits_per_sample & BTAV_A2DP_CODEC_BITS_PER_SAMPLE_32) { result_config_cie.bits_per_sample = codec_user_config_.bits_per_sample; - codec_capability_.bits_per_sample = codec_user_config_.bits_per_sample; codec_config_.bits_per_sample = codec_user_config_.bits_per_sample; } break; case BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE: result_config_cie.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; - codec_capability_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; codec_config_.bits_per_sample = BTAV_A2DP_CODEC_BITS_PER_SAMPLE_NONE; break; } @@ -984,9 +976,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec break; } - // Compute the common capability - codec_capability_.bits_per_sample = bits_per_sample; - // No user preference - try yhe codec audio config if (select_audio_bits_per_sample(&codec_audio_config_, p_a2dp_opus_caps->bits_per_sample, &result_config_cie, &codec_config_)) { @@ -1023,19 +1012,16 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_CHANNEL_MODE_MONO: if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { result_config_cie.channelMode = A2DP_OPUS_CHANNEL_MODE_MONO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO: if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { result_config_cie.channelMode = A2DP_OPUS_CHANNEL_MODE_STEREO; - codec_capability_.channel_mode = codec_user_config_.channel_mode; codec_config_.channel_mode = codec_user_config_.channel_mode; } break; case BTAV_A2DP_CODEC_CHANNEL_MODE_NONE: - codec_capability_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; codec_config_.channel_mode = BTAV_A2DP_CODEC_CHANNEL_MODE_NONE; break; } @@ -1054,14 +1040,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec break; } - // Compute the common capability - if (channelMode & A2DP_OPUS_CHANNEL_MODE_MONO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_MONO; - } - if (channelMode & A2DP_OPUS_CHANNEL_MODE_STEREO) { - codec_capability_.channel_mode |= BTAV_A2DP_CODEC_CHANNEL_MODE_STEREO; - } - // No user preference - try the codec audio config if (select_audio_channel_mode(&codec_audio_config_, channelMode, &result_config_cie, &codec_config_)) { @@ -1095,19 +1073,16 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec case BTAV_A2DP_CODEC_FRAME_SIZE_20MS: if (frameSize & A2DP_OPUS_20MS_FRAMESIZE) { result_config_cie.future1 = A2DP_OPUS_20MS_FRAMESIZE; - codec_capability_.codec_specific_1 = codec_user_config_.codec_specific_1; codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; } break; case BTAV_A2DP_CODEC_FRAME_SIZE_10MS: if (frameSize & A2DP_OPUS_10MS_FRAMESIZE) { result_config_cie.future1 = A2DP_OPUS_10MS_FRAMESIZE; - codec_capability_.codec_specific_1 = codec_user_config_.codec_specific_1; codec_config_.codec_specific_1 = codec_user_config_.codec_specific_1; } break; case BTAV_A2DP_CODEC_FRAME_SIZE_NONE: - codec_capability_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_NONE; codec_config_.codec_specific_1 = BTAV_A2DP_CODEC_FRAME_SIZE_NONE; break; } @@ -1165,7 +1140,6 @@ tA2DP_STATUS A2dpCodecConfigOpusBase::setCodecConfig(const uint8_t* p_peer_codec fail: // Restore the internal state codec_config_ = saved_codec_config; - codec_capability_ = saved_codec_capability; codec_selectable_capability_ = saved_codec_selectable_capability; codec_user_config_ = saved_codec_user_config; codec_audio_config_ = saved_codec_audio_config; diff --git a/system/stack/acl/btm_acl.cc b/system/stack/acl/btm_acl.cc index 2a55ee393d..69afab3bfa 100644 --- a/system/stack/acl/btm_acl.cc +++ b/system/stack/acl/btm_acl.cc @@ -38,6 +38,7 @@ #include <cstdint> +#include "bta/gatt/bta_gattc_int.h" #include "bta/include/bta_dm_acl.h" #include "bta/sys/bta_sys.h" #include "common/metrics.h" @@ -737,8 +738,6 @@ void BTM_default_unblock_role_switch() { HCI_ENABLE_CENTRAL_PERIPHERAL_SWITCH); } -extern void bta_gattc_continue_discovery_if_needed(const RawAddress& bd_addr, uint16_t acl_handle); - static void maybe_chain_more_commands_after_read_remote_version_complete(uint8_t /* status */, uint16_t handle) { tACL_CONN* p_acl_cb = internal_.acl_get_connection_from_handle(handle); diff --git a/system/stack/gatt/gatt_main.cc b/system/stack/gatt/gatt_main.cc index b89327f93d..56d268422c 100644 --- a/system/stack/gatt/gatt_main.cc +++ b/system/stack/gatt/gatt_main.cc @@ -497,6 +497,7 @@ static void gatt_le_connect_cback(uint16_t /* chan */, const RawAddress& bd_addr if (p_tcb != nullptr) { bluetooth::shim::arbiter::GetArbiter().OnLeDisconnect(p_tcb->tcb_idx); } + connection_manager::on_connection_complete(bd_addr); gatt_cleanup_upon_disc(bd_addr, static_cast<tGATT_DISCONN_REASON>(reason), transport); return; } diff --git a/system/stack/hid/hidh_conn.cc b/system/stack/hid/hidh_conn.cc index d658c1ab29..cdc7906d16 100644 --- a/system/stack/hid/hidh_conn.cc +++ b/system/stack/hid/hidh_conn.cc @@ -74,7 +74,7 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed); static void hidh_l2cif_disconnect_cfm(uint16_t l2cap_cid, uint16_t result); static void hidh_l2cif_disconnect_cfm_actual(uint16_t l2cap_cid, uint16_t result); static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg); -static void hidh_l2cif_disconnect(uint16_t l2cap_cid); +static bool hidh_l2cif_disconnect(uint16_t l2cap_cid); static void hidh_l2cif_cong_ind(uint16_t l2cap_cid, bool congested); static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result); @@ -165,10 +165,12 @@ tHID_STATUS hidh_conn_disconnect(uint8_t dhandle) { log::warn("Unable to set L2CAP idle timeout peer:{}", hh_cb.devices[dhandle].addr); } /* Disconnect channels one by one */ - if (p_hcon->intr_cid) { - hidh_l2cif_disconnect(p_hcon->intr_cid); - } else if (p_hcon->ctrl_cid) { - hidh_l2cif_disconnect(p_hcon->ctrl_cid); + uint16_t cid = (p_hcon->intr_cid != 0 ? p_hcon->intr_cid : p_hcon->ctrl_cid); + if (!hidh_l2cif_disconnect(cid)) { + if (com::android::bluetooth::flags::disconnect_hid_channels_serially()) { + // call the disconnection callback directly because l2cap won't call it. + hidh_l2cif_disconnect_cfm_actual(cid, 0); + } } BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", "local initiated"); @@ -559,14 +561,16 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) { // TODO: after disconnect_hid_channels_serially aflags is the default, // remove this function and call L2CA_DisconnectReq directly. -static void hidh_l2cif_disconnect(uint16_t l2cap_cid) { +static bool hidh_l2cif_disconnect(uint16_t l2cap_cid) { if (!stack::l2cap::get_interface().L2CA_DisconnectReq(l2cap_cid)) { log::warn("Unable to send L2CAP disconnect request cid:{}", l2cap_cid); + return false; } if (!com::android::bluetooth::flags::disconnect_hid_channels_serially()) { hidh_l2cif_disconnect_cfm_actual(l2cap_cid, 0); } + return true; } /******************************************************************************* diff --git a/system/stack/include/a2dp_codec_api.h b/system/stack/include/a2dp_codec_api.h index 3c4f3f7c76..a14542ac14 100644 --- a/system/stack/include/a2dp_codec_api.h +++ b/system/stack/include/a2dp_codec_api.h @@ -103,14 +103,6 @@ public: // Returns a copy of the current codec configuration. btav_a2dp_codec_config_t getCodecConfig(); - // Gets the current codec capability. - // The capability is computed by intersecting the local codec's capability - // and the peer's codec capability. However, if there is an explicit user - // configuration for some of the parameters, the result codec configuration - // and capability is restricted to the user's configuration choice. - // Returns a copy of the current codec capability. - btav_a2dp_codec_config_t getCodecCapability(); - // Gets the codec local capability. // Returns a copy of the codec local capability. btav_a2dp_codec_config_t getCodecLocalCapability(); @@ -249,7 +241,6 @@ protected: btav_a2dp_codec_priority_t default_codec_priority_; btav_a2dp_codec_config_t codec_config_; - btav_a2dp_codec_config_t codec_capability_; btav_a2dp_codec_config_t codec_local_capability_; btav_a2dp_codec_config_t codec_selectable_capability_; diff --git a/system/stack/include/a2dp_ext.h b/system/stack/include/a2dp_ext.h index ecada4bee7..f03b0ff53d 100644 --- a/system/stack/include/a2dp_ext.h +++ b/system/stack/include/a2dp_ext.h @@ -45,12 +45,7 @@ public: void setCodecConfig(btav_a2dp_codec_config_t codec_parameters, uint8_t const codec_config[AVDT_CODEC_SIZE], - std::vector<uint8_t> const& vendor_specific_parameters) { - codec_config_ = codec_parameters; - codec_capability_ = codec_parameters; - memcpy(ota_codec_config_, codec_config, sizeof(ota_codec_config_)); - vendor_specific_parameters_ = vendor_specific_parameters; - } + std::vector<uint8_t> const& vendor_specific_parameters); private: [[maybe_unused]] bool is_source_; // True if local is Source diff --git a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h index 5ba233ee05..67ccd41d3f 100644 --- a/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h +++ b/system/stack/test/fuzzers/a2dp/codec/a2dpCodecConfigFuzzFunctions.h @@ -137,17 +137,6 @@ std::vector<std::function<void(FuzzedDataProvider*)>> a2dp_codec_config_operatio codec_config->getCodecConfig(); }, - // getCodecCapability - [](FuzzedDataProvider* fdp) -> void { - std::shared_ptr<A2dpCodecConfig> codec_config( - getArbitraryVectorElement(fdp, a2dp_codec_config_vect, false)); - if (codec_config == nullptr) { - return; - } - - codec_config->getCodecCapability(); - }, - // getCodecLocalCapability [](FuzzedDataProvider* fdp) -> void { std::shared_ptr<A2dpCodecConfig> codec_config( diff --git a/system/test/Android.bp b/system/test/Android.bp index fabb5e9847..c38b178885 100644 --- a/system/test/Android.bp +++ b/system/test/Android.bp @@ -18,11 +18,6 @@ filegroup { } filegroup { - name: "TestMockAudioA2dp", - srcs: ["mock/mock_audio_a2dp*.cc"], -} - -filegroup { name: "TestMockBtaAg", srcs: [ "mock/mock_bta_ag_*.cc", @@ -354,13 +349,6 @@ filegroup { } filegroup { - name: "TestMockLegacyHciCommands", - srcs: [ - "mock/mock_hcic_*.cc", - ], -} - -filegroup { name: "TestMockMainShimEntry", srcs: [ "mock/mock_main_shim_entry.cc", @@ -497,13 +485,6 @@ filegroup { } filegroup { - name: "TestMockStackEatt", - srcs: [ - "mock/mock_stack_eatt*.cc", - ], -} - -filegroup { name: "TestMockStackGatt", srcs: [ "mock/mock_stack_gatt*.cc", @@ -511,13 +492,6 @@ filegroup { } filegroup { - name: "TestMockRustFfi", - srcs: [ - "mock/mock_rust_ffi_connection*.cc", - ], -} - -filegroup { name: "TestMockStackBtu", srcs: [ "mock/mock_stack_btu*.cc", @@ -525,13 +499,6 @@ filegroup { } filegroup { - name: "TestMockMainBte", - srcs: [ - "mock/mock_main_bte*.cc", - ], -} - -filegroup { name: "TestMockBtu", srcs: [ "mock/mock_btu_*cc", diff --git a/system/test/headless/android_namespace.cc b/system/test/headless/android_namespace.cc deleted file mode 100644 index 2c4eee7f74..0000000000 --- a/system/test/headless/android_namespace.cc +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } -} // "C" diff --git a/system/test/headless/config.cc b/system/test/headless/config.cc deleted file mode 100644 index 7a3aab62a0..0000000000 --- a/system/test/headless/config.cc +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2023 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "bt_config" - -#include "gd/hal/snoop_logger.h" -#include "test/headless/log.h" - -using namespace bluetooth::hal; - -class Config { - Config() {} - - void Help() const { - // setprop persist.bluetooth.btsnoopdefaultmode full - LOG_CONSOLE("Flag: %s", SnoopLogger::kBtSnoopLogPersists.c_str()); - // setprop persist.bluetooth.btsnooplogpersists 1 - } -}; diff --git a/system/test/mock/mock_bta_gatts_api.cc b/system/test/mock/mock_bta_gatts_api.cc index ca13a393c8..3d57cbba78 100644 --- a/system/test/mock/mock_bta_gatts_api.cc +++ b/system/test/mock/mock_bta_gatts_api.cc @@ -65,9 +65,4 @@ void BTA_GATTS_SendRsp(uint16_t /* conn_id */, uint32_t /* trans_id */, tGATT_ST inc_func_call_count(__func__); } void BTA_GATTS_StopService(uint16_t /* service_id */) { inc_func_call_count(__func__); } -void bta_gatts_add_service_impl(tGATT_IF /* server_if */, - std::vector<btgatt_db_element_t> /* service */, - BTA_GATTS_AddServiceCb /* cb */) { - inc_func_call_count(__func__); -} void BTA_GATTS_InitBonded(void) { inc_func_call_count(__func__); } diff --git a/system/test/mock/mock_bta_leaudio.cc b/system/test/mock/mock_bta_leaudio.cc index 24824032a3..c135ae9b3d 100644 --- a/system/test/mock/mock_bta_leaudio.cc +++ b/system/test/mock/mock_bta_leaudio.cc @@ -42,8 +42,9 @@ class HalVersionManager { } // namespace bluetooth void LeAudioClient::AddFromStorage( - const RawAddress& /* addr */, bool /* autoconnect */, int /* sink_audio_location */, - int /* source_audio_location */, int /* sink_supported_context_types */, + const RawAddress& /* addr */, bool /* autoconnect */, + std::optional<int> /* sink_audio_location */, + std::optional<int> /* source_audio_location */, int /* sink_supported_context_types */, int /* source_supported_context_types */, const std::vector<uint8_t>& /* handles */, const std::vector<uint8_t>& /* sink_pacs */, const std::vector<uint8_t>& /* source_pacs */, const std::vector<uint8_t>& /* ases */, const std::vector<uint8_t>& /* gmap */) { diff --git a/system/test/mock/mock_btif_profile_storage.cc b/system/test/mock/mock_btif_profile_storage.cc index a65103fa8e..51ab3f6e69 100644 --- a/system/test/mock/mock_btif_profile_storage.cc +++ b/system/test/mock/mock_btif_profile_storage.cc @@ -74,7 +74,9 @@ struct btif_storage_remove_leaudio btif_storage_remove_leaudio; struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has; struct btif_storage_set_hearing_aid_acceptlist btif_storage_set_hearing_aid_acceptlist; struct btif_storage_set_hidd btif_storage_set_hidd; -struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location; +struct btif_storage_set_leaudio_sink_audio_location btif_storage_set_leaudio_sink_audio_location; +struct btif_storage_set_leaudio_source_audio_location + btif_storage_set_leaudio_source_audio_location; struct btif_storage_set_leaudio_autoconnect btif_storage_set_leaudio_autoconnect; struct btif_storage_set_leaudio_has_acceptlist btif_storage_set_leaudio_has_acceptlist; struct btif_storage_set_leaudio_has_active_preset btif_storage_set_leaudio_has_active_preset; @@ -257,11 +259,16 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) { inc_func_call_count(__func__); return test::mock::btif_profile_storage::btif_storage_set_hidd(remote_bd_addr); } -void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location, - uint32_t source_location) { +void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) { inc_func_call_count(__func__); - test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location(addr, sink_location, - source_location); + test::mock::btif_profile_storage::btif_storage_set_leaudio_sink_audio_location(addr, + sink_location); +} +void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr, + uint32_t source_location) { + inc_func_call_count(__func__); + test::mock::btif_profile_storage::btif_storage_set_leaudio_source_audio_location(addr, + source_location); } void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect) { inc_func_call_count(__func__); diff --git a/system/test/mock/mock_btif_profile_storage.h b/system/test/mock/mock_btif_profile_storage.h index 1d0bbd7c96..816dd1f33b 100644 --- a/system/test/mock/mock_btif_profile_storage.h +++ b/system/test/mock/mock_btif_profile_storage.h @@ -401,18 +401,25 @@ struct btif_storage_set_hidd { }; extern struct btif_storage_set_hidd btif_storage_set_hidd; -// Name: btif_storage_set_leaudio_audio_location -// Params: const RawAddress& addr, uint32_t sink_location, uint32_t -// source_location Return: void -struct btif_storage_set_leaudio_audio_location { - std::function<void(const RawAddress& addr, uint32_t sink_location, uint32_t source_location)> - body{[](const RawAddress& /* addr */, uint32_t /* sink_location */, - uint32_t /* source_location */) {}}; - void operator()(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) { - body(addr, sink_location, source_location); - } -}; -extern struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location; +// Name: btif_storage_set_leaudio_sink_audio_location +// Params: const RawAddress& addr, uint32_t sink_location, Return: void +struct btif_storage_set_leaudio_sink_audio_location { + std::function<void(const RawAddress& addr, uint32_t sink_location)> body{ + [](const RawAddress& /* addr */, uint32_t /* sink_location */) {}}; + void operator()(const RawAddress& addr, uint32_t sink_location) { body(addr, sink_location); } +}; +extern struct btif_storage_set_leaudio_sink_audio_location + btif_storage_set_leaudio_sink_audio_location; + +// Name: btif_storage_set_leaudio_source_audio_location +// Params: const RawAddress& addr, uint32_t source_location, Return: void +struct btif_storage_set_leaudio_source_audio_location { + std::function<void(const RawAddress& addr, uint32_t source_location)> body{ + [](const RawAddress& /* addr */, uint32_t /* source_location */) {}}; + void operator()(const RawAddress& addr, uint32_t source_location) { body(addr, source_location); } +}; +extern struct btif_storage_set_leaudio_sink_audio_location + btif_storage_set_leaudio_sink_audio_location; // Name: btif_storage_set_leaudio_autoconnect // Params: const RawAddress& addr, bool autoconnect diff --git a/system/test/mock/mock_main_shim_metrics_api.cc b/system/test/mock/mock_main_shim_metrics_api.cc index 2870d67158..259fa2dcfb 100644 --- a/system/test/mock/mock_main_shim_metrics_api.cc +++ b/system/test/mock/mock_main_shim_metrics_api.cc @@ -61,6 +61,12 @@ struct LogMetricLeConnectionLifecycle LogMetricLeConnectionLifecycle; struct LogMetricLeConnectionCompletion LogMetricLeConnectionCompletion; struct LogMetricRfcommConnectionAtClose LogMetricRfcommConnectionAtClose; struct LogMetricLeConnectionRejected LogMetricLeConnectionRejected; +struct LogMetricHfpAgVersion LogMetricHfpAgVersion; +struct LogMetricHfpHfVersion LogMetricHfpHfVersion; +struct LogMetricHfpRfcommChannelFail LogMetricHfpRfcommChannelFail; +struct LogMetricHfpRfcommCollisionFail LogMetricHfpRfcommCollisionFail; +struct LogMetricHfpRfcommAgOpenFail LogMetricHfpRfcommAgOpenFail; +struct LogMetricHfpSlcFail LogMetricHfpSlcFail; } // namespace main_shim_metrics_api } // namespace mock @@ -235,4 +241,34 @@ void bluetooth::shim::LogMetricLeConnectionRejected(bluetooth::hci::Address addr test::mock::main_shim_metrics_api::LogMetricLeConnectionRejected(address); } +void bluetooth::shim::LogMetricHfpAgVersion(bluetooth::hci::Address address, uint16_t version) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpAgVersion(address, version); +} + +void bluetooth::shim::LogMetricHfpHfVersion(bluetooth::hci::Address address, uint16_t version) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpHfVersion(address, version); +} + +void bluetooth::shim::LogMetricHfpRfcommChannelFail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpRfcommChannelFail(address); +} + +void bluetooth::shim::LogMetricHfpRfcommCollisionFail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpRfcommCollisionFail(address); +} + +void bluetooth::shim::LogMetricHfpRfcommAgOpenFail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpRfcommAgOpenFail(address); +} + +void bluetooth::shim::LogMetricHfpSlcFail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricHfpSlcFail(address); +} + // END mockcify generation diff --git a/system/test/mock/mock_main_shim_metrics_api.h b/system/test/mock/mock_main_shim_metrics_api.h index 4fef93db51..8a245bbe37 100644 --- a/system/test/mock/mock_main_shim_metrics_api.h +++ b/system/test/mock/mock_main_shim_metrics_api.h @@ -413,6 +413,67 @@ struct LogMetricLeConnectionRejected { void operator()(bluetooth::hci::Address address) { body(address); } }; extern struct LogMetricLeConnectionRejected LogMetricLeConnectionRejected; + +// Name: LogMetricHfpAgVersion +// Params: bluetooth::hci::Address, uint16_t version +// Returns: void +struct LogMetricHfpAgVersion { + std::function<void(bluetooth::hci::Address address, uint16_t version)> body{ + [](bluetooth::hci::Address /* address */, uint16_t /* version */) {}}; + void operator()(bluetooth::hci::Address address, uint16_t version) { body(address, version); } +}; +extern struct LogMetricHfpAgVersion LogMetricHfpAgVersion; + +// Name: LogMetricHfpHfVersion +// Params: bluetooth::hci::Address, uint16_t version +// Returns: void +struct LogMetricHfpHfVersion { + std::function<void(bluetooth::hci::Address address, uint16_t version)> body{ + [](bluetooth::hci::Address /* address */, uint16_t /* version */) {}}; + void operator()(bluetooth::hci::Address address, uint16_t version) { body(address, version); } +}; +extern struct LogMetricHfpHfVersion LogMetricHfpHfVersion; + +// Name: LogMetricHfpRfcommChannelFail +// Params: bluetooth::hci::Address +// Returns: void +struct LogMetricHfpRfcommChannelFail { + std::function<void(bluetooth::hci::Address address)> body{ + [](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct LogMetricHfpRfcommChannelFail LogMetricHfpRfcommChannelFail; + +// Name: LogMetricHfpRfcommCollisionFail +// Params: bluetooth::hci::Address +// Returns: void +struct LogMetricHfpRfcommCollisionFail { + std::function<void(bluetooth::hci::Address address)> body{ + [](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct LogMetricHfpRfcommCollisionFail LogMetricHfpRfcommCollisionFail; + +// Name: LogMetricHfpRfcommAgOpenFail +// Params: bluetooth::hci::Address +// Returns: void +struct LogMetricHfpRfcommAgOpenFail { + std::function<void(bluetooth::hci::Address address)> body{ + [](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct LogMetricHfpRfcommAgOpenFail LogMetricHfpRfcommAgOpenFail; + +// Name: LogMetricHfpSlcFail +// Params: bluetooth::hci::Address +// Returns: void +struct LogMetricHfpSlcFail { + std::function<void(bluetooth::hci::Address address)> body{ + [](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct LogMetricHfpSlcFail LogMetricHfpSlcFail; + } // namespace main_shim_metrics_api } // namespace mock } // namespace test diff --git a/system/test/mock/mock_stack_a2dp_codec_config.cc b/system/test/mock/mock_stack_a2dp_codec_config.cc index 2e4bc3f517..682900bb10 100644 --- a/system/test/mock/mock_stack_a2dp_codec_config.cc +++ b/system/test/mock/mock_stack_a2dp_codec_config.cc @@ -22,6 +22,7 @@ #include <string> #include "a2dp_codec_api.h" +#include "a2dp_ext.h" #include "bta/av/bta_av_int.h" #include "stack/include/bt_hdr.h" #include "test/common/mock_functions.h" @@ -200,11 +201,6 @@ btav_a2dp_codec_config_t A2dpCodecConfig::getCodecAudioConfig() { btav_a2dp_codec_config_t config; return config; } -btav_a2dp_codec_config_t A2dpCodecConfig::getCodecCapability() { - inc_func_call_count(__func__); - btav_a2dp_codec_config_t config; - return config; -} btav_a2dp_codec_config_t A2dpCodecConfig::getCodecConfig() { inc_func_call_count(__func__); btav_a2dp_codec_config_t config; @@ -319,3 +315,9 @@ void A2dpCodecConfig::setCodecPriority(btav_a2dp_codec_priority_t /* codec_prior } void A2dpCodecConfig::setDefaultCodecPriority() { inc_func_call_count(__func__); } void A2dpCodecs::debug_codec_dump(int /* fd */) { inc_func_call_count(__func__); } +void A2dpCodecConfigExt::setCodecConfig( + btav_a2dp_codec_config_t /*codec_parameters*/, + uint8_t const /*codec_config*/[AVDT_CODEC_SIZE], + std::vector<uint8_t> const& /*vendor_specific_parameters*/) { + inc_func_call_count(__func__); +} diff --git a/system/test/mock/mock_stack_metrics_logging.cc b/system/test/mock/mock_stack_metrics_logging.cc index 227bc7fd85..751fcc3794 100644 --- a/system/test/mock/mock_stack_metrics_logging.cc +++ b/system/test/mock/mock_stack_metrics_logging.cc @@ -57,6 +57,12 @@ struct log_le_device_in_accept_list log_le_device_in_accept_list; struct log_le_connection_lifecycle log_le_connection_lifecycle; struct log_le_connection_completion log_le_connection_completion; struct log_le_connection_rejected log_le_connection_rejected; +struct log_hfp_ag_version log_hfp_ag_version; +struct log_hfp_hf_version log_hfp_hf_version; +struct log_hfp_rfcomm_channel_fail log_hfp_rfcomm_channel_fail; +struct log_hfp_rfcomm_collision_fail log_hfp_rfcomm_collision_fail; +struct log_hfp_rfcomm_ag_open_fail log_hfp_rfcomm_ag_open_fail; +struct log_hfp_slc_fail log_hfp_slc_fail; } // namespace stack_metrics_logging } // namespace mock @@ -166,4 +172,34 @@ void log_le_connection_rejected(bluetooth::hci::Address address) { inc_func_call_count(__func__); test::mock::stack_metrics_logging::log_le_connection_rejected(address); } + +void log_hfp_ag_version(bluetooth::hci::Address address, uint16_t version) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_ag_version(address, version); +} + +void log_hfp_hf_version(bluetooth::hci::Address address, uint16_t version) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_hf_version(address, version); +} + +void log_hfp_rfcomm_channel_fail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_rfcomm_channel_fail(address); +} + +void log_hfp_rfcomm_collision_fail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_rfcomm_collision_fail(address); +} + +void log_hfp_rfcomm_ag_open_fail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_rfcomm_ag_open_fail(address); +} + +void log_hfp_slc_fail(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_hfp_slc_fail(address); +} // END mockcify generation diff --git a/system/test/mock/mock_stack_metrics_logging.h b/system/test/mock/mock_stack_metrics_logging.h index 03b5b4645d..d807c1f761 100644 --- a/system/test/mock/mock_stack_metrics_logging.h +++ b/system/test/mock/mock_stack_metrics_logging.h @@ -255,6 +255,50 @@ struct log_le_connection_rejected { extern struct log_le_connection_rejected log_le_connection_rejected; +// Name: log_hfp_ag_version +struct log_hfp_ag_version { + std::function<void(bluetooth::hci::Address, uint16_t)> body{ + [](bluetooth::hci::Address /* address */, uint16_t /* version */) {}}; + void operator()(bluetooth::hci::Address address, uint16_t version) { body(address, version); } +}; +extern struct log_hfp_ag_version log_hfp_ag_version; + +// Name: log_hfp_hf_version +struct log_hfp_hf_version { + std::function<void(bluetooth::hci::Address, uint16_t)> body{ + [](bluetooth::hci::Address /* address */, uint16_t /* version */) {}}; + void operator()(bluetooth::hci::Address address, uint16_t version) { body(address, version); } +}; +extern struct log_hfp_hf_version log_hfp_hf_version; + +// Name: log_hfp_rfcomm_channel_fail +struct log_hfp_rfcomm_channel_fail { + std::function<void(bluetooth::hci::Address)> body{[](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct log_hfp_rfcomm_channel_fail log_hfp_rfcomm_channel_fail; + +// Name: log_hfp_rfcomm_collision_fail +struct log_hfp_rfcomm_collision_fail { + std::function<void(bluetooth::hci::Address)> body{[](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct log_hfp_rfcomm_collision_fail log_hfp_rfcomm_collision_fail; + +// Name: log_hfp_rfcomm_ag_open_fail +struct log_hfp_rfcomm_ag_open_fail { + std::function<void(bluetooth::hci::Address)> body{[](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct log_hfp_rfcomm_ag_open_fail log_hfp_rfcomm_ag_open_fail; + +// Name: log_hfp_slc_fail +struct log_hfp_slc_fail { + std::function<void(bluetooth::hci::Address)> body{[](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; +extern struct log_hfp_slc_fail log_hfp_slc_fail; + } // namespace stack_metrics_logging } // namespace mock } // namespace test |