diff options
420 files changed, 6929 insertions, 9473 deletions
diff --git a/Android.bp b/Android.bp index eb330fa827..d0d7a7db40 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", @@ -173,6 +174,7 @@ java_defaults { "-Xep:ReferenceEquality:ERROR", "-Xep:ReturnAtTheEndOfVoidFunction:ERROR", "-Xep:ReturnFromVoid:ERROR", + "-Xep:SelfAssertion:ERROR", "-Xep:StaticAssignmentInConstructor:ERROR", "-Xep:StaticGuardedByInstance:ERROR", "-Xep:StringCaseLocaleUsage: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/aidl/android/bluetooth/IBluetoothHeadset.aidl b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl index 49a5cd6650..3b3292cd16 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl @@ -69,8 +69,6 @@ interface IBluetoothHeadset { @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE,android.Manifest.permission.BLUETOOTH_PRIVILEGED})") boolean stopScoUsingVirtualVoiceCall(in AttributionSource attributionSource); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE})") - void phoneStateChanged(int numActive, int numHeld, int callState, String number, int type, String name, in AttributionSource attributionSource); - @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE})") boolean setActiveDevice(in BluetoothDevice device, in AttributionSource attributionSource); @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)") BluetoothDevice getActiveDevice(in AttributionSource attributionSource); diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp index 3b0411135c..a003f5b579 100644 --- a/android/app/jni/com_android_bluetooth_le_audio.cpp +++ b/android/app/jni/com_android_bluetooth_le_audio.cpp @@ -235,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); @@ -245,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); @@ -268,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( diff --git a/android/app/lib-lint-baseline.xml b/android/app/lib-lint-baseline.xml index 0af37b746f..c2a527c3fc 100644 --- a/android/app/lib-lint-baseline.xml +++ b/android/app/lib-lint-baseline.xml @@ -129,7 +129,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1229" + line="1228" column="35"/> </issue> @@ -140,7 +140,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1240" + line="1239" column="35"/> </issue> @@ -151,7 +151,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1251" + line="1250" column="35"/> </issue> @@ -162,7 +162,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1262" + line="1261" column="35"/> </issue> @@ -173,7 +173,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1277" + line="1276" column="35"/> </issue> @@ -184,7 +184,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1288" + line="1287" column="35"/> </issue> @@ -195,7 +195,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1295" + line="1294" column="35"/> </issue> @@ -206,7 +206,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1306" + line="1305" column="35"/> </issue> @@ -217,7 +217,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1511" + line="1510" column="35"/> </issue> @@ -228,7 +228,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1522" + line="1521" column="35"/> </issue> @@ -239,7 +239,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1759" + line="1758" column="35"/> </issue> @@ -250,7 +250,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java" - line="1770" + line="1769" column="35"/> </issue> @@ -305,7 +305,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java" - line="82" + line="81" column="35"/> </issue> @@ -426,7 +426,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="824" + line="807" column="9"/> </issue> @@ -437,7 +437,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="824" + line="807" column="9"/> </issue> @@ -448,7 +448,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="824" + line="807" column="9"/> </issue> @@ -459,7 +459,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="824" + line="807" column="9"/> </issue> @@ -470,7 +470,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java" - line="922" + line="921" column="9"/> </issue> @@ -492,7 +492,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java" - line="554" + line="555" column="13"/> </issue> @@ -569,7 +569,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java" - line="801" + line="802" column="33"/> </issue> @@ -580,7 +580,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java" - line="809" + line="810" column="26"/> </issue> @@ -591,7 +591,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java" - line="822" + line="823" column="33"/> </issue> @@ -602,7 +602,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java" - line="842" + line="843" column="26"/> </issue> @@ -613,7 +613,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java" - line="917" + line="918" column="45"/> </issue> @@ -624,7 +624,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="1155" + line="1149" column="20"/> </issue> @@ -635,7 +635,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="1160" + line="1154" column="20"/> </issue> @@ -646,7 +646,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="2004" + line="1996" column="43"/> </issue> @@ -657,7 +657,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="2009" + line="2001" column="45"/> </issue> @@ -668,7 +668,7 @@ errorLine2=" ~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="2013" + line="2005" column="34"/> </issue> @@ -679,7 +679,7 @@ errorLine2=" ~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="2245" + line="2237" column="33"/> </issue> @@ -690,7 +690,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="7279" + line="7293" column="28"/> </issue> @@ -701,7 +701,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="7281" + line="7295" column="28"/> </issue> @@ -1020,7 +1020,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java" - line="1262" + line="1261" column="49"/> </issue> @@ -1031,7 +1031,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java" - line="103" + line="104" column="49"/> </issue> @@ -1042,7 +1042,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java" - line="152" + line="153" column="45"/> </issue> @@ -1053,7 +1053,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java" - line="277" + line="276" column="41"/> </issue> @@ -1075,7 +1075,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java" - line="646" + line="656" column="28"/> </issue> @@ -1086,7 +1086,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java" - line="683" + line="693" column="28"/> </issue> @@ -1097,7 +1097,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java" - line="713" + line="723" column="28"/> </issue> @@ -1108,7 +1108,7 @@ errorLine2=" ~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java" - line="859" + line="855" column="63"/> </issue> @@ -1130,7 +1130,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java" - line="106" + line="105" column="26"/> </issue> @@ -1141,7 +1141,7 @@ errorLine2=" ~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java" - line="176" + line="177" column="26"/> </issue> @@ -1412,12 +1412,12 @@ <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" mHandler = new Handler(headsetService.getStateMachinesThreadLooper());" - errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> + errorLine1=" mHandler = new Handler(headsetService.getStateMachinesThreadLooper());" + errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java" - line="86" - column="51"/> + line="91" + column="47"/> </issue> <issue @@ -1427,7 +1427,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="272" + line="273" column="38"/> </issue> @@ -1438,7 +1438,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="274" + line="275" column="42"/> </issue> @@ -1449,7 +1449,7 @@ errorLine2=" ~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="287" + line="288" column="26"/> </issue> @@ -1460,7 +1460,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="440" + line="436" column="42"/> </issue> @@ -1471,7 +1471,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="512" + line="508" column="30"/> </issue> @@ -1482,7 +1482,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="906" + line="866" column="48"/> </issue> @@ -1493,7 +1493,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="954" + line="914" column="48"/> </issue> @@ -1504,29 +1504,18 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="974" + line="934" column="34"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" devices.add(stateMachine.getDevice());" - errorLine2=" ~~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="975" - column="46"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" errorLine1=" return stateMachine.getConnectionState();" errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1022" + line="982" column="33"/> </issue> @@ -1537,7 +1526,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1136" + line="1096" column="38"/> </issue> @@ -1548,7 +1537,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1138" + line="1098" column="42"/> </issue> @@ -1559,7 +1548,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1154" + line="1114" column="48"/> </issue> @@ -1570,7 +1559,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1228" + line="1188" column="48"/> </issue> @@ -1581,7 +1570,7 @@ errorLine2=" ~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1283" + line="1243" column="26"/> </issue> @@ -1592,7 +1581,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1419" + line="1379" column="30"/> </issue> @@ -1603,7 +1592,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1462" + line="1422" column="35"/> </issue> @@ -1611,21 +1600,10 @@ id="VisibleForTests" message="This method should only be accessed from tests or within private scope" errorLine1=" if (mSystemInterface.isInCall() || mSystemInterface.isRinging()) {" - errorLine2=" ~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1473" - column="34"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" - errorLine1=" if (mSystemInterface.isInCall() || mSystemInterface.isRinging()) {" errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1473" + line="1433" column="65"/> </issue> @@ -1636,7 +1614,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1491" + line="1451" column="38"/> </issue> @@ -1647,7 +1625,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1530" + line="1490" column="42"/> </issue> @@ -1658,29 +1636,18 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1589" + line="1549" column="30"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" devices.add(stateMachine.getDevice());" - errorLine2=" ~~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1614" - column="46"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" errorLine1=" if (mSystemInterface.getVoiceRecognitionWakeLock().isHeld()) {" errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1824" + line="1784" column="38"/> </issue> @@ -1691,7 +1658,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1826" + line="1786" column="42"/> </issue> @@ -1702,7 +1669,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1908" + line="1868" column="35"/> </issue> @@ -1713,7 +1680,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1921" + line="1881" column="35"/> </issue> @@ -1724,7 +1691,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1922" + line="1882" column="34"/> </issue> @@ -1735,7 +1702,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1949" + line="1909" column="38"/> </issue> @@ -1746,7 +1713,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1951" + line="1911" column="42"/> </issue> @@ -1757,140 +1724,151 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="1972" + line="1932" column="35"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" int connectionState = stateMachine.getConnectionState();" - errorLine2=" ~~~~~~~~~~~~~~~~~~"> + errorLine1=" boolean isCallIdleBefore = mSystemInterface.isCallIdle();" + errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2119" - column="48"/> + line="1984" + column="65"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" if (mVoiceRecognitionStarted || mVirtualCallStarted || !mSystemInterface.isCallIdle()) {" - errorLine2=" ~~~~~~~~~~"> + errorLine1=" mSystemInterface.getHeadsetPhoneState().setNumActiveCall(numActive);" + errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2267" - column="86"/> + line="1985" + column="38"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" + mSystemInterface.isCallIdle());" - errorLine2=" ~~~~~~~~~~"> + errorLine1=" mSystemInterface.getHeadsetPhoneState().setNumHeldCall(numHeld);" + errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2275" - column="52"/> + line="1986" + column="38"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" return mSystemInterface.isInCall()" - errorLine2=" ~~~~~~~~"> + errorLine1=" mSystemInterface.getHeadsetPhoneState().setCallState(callState);" + errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2303" - column="33"/> + line="1987" + column="38"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" || (mSystemInterface.isRinging() && isInbandRingingEnabled());" - errorLine2=" ~~~~~~~~~"> + errorLine1=" && !mSystemInterface.isCallIdle()" + errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2304" - column="38"/> + line="1991" + column="50"/> </issue> <issue id="VisibleForTests" - message="This method should only be accessed from tests or within package private scope" - errorLine1=" if (a2dpService != null && a2dpService.okToConnect(device, true)) {" - errorLine2=" ~~~~~~~~~~~"> + message="This method should only be accessed from tests or within private scope" + errorLine1=" && mSystemInterface.isCallIdle()" + errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2534" - column="56"/> + line="2009" + column="49"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" + mSystemInterface.isInCall()" - errorLine2=" ~~~~~~~~"> + errorLine1=" int connectionState = stateMachine.getConnectionState();" + errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2599" + line="2078" column="48"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" + mSystemInterface.isRinging()" - errorLine2=" ~~~~~~~~~"> + errorLine1=" if (mVoiceRecognitionStarted || mVirtualCallStarted || !mSystemInterface.isCallIdle()) {" + errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2603" - column="48"/> + line="2226" + column="86"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" ProfileService.println(sb, "Telecom.isInCall(): " + mSystemInterface.isInCall());" - errorLine2=" ~~~~~~~~"> + errorLine1=" + mSystemInterface.isCallIdle());" + errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2681" - column="82"/> + line="2234" + column="52"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" ProfileService.println(sb, "Telecom.isRinging(): " + mSystemInterface.isRinging());" - errorLine2=" ~~~~~~~~~"> + errorLine1=" || (mSystemInterface.isRinging() && isInbandRingingEnabled());" + errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2682" - column="83"/> + line="2263" + column="38"/> + </issue> + + <issue + id="VisibleForTests" + message="This method should only be accessed from tests or within package private scope" + errorLine1=" if (a2dpService != null && a2dpService.okToConnect(device, true)) {" + errorLine2=" ~~~~~~~~~~~"> + <location + file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" + line="2493" + column="56"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" sb, "==== StateMachine for " + stateMachine.getDevice() + " ====");" - errorLine2=" ~~~~~~~~~"> + errorLine1=" + mSystemInterface.isRinging()" + errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2685" - column="69"/> + line="2562" + column="48"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" boolean result = mNativeInterface.enableSwb(swbCodec, enable, device);" - errorLine2=" ~~~~~~~~~"> + errorLine1=" ProfileService.println(sb, "Telecom.isRinging(): " + mSystemInterface.isRinging());" + errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java" - line="2694" - column="43"/> + line="2641" + column="83"/> </issue> <issue @@ -1900,7 +1878,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="210" + line="208" column="34"/> </issue> @@ -1911,7 +1889,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="214" + line="212" column="30"/> </issue> @@ -1922,7 +1900,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="349" + line="347" column="29"/> </issue> @@ -1933,7 +1911,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="374" + line="372" column="29"/> </issue> @@ -1944,7 +1922,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="529" + line="527" column="39"/> </issue> @@ -1955,7 +1933,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="590" + line="588" column="43"/> </issue> @@ -1966,7 +1944,7 @@ errorLine2=" ~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="665" + line="663" column="47"/> </issue> @@ -1977,7 +1955,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="847" + line="845" column="46"/> </issue> @@ -1988,7 +1966,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="851" + line="849" column="46"/> </issue> @@ -1999,7 +1977,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1023" + line="1021" column="47"/> </issue> @@ -2010,7 +1988,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1039" + line="1037" column="47"/> </issue> @@ -2021,7 +1999,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1049" + line="1047" column="43"/> </issue> @@ -2032,7 +2010,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1062" + line="1060" column="38"/> </issue> @@ -2043,7 +2021,7 @@ errorLine2=" ~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1075" + line="1073" column="42"/> </issue> @@ -2054,7 +2032,7 @@ errorLine2=" ~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1083" + line="1081" column="38"/> </issue> @@ -2065,7 +2043,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1095" + line="1093" column="42"/> </issue> @@ -2076,7 +2054,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1115" + line="1113" column="46"/> </issue> @@ -2087,7 +2065,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1149" + line="1147" column="46"/> </issue> @@ -2098,18 +2076,7 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1152" - column="46"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" - errorLine1=" mSystemInterface.sendDtmf(event.valueInt, event.device);" - errorLine2=" ~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1161" + line="1150" column="46"/> </issue> @@ -2120,18 +2087,18 @@ errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1255" + line="1253" column="34"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" mSystemInterface.queryPhoneState();" + errorLine1=" mSystemInterface.queryPhoneState(mHeadsetService);" errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1276" + line="1274" column="34"/> </issue> @@ -2142,7 +2109,7 @@ errorLine2=" ~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1309" + line="1307" column="47"/> </issue> @@ -2153,7 +2120,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1336" + line="1334" column="53"/> </issue> @@ -2164,7 +2131,7 @@ errorLine2=" ~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1347" + line="1345" column="43"/> </issue> @@ -2175,7 +2142,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1379" + line="1377" column="47"/> </issue> @@ -2186,7 +2153,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1395" + line="1393" column="47"/> </issue> @@ -2197,7 +2164,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1583" + line="1581" column="47"/> </issue> @@ -2208,7 +2175,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1613" + line="1611" column="46"/> </issue> @@ -2219,7 +2186,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1926" + line="1923" column="30"/> </issue> @@ -2230,7 +2197,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1933" + line="1930" column="34"/> </issue> @@ -2241,7 +2208,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1941" + line="1938" column="34"/> </issue> @@ -2252,7 +2219,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1948" + line="1945" column="34"/> </issue> @@ -2263,7 +2230,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1960" + line="1957" column="30"/> </issue> @@ -2274,7 +2241,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1969" + line="1966" column="34"/> </issue> @@ -2285,7 +2252,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1973" + line="1970" column="34"/> </issue> @@ -2296,7 +2263,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1975" + line="1972" column="34"/> </issue> @@ -2307,7 +2274,7 @@ errorLine2=" ~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="1978" + line="1975" column="30"/> </issue> @@ -2318,7 +2285,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2108" + line="2103" column="63"/> </issue> @@ -2329,7 +2296,7 @@ errorLine2=" ~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2146" + line="2141" column="26"/> </issue> @@ -2340,7 +2307,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2413" + line="2406" column="26"/> </issue> @@ -2351,7 +2318,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2474" + line="2467" column="26"/> </issue> @@ -2362,7 +2329,7 @@ errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2592" + line="2584" column="30"/> </issue> @@ -2373,29 +2340,18 @@ errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2593" + line="2585" column="30"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" } else if (mSystemInterface.isInCall()) {" - errorLine2=" ~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2594" - column="37"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" errorLine1=" mSystemInterface.hangupCall(device);" errorLine2=" ~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2601" + line="2593" column="34"/> </issue> @@ -2406,7 +2362,7 @@ errorLine2=" ~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2604" + line="2596" column="35"/> </issue> @@ -2417,7 +2373,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2731" + line="2723" column="26"/> </issue> @@ -2428,7 +2384,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java" - line="2731" + line="2723" column="49"/> </issue> @@ -2439,7 +2395,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java" - line="623" + line="624" column="51"/> </issue> @@ -2450,7 +2406,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java" - line="66" + line="67" column="12"/> </issue> @@ -2461,7 +2417,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java" - line="67" + line="68" column="16"/> </issue> @@ -2472,7 +2428,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java" - line="68" + line="69" column="17"/> </issue> @@ -2483,7 +2439,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="196" + line="204" column="5"/> </issue> @@ -2494,51 +2450,18 @@ errorLine2=" ~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="540" + line="593" column="29"/> </issue> <issue id="VisibleForTests" message="This method should only be accessed from tests or within private scope" - errorLine1=" LeAudioTmapGattServer.TMAP_ROLE_FLAG_CG | LeAudioTmapGattServer.TMAP_ROLE_FLAG_UMS;" - errorLine2=" ~~~~~~~~~~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="633" - column="39"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" - errorLine1=" LeAudioTmapGattServer.TMAP_ROLE_FLAG_CG | LeAudioTmapGattServer.TMAP_ROLE_FLAG_UMS;" - errorLine2=" ~~~~~~~~~~~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="633" - column="81"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" - errorLine1=" mTmapRoleMask |= LeAudioTmapGattServer.TMAP_ROLE_FLAG_BMS;" - errorLine2=" ~~~~~~~~~~~~~~~~~~"> - <location - file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="646" - column="52"/> - </issue> - - <issue - id="VisibleForTests" - message="This method should only be accessed from tests or within private scope" errorLine1=" mTmapGattServer.stop();" errorLine2=" ~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="706" + line="683" column="29"/> </issue> @@ -2549,7 +2472,7 @@ errorLine2=" ~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="2808" + line="2775" column="52"/> </issue> @@ -2560,7 +2483,7 @@ errorLine2=" ~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="3541" + line="3516" column="52"/> </issue> @@ -2571,7 +2494,7 @@ errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java" - line="4790" + line="4765" column="29"/> </issue> @@ -2670,7 +2593,7 @@ errorLine2=" ~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java" - line="104" + line="103" column="31"/> </issue> @@ -2758,7 +2681,7 @@ errorLine2=" ~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="429" + line="467" column="35"/> </issue> @@ -2769,7 +2692,7 @@ errorLine2=" ~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java" - line="216" + line="201" column="27"/> </issue> @@ -2780,7 +2703,7 @@ errorLine2=" ~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java" - line="575" + line="574" column="35"/> </issue> @@ -2802,7 +2725,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="6560" + line="6561" column="17"/> </issue> @@ -2813,7 +2736,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="235" + line="273" column="13"/> </issue> @@ -2824,7 +2747,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java" - line="418" + line="456" column="25"/> </issue> @@ -2835,7 +2758,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java" - line="177" + line="162" column="13"/> </issue> @@ -2846,7 +2769,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java" - line="325" + line="310" column="13"/> </issue> @@ -2857,7 +2780,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java" - line="559" + line="558" column="25"/> </issue> @@ -2901,7 +2824,7 @@ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java" - line="627" + line="628" column="5"/> </issue> @@ -2912,7 +2835,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java" - line="759" + line="755" column="9"/> </issue> @@ -2989,7 +2912,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java" - line="229" + line="230" column="13"/> </issue> @@ -3000,7 +2923,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java" - line="370" + line="365" column="13"/> </issue> @@ -3022,7 +2945,7 @@ errorLine2=" ^"> <location file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hid/HidHostService.java" - line="348" + line="335" column="13"/> </issue> 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/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/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java index 559578dc71..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; @@ -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/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 8d8690a4bb..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); @@ -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); } } @@ -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 eac5f2644b..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); 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 c84ec49689..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,13 +19,16 @@ 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; import static com.android.bluetooth.flags.Flags.leaudioBigDependsOnAudioState; import static com.android.bluetooth.flags.Flags.leaudioBroadcastApiGetLocalMetadata; -import static com.android.bluetooth.flags.Flags.leaudioBroadcastAssistantPeripheralEntrustment; import static com.android.bluetooth.flags.Flags.leaudioBroadcastPreventResumeInterruption; import static com.android.bluetooth.flags.Flags.leaudioBroadcastResyncHelper; import static com.android.bluetooth.flags.Flags.leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator; @@ -84,12 +87,10 @@ import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; import java.time.Duration; -import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; -import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -176,7 +177,6 @@ public class BassClientService extends ProfileService { private final Map<BluetoothDevice, Pair<Integer, Integer>> mSinksWaitingForPast = new HashMap<>(); private final Map<Integer, PauseType> mPausedBroadcastIds = new HashMap<>(); - private final Deque<AddSourceData> mPendingAddSources = new ArrayDeque<>(); private final Map<Integer, HashSet<BluetoothDevice>> mLocalBroadcastReceivers = new ConcurrentHashMap<>(); private final BassScanCallbackWrapper mBassScanCallback = new BassScanCallbackWrapper(); @@ -1618,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) { @@ -1678,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; @@ -1699,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; } @@ -1761,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; @@ -1781,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(); } @@ -1808,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(); @@ -1858,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; @@ -3162,43 +3161,34 @@ public class BassClientService extends ProfileService { return; } - if (leaudioBroadcastAssistantPeripheralEntrustment()) { - if (isLocalBroadcast(sourceMetadata)) { - LeAudioService leAudioService = mServiceFactory.getLeAudioService(); - if (leaudioBigDependsOnAudioState()) { - if (leAudioService == null - || !(leAudioService.isPaused(sourceMetadata.getBroadcastId()) - || leAudioService.isPlaying(sourceMetadata.getBroadcastId()))) { - Log.w(TAG, "addSource: Local source can't be add"); + if (isLocalBroadcast(sourceMetadata)) { + LeAudioService leAudioService = mServiceFactory.getLeAudioService(); + if (leaudioBigDependsOnAudioState()) { + if (leAudioService == null + || !(leAudioService.isPaused(sourceMetadata.getBroadcastId()) + || leAudioService.isPlaying(sourceMetadata.getBroadcastId()))) { + Log.w(TAG, "addSource: Local source can't be add"); - mCallbacks.notifySourceAddFailed( - sink, - sourceMetadata, - BluetoothStatusCodes.ERROR_LOCAL_NOT_ENOUGH_RESOURCES); + mCallbacks.notifySourceAddFailed( + sink, + sourceMetadata, + BluetoothStatusCodes.ERROR_LOCAL_NOT_ENOUGH_RESOURCES); - return; - } - } else { - if (leAudioService == null - || !leAudioService.isPlaying(sourceMetadata.getBroadcastId())) { - Log.w(TAG, "addSource: Local source can't be add"); + return; + } + } else { + if (leAudioService == null + || !leAudioService.isPlaying(sourceMetadata.getBroadcastId())) { + Log.w(TAG, "addSource: Local source can't be add"); - mCallbacks.notifySourceAddFailed( - sink, - sourceMetadata, - BluetoothStatusCodes.ERROR_LOCAL_NOT_ENOUGH_RESOURCES); + mCallbacks.notifySourceAddFailed( + sink, + sourceMetadata, + BluetoothStatusCodes.ERROR_LOCAL_NOT_ENOUGH_RESOURCES); - return; - } + return; } } - } else { - if (!isAllowedToAddSource()) { - Log.d(TAG, "Add source to pending list"); - mPendingAddSources.push(new AddSourceData(sink, sourceMetadata, isGroupOp)); - - return; - } } // Remove pausedBroadcastId in case that broadcast was paused before. @@ -3728,13 +3718,12 @@ public class BassClientService extends ProfileService { } /** - * Stops or suspends source receivers for the given broadcast ID + * Suspends source receivers for the given broadcast ID * * @param broadcastId The broadcast ID for which the receivers should be stopped or suspended - * @param store Determines whether the operation is a suspension (true) or a stop (false) */ - private void stopOrSuspendSourceReceivers(int broadcastId, boolean store) { - log("stopSourceReceivers broadcastId: " + broadcastId + ", store: " + store); + private void suspendSourceReceivers(int broadcastId) { + log("stopSourceReceivers broadcastId: " + broadcastId); Map<BluetoothDevice, Integer> sourcesToRemove = new HashMap<>(); HashSet<Integer> broadcastIdsToStopMonitoring = new HashSet<>(); @@ -3754,10 +3743,8 @@ public class BassClientService extends ProfileService { continue; } - if (store) { - sEventLogger.logd(TAG, "Add broadcast sink to paused cache: " + device); - mPausedBroadcastSinks.add(device); - } + sEventLogger.logd(TAG, "Add broadcast sink to paused cache: " + device); + mPausedBroadcastSinks.add(device); sourcesToRemove.put(device, receiveState.getSourceId()); } @@ -3779,12 +3766,8 @@ public class BassClientService extends ProfileService { sourcesToRemove.put(device, receiveState.getSourceId()); } - if (store) { - sEventLogger.logd(TAG, "Add broadcast sink to paused cache: " + device); - mPausedBroadcastSinks.add(device); - } else { - mPausedBroadcastSinks.remove(device); - } + sEventLogger.logd(TAG, "Add broadcast sink to paused cache: " + device); + mPausedBroadcastSinks.add(device); } } } @@ -3805,25 +3788,6 @@ public class BassClientService extends ProfileService { } } - private boolean isAllowedToAddSource() { - /* Check if should wait for status update */ - if (mUnicastSourceStreamStatus.isEmpty()) { - /* Assistant was not active, inform about activation */ - if (!mIsAssistantActive) { - mIsAssistantActive = true; - - LeAudioService leAudioService = mServiceFactory.getLeAudioService(); - if (leAudioService != null) { - leAudioService.activeBroadcastAssistantNotification(true); - } - } - - return false; - } - - return mUnicastSourceStreamStatus.get() == STATUS_LOCAL_STREAM_SUSPENDED; - } - /** Return true if there is any non primary device receiving broadcast */ private boolean isAudioSharingModeOn(Integer broadcastId) { HashSet<BluetoothDevice> devices = mLocalBroadcastReceivers.get(broadcastId); @@ -4127,25 +4091,23 @@ public class BassClientService extends ProfileService { } /** Request receivers to suspend broadcast sources synchronization */ - public void suspendReceiversSourceSynchronization(int broadcastId) { + @VisibleForTesting + void suspendReceiversSourceSynchronization(int broadcastId) { sEventLogger.logd(TAG, "Suspend receivers source synchronization: " + broadcastId); - stopOrSuspendSourceReceivers(broadcastId, /* store */ true); + suspendSourceReceivers(broadcastId); } /** Request all receivers to suspend broadcast sources synchronization */ - public void suspendAllReceiversSourceSynchronization() { + @VisibleForTesting + void suspendAllReceiversSourceSynchronization() { sEventLogger.logd(TAG, "Suspend all receivers source synchronization"); - stopOrSuspendSourceReceivers(BassConstants.INVALID_BROADCAST_ID, /* store */ true); + suspendSourceReceivers(BassConstants.INVALID_BROADCAST_ID); } /** Request receivers to stop broadcast sources synchronization and remove them */ public void stopReceiversSourceSynchronization(int broadcastId) { sEventLogger.logd(TAG, "Stop receivers source synchronization: " + broadcastId); - if (leaudioBroadcastAssistantPeripheralEntrustment()) { - stopSourceReceivers(broadcastId); - } else { - stopOrSuspendSourceReceivers(broadcastId, /* store */ false); - } + stopSourceReceivers(broadcastId); } /** Request receivers to resume broadcast source synchronization */ @@ -4161,8 +4123,7 @@ public class BassClientService extends ProfileService { for (BluetoothLeBroadcastMetadata metadata : entry.values()) { - if (leaudioBroadcastAssistantPeripheralEntrustment() - || leaudioBroadcastResyncHelper()) { + if (leaudioBroadcastResyncHelper()) { if (metadata == null) { Log.w( TAG, @@ -4271,17 +4232,13 @@ public class BassClientService extends ProfileService { if ((leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator() && hasPrimaryDeviceManagedExternalBroadcast()) || (!leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator() - && areReceiversReceivingOnlyExternalBroadcast(getConnectedDevices()))) { - if (leaudioBroadcastAssistantPeripheralEntrustment()) { - cacheSuspendingSources(BassConstants.INVALID_BROADCAST_ID); - List<Pair<BluetoothLeBroadcastReceiveState, BluetoothDevice>> sourcesToStop = - getReceiveStateDevicePairs(BassConstants.INVALID_BROADCAST_ID); - for (Pair<BluetoothLeBroadcastReceiveState, BluetoothDevice> pair : - sourcesToStop) { - stopBigMonitoring(pair.first.getBroadcastId(), /* hostInitiated */ true); - } - } else { - suspendAllReceiversSourceSynchronization(); + && areReceiversReceivingOnlyExternalBroadcast(getConnectedDevices()))) { + cacheSuspendingSources(BassConstants.INVALID_BROADCAST_ID); + List<Pair<BluetoothLeBroadcastReceiveState, BluetoothDevice>> sourcesToStop = + getReceiveStateDevicePairs(BassConstants.INVALID_BROADCAST_ID); + for (Pair<BluetoothLeBroadcastReceiveState, BluetoothDevice> pair : + sourcesToStop) { + stopBigMonitoring(pair.first.getBroadcastId(), /* hostInitiated */ true); } } if (!leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator()) { @@ -4298,18 +4255,6 @@ public class BassClientService extends ProfileService { if (!mPausedBroadcastSinks.isEmpty()) { resumeReceiversSourceSynchronization(); } - - if (!leaudioBroadcastAssistantPeripheralEntrustment()) { - /* Add pending sources if there are some */ - while (!mPendingAddSources.isEmpty()) { - AddSourceData addSourceData = mPendingAddSources.pop(); - - addSource( - addSourceData.mSink, - addSourceData.mSourceMetadata, - addSourceData.mIsGroupOp); - } - } } else if (status == STATUS_LOCAL_STREAM_STREAMING) { Log.d(TAG, "Ignore STREAMING source status"); } else if (status == STATUS_LOCAL_STREAM_REQUESTED_NO_CONTEXT_VALIDATE) { @@ -4922,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"); } @@ -4931,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); } } @@ -5001,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); } @@ -5043,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 24af973437..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; @@ -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); @@ -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 963ff62337..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; } } @@ -668,21 +672,21 @@ class AdapterProperties { } private static boolean validateProfileConnectionState(int state) { - return (state == BluetoothProfile.STATE_DISCONNECTED - || state == BluetoothProfile.STATE_CONNECTING - || state == BluetoothProfile.STATE_CONNECTED - || state == BluetoothProfile.STATE_DISCONNECTING); + 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); @@ -691,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; } @@ -706,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 { @@ -716,7 +719,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: if (mProfilesConnected > 0) { mProfilesConnected--; } else { @@ -726,7 +729,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: if (mProfilesDisconnecting > 0) { mProfilesDisconnecting--; } else { @@ -738,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: @@ -785,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 { diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java index e180e8ba87..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; @@ -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); } @@ -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); } diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java index 1411961bee..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; @@ -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); } } diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java index ce55d94619..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); 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 3cf3222bf1..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; @@ -348,6 +350,7 @@ public class RemoteDevices { @VisibleForTesting int mDeviceType; @VisibleForTesting ParcelUuid[] mUuidsBrEdr; @VisibleForTesting ParcelUuid[] mUuidsLe; + @VisibleForTesting boolean mHfpBatteryIndicator = false; private BluetoothSinkAudioPolicy mAudioPolicy; DeviceProperties() { @@ -743,6 +746,21 @@ public class RemoteDevices { } } + /** + * @param hfpBatteryIndicator is set to true based on the HF battery indicator support + * received from AT+BIND command and set to false in disconnect path. + */ + void setHfpBatteryIndicatorStatus(boolean hfpBatteryIndicator) { + this.mHfpBatteryIndicator = hfpBatteryIndicator; + } + + /** + * @return mHfpBatteryIndicator + */ + boolean isHfpBatteryIndicatorEnabled() { + return mHfpBatteryIndicator; + } + void setBatteryLevelFromHfp(int batteryLevel) { synchronized (mObject) { if (mBatteryLevelFromHfp == batteryLevel) { @@ -956,6 +974,9 @@ public class RemoteDevices { deviceProperties.setBatteryLevelFromHfp(BluetoothDevice.BATTERY_LEVEL_UNKNOWN); } + if (Flags.enableBatteryLevelUpdateOnlyThroughHfIndicator()) { + deviceProperties.setHfpBatteryIndicatorStatus(false); + } int newBatteryLevel = deviceProperties.getBatteryLevel(); if (prevBatteryLevel == newBatteryLevel) { debugLog("Battery level was not changed due to reset, device=" + device); @@ -1386,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); } @@ -1537,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, @@ -1610,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 = @@ -1689,11 +1716,28 @@ 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); } } + /** Handle Indicator status events from Hands-free. */ + public void handleHfIndicatorStatus( + BluetoothDevice device, int indicatorId, boolean indicatorStatus) { + mMainHandler.post(() -> onHfIndicatorStatus(device, indicatorId, indicatorStatus)); + } + + @VisibleForTesting + void onHfIndicatorStatus(BluetoothDevice device, int indicatorId, boolean indicatorStatus) { + if (device == null) { + Log.e(TAG, "onHfIndicatorStatus() remote device is null"); + return; + } + if (indicatorId == HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS) { + getDeviceProperties(device).setHfpBatteryIndicatorStatus(indicatorStatus); + } + } + /** Handle indication events from Hands-free. */ public void handleHfIndicatorValueChanged( BluetoothDevice device, int indicatorId, int indicatorValue) { @@ -1746,6 +1790,20 @@ public class RemoteDevices { Log.e(TAG, "onVendorSpecificHeadsetEvent() arguments are null"); return; } + + if (Flags.enableBatteryLevelUpdateOnlyThroughHfIndicator()) { + DeviceProperties deviceProperties = getDeviceProperties(device); + if ((deviceProperties.isHfpBatteryIndicatorEnabled()) + && ((BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_XEVENT.equals(cmd)) + || (BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV.equals( + cmd)))) { + infoLog( + "Ignoring Battery Level update through vendor specific command as" + + "HfpBatteryIndicator support is enabled."); + return; + } + } + int batteryPercent = BluetoothDevice.BATTERY_LEVEL_UNKNOWN; switch (cmd) { case BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_XEVENT: @@ -1873,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. */ @@ -1888,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/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/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/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java index 684d08c59d..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 { @@ -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/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java index ab3b63fc0a..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); } } 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/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java index 9e9c224d52..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); 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/BluetoothHeadsetProxy.java b/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java index 96a573ffd2..f13ce9e3f6 100644 --- a/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java +++ b/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java @@ -47,12 +47,6 @@ public class BluetoothHeadsetProxy { adapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset); } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public void phoneStateChanged( - int numActive, int numHeld, int callState, String number, int type, String name) { - mBluetoothHeadset.phoneStateChanged(numActive, numHeld, callState, number, type, name); - } - @RequiresPermission(BLUETOOTH_CONNECT) public List<BluetoothDevice> getConnectedDevices() { return mBluetoothHeadset.getConnectedDevices(); diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java index 9dbcd6d4e8..97c1da1616 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java @@ -557,8 +557,7 @@ public class HeadsetNativeInterface { * @param device current active SCO device * @return True on success, False on failure */ - @VisibleForTesting - public boolean enableSwb(int swbCodec, boolean enable, BluetoothDevice device) { + boolean enableSwb(int swbCodec, boolean enable, BluetoothDevice device) { return enableSwbNative(swbCodec, enable, getByteAddress(device)); } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java index 4c20b42c90..84fa8239b1 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); @@ -765,24 +769,6 @@ public class HeadsetService extends ProfileService { } @Override - public void phoneStateChanged( - int numActive, - int numHeld, - int callState, - String number, - int type, - String name, - AttributionSource source) { - HeadsetService service = getService(source); - if (service == null) { - return; - } - - service.enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, null); - service.phoneStateChanged(numActive, numHeld, callState, number, type, name, false); - } - - @Override public boolean sendVendorSpecificResultCode( BluetoothDevice device, String command, String arg, AttributionSource source) { HeadsetService service = getService(source); @@ -840,13 +826,14 @@ public class HeadsetService extends ProfileService { return sHeadsetService; } - private static synchronized void setHeadsetService(HeadsetService instance) { + @VisibleForTesting + public static synchronized void setHeadsetService(HeadsetService instance) { logD("setHeadsetService(): set to: " + instance); sHeadsetService = instance; } 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 +868,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 +915,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 +933,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 +979,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 +1013,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 +1114,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 +1187,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 +1340,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 +1411,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 +1546,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; } @@ -1955,8 +1938,7 @@ public class HeadsetService extends ProfileService { } } - @VisibleForTesting - void phoneStateChanged( + public void phoneStateChanged( int numActive, int numHeld, int callState, @@ -2053,8 +2035,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 +2075,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". @@ -2159,13 +2140,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 +2249,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 +2482,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 b04012c91b..08cf564fc4 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; @@ -53,6 +57,7 @@ import com.android.bluetooth.btservice.AdapterService; import com.android.bluetooth.btservice.MetricsLogger; import com.android.bluetooth.btservice.ProfileService; import com.android.bluetooth.btservice.storage.DatabaseManager; +import com.android.bluetooth.flags.Flags; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.State; import com.android.internal.util.StateMachine; @@ -544,7 +549,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnected extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @Override @@ -572,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 @@ -580,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); @@ -588,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; @@ -652,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( @@ -664,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: @@ -701,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)); } @@ -715,7 +737,7 @@ class HeadsetStateMachine extends StateMachine { class Connecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } @Override @@ -748,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; } @@ -897,7 +923,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; } @Override @@ -988,7 +1014,7 @@ class HeadsetStateMachine extends StateMachine { private abstract class ConnectedBase extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } /** @@ -1271,7 +1297,7 @@ class HeadsetStateMachine extends StateMachine { // Reset NREC on connect event. Headset will override later processNoiseReductionEvent(true); // Query phone state for initial setup - mSystemInterface.queryPhoneState(); + mSystemInterface.queryPhoneState(mHeadsetService); // Remove pending connection attempts that were deferred during the pending // state. This is to prevent auto connect attempts from disconnecting // devices that previously successfully connected. @@ -1284,6 +1310,9 @@ class HeadsetStateMachine extends StateMachine { broadcastStateTransitions(); logSuccessIfNeeded(); + logHfpSessionMetric( + mDevice, + BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECTED); } @Override @@ -1307,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); @@ -1420,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)); } @@ -1758,8 +1784,7 @@ class HeadsetStateMachine extends StateMachine { * * @return device in focus */ - @VisibleForTesting - public BluetoothDevice getDevice() { + BluetoothDevice getDevice() { return mDevice; } @@ -2077,7 +2102,7 @@ class HeadsetStateMachine extends StateMachine { @VisibleForTesting void processAtChld(int chld, BluetoothDevice device) { - if (mSystemInterface.processChld(chld)) { + if (mSystemInterface.processChld(mHeadsetService, chld)) { mNativeInterface.atResponseCode(device, HeadsetHalConstants.AT_RESPONSE_OK, 0); } else { mNativeInterface.atResponseCode(device, HeadsetHalConstants.AT_RESPONSE_ERROR, 0); @@ -2652,6 +2677,11 @@ class HeadsetStateMachine extends StateMachine { sendIndicatorIntent(device, indId, -1); break; case HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS: + if (Flags.enableBatteryLevelUpdateOnlyThroughHfIndicator()) { + mAdapterService + .getRemoteDevices() + .handleHfIndicatorStatus(device, indId, true); + } log("Send Broadcast intent for the Battery Level indicator."); sendIndicatorIntent(device, indId, -1); break; @@ -2837,4 +2867,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 78e350fc37..4a82d74f83 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java @@ -16,10 +16,7 @@ package com.android.bluetooth.hfp; -import static android.Manifest.permission.BLUETOOTH_CONNECT; -import static android.Manifest.permission.MODIFY_PHONE_STATE; -import android.annotation.RequiresPermission; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothSinkAudioPolicy; @@ -184,10 +181,10 @@ class HeadsetSystemInterface { * @param chld index of the call to hold */ @VisibleForTesting - public boolean processChld(int chld) { + public boolean processChld(HeadsetService headsetService, int chld) { BluetoothInCallService bluetoothInCallService = getBluetoothInCallServiceInstance(); if (bluetoothInCallService != null) { - return bluetoothInCallService.processChld(chld); + return bluetoothInCallService.processChld(headsetService, chld); } else { Log.e(TAG, "Handsfree phone proxy null for sending DTMF"); } @@ -292,11 +289,10 @@ class HeadsetSystemInterface { * through {@link BluetoothHeadset#phoneStateChanged(int, int, int, String, int)} */ @VisibleForTesting - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public void queryPhoneState() { + public void queryPhoneState(HeadsetService headsetService) { BluetoothInCallService bluetoothInCallService = getBluetoothInCallServiceInstance(); if (bluetoothInCallService != null) { - bluetoothInCallService.queryPhoneState(); + bluetoothInCallService.queryPhoneState(headsetService); } else { Log.e(TAG, "Handsfree phone proxy null for query phone state"); } @@ -307,8 +303,7 @@ class HeadsetSystemInterface { * * @return True iff we are in a phone call */ - @VisibleForTesting - public boolean isInCall() { + boolean isInCall() { return ((mHeadsetPhoneState.getNumActiveCall() > 0) || (mHeadsetPhoneState.getNumHeldCall() > 0) || ((mHeadsetPhoneState.getCallState() != HeadsetHalConstants.CALL_STATE_IDLE) diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java index 4e0dae8c13..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(); diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java index 8bb8a4700b..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; @@ -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; } diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java index 2dc7bbaa6b..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; @@ -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/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 a1eb100dd7..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(); } @@ -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/LeAudioService.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java index d535f0b1c9..41e8bdefba 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java @@ -19,12 +19,16 @@ 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; import static com.android.bluetooth.flags.Flags.leaudioBigDependsOnAudioState; import static com.android.bluetooth.flags.Flags.leaudioBroadcastApiManagePrimaryGroup; -import static com.android.bluetooth.flags.Flags.leaudioBroadcastAssistantPeripheralEntrustment; import static com.android.bluetooth.flags.Flags.leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator; import static com.android.bluetooth.flags.Flags.leaudioUseAudioRecordingListener; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -79,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; @@ -211,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; @@ -293,7 +302,7 @@ public class LeAudioService extends ProfileService { } } - private static class LeAudioGroupDescriptor { + private class LeAudioGroupDescriptor { LeAudioGroupDescriptor(int groupId, boolean isInbandRingtonEnabled) { mGroupId = groupId; mIsConnected = false; @@ -332,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; } @@ -348,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; } @@ -870,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; } @@ -981,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( @@ -1043,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 { @@ -1414,17 +1432,15 @@ public class LeAudioService extends ProfileService { Log.d(TAG, "pauseBroadcast: Broadcast is stopped, skip pause request"); } } else { - if (leaudioBroadcastAssistantPeripheralEntrustment()) { - if (!isPlaying(broadcastId)) { - Log.d(TAG, "pauseBroadcast: Broadcast is not playing, skip pause request"); - return; - } + if (!isPlaying(broadcastId)) { + Log.d(TAG, "pauseBroadcast: Broadcast is not playing, skip pause request"); + return; + } - // Due to broadcast pause sinks may lose synchronization - BassClientService bassClientService = getBassClientService(); - if (bassClientService != null) { - bassClientService.cacheSuspendingSources(broadcastId); - } + // Due to broadcast pause sinks may lose synchronization + BassClientService bassClientService = getBassClientService(); + if (bassClientService != null) { + bassClientService.cacheSuspendingSources(broadcastId); } Log.d(TAG, "pauseBroadcast"); @@ -1731,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; } @@ -1742,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(); @@ -1789,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) { @@ -1808,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."); @@ -1858,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); @@ -1883,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."); @@ -1936,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( @@ -1945,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) { @@ -1973,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() { @@ -2146,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)) { @@ -2161,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 @@ -2180,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) @@ -2196,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; } @@ -2204,13 +2214,16 @@ public class LeAudioService extends ProfileService { } if (device.equals(mActiveAudioInDevice) || device.equals(mActiveAudioOutDevice)) { - Log.i(TAG, "Audio manager disactivate LeAudio device " + mExposedActiveDevice); - mExposedActiveDevice = null; - setActiveDevice(null); + mEventLogger.loge( + TAG, + "[From AudioManager]: Audio manager autonomusly disactivated LeAudio device." + + " Probably restarting and device shall be re-added " + + mExposedActiveDevice); + return; } - Log.i( + mEventLogger.logd( TAG, ("LeAudio active device switch: " + mExposedActiveDevice @@ -2288,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); @@ -2376,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 = @@ -2396,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, @@ -2550,7 +2572,7 @@ public class LeAudioService extends ProfileService { + groupId + ", exposedDevice: " + mExposedActiveDevice); - sentActiveDeviceChangeIntent(mExposedActiveDevice); + sendActiveDeviceChangeIntent(mExposedActiveDevice); } return true; } @@ -2608,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(" @@ -2809,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); } } } @@ -3686,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: @@ -3931,9 +3956,7 @@ public class LeAudioService extends ProfileService { BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST)); if (bassClientService != null) { - if (!leaudioBroadcastAssistantPeripheralEntrustment()) { - bassClientService.suspendReceiversSourceSynchronization(broadcastId); - } else if (leaudioBigDependsOnAudioState()) { + if (leaudioBigDependsOnAudioState()) { bassClientService.cacheSuspendingSources(broadcastId); } } @@ -4124,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; @@ -4332,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; @@ -4483,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); @@ -4491,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); @@ -4736,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(); @@ -4753,36 +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 (Flags.leaudioBroadcastVolumeControlPrimaryGroupOnly()) { - 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"); - } - } else { - Set<Integer> broadcastGroups = - activeBroadcastSinks.stream() - .map(dev -> getGroupId(dev)) - .filter(id -> id != IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID) - .collect(Collectors.toSet()); - - Log.d(TAG, "Setting volume for broadcast sink groups: " + broadcastGroups); - broadcastGroups.forEach( - groupId -> volumeControlService.setGroupVolume(groupId, volume)); - } + 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); } } @@ -4875,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(); @@ -4892,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; @@ -5765,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); @@ -5848,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); @@ -6248,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 f519edb0a1..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); @@ -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/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 35f38d90d6..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; @@ -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,20 +590,20 @@ 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. @@ -612,11 +614,11 @@ public class ScanController { // Check if a scan record matches a specific filters or original address 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; } @@ -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/ScanManager.java b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java index b5e8a047e0..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) { @@ -465,16 +469,16 @@ public class ScanManager { private static boolean requiresLocationOn(ScanClient client) { boolean isFiltered = isFilteredScan(client); - return !client.hasDisavowedLocation && !isFiltered; + return !client.mHasDisavowedLocation && !isFiltered; } private static boolean isFilteredScan(ScanClient client) { - if ((client.filters == null) || client.filters.isEmpty()) { + 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 static boolean isBatchClient(ScanClient client) { - if (client == null || client.settings == null) { + 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()); @@ -792,7 +796,7 @@ public class ScanManager { } private static boolean upgradeScanModeByOneLevel(ScanClient client) { - switch (client.scanModeApp) { + 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++; } } @@ -1297,24 +1301,24 @@ public class ScanManager { } private static boolean isAutoBatchScanClientEnabled(ScanClient client) { - return client.stats != null && client.stats.isAutoBatchScan(client.scannerId); + return client.mStats != null && client.mStats.isAutoBatchScan(client.mScannerId); } private static boolean isAllMatchesAutoBatchScanClient(ScanClient client) { - return client.settings.getCallbackType() + return client.mSettings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH; } private static boolean isOpportunisticScanClient(ScanClient client) { - return client.settings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; + return client.mSettings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; } private static boolean isTimeoutScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanTimeout(client.scannerId); + return (client.mStats != null) && client.mStats.isScanTimeout(client.mScannerId); } private static boolean isDowngradedScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanDowngraded(client.scannerId); + return (client.mStats != null) && client.mStats.isScanDowngraded(client.mScannerId); } private static boolean isForceDowngradedScanClient(ScanClient client) { @@ -1322,12 +1326,12 @@ public class ScanManager { } private static boolean isFirstMatchScanClient(ScanClient client) { - return (client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) + 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 = @@ -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; } } @@ -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; @@ -1847,7 +1851,7 @@ public class ScanManager { if (client == null) { return DELIVERY_MODE_IMMEDIATE; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; if (settings == null) { return DELIVERY_MODE_IMMEDIATE; } @@ -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/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/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 057823fa5c..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) { @@ -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; } /** @@ -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); } } 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/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 0be28709f0..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; @@ -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/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/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/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/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/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 99b0efc2a3..3c1c223d56 100644 --- a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java +++ b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java @@ -16,16 +16,12 @@ package com.android.bluetooth.telephony; -import static android.Manifest.permission.BLUETOOTH_CONNECT; -import static android.Manifest.permission.MODIFY_PHONE_STATE; import static java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; import android.annotation.NonNull; -import android.annotation.RequiresPermission; import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothHeadset; import android.bluetooth.BluetoothLeCall; import android.bluetooth.BluetoothLeCallControl; import android.bluetooth.BluetoothManager; @@ -57,7 +53,6 @@ import androidx.annotation.VisibleForTesting; import com.android.bluetooth.Utils; import com.android.bluetooth.flags.Flags; -import com.android.bluetooth.hfp.BluetoothHeadsetProxy; import com.android.bluetooth.hfp.HeadsetService; import com.android.bluetooth.tbs.BluetoothLeCallControlProxy; @@ -124,8 +119,6 @@ public class BluetoothInCallService extends InCallService { private static final Object LOCK = new Object(); - @VisibleForTesting BluetoothHeadsetProxy mBluetoothHeadset; - @VisibleForTesting BluetoothLeCallControlProxy mBluetoothLeCallControl; private ExecutorService mExecutor; @@ -157,14 +150,9 @@ public class BluetoothInCallService extends InCallService { private final BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile.ServiceListener() { @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onServiceConnected(int profile, BluetoothProfile proxy) { Log.d(TAG, "onServiceConnected for profile: " + profile); synchronized (LOCK) { - if (profile == BluetoothProfile.HEADSET) { - mBluetoothHeadset = new BluetoothHeadsetProxy((BluetoothHeadset) proxy); - updateHeadsetWithCallState(true /* force */); - } else { mBluetoothLeCallControl = new BluetoothLeCallControlProxy((BluetoothLeCallControl) proxy); @@ -179,7 +167,6 @@ public class BluetoothInCallService extends InCallService { mBluetoothLeCallControlCallback); Log.d(TAG, "isBearerRegistered: " + isBearerRegistered); sendTbsCurrentCallsList(); - } } Log.d(TAG, "Calls updated for profile: " + profile); } @@ -187,11 +174,7 @@ public class BluetoothInCallService extends InCallService { @Override public void onServiceDisconnected(int profile) { synchronized (LOCK) { - if (profile == BluetoothProfile.HEADSET) { - mBluetoothHeadset = null; - } else { mBluetoothLeCallControl = null; - } } } }; @@ -204,7 +187,7 @@ public class BluetoothInCallService extends InCallService { intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); Log.d(TAG, "Bluetooth Adapter state: " + state); if (state == BluetoothAdapter.STATE_ON) { - queryPhoneState(); + queryPhoneState(HeadsetService.getHeadsetService()); } else if (state == BluetoothAdapter.STATE_TURNING_OFF) { clear(); } @@ -229,7 +212,6 @@ public class BluetoothInCallService extends InCallService { return mLastState; } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) void onStateChanged(BluetoothCall call, int state) { if (mCallInfo.isNullCall(call)) { return; @@ -272,37 +254,39 @@ public class BluetoothInCallService extends InCallService { return; } mLastState = state; - updateHeadsetWithCallState(false /* force */); + updateHeadsetWithCallState(HeadsetService.getHeadsetService(), false /* force */); } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onStateChanged(Call call, int state) { super.onStateChanged(call, state); onStateChanged(getBluetoothCallById(System.identityHashCode(call)), state); } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - void onDetailsChanged(BluetoothCall call, Call.Details details) { + @VisibleForTesting + void onDetailsChanged( + HeadsetService headsetService, BluetoothCall call, Call.Details details) { if (mCallInfo.isNullCall(call)) { return; } if (call.isExternalCall()) { - onCallRemoved(call, false /* forceRemoveCallback */); + onCallRemoved(headsetService, call, false /* forceRemoveCallback */); } else { - onCallAdded(call); + onCallAdded(headsetService, call); } } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onDetailsChanged(Call call, Call.Details details) { super.onDetailsChanged(call, details); - onDetailsChanged(getBluetoothCallById(System.identityHashCode(call)), details); + onDetailsChanged( + HeadsetService.getHeadsetService(), + getBluetoothCallById(System.identityHashCode(call)), + details); } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - void onParentChanged(BluetoothCall call) { + @VisibleForTesting + void onParentChanged(HeadsetService headsetService, BluetoothCall call) { if (mCallInfo.isNullCall(call) || call.isExternalCall()) { Log.w(TAG, "null call or external call"); return; @@ -315,18 +299,20 @@ public class BluetoothInCallService extends InCallService { "Ignoring onIsConferenceChanged from child BluetoothCall with new parent"); return; } - updateHeadsetWithCallState(false /* force */); + updateHeadsetWithCallState(headsetService, false /* force */); } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onParentChanged(Call call, Call parent) { super.onParentChanged(call, parent); - onParentChanged(getBluetoothCallById(System.identityHashCode(call))); + onParentChanged( + HeadsetService.getHeadsetService(), + getBluetoothCallById(System.identityHashCode(call))); } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - void onChildrenChanged(BluetoothCall call, List<BluetoothCall> children) { + @VisibleForTesting + void onChildrenChanged( + HeadsetService headsetService, BluetoothCall call, List<BluetoothCall> children) { if (mCallInfo.isNullCall(call) || call.isExternalCall()) { Log.w(TAG, "null call or external call"); return; @@ -339,14 +325,14 @@ public class BluetoothInCallService extends InCallService { Log.d(TAG, "Ignoring onIsConferenceChanged from parent with only one child call"); return; } - updateHeadsetWithCallState(false /* force */); + updateHeadsetWithCallState(headsetService, false /* force */); } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onChildrenChanged(Call call, List<Call> children) { super.onChildrenChanged(call, children); onChildrenChanged( + HeadsetService.getHeadsetService(), getBluetoothCallById(System.identityHashCode(call)), getBluetoothCallsByIds(BluetoothCall.getIds(children))); } @@ -378,10 +364,8 @@ public class BluetoothInCallService extends InCallService { BluetoothInCallService( Context context, CallInfo callInfo, - BluetoothHeadsetProxy headset, BluetoothLeCallControlProxy leCallControl) { this(callInfo); - mBluetoothHeadset = headset; mBluetoothLeCallControl = leCallControl; attachBaseContext(context); } @@ -554,11 +538,10 @@ public class BluetoothInCallService extends InCallService { } } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public boolean queryPhoneState() { + public boolean queryPhoneState(HeadsetService headsetService) { synchronized (LOCK) { Log.i(TAG, "queryPhoneState"); - updateHeadsetWithCallState(true); + updateHeadsetWithCallState(headsetService, true); return true; } } @@ -596,20 +579,20 @@ public class BluetoothInCallService extends InCallService { return isHighDef; } - public boolean processChld(int chld) { + public boolean processChld(HeadsetService headsetService, int chld) { synchronized (LOCK) { final long token = Binder.clearCallingIdentity(); try { Log.i(TAG, "processChld " + chld); - return _processChld(chld); + return processChldLocked(headsetService, chld); } finally { Binder.restoreCallingIdentity(token); } } } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public void onCallAdded(BluetoothCall call) { + @VisibleForTesting + void onCallAdded(HeadsetService headsetService, BluetoothCall call) { synchronized (LOCK) { if (call.isExternalCall()) { Log.d(TAG, "onCallAdded: external call"); @@ -626,7 +609,7 @@ public class BluetoothInCallService extends InCallService { mMaxNumberOfCalls = Integer.max(mMaxNumberOfCalls, mBluetoothCallHashMap.size()); } - updateHeadsetWithCallState(false /* force */); + updateHeadsetWithCallState(headsetService, false /* force */); BluetoothLeCall tbsCall = createTbsCall(call); if (mBluetoothLeCallControl != null && tbsCall != null) { @@ -666,10 +649,9 @@ public class BluetoothInCallService extends InCallService { } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onCallAdded(Call call) { super.onCallAdded(call); - onCallAdded(new BluetoothCall(call)); + onCallAdded(HeadsetService.getHeadsetService(), new BluetoothCall(call)); } /** @@ -681,8 +663,8 @@ public class BluetoothInCallService extends InCallService { * callback when the {@code BluetoothCall} is external so that the call can be added back if * no longer external. */ - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public void onCallRemoved(BluetoothCall call, boolean forceRemoveCallback) { + public void onCallRemoved( + HeadsetService headsetService, BluetoothCall call, boolean forceRemoveCallback) { synchronized (LOCK) { Log.i(TAG, "onCallRemoved, forceRemoveCallback=" + forceRemoveCallback); CallStateCallback callback = getCallback(call); @@ -727,7 +709,7 @@ public class BluetoothInCallService extends InCallService { } } - updateHeadsetWithCallState(false /* force */); + updateHeadsetWithCallState(headsetService, false /* force */); if (Flags.maintainCallIndexAfterConference() && mConferenceCallClccIndexMap.size() > 0) { @@ -747,7 +729,6 @@ public class BluetoothInCallService extends InCallService { } @Override - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) public void onCallRemoved(Call call) { super.onCallRemoved(call); BluetoothCall bluetoothCall = getBluetoothCallById(System.identityHashCode(call)); @@ -755,7 +736,8 @@ public class BluetoothInCallService extends InCallService { Log.w(TAG, "onCallRemoved, BluetoothCall is removed before registered"); return; } - onCallRemoved(bluetoothCall, true /* forceRemoveCallback */); + onCallRemoved( + HeadsetService.getHeadsetService(), bluetoothCall, true /* forceRemoveCallback */); } @Override @@ -772,7 +754,6 @@ public class BluetoothInCallService extends InCallService { mAdapter = requireNonNull(getSystemService(BluetoothManager.class)).getAdapter(); mTelephonyManager = requireNonNull(getSystemService(TelephonyManager.class)); mTelecomManager = requireNonNull(getSystemService(TelecomManager.class)); - mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET); mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.LE_CALL_CONTROL); mBluetoothAdapterReceiver = new BluetoothAdapterReceiver(); IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); @@ -804,10 +785,6 @@ public class BluetoothInCallService extends InCallService { unregisterReceiver(mBluetoothAdapterReceiver); mBluetoothAdapterReceiver = null; } - if (mBluetoothHeadset != null) { - mBluetoothHeadset.closeBluetoothHeadsetProxy(mAdapter); - mBluetoothHeadset = null; - } if (mBluetoothLeCallControl != null) { mBluetoothLeCallControl.unregisterBearer(); mBluetoothLeCallControl.closeBluetoothLeCallControlProxy(mAdapter); @@ -1125,8 +1102,7 @@ public class BluetoothInCallService extends InCallService { return call.mClccIndex; } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - private boolean _processChld(int chld) { + private boolean processChldLocked(HeadsetService headsetService, int chld) { BluetoothCall activeCall = mCallInfo.getActiveCall(); BluetoothCall ringingCall = mCallInfo.getRingingOrSimulatedRingingCall(); if (ringingCall == null) { @@ -1185,7 +1161,7 @@ public class BluetoothInCallService extends InCallService { && activeCall.can(Connection.CAPABILITY_SWAP_CONFERENCE)) { activeCall.swapConference(); Log.i(TAG, "CDMA calls in conference swapped, updating headset"); - updateHeadsetWithCallState(true /* force */); + updateHeadsetWithCallState(headsetService, true /* force */); return true; } else if (!mCallInfo.isNullCall(ringingCall)) { ringingCall.answer(VideoProfile.STATE_AUDIO_ONLY); @@ -1225,8 +1201,12 @@ public class BluetoothInCallService extends InCallService { * state have occurred, {@code false} if the state should only be sent if the state has * changed. */ - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - private void updateHeadsetWithCallState(boolean force) { + private void updateHeadsetWithCallState(HeadsetService headsetService, boolean force) { + if (headsetService == null) { + Log.i(TAG, "updateHeadsetWithCallState skipped: No headset service"); + return; + } + BluetoothCall activeCall = mCallInfo.getActiveCall(); BluetoothCall ringingCall = mCallInfo.getRingingOrSimulatedRingingCall(); BluetoothCall heldCall = mCallInfo.getHeldCall(); @@ -1288,85 +1268,58 @@ public class BluetoothInCallService extends InCallService { } } - if (mBluetoothHeadset != null - && (force - || (!callsPendingSwitch - && (numActiveCalls != mNumActiveCalls - || numChildrenOfActiveCall != mNumChildrenOfActiveCall - || numHeldCalls != mNumHeldCalls - || bluetoothCallState != mBluetoothCallState - || !TextUtils.equals(ringingAddress, mRingingAddress) - || ringingAddressType != mRingingAddressType - || (!Objects.equals(heldCall, mOldHeldCall) - && !ignoreHeldCallChange))))) { - - // If the BluetoothCall is transitioning into the alerting state, send DIALING first. - // Some devices expect to see a DIALING state prior to seeing an ALERTING state - // so we need to send it first. - boolean sendDialingFirst = - mBluetoothCallState != bluetoothCallState - && bluetoothCallState == CALL_STATE_ALERTING; - - mOldHeldCall = heldCall; - mNumActiveCalls = numActiveCalls; - mNumChildrenOfActiveCall = numChildrenOfActiveCall; - mNumHeldCalls = numHeldCalls; - mBluetoothCallState = bluetoothCallState; - mRingingAddress = ringingAddress; - mRingingAddressType = ringingAddressType; - - if (sendDialingFirst) { - // Log in full to make logs easier to debug. - Log.i( - TAG, - "updateHeadsetWithCallState " - + "numActive " - + mNumActiveCalls - + ", " - + "numHeld " - + mNumHeldCalls - + ", " - + "callState " - + CALL_STATE_DIALING - + ", " - + "ringing type " - + mRingingAddressType); - mBluetoothHeadset.phoneStateChanged( - mNumActiveCalls, - mNumHeldCalls, - CALL_STATE_DIALING, - mRingingAddress, - mRingingAddressType, - ringingName); - } + boolean callsDetailsChanged = + numActiveCalls != mNumActiveCalls + || numChildrenOfActiveCall != mNumChildrenOfActiveCall + || numHeldCalls != mNumHeldCalls + || bluetoothCallState != mBluetoothCallState + || !TextUtils.equals(ringingAddress, mRingingAddress) + || ringingAddressType != mRingingAddressType + || (!Objects.equals(heldCall, mOldHeldCall) && !ignoreHeldCallChange); - Log.i( - TAG, - "updateHeadsetWithCallState " - + "numActive " - + mNumActiveCalls - + ", " - + "numHeld " - + mNumHeldCalls - + ", " - + "callState " - + mBluetoothCallState - + ", " - + "ringing type " - + mRingingAddressType); - - mBluetoothHeadset.phoneStateChanged( - mNumActiveCalls, - mNumHeldCalls, - mBluetoothCallState, - mRingingAddress, - mRingingAddressType, - ringingName); - - mHeadsetUpdatedRecently = true; - } else { + if (!(force || (!callsPendingSwitch && callsDetailsChanged))) { Log.i(TAG, "updateHeadsetWithCallState skipped"); + return; } + + mOldHeldCall = heldCall; + mNumActiveCalls = numActiveCalls; + mNumChildrenOfActiveCall = numChildrenOfActiveCall; + mNumHeldCalls = numHeldCalls; + mRingingAddress = ringingAddress; + mRingingAddressType = ringingAddressType; + + // If the BluetoothCall is transitioning into the alerting state, send DIALING first. + // Some devices expect to see a DIALING state prior to seeing an ALERTING state + // so we need to send it first. + if (mBluetoothCallState != bluetoothCallState + && bluetoothCallState == CALL_STATE_ALERTING) { + phoneStateChanged(headsetService, CALL_STATE_DIALING, ringingName); + } + + phoneStateChanged(headsetService, bluetoothCallState, ringingName); + + mBluetoothCallState = bluetoothCallState; + mHeadsetUpdatedRecently = true; + } + + private void phoneStateChanged( + HeadsetService headsetService, int callState, String ringingName) { + Log.i( + TAG, + "updateHeadsetWithCallState " + + (" numActive=" + mNumActiveCalls) + + (" numHeld=" + mNumHeldCalls) + + (" callState=" + callState) + + (" ringingType=" + mRingingAddressType)); + headsetService.phoneStateChanged( + mNumActiveCalls, + mNumHeldCalls, + callState, + mRingingAddress, + mRingingAddressType, + ringingName, + false); // isVirtualCall } private int getBluetoothCallStateForUpdate() { diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java index 8924f3219b..6adc1df93f 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java @@ -31,7 +31,6 @@ import static android.bluetooth.IBluetoothCsipSetCoordinator.CSIS_GROUP_ID_INVAL import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID; import static android.bluetooth.IBluetoothVolumeControl.VOLUME_CONTROL_UNKNOWN_VOLUME; -import static com.android.bluetooth.flags.Flags.leaudioBroadcastVolumeControlPrimaryGroupOnly; import static com.android.bluetooth.flags.Flags.vcpDeviceVolumeApiImprovements; import static java.util.Objects.requireNonNull; @@ -935,13 +934,6 @@ public class VolumeControlService extends ProfileService { if (leAudioService != null) { int currentlyActiveGroupId = leAudioService.getActiveGroupId(); if (currentlyActiveGroupId == GROUP_ID_INVALID || groupId != currentlyActiveGroupId) { - if (!leaudioBroadcastVolumeControlPrimaryGroupOnly()) { - Log.i( - TAG, - "Skip updating to audio system if not updating volume for current" - + " active group"); - return; - } BassClientService bassClientService = mFactory.getBassClientService(); if (bassClientService == null || bassClientService.getSyncedBroadcastSinks().stream() 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/telephony/BluetoothInCallServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java index a9eea3da60..e15141dcb7 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java @@ -17,6 +17,7 @@ package com.android.bluetooth.telephony; import static com.android.bluetooth.TestUtils.MockitoRule; +import static com.android.bluetooth.TestUtils.mockGetSystemService; import static com.google.common.truth.Truth.assertThat; @@ -49,12 +50,11 @@ import androidx.test.core.app.ApplicationProvider; import androidx.test.filters.MediumTest; import androidx.test.runner.AndroidJUnit4; -import com.android.bluetooth.TestUtils; import com.android.bluetooth.flags.Flags; -import com.android.bluetooth.hfp.BluetoothHeadsetProxy; import com.android.bluetooth.hfp.HeadsetService; import com.android.bluetooth.tbs.BluetoothLeCallControlProxy; +import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -71,7 +71,7 @@ import java.util.UUID; @MediumTest @RunWith(AndroidJUnit4.class) public class BluetoothInCallServiceTest { - private static final String TAG = BluetoothInCallServiceTest.class.getSimpleName(); + private static final String TAG = "BluetoothInCallServiceTest"; private static final int TEST_DTMF_TONE = 0; private static final String TEST_ACCOUNT_ADDRESS = "//foo.com/"; @@ -99,7 +99,6 @@ public class BluetoothInCallServiceTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); - @Mock private BluetoothHeadsetProxy mMockBluetoothHeadset; @Mock private HeadsetService mHeadsetService; @Mock private BluetoothLeCallControlProxy mLeCallControl; @Mock private BluetoothInCallService.CallInfo mMockCallInfo; @@ -108,20 +107,27 @@ public class BluetoothInCallServiceTest { @Before public void setUp() { + doReturn(true).when(mHeadsetService).isAvailable(); + HeadsetService.setHeadsetService(mHeadsetService); + doReturn(true).when(mMockCallInfo).isNullCall(null); doReturn(false).when(mMockCallInfo).isNullCall(notNull()); Context spiedContext = spy(new ContextWrapper(ApplicationProvider.getApplicationContext())); mMockTelephonyManager = - TestUtils.mockGetSystemService( + mockGetSystemService( spiedContext, Context.TELEPHONY_SERVICE, TelephonyManager.class); mBluetoothInCallService = - new BluetoothInCallService( - spiedContext, mMockCallInfo, mMockBluetoothHeadset, mLeCallControl); + new BluetoothInCallService(spiedContext, mMockCallInfo, mLeCallControl); mBluetoothInCallService.onCreate(); } + @After + public void tearDown() { + HeadsetService.setHeadsetService(null); + } + @Test public void headsetAnswerCall() { BluetoothCall mockCall = createRingingCall(UUID.randomUUID()); @@ -211,7 +217,7 @@ public class BluetoothInCallServiceTest { doReturn(Uri.parse("tel:555-000")).when(activeCall).getHandle(); doReturn(List.of(activeCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); mBluetoothInCallService.listCurrentCalls(mHeadsetService); @@ -227,7 +233,7 @@ public class BluetoothInCallServiceTest { @Test public void bluetoothCallQualityReport() { BluetoothCall activeCall = createForegroundCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); mBluetoothInCallService.sendBluetoothCallQualityReport( 10, // long timestamp @@ -264,7 +270,7 @@ public class BluetoothInCallServiceTest { doReturn(List.of(silentRingingCall)).when(mMockCallInfo).getBluetoothCalls(); doReturn(silentRingingCall).when(mMockCallInfo).getRingingOrSimulatedRingingCall(); - mBluetoothInCallService.onCallAdded(silentRingingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, silentRingingCall); mBluetoothInCallService.listCurrentCalls(mHeadsetService); @@ -282,9 +288,11 @@ public class BluetoothInCallServiceTest { BluetoothCall parentCall = createActiveCall(UUID.randomUUID()); final BluetoothCall confCall1 = getMockCall(UUID.randomUUID()); final BluetoothCall confCall2 = createHeldCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(parentCall); - mBluetoothInCallService.onCallAdded(confCall1); - mBluetoothInCallService.onCallAdded(confCall2); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); + verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); + + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1); + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2); doReturn(List.of(parentCall, confCall1, confCall2)).when(mMockCallInfo).getBluetoothCalls(); doReturn(Call.STATE_ACTIVE).when(confCall1).getState(); @@ -308,31 +316,32 @@ public class BluetoothInCallServiceTest { doReturn(parentId).when(confCall1).getParentId(); doReturn(parentId).when(confCall2).getParentId(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.queryPhoneState(); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + mBluetoothInCallService.queryPhoneState(mHeadsetService); + verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false); doReturn(true).when(parentCall).wasConferencePreviouslyMerged(); List<BluetoothCall> children = mBluetoothInCallService.getBluetoothCallsByIds(parentCall.getChildrenIds()); - mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + mBluetoothInCallService + .getCallback(parentCall) + .onChildrenChanged(mHeadsetService, parentCall, children); + verify(mHeadsetService, times(2)) + .phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); // Spurious BluetoothCall to onIsConferencedChanged. - mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children); + mBluetoothInCallService + .getCallback(parentCall) + .onChildrenChanged(mHeadsetService, parentCall, children); // Make sure the BluetoothCall has only occurred collectively 2 times (not on the third) - verify(mMockBluetoothHeadset, times(2)) + verify(mHeadsetService, times(3)) .phoneStateChanged( - any(int.class), - any(int.class), - any(int.class), + anyInt(), + anyInt(), + anyInt(), + anyString(), + anyInt(), nullable(String.class), - any(int.class), - nullable(String.class)); + eq(false)); } @Test @@ -344,9 +353,9 @@ public class BluetoothInCallServiceTest { doReturn(Uri.parse("tel:555-0001")).when(foregroundCall).getHandle(); final BluetoothCall heldCall = createHeldCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555-0002")).when(heldCall).getHandle(); - mBluetoothInCallService.onCallAdded(parentCall); - mBluetoothInCallService.onCallAdded(foregroundCall); - mBluetoothInCallService.onCallAdded(heldCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, foregroundCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall); doReturn(List.of(parentCall, foregroundCall, heldCall)) .when(mMockCallInfo) @@ -394,9 +403,9 @@ public class BluetoothInCallServiceTest { doReturn(Uri.parse("tel:555-0000")).when(parentCall).getHandle(); doReturn(Uri.parse("tel:555-0001")).when(confCall1).getHandle(); doReturn(Uri.parse("tel:555-0002")).when(confCall2).getHandle(); - mBluetoothInCallService.onCallAdded(parentCall); - mBluetoothInCallService.onCallAdded(confCall1); - mBluetoothInCallService.onCallAdded(confCall2); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1); + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2); doReturn(List.of(parentCall, confCall1, confCall2)).when(mMockCallInfo).getBluetoothCalls(); doReturn(Call.STATE_ACTIVE).when(confCall1).getState(); @@ -436,7 +445,7 @@ public class BluetoothInCallServiceTest { // This test does not define a value for getForegroundCall(), so this ringing // BluetoothCall will be treated as if it is a waiting BluetoothCall // when listCurrentCalls() is invoked. - mBluetoothInCallService.onCallAdded(waitingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, waitingCall); doReturn(true).when(waitingCall).isIncoming(); doReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000"))) @@ -471,7 +480,7 @@ public class BluetoothInCallServiceTest { public void newCallClccResponse() { BluetoothCall newCall = createForegroundCall(UUID.randomUUID()); doReturn(List.of(newCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(newCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, newCall); doReturn(Call.STATE_NEW).when(newCall).getState(); @@ -494,7 +503,7 @@ public class BluetoothInCallServiceTest { BluetoothCall activeCall = createForegroundCall(UUID.randomUUID()); doReturn(List.of(activeCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(Call.STATE_ACTIVE).when(activeCall).getState(); doReturn(true).when(activeCall).isIncoming(); @@ -535,7 +544,7 @@ public class BluetoothInCallServiceTest { public void ringingCallClccResponse() { BluetoothCall ringingCall = createForegroundCall(UUID.randomUUID()); doReturn(List.of(ringingCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); doReturn(Call.STATE_RINGING).when(ringingCall).getState(); doReturn(true).when(ringingCall).isIncoming(); @@ -572,7 +581,7 @@ public class BluetoothInCallServiceTest { doReturn(calls).when(mMockCallInfo).getBluetoothCalls(); BluetoothCall ringingCall = createForegroundCall(UUID.randomUUID()); calls.add(ringingCall); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); doReturn(Call.STATE_RINGING).when(ringingCall).getState(); doReturn(true).when(ringingCall).isIncoming(); @@ -581,7 +590,6 @@ public class BluetoothInCallServiceTest { .when(ringingCall) .getGatewayInfo(); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) .clccResponse( @@ -597,7 +605,7 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_ACTIVE).when(ringingCall).getState(); BluetoothCall newHoldingCall = createHeldCall(UUID.randomUUID()); calls.add(0, newHoldingCall); - mBluetoothInCallService.onCallAdded(newHoldingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, newHoldingCall); doReturn(Call.STATE_HOLDING).when(newHoldingCall).getState(); doReturn(true).when(newHoldingCall).isIncoming(); @@ -620,7 +628,7 @@ public class BluetoothInCallServiceTest { public void alertingCallClccResponse() { BluetoothCall dialingCall = createForegroundCall(UUID.randomUUID()); doReturn(List.of(dialingCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(dialingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, dialingCall); doReturn(Call.STATE_DIALING).when(dialingCall).getState(); doReturn(Uri.parse("tel:555-0000")).when(dialingCall).getHandle(); @@ -628,7 +636,6 @@ public class BluetoothInCallServiceTest { .when(dialingCall) .getGatewayInfo(); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) .clccResponse( @@ -657,7 +664,7 @@ public class BluetoothInCallServiceTest { doReturn(calls).when(mMockCallInfo).getBluetoothCalls(); BluetoothCall dialingCall = createForegroundCall(UUID.randomUUID()); calls.add(dialingCall); - mBluetoothInCallService.onCallAdded(dialingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, dialingCall); doReturn(Call.STATE_DIALING).when(dialingCall).getState(); doReturn(Uri.parse("tel:555-0000")).when(dialingCall).getHandle(); @@ -666,7 +673,7 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); BluetoothCall holdingCall = createHeldCall(UUID.randomUUID()); calls.add(holdingCall); - mBluetoothInCallService.onCallAdded(holdingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall); doReturn(Call.STATE_HOLDING).when(holdingCall).getState(); doReturn(true).when(holdingCall).isIncoming(); @@ -675,7 +682,6 @@ public class BluetoothInCallServiceTest { .when(holdingCall) .getGatewayInfo(); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) .clccResponse( @@ -712,9 +718,8 @@ public class BluetoothInCallServiceTest { doReturn(Uri.parse("tel:555-0000")).when(parentCall).getHandle(); doReturn(List.of(parentCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService).clccResponse(1, 1, CALL_STATE_ACTIVE, 0, true, "5550000", 129); @@ -733,9 +738,9 @@ public class BluetoothInCallServiceTest { doReturn(Uri.parse("tel:555-0001")).when(childCall1).getHandle(); doReturn(Uri.parse("tel:555-0002")).when(childCall2).getHandle(); - mBluetoothInCallService.onCallAdded(parentCall); - mBluetoothInCallService.onCallAdded(childCall1); - mBluetoothInCallService.onCallAdded(childCall2); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, childCall1); + mBluetoothInCallService.onCallAdded(mHeadsetService, childCall2); addCallCapability(parentCall, Connection.CAPABILITY_MANAGE_CONFERENCE); Integer parentId = parentCall.getId(); @@ -751,7 +756,6 @@ public class BluetoothInCallServiceTest { doReturn(true).when(parentCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE); doReturn(true).when(parentCall).isIncoming(); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) @@ -775,9 +779,8 @@ public class BluetoothInCallServiceTest { doReturn(true).when(conferenceCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE); doReturn(true).when(conferenceCall).isIncoming(); - mBluetoothInCallService.onCallAdded(conferenceCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService).clccResponse(1, 1, 0, 0, true, "5551234", 129); } @@ -792,7 +795,7 @@ public class BluetoothInCallServiceTest { // active call is added BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); calls.add(activeCall); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(Call.STATE_ACTIVE).when(activeCall).getState(); doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle(); @@ -803,7 +806,7 @@ public class BluetoothInCallServiceTest { // holding call is added BluetoothCall holdingCall = createHeldCall(UUID.randomUUID()); calls.add(holdingCall); - mBluetoothInCallService.onCallAdded(holdingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall); doReturn(Call.STATE_HOLDING).when(holdingCall).getState(); doReturn(true).when(holdingCall).isIncoming(); @@ -813,7 +816,6 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); // needs to have at least one CLCC response before merge to enable call inference - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) .clccResponse( @@ -827,8 +829,8 @@ public class BluetoothInCallServiceTest { DisconnectCause cause = new DisconnectCause(DisconnectCause.OTHER); doReturn(cause).when(activeCall).getDisconnectCause(); doReturn(cause).when(holdingCall).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall, true); - mBluetoothInCallService.onCallRemoved(holdingCall, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, holdingCall, true); BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID()); addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE); @@ -843,9 +845,8 @@ public class BluetoothInCallServiceTest { // parent call arrived, but children have not, then do inference on children calls.add(conferenceCall); assertThat(calls).hasSize(1); - mBluetoothInCallService.onCallAdded(conferenceCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.listCurrentCalls(mHeadsetService); verify(mHeadsetService) .clccResponse( @@ -856,10 +857,10 @@ public class BluetoothInCallServiceTest { // real children arrive, no change on CLCC response calls.add(activeCall); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(true).when(activeCall).isConference(); calls.add(holdingCall); - mBluetoothInCallService.onCallAdded(holdingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall); doReturn(Call.STATE_ACTIVE).when(holdingCall).getState(); doReturn(true).when(holdingCall).isConference(); doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds(); @@ -877,8 +878,8 @@ public class BluetoothInCallServiceTest { cause = new DisconnectCause(DisconnectCause.LOCAL); doReturn(cause).when(activeCall).getDisconnectCause(); doReturn(cause).when(holdingCall).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall, true); - mBluetoothInCallService.onCallRemoved(holdingCall, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, holdingCall, true); calls.remove(activeCall); calls.remove(holdingCall); assertThat(calls).hasSize(1); @@ -890,7 +891,7 @@ public class BluetoothInCallServiceTest { // when parent is removed doReturn(cause).when(conferenceCall).getDisconnectCause(); calls.remove(conferenceCall); - mBluetoothInCallService.onCallRemoved(conferenceCall, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, conferenceCall, true); clearInvocations(mHeadsetService); mBluetoothInCallService.listCurrentCalls(mHeadsetService); @@ -921,8 +922,8 @@ public class BluetoothInCallServiceTest { new DisconnectCause(DisconnectCause.OTHER, "IMS_MERGED_SUCCESSFULLY"); doReturn(cause).when(activeCall_1).getDisconnectCause(); doReturn(cause).when(activeCall_2).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall_1, true); - mBluetoothInCallService.onCallRemoved(activeCall_2, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true); BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID()); addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE); @@ -938,14 +939,14 @@ public class BluetoothInCallServiceTest { calls.add(conferenceCall); doReturn(3).when(conferenceCall).getParentId(); doReturn(3).when(conferenceCall).getId(); - mBluetoothInCallService.onCallAdded(conferenceCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall); // Call_1 and Call_2 are part of conference calls.add(activeCall_1); - mBluetoothInCallService.onCallAdded(activeCall_1); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1); doReturn(true).when(activeCall_1).isConference(); calls.add(activeCall_2); - mBluetoothInCallService.onCallAdded(activeCall_2); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2); doReturn(Call.STATE_ACTIVE).when(activeCall_2).getState(); doReturn(true).when(activeCall_2).isConference(); doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds(); @@ -977,7 +978,7 @@ public class BluetoothInCallServiceTest { // Call 1 active call is added BluetoothCall activeCall_1 = createActiveCall(UUID.randomUUID()); calls.add(activeCall_1); - mBluetoothInCallService.onCallAdded(activeCall_1); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1); doReturn(Call.STATE_ACTIVE).when(activeCall_1).getState(); doReturn(Uri.parse("tel:555-0001")).when(activeCall_1).getHandle(); @@ -988,7 +989,7 @@ public class BluetoothInCallServiceTest { // Call 2 holding call is added BluetoothCall activeCall_2 = createHeldCall(UUID.randomUUID()); calls.add(activeCall_2); - mBluetoothInCallService.onCallAdded(activeCall_2); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2); doReturn(Call.STATE_HOLDING).when(activeCall_2).getState(); doReturn(true).when(activeCall_2).isIncoming(); @@ -1013,8 +1014,8 @@ public class BluetoothInCallServiceTest { new DisconnectCause(DisconnectCause.OTHER, "IMS_MERGED_SUCCESSFULLY"); doReturn(cause).when(activeCall_1).getDisconnectCause(); doReturn(cause).when(activeCall_2).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall_1, true); - mBluetoothInCallService.onCallRemoved(activeCall_2, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true); BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID()); addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE); @@ -1029,7 +1030,7 @@ public class BluetoothInCallServiceTest { // parent call arrived, but children have not, then do inference on children calls.add(conferenceCall); assertThat(calls).hasSize(1); - mBluetoothInCallService.onCallAdded(conferenceCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall); clearInvocations(mHeadsetService); mBluetoothInCallService.listCurrentCalls(mHeadsetService); @@ -1042,10 +1043,10 @@ public class BluetoothInCallServiceTest { // real children arrive, no change on CLCC response calls.add(activeCall_1); - mBluetoothInCallService.onCallAdded(activeCall_1); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1); doReturn(true).when(activeCall_1).isConference(); calls.add(activeCall_2); - mBluetoothInCallService.onCallAdded(activeCall_2); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2); doReturn(Call.STATE_ACTIVE).when(activeCall_2).getState(); doReturn(true).when(activeCall_2).isConference(); doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds(); @@ -1063,14 +1064,14 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_DISCONNECTED).when(activeCall_1).getState(); cause = new DisconnectCause(DisconnectCause.OTHER); doReturn(cause).when(activeCall_1).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall_1, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true); doReturn(false).when(activeCall_1).isConference(); calls.remove(activeCall_1); assertThat(calls).hasSize(2); // Call 2 removed from conf doReturn(cause).when(activeCall_2).getDisconnectCause(); - mBluetoothInCallService.onCallRemoved(activeCall_2, true); + mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true); doReturn(false).when(activeCall_2).isConference(); clearInvocations(mHeadsetService); @@ -1087,17 +1088,17 @@ public class BluetoothInCallServiceTest { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); doReturn(Uri.parse("tel:5550000")).when(ringingCall).getHandle(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.queryPhoneState(); + mBluetoothInCallService.queryPhoneState(mHeadsetService); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("5550000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "5550000", + PhoneNumberUtils.TOA_Unknown, + null, + false); } @Test @@ -1105,8 +1106,8 @@ public class BluetoothInCallServiceTest { BluetoothCall parentConfCall = createActiveCall(UUID.randomUUID()); final BluetoothCall confCall1 = getMockCall(UUID.randomUUID()); final BluetoothCall confCall2 = getMockCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(confCall1); - mBluetoothInCallService.onCallAdded(confCall2); + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1); + mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2); doReturn(Uri.parse("tel:555-0000")).when(parentConfCall).getHandle(); addCallCapability(parentConfCall, Connection.CAPABILITY_SWAP_CONFERENCE); doReturn(true).when(parentConfCall).wasConferencePreviouslyMerged(); @@ -1114,11 +1115,9 @@ public class BluetoothInCallServiceTest { List<Integer> childrenIds = Arrays.asList(confCall1.getId(), confCall2.getId()); doReturn(childrenIds).when(parentConfCall).getChildrenIds(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.queryPhoneState(); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + mBluetoothInCallService.queryPhoneState(mHeadsetService); + verify(mHeadsetService, times(2)) + .phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test @@ -1126,7 +1125,8 @@ public class BluetoothInCallServiceTest { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); Log.i("BluetoothInCallService", "asdf start " + Integer.toString(ringingCall.hashCode())); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEHELD); + boolean didProcess = + mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_RELEASEHELD); verify(ringingCall).reject(eq(false), nullable(String.class)); assertThat(didProcess).isTrue(); @@ -1135,7 +1135,8 @@ public class BluetoothInCallServiceTest { @Test public void processChldTypeReleaseHeldHold() { BluetoothCall onHoldCall = createHeldCall(UUID.randomUUID()); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEHELD); + boolean didProcess = + mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_RELEASEHELD); verify(onHoldCall).disconnect(); assertThat(didProcess).isTrue(); @@ -1147,7 +1148,8 @@ public class BluetoothInCallServiceTest { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); boolean didProcess = - mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD); + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD); verify(activeCall).disconnect(); verify(ringingCall).answer(any(int.class)); @@ -1159,7 +1161,8 @@ public class BluetoothInCallServiceTest { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); boolean didProcess = - mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD); + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD); verify(activeCall).disconnect(); // BluetoothCall unhold will occur as part of CallsManager auto-unholding @@ -1171,7 +1174,9 @@ public class BluetoothInCallServiceTest { public void processChldHoldActiveRinging() { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); + boolean didProcess = + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); verify(ringingCall).answer(any(int.class)); assertThat(didProcess).isTrue(); @@ -1181,7 +1186,9 @@ public class BluetoothInCallServiceTest { public void processChldHoldActiveUnhold() { BluetoothCall heldCall = createHeldCall(UUID.randomUUID()); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); + boolean didProcess = + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); verify(heldCall).unhold(); assertThat(didProcess).isTrue(); @@ -1192,7 +1199,9 @@ public class BluetoothInCallServiceTest { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); addCallCapability(activeCall, Connection.CAPABILITY_HOLD); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); + boolean didProcess = + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); verify(activeCall).hold(); assertThat(didProcess).isTrue(); @@ -1203,7 +1212,8 @@ public class BluetoothInCallServiceTest { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); addCallCapability(activeCall, Connection.CAPABILITY_MERGE_CONFERENCE); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_ADDHELDTOCONF); + boolean didProcess = + mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_ADDHELDTOCONF); verify(activeCall).mergeConference(); assertThat(didProcess).isTrue(); @@ -1215,11 +1225,12 @@ public class BluetoothInCallServiceTest { BluetoothCall conferenceableCall = getMockCall(UUID.randomUUID()); ArrayList<Integer> conferenceableCalls = new ArrayList<>(); conferenceableCalls.add(conferenceableCall.getId()); - mBluetoothInCallService.onCallAdded(conferenceableCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceableCall); doReturn(conferenceableCalls).when(activeCall).getConferenceableCalls(); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_ADDHELDTOCONF); + boolean didProcess = + mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_ADDHELDTOCONF); verify(activeCall).conference(conferenceableCall); assertThat(didProcess).isTrue(); @@ -1240,13 +1251,12 @@ public class BluetoothInCallServiceTest { List<Integer> childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId()); doReturn(childrenIds).when(parentCall).getChildrenIds(); - clearInvocations(mMockBluetoothHeadset); - boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); + boolean didProcess = + mBluetoothInCallService.processChld( + mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD); verify(parentCall).swapConference(); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false); assertThat(didProcess).isTrue(); } @@ -1256,16 +1266,17 @@ public class BluetoothInCallServiceTest { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("555000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "555000", + PhoneNumberUtils.TOA_Unknown, + null, + false); } @Test @@ -1274,16 +1285,17 @@ public class BluetoothInCallServiceTest { doReturn(true).when(ringingCall).isSilentRingingRequested(); doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); - verify(mMockBluetoothHeadset, never()) + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); } @Test @@ -1299,56 +1311,51 @@ public class BluetoothInCallServiceTest { List<Integer> childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId()); doReturn(childrenIds).when(parentCall).getChildrenIds(); - mBluetoothInCallService.onCallAdded(parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false); } @Test public void onCallRemoved() { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(null).when(mMockCallInfo).getActiveCall(); doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle(); - mBluetoothInCallService.onCallRemoved(activeCall, true /* forceRemoveCallback */); + mBluetoothInCallService.onCallRemoved( + mHeadsetService, activeCall, true /* forceRemoveCallback */); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test public void onDetailsChangeExternalRemovesCall() { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(null).when(mMockCallInfo).getActiveCall(); doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle(); doReturn(true).when(activeCall).isExternalCall(); - mBluetoothInCallService.getCallback(activeCall).onDetailsChanged(activeCall, null); + mBluetoothInCallService + .getCallback(activeCall) + .onDetailsChanged(mHeadsetService, activeCall, null); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test public void onDetailsChangeExternalAddsCall() { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle(); BluetoothInCallService.CallStateCallback callBack = mBluetoothInCallService.getCallback(activeCall); doReturn(true).when(activeCall).isExternalCall(); - callBack.onDetailsChanged(activeCall, null); + callBack.onDetailsChanged(mHeadsetService, activeCall, null); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test @@ -1359,37 +1366,39 @@ public class BluetoothInCallServiceTest { doReturn(List.of(connectingCall, activeCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(connectingCall); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, connectingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); mBluetoothInCallService .getCallback(activeCall) .onStateChanged(activeCall, Call.STATE_HOLDING); - verify(mMockBluetoothHeadset, never()) + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); } @Test public void onCallAddedAudioProcessing() { BluetoothCall call = getMockCall(UUID.randomUUID()); doReturn(Call.STATE_AUDIO_PROCESSING).when(call).getState(); - mBluetoothInCallService.onCallAdded(call); + mBluetoothInCallService.onCallAdded(mHeadsetService, call); - verify(mMockBluetoothHeadset, never()) + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); } @Test @@ -1397,16 +1406,17 @@ public class BluetoothInCallServiceTest { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("555000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "555000", + PhoneNumberUtils.TOA_Unknown, + null, + false); doReturn(Call.STATE_AUDIO_PROCESSING).when(ringingCall).getState(); doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall(); @@ -1415,42 +1425,39 @@ public class BluetoothInCallServiceTest { .getCallback(ringingCall) .onStateChanged(ringingCall, Call.STATE_AUDIO_PROCESSING); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test public void onCallStateChangedAudioProcessingToSimulatedRinging() { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555-0000")).when(ringingCall).getHandle(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); mBluetoothInCallService .getCallback(ringingCall) .onStateChanged(ringingCall, Call.STATE_SIMULATED_RINGING); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("555-0000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "555-0000", + PhoneNumberUtils.TOA_Unknown, + null, + false); } @Test public void onCallStateChangedAudioProcessingToActive() { BluetoothCall activeCall = createActiveCall(UUID.randomUUID()); doReturn(Call.STATE_ACTIVE).when(activeCall).getState(); - mBluetoothInCallService.onCallAdded(activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); mBluetoothInCallService .getCallback(activeCall) .onStateChanged(activeCall, Call.STATE_ACTIVE); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test @@ -1467,74 +1474,56 @@ public class BluetoothInCallServiceTest { .get(activeCall.getId()) .onStateChanged(activeCall, Call.STATE_DIALING); - verify(mMockBluetoothHeadset, never()) + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); } @Test public void onCallStateChangedAlerting() { BluetoothCall outgoingCall = createOutgoingCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(outgoingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, outgoingCall); mBluetoothInCallService .getCallback(outgoingCall) .onStateChanged(outgoingCall, Call.STATE_DIALING); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_DIALING), - eq(""), - eq(128), - nullable(String.class)); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_ALERTING), - eq(""), - eq(128), - nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_DIALING, "", 128, null, false); + verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_ALERTING, "", 128, null, false); } @Test public void onCallStateChangedDisconnected() { BluetoothCall disconnectedCall = createDisconnectedCall(UUID.randomUUID()); doReturn(true).when(mMockCallInfo).hasOnlyDisconnectedCalls(); - mBluetoothInCallService.onCallAdded(disconnectedCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, disconnectedCall); mBluetoothInCallService .getCallback(disconnectedCall) .onStateChanged(disconnectedCall, Call.STATE_DISCONNECTED); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_DISCONNECTED), - eq(""), - eq(128), - nullable(String.class)); + verify(mHeadsetService) + .phoneStateChanged(0, 0, CALL_STATE_DISCONNECTED, "", 128, null, false); } @Test public void onCallStateChanged() { BluetoothCall ringingCall = createRingingCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555-0000")).when(ringingCall).getHandle(); - mBluetoothInCallService.onCallAdded(ringingCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("555-0000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "555-0000", + PhoneNumberUtils.TOA_Unknown, + null, + false); // Switch to active doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall(); @@ -1544,29 +1533,27 @@ public class BluetoothInCallServiceTest { .getCallback(ringingCall) .onStateChanged(ringingCall, Call.STATE_ACTIVE); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false); } @Test public void onCallStateChangedGSMSwap() { BluetoothCall heldCall = createHeldCall(UUID.randomUUID()); doReturn(Uri.parse("tel:555-0000")).when(heldCall).getHandle(); - mBluetoothInCallService.onCallAdded(heldCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall); doReturn(2).when(mMockCallInfo).getNumHeldCalls(); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.getCallback(heldCall).onStateChanged(heldCall, Call.STATE_HOLDING); - verify(mMockBluetoothHeadset, never()) + verify(mHeadsetService, never()) .phoneStateChanged( - eq(0), - eq(2), - eq(CALL_STATE_HELD), - eq("5550000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 2, + CALL_STATE_HELD, + "5550000", + PhoneNumberUtils.TOA_Unknown, + null, + false); } @Test @@ -1577,9 +1564,9 @@ public class BluetoothInCallServiceTest { BluetoothCall parentCall = createActiveCall(UUID.randomUUID()); BluetoothCall activeCall = getMockCall(UUID.randomUUID()); BluetoothCall heldCall = createHeldCall(UUID.randomUUID()); - mBluetoothInCallService.onCallAdded(parentCall); - mBluetoothInCallService.onCallAdded(activeCall); - mBluetoothInCallService.onCallAdded(heldCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall); Integer parentId = parentCall.getId(); doReturn(parentId).when(activeCall).getParentId(); doReturn(parentId).when(heldCall).getParentId(); @@ -1592,51 +1579,58 @@ public class BluetoothInCallServiceTest { addCallCapability(parentCall, Connection.CAPABILITY_SWAP_CONFERENCE); - clearInvocations(mMockBluetoothHeadset); + clearInvocations(mHeadsetService); // Be sure that onIsConferencedChanged rejects spurious changes during set up of // CDMA "conference" - mBluetoothInCallService.getCallback(activeCall).onParentChanged(activeCall); - verify(mMockBluetoothHeadset, never()) + mBluetoothInCallService + .getCallback(activeCall) + .onParentChanged(mHeadsetService, activeCall); + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); - mBluetoothInCallService.getCallback(heldCall).onParentChanged(heldCall); - verify(mMockBluetoothHeadset, never()) + mBluetoothInCallService.getCallback(heldCall).onParentChanged(mHeadsetService, heldCall); + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); mBluetoothInCallService .getCallback(parentCall) .onChildrenChanged( - parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls)); - verify(mMockBluetoothHeadset, never()) + mHeadsetService, + parentCall, + mBluetoothInCallService.getBluetoothCallsByIds(calls)); + verify(mHeadsetService, never()) .phoneStateChanged( anyInt(), anyInt(), anyInt(), anyString(), anyInt(), - nullable(String.class)); + nullable(String.class), + eq(false)); calls.add(heldCall.getId()); - mBluetoothInCallService.onCallAdded(heldCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall); mBluetoothInCallService .getCallback(parentCall) .onChildrenChanged( - parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls)); - verify(mMockBluetoothHeadset) - .phoneStateChanged( - eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class)); + mHeadsetService, + parentCall, + mBluetoothInCallService.getBluetoothCallsByIds(calls)); + verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false); } @Test @@ -1646,20 +1640,20 @@ public class BluetoothInCallServiceTest { Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED); intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON); - clearInvocations(mMockBluetoothHeadset); mBluetoothInCallService.mBluetoothAdapterReceiver = mBluetoothInCallService.new BluetoothAdapterReceiver(); mBluetoothInCallService.mBluetoothAdapterReceiver.onReceive( mBluetoothInCallService, intent); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .phoneStateChanged( - eq(0), - eq(0), - eq(CALL_STATE_INCOMING), - eq("5550000"), - eq(PhoneNumberUtils.TOA_Unknown), - nullable(String.class)); + 0, + 0, + CALL_STATE_INCOMING, + "5550000", + PhoneNumberUtils.TOA_Unknown, + null, + false); } @Test @@ -1667,7 +1661,6 @@ public class BluetoothInCallServiceTest { mBluetoothInCallService.clear(); assertThat(mBluetoothInCallService.mBluetoothAdapterReceiver).isNull(); - assertThat(mBluetoothInCallService.mBluetoothHeadset).isNull(); } @Test @@ -1844,9 +1837,9 @@ public class BluetoothInCallServiceTest { doReturn(List.of(baseCall, firstCall, secondCall)).when(mMockCallInfo).getBluetoothCalls(); - mBluetoothInCallService.onCallAdded(baseCall); - mBluetoothInCallService.onCallAdded(firstCall); - mBluetoothInCallService.onCallAdded(secondCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, secondCall); doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle(); doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle(); @@ -1877,8 +1870,8 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_ACTIVE).when(baseCall).getState(); doReturn(Call.STATE_RINGING).when(firstCall).getState(); - mBluetoothInCallService.onCallAdded(baseCall); - mBluetoothInCallService.onCallAdded(firstCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall); doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle(); doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle(); @@ -1910,9 +1903,9 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_RINGING).when(firstCall).getState(); doReturn(Call.STATE_RINGING).when(secondCall).getState(); - mBluetoothInCallService.onCallAdded(baseCall); - mBluetoothInCallService.onCallAdded(firstCall); - mBluetoothInCallService.onCallAdded(secondCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall); + mBluetoothInCallService.onCallAdded(mHeadsetService, secondCall); doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle(); doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle(); @@ -2000,7 +1993,7 @@ public class BluetoothInCallServiceTest { } private void ManageCall(BluetoothCall call, String TeleString, int STATE) { - mBluetoothInCallService.onCallAdded(call); + mBluetoothInCallService.onCallAdded(mHeadsetService, call); doReturn(STATE).when(call).getState(); doReturn(Uri.parse(TeleString)).when(call).getHandle(); doReturn(new GatewayInfo(null, null, Uri.parse(TeleString))).when(call).getGatewayInfo(); 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 79ebced7de..18a4b4d053 100644 --- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java @@ -72,7 +72,7 @@ public class CallInfoTest { mockGetSystemService( spiedContext, Context.TELECOM_SERVICE, TelecomManager.class, mTelecomManager); - mBluetoothInCallService = new BluetoothInCallService(spiedContext, null, null, null); + mBluetoothInCallService = new BluetoothInCallService(spiedContext, null, null); mBluetoothInCallService.onCreate(); mMockCallInfo = spy(mBluetoothInCallService.new CallInfo()); diff --git a/android/app/tests/unit/Android.bp b/android/app/tests/unit/Android.bp index e0ed60ac22..01d195cc43 100644 --- a/android/app/tests/unit/Android.bp +++ b/android/app/tests/unit/Android.bp @@ -43,6 +43,7 @@ android_test { "flag-junit", "framework-bluetooth-pre-jarjar", "gson", + "guava-android-testlib", "mmslib", "mockito-target-extended", "modules-utils-handlerexecutor", diff --git a/android/app/tests/unit/AndroidTest.xml b/android/app/tests/unit/AndroidTest.xml index f640db51d4..21fa4cb955 100644 --- a/android/app/tests/unit/AndroidTest.xml +++ b/android/app/tests/unit/AndroidTest.xml @@ -62,6 +62,8 @@ So instead we use the app cache folder for filter --> <option name="test-filter-dir" value="/data/data/com.android.bluetooth/cache" /> <option name="hidden-api-checks" value="false"/> + <!-- Ignores tests introduced by guava-android-testlib --> + <option name="exclude-annotation" value="org.junit.Ignore"/> </test> <!-- Only run if the Bluetooth Mainline module is installed. --> @@ -69,5 +71,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/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 5b17d2805f..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) 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/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 66ad64ddea..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( @@ -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/AvrcpItemTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java index a059bb12c4..dbadfc526a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java @@ -20,7 +20,6 @@ import static com.android.bluetooth.TestUtils.getTestDevice; import static com.google.common.truth.Truth.assertThat; -import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.net.Uri; import android.support.v4.media.MediaBrowserCompat.MediaItem; @@ -29,6 +28,8 @@ import android.support.v4.media.MediaMetadataCompat; import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -601,33 +602,15 @@ public final class AvrcpItemTest { } @Test - public void equals_withItself() { - AvrcpItem.Builder builder = new AvrcpItem.Builder(); + public void equals() { + AvrcpItem item = new AvrcpItem.Builder().build(); + AvrcpItem itemEqual = new AvrcpItem.Builder().build(); - AvrcpItem item = builder.build(); - - assertThat(item).isEqualTo(item); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void equals_withDifferentInstance() { - AvrcpItem.Builder builder = new AvrcpItem.Builder(); String notAvrcpItem = "notAvrcpItem"; - AvrcpItem item = builder.build(); - - assertThat(item).isNotEqualTo(notAvrcpItem); - } - - @Test - public void equals_withItemContainingSameInfo() { - AvrcpItem.Builder builder = new AvrcpItem.Builder(); - AvrcpItem.Builder builderEqual = new AvrcpItem.Builder(); - - AvrcpItem item = builder.build(); - AvrcpItem itemEqual = builderEqual.build(); - - assertThat(item).isEqualTo(itemEqual); + new EqualsTester() + .addEqualityGroup(item, item, itemEqual) + .addEqualityGroup(notAvrcpItem) + .testEquals(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java index edf38bad24..dab7613a9a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java @@ -20,7 +20,6 @@ import static com.android.bluetooth.TestUtils.getTestDevice; import static com.google.common.truth.Truth.assertThat; -import android.annotation.SuppressLint; import android.bluetooth.BluetoothDevice; import android.platform.test.annotations.EnableFlags; import android.platform.test.flag.junit.SetFlagsRule; @@ -31,6 +30,8 @@ import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.avrcpcontroller.BrowseTree.BrowseNode; import com.android.bluetooth.flags.Flags; +import com.google.common.testing.EqualsTester; + import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -223,21 +224,18 @@ public class BrowseNodeTest { } @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void equals_withDifferentClass() { - AvrcpItem avrcpItem = new AvrcpItem.Builder().setUuid(TEST_UUID).build(); - - assertThat(mRootNode).isNotEqualTo(avrcpItem); - } - - @Test - public void equals_withSameId() { + public void equals() { BrowseNode browseNodeOne = mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); BrowseNode browseNodeTwo = mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build()); - assertThat(browseNodeOne).isEqualTo(browseNodeTwo); + AvrcpItem avrcpItem = new AvrcpItem.Builder().setUuid(TEST_UUID).build(); + + new EqualsTester() + .addEqualityGroup(browseNodeOne, browseNodeTwo) + .addEqualityGroup(avrcpItem) + .testEquals(); } @Test 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 02a63b298b..03afb2826a 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 @@ -22,6 +22,8 @@ import android.annotation.SuppressLint; import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -422,30 +424,17 @@ public class BipAttachmentFormatTest { } @Test - public void testEquals_withSameInstance() { - BipAttachmentFormat attachment = - new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); - - assertThat(attachment).isEqualTo(attachment); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void testEquals_withDifferentClass() { - BipAttachmentFormat attachment = - new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); - String notAttachment = "notAttachment"; - - assertThat(attachment).isNotEqualTo(notAttachment); - } - - @Test - public void testEquals_withSameInfo() { + public void testEquals() { BipAttachmentFormat attachment = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); BipAttachmentFormat attachmentEqual = new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null); - assertThat(attachment).isEqualTo(attachmentEqual); + String notAttachment = "notAttachment"; + + new EqualsTester() + .addEqualityGroup(attachment, attachment, attachmentEqual) + .addEqualityGroup(notAttachment) + .testEquals(); } } 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 bf3b29a00d..5d93884efb 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 @@ -22,6 +22,8 @@ import android.annotation.SuppressLint; import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -213,29 +215,7 @@ public class BipDatetimeTest { } @Test - public void testEquals_withSameInstance() { - TimeZone utc = TimeZone.getTimeZone("UTC"); - utc.setRawOffset(0); - - BipDateTime bipDate = new BipDateTime(makeDate(1, 1, 2000, 6, 1, 15, utc)); - - assertThat(bipDate).isEqualTo(bipDate); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void testEquals_withDifferentClass() { - TimeZone utc = TimeZone.getTimeZone("UTC"); - utc.setRawOffset(0); - - BipDateTime bipDate = new BipDateTime(makeDate(1, 1, 2000, 6, 1, 15, utc)); - String notBipDate = "notBipDate"; - - assertThat(bipDate).isNotEqualTo(notBipDate); - } - - @Test - public void testEquals_withSameInfo() { + public void testEquals() { TimeZone utc = TimeZone.getTimeZone("UTC"); utc.setRawOffset(0); Date date = makeDate(1, 1, 2000, 6, 1, 15, utc); @@ -243,6 +223,11 @@ public class BipDatetimeTest { BipDateTime bipDate = new BipDateTime(date); BipDateTime bipDateEqual = new BipDateTime(date); - assertThat(bipDate).isEqualTo(bipDateEqual); + String notBipDate = "notBipDate"; + + new EqualsTester() + .addEqualityGroup(bipDate, bipDate, bipDateEqual) + .addEqualityGroup(notBipDate) + .testEquals(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java index 58f89753cd..8d0415dcaa 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java @@ -18,10 +18,10 @@ package com.android.bluetooth.avrcpcontroller; import static com.google.common.truth.Truth.assertThat; -import android.annotation.SuppressLint; - import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -240,33 +240,15 @@ public class BipImageDescriptorTest { } @Test - public void testEquals_sameInstance() { - BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); - - BipImageDescriptor descriptor = builder.build(); - - assertThat(descriptor).isEqualTo(descriptor); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void testEquals_differentClass() { - BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); + public void testEquals() { + BipImageDescriptor descriptor = new BipImageDescriptor.Builder().build(); + BipImageDescriptor descriptorEqual = new BipImageDescriptor.Builder().build(); - BipImageDescriptor descriptor = builder.build(); String notDescriptor = "notDescriptor"; - assertThat(descriptor).isNotEqualTo(notDescriptor); - } - - @Test - public void testEquals_sameInfo() { - BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder(); - BipImageDescriptor.Builder builderEqual = new BipImageDescriptor.Builder(); - - BipImageDescriptor descriptor = builder.build(); - BipImageDescriptor descriptorEqual = builderEqual.build(); - - assertThat(descriptor).isEqualTo(descriptorEqual); + new EqualsTester() + .addEqualityGroup(descriptor, descriptor, descriptorEqual) + .addEqualityGroup(notDescriptor) + .testEquals(); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java index 2f1e60cf34..75d04f6c8b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java @@ -18,10 +18,10 @@ package com.android.bluetooth.avrcpcontroller; import static com.google.common.truth.Truth.assertThat; -import android.annotation.SuppressLint; - import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -308,37 +308,18 @@ public class BipImageFormatTest { } @Test - public void testEquals_withSameInstance() { - BipImageFormat format = - BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), - BipPixel.createFixed(1280, 1024), - -1); - - assertThat(format).isEqualTo(format); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void testEquals_withDifferentClass() { - BipImageFormat format = - BipImageFormat.createNative( - new BipEncoding(BipEncoding.JPEG, null), - BipPixel.createFixed(1280, 1024), - -1); - String notFormat = "notFormat"; - - assertThat(format).isNotEqualTo(notFormat); - } - - @Test - public void testEquals_withSameInfo() { + public void testEquals() { BipEncoding encoding = new BipEncoding(BipEncoding.JPEG, null); BipPixel pixel = BipPixel.createFixed(1280, 1024); BipImageFormat format = BipImageFormat.createNative(encoding, pixel, -1); BipImageFormat formatEqual = BipImageFormat.createNative(encoding, pixel, -1); - assertThat(format).isEqualTo(formatEqual); + String notFormat = "notFormat"; + + new EqualsTester() + .addEqualityGroup(format, format, formatEqual) + .addEqualityGroup(notFormat) + .testEquals(); } } 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 5aef26da78..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<>(); @@ -3318,9 +3321,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT - }) public void testAddSourceForExternalBroadcast_triggerSetContextMask() { final int testGroupId = 1; prepareConnectedDeviceGroup(); @@ -4051,20 +4051,15 @@ public class BassClientServiceTest { verifyAddSourceForGroup(meta); prepareRemoteSourceState(meta, /* isPaSynced */ true, /* isBisSynced */ false); - if (Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - injectRemoteSourceStateChanged(meta, /* isPaSynced */ true, /* isBisSynced */ true); - verify(mLeAudioService).activeBroadcastAssistantNotification(eq(true)); - Mockito.clearInvocations(mLeAudioService); + injectRemoteSourceStateChanged(meta, /* isPaSynced */ true, /* isBisSynced */ true); + verify(mLeAudioService).activeBroadcastAssistantNotification(eq(true)); + Mockito.clearInvocations(mLeAudioService); - /* Imitate broadcast source stop, sink notify about loosing PA and BIS sync */ - injectRemoteSourceStateChanged(meta, /* isPaSynced */ false, /* isBisSynced */ false); + /* Imitate broadcast source stop, sink notify about loosing PA and BIS sync */ + injectRemoteSourceStateChanged(meta, /* isPaSynced */ false, /* isBisSynced */ false); - /* Unicast would like to stream */ - mBassClientService.cacheSuspendingSources(TEST_BROADCAST_ID); - } else { - mBassClientService.suspendAllReceiversSourceSynchronization(); - verifyRemoveMessageAndInjectSourceRemoval(); - } + /* Unicast would like to stream */ + mBassClientService.cacheSuspendingSources(TEST_BROADCAST_ID); mBassClientService.resumeReceiversSourceSynchronization(); handleHandoverSupport(); @@ -4093,12 +4088,8 @@ public class BassClientServiceTest { mBassClientService.handleUnicastSourceStreamStatusChange( 0 /* STATUS_LOCAL_STREAM_REQUESTED */); - if (Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - /* Imitate broadcast source stop, sink notify about loosing PA and BIS sync */ - injectRemoteSourceStateChanged(meta, /* isPaSynced */ false, /* isBisSynced */ false); - } else { - verifyRemoveMessageAndInjectSourceRemoval(); - } + /* Imitate broadcast source stop, sink notify about loosing PA and BIS sync */ + injectRemoteSourceStateChanged(meta, /* isPaSynced */ false, /* isBisSynced */ false); /* Unicast finished streaming */ mBassClientService.handleUnicastSourceStreamStatusChange( @@ -4115,7 +4106,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT) public void testHandleUnicastSourceStreamStatusChange_MultipleRequests() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -4312,7 +4302,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT) public void testLocalAddSourceWhenBroadcastIsPlaying() throws RemoteException { doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID); if (Flags.leaudioBigDependsOnAudioState()) { @@ -4324,7 +4313,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT, Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE }) public void testLocalAddSourceWhenBroadcastIsPaused() throws RemoteException { @@ -4335,7 +4323,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT) public void testLocalAddSourceWhenBroadcastIsStopped() throws RemoteException { doReturn(false).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID); if (Flags.leaudioBigDependsOnAudioState()) { @@ -6749,9 +6736,6 @@ public class BassClientServiceTest { // Suspend receivers, HOST_INTENTIONAL mBassClientService.suspendReceiversSourceSynchronization(TEST_BROADCAST_ID); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @@ -6763,9 +6747,6 @@ public class BassClientServiceTest { // Suspend receivers, HOST_INTENTIONAL mBassClientService.suspendReceiversSourceSynchronization(TEST_BROADCAST_ID); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @@ -6777,9 +6758,6 @@ public class BassClientServiceTest { // Suspend all receivers, HOST_INTENTIONAL mBassClientService.suspendAllReceiversSourceSynchronization(); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @@ -6791,9 +6769,6 @@ public class BassClientServiceTest { // Suspend all receivers, HOST_INTENTIONAL mBassClientService.suspendAllReceiversSourceSynchronization(); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @@ -6806,9 +6781,6 @@ public class BassClientServiceTest { mBassClientService.handleUnicastSourceStreamStatusChange( 0 /* STATUS_LOCAL_STREAM_REQUESTED */); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } /* Unicast finished streaming */ mBassClientService.handleUnicastSourceStreamStatusChange( @@ -6826,9 +6798,6 @@ public class BassClientServiceTest { mBassClientService.handleUnicastSourceStreamStatusChange( 0 /* STATUS_LOCAL_STREAM_REQUESTED */); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } /* Unicast finished streaming */ mBassClientService.handleUnicastSourceStreamStatusChange( @@ -6839,7 +6808,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT, Flags.FLAG_LEAUDIO_MONITOR_UNICAST_SOURCE_WHEN_MANAGED_BY_BROADCAST_DELEGATOR }) public void hostIntentional_handleUnicastSourceStreamStatusChange_beforeResumeCompleted() { @@ -7684,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); @@ -7710,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); @@ -7774,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); @@ -7808,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); @@ -7865,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 @@ -7883,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); @@ -7922,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 @@ -7940,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); @@ -7972,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 @@ -8021,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 393081d6d6..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; @@ -192,12 +197,12 @@ public class BassClientStateMachineTest { 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); } 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/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 79dc4def5e..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,12 @@ 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; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -36,6 +42,8 @@ import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties; import com.android.bluetooth.flags.Flags; import com.android.bluetooth.hfp.HeadsetHalConstants; +import org.hamcrest.Matcher; +import org.hamcrest.core.AllOf; import org.junit.After; import org.junit.Before; import org.junit.Ignore; @@ -43,7 +51,9 @@ import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; +import org.mockito.hamcrest.MockitoHamcrest; import java.util.ArrayList; @@ -54,6 +64,7 @@ public class RemoteDevicesTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private AdapterService mAdapterService; + private InOrder mInOrder; private final ArgumentCaptor<Intent> mIntentArgument = ArgumentCaptor.forClass(Intent.class); private final ArgumentCaptor<String> mStringArgument = ArgumentCaptor.forClass(String.class); @@ -69,6 +80,7 @@ public class RemoteDevicesTest { @Before public void setUp() { + mInOrder = inOrder(mAdapterService); mHandlerThread = new HandlerThread("RemoteDevicesTestHandlerThread"); mHandlerThread.start(); mTestLooperManager = @@ -266,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( @@ -315,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()) @@ -581,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)) @@ -632,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()) @@ -846,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(); @@ -858,4 +870,133 @@ public class RemoteDevicesTest { private static void clearBatteryServiceForTesting(BatteryService service) { BatteryService.setBatteryService(service); } + + private void verifyIntentSent(Matcher<Intent>... matchers) { + mInOrder.verify(mAdapterService) + .sendBroadcast( + MockitoHamcrest.argThat(AllOf.allOf(matchers)), + eq(BLUETOOTH_CONNECT), + any(Bundle.class)); + } + + private void verifyBatteryLevelUpdateIntent(int batteryLevel) { + verifyIntentSent( + hasAction(BluetoothDevice.ACTION_BATTERY_LEVEL_CHANGED), + hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice), + hasExtra(BluetoothDevice.EXTRA_BATTERY_LEVEL, batteryLevel)); + } + + private void verifyNoIntentSentForBatteryLevelUpdate() { + mInOrder.verify(mAdapterService, never()).sendBroadcastAsUser(any(), any(), any(), any()); + mInOrder.verify(mAdapterService, never()) + .sendBroadcastWithMultiplePermissions(any(), any()); + } + + @Test + @EnableFlags(Flags.FLAG_ENABLE_BATTERY_LEVEL_UPDATE_ONLY_THROUGH_HF_INDICATOR) + public void testResetBatteryLevel_testHfpBatteryIndicatorEnabled() { + int batteryLevel = 25; + + // Verify that device property is null initially + assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNull(); + + // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent + mRemoteDevices.updateBatteryLevel(mDevice, batteryLevel, /* fromBas= */ false); + + verifyBatteryLevelUpdateIntent(batteryLevel); + + // Verify that user can get battery level after the update + assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull(); + assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) + .isEqualTo(batteryLevel); + + // Verify that the HFP indicator is disabled + assertThat(mRemoteDevices.getDeviceProperties(mDevice).isHfpBatteryIndicatorEnabled()) + .isEqualTo(false); + + // Set HF indicator + mRemoteDevices.onHfIndicatorStatus( + mDevice, HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS, true); + + // Verify that the HFP indicator is enabled + assertThat(mRemoteDevices.getDeviceProperties(mDevice).isHfpBatteryIndicatorEnabled()) + .isEqualTo(true); + + // Try to set battery level with vendor specific event + mRemoteDevices.onVendorSpecificHeadsetEvent( + mDevice, + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV, + BluetoothAssignedNumbers.APPLE, + BluetoothHeadset.AT_CMD_TYPE_SET, + new Object[] { + 3, + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 5, + 2, + 1, + 3, + 10 + }); + + // Vendor specific event xevent + mRemoteDevices.onVendorSpecificHeadsetEvent( + mDevice, + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_XEVENT, + BluetoothAssignedNumbers.PLANTRONICS, + BluetoothHeadset.AT_CMD_TYPE_SET, + getXEventArray(3, 8)); + + verifyNoIntentSentForBatteryLevelUpdate(); + + // Verify that the battery level is still same + assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) + .isEqualTo(batteryLevel); + + int newBatteryLevel = 60; + + // Verify that updating battery level triggers ACTION_BATTERY_LEVEL_CHANGED intent + mRemoteDevices.updateBatteryLevel(mDevice, newBatteryLevel, false); + + verifyBatteryLevelUpdateIntent(newBatteryLevel); + + // Verify that user can get battery level after the update + assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull(); + assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) + .isEqualTo(newBatteryLevel); + + // Verify that the HFP indicator is enabled + assertThat(mRemoteDevices.getDeviceProperties(mDevice).isHfpBatteryIndicatorEnabled()) + .isEqualTo(true); + + // Set HF indicator to false + mRemoteDevices.onHfIndicatorStatus( + mDevice, HeadsetHalConstants.HF_INDICATOR_BATTERY_LEVEL_STATUS, false); + + // Verify that the HFP indicator is disabled + assertThat(mRemoteDevices.getDeviceProperties(mDevice).isHfpBatteryIndicatorEnabled()) + .isEqualTo(false); + + // Try to set battery level with vendor specific event + mRemoteDevices.onVendorSpecificHeadsetEvent( + mDevice, + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV, + BluetoothAssignedNumbers.APPLE, + BluetoothHeadset.AT_CMD_TYPE_SET, + new Object[] { + 3, + BluetoothHeadset.VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL, + 4, + 2, + 1, + 3, + 10 + }); + + newBatteryLevel = 50; + verifyBatteryLevelUpdateIntent(newBatteryLevel); + + // Verify that the battery level is still same + assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel()) + .isEqualTo(newBatteryLevel); + } } 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/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/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/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..9fadbcb9a7 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); } @@ -168,18 +170,4 @@ public class BluetoothHeadsetBinderTest { mBinder.stopScoUsingVirtualVoiceCall(mAttributionSource); verify(mService).stopScoUsingVirtualVoiceCall(); } - - @Test - public void phoneStateChanged() { - int numActive = 2; - int numHeld = 5; - int callState = HeadsetHalConstants.CALL_STATE_IDLE; - String number = "000-000-0000"; - int type = 0; - String name = "Unknown"; - mBinder.phoneStateChanged( - numActive, numHeld, callState, number, type, name, mAttributionSource); - verify(mService) - .phoneStateChanged(numActive, numHeld, callState, number, type, name, false); - } } 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..6f9a0afd36 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); @@ -1509,7 +1478,7 @@ public class HeadsetStateMachineTest { @Test public void testProcessAtChld_withProcessChldTrue() { int chld = 1; - when(mSystemInterface.processChld(chld)).thenReturn(true); + when(mSystemInterface.processChld(mHeadsetService, chld)).thenReturn(true); mHeadsetStateMachine.processAtChld(chld, mDevice); @@ -1519,7 +1488,7 @@ public class HeadsetStateMachineTest { @Test public void testProcessAtChld_withProcessChldFalse() { int chld = 1; - when(mSystemInterface.processChld(chld)).thenReturn(false); + when(mSystemInterface.processChld(mHeadsetService, chld)).thenReturn(false); mHeadsetStateMachine.processAtChld(chld, mDevice); @@ -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/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 26a10f68f1..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); 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 8732e2ab19..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 @@ -1405,11 +1405,7 @@ public class LeAudioBroadcastServiceTest { state_event.valueInt2 = LeAudioStackEvent.BROADCAST_STATE_PAUSED; mService.messageFromNative(state_event); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verify(mBassClientService).suspendReceiversSourceSynchronization(eq(broadcastId)); - } else { - verify(mBassClientService).cacheSuspendingSources(eq(broadcastId)); - } + verify(mBassClientService).cacheSuspendingSources(eq(broadcastId)); /* Internal broadcast resumed due to onAudioResumed */ state_event.valueInt2 = LeAudioStackEvent.BROADCAST_STATE_STREAMING; 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 9f608b8708..2321581fa2 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(); @@ -1243,9 +1225,11 @@ public class LeAudioServiceTest { assertThat(connInfo.isSuppressNoisyIntent()).isTrue(); // AudioManager removes audio device + // We just ignore it as AudioManager is going to restart and re-add devices injectAudioDeviceRemoved( - mSingleDevice, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, true); - verify(mNativeInterface, times(1)).groupSetActive(-1); + mSingleDevice, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, false); + + verify(mNativeInterface, never()).groupSetActive(-1); } /** Test setting active device group without Ringtone context */ @@ -1630,14 +1614,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,9 +2210,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); - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BROADCAST_VOLUME_CONTROL_PRIMARY_GROUP_ONLY); - int groupId = 1; int groupId2 = 2; int volume = 100; @@ -2439,7 +2416,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(); @@ -2452,9 +2429,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/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/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java index 2312d11787..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; } @@ -412,8 +412,8 @@ 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; } @@ -479,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); }); } @@ -507,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); } } @@ -530,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); }); } @@ -552,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); }); } @@ -574,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); }); } @@ -602,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); } } @@ -635,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); } } @@ -661,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); }); } @@ -699,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 @@ -707,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); }); } @@ -771,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); }); } @@ -804,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); }); } @@ -847,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); } } @@ -885,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 @@ -894,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); }); } @@ -928,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); } } @@ -969,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 @@ -980,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); } } @@ -1009,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 @@ -1019,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); }); } @@ -1124,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(); @@ -1167,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(); @@ -1292,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( @@ -1494,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), @@ -1802,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 @@ -1826,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 @@ -1944,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), @@ -1976,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), @@ -1995,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/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/map/MsgTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java index 041a7ff86d..f9f0b50fa1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java @@ -18,11 +18,11 @@ package com.android.bluetooth.map; import static com.google.common.truth.Truth.assertThat; -import android.annotation.SuppressLint; - import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; +import com.google.common.testing.EqualsTester; + import org.junit.Test; import org.junit.runner.RunWith; @@ -53,50 +53,22 @@ public class MsgTest { } @Test - public void equals_withSameInstance() { - BluetoothMapContentObserver.Msg msg = - new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); - - assertThat(msg.equals(msg)).isTrue(); - } - - @Test - public void equals_withNull() { - BluetoothMapContentObserver.Msg msg = - new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); - - assertThat(msg).isNotNull(); - } - - @Test - @SuppressLint("TruthIncompatibleType") // That the point of this test - public void equals_withDifferentClass() { - BluetoothMapContentObserver.Msg msg = - new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); - String msgOfDifferentClass = "msg_of_different_class"; - - assertThat(msg).isNotEqualTo(msgOfDifferentClass); - } - - @Test - public void equals_withDifferentId() { + public void equals() { long idOne = 1; long idTwo = 2; BluetoothMapContentObserver.Msg msg = new BluetoothMapContentObserver.Msg(idOne, TEST_FOLDER_ID, TEST_READ_FLAG); + BluetoothMapContentObserver.Msg msgWithSameId = + new BluetoothMapContentObserver.Msg(idOne, TEST_FOLDER_ID, TEST_READ_FLAG); BluetoothMapContentObserver.Msg msgWithDifferentId = new BluetoothMapContentObserver.Msg(idTwo, TEST_FOLDER_ID, TEST_READ_FLAG); - assertThat(msg).isNotEqualTo(msgWithDifferentId); - } - - @Test - public void equals_withEqualInstance() { - BluetoothMapContentObserver.Msg msg = - new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); - BluetoothMapContentObserver.Msg msgWithSameId = - new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG); + String msgOfDifferentClass = "msg_of_different_class"; - assertThat(msg).isEqualTo(msgWithSameId); + new EqualsTester() + .addEqualityGroup(msg, msg, msgWithSameId) + .addEqualityGroup(msgWithDifferentId, msgWithDifferentId) + .addEqualityGroup(msgOfDifferentClass) + .testEquals(); } } 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/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/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/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 b48329a9c3..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 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/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/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java index e32b68591a..35d8ee3ce1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlServiceTest.java @@ -694,7 +694,6 @@ public class VolumeControlServiceTest { /** Test if phone will set volume which is read from the buds */ @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_VOLUME_CONTROL_PRIMARY_GROUP_ONLY) public void connectedDeviceWithUserPersistFlagSet() { int groupId = 1; int volumeDevice = 56; @@ -1440,7 +1439,6 @@ public class VolumeControlServiceTest { /** Test Volume Control changed for broadcast primary group. */ @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_VOLUME_CONTROL_PRIMARY_GROUP_ONLY) public void volumeControlChangedForBroadcastPrimaryGroup() { int groupId = 1; int groupVolume = 30; 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 fe4b50d9cb..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" @@ -138,3 +132,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "enable_battery_level_update_only_through_hf_indicator" + namespace: "bluetooth" + description: "Flag to ignore vendor specific battery level update when HF indicator support is enabled." + bug: "385870861" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/leaudio.aconfig b/flags/leaudio.aconfig index 7a6904f120..4535d65a98 100644 --- a/flags/leaudio.aconfig +++ b/flags/leaudio.aconfig @@ -86,26 +86,6 @@ flag { } flag { - name: "leaudio_broadcast_assistant_peripheral_entrustment" - namespace: "bluetooth" - description: "Give peripheral devices more responsibility for source handling" - bug: "333050419" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -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" @@ -126,16 +106,6 @@ flag { } flag { - name: "leaudio_broadcast_update_metadata_callback" - namespace: "bluetooth" - description: "Notify upper layer with callback when medadata is updated" - bug: "347710374" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { name: "headtracker_sdu_size" namespace: "bluetooth" description: "Use updated headtracker SDU size" @@ -166,16 +136,6 @@ flag { } flag { - name: "leaudio_broadcast_volume_control_primary_group_only" - namespace: "bluetooth" - description: "Only control broadcast primary group volume" - bug: "354201794" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { name: "leaudio_set_codec_config_preference" namespace: "bluetooth" description: "New apis to set codec config preference" 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/flags/rfcomm.aconfig b/flags/rfcomm.aconfig index 1ea744c092..fcd640695e 100644 --- a/flags/rfcomm.aconfig +++ b/flags/rfcomm.aconfig @@ -30,3 +30,23 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "indicate_rfcomm_connection_complete_after_msc" + namespace: "bluetooth" + description: "Indicate RFCOMM connection complete after sending Modem Status Command" + bug: "393594567" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "rfcomm_fix_mux_collision_handling" + namespace: "bluetooth" + description: "Properly handle incoming connections while connecting" + bug: "399420482" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/framework/java/android/bluetooth/BluetoothA2dp.java b/framework/java/android/bluetooth/BluetoothA2dp.java index 06e98105cd..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,33 +1096,6 @@ 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; 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 bf5ec5ae21..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; @@ -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; 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/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 08642c3800..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; } diff --git a/framework/java/android/bluetooth/BluetoothHeadset.java b/framework/java/android/bluetooth/BluetoothHeadset.java index dc99736bbf..448bb05ea0 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; } /** @@ -1127,36 +1130,6 @@ public final class BluetoothHeadset implements BluetoothProfile { } /** - * Notify Headset of phone state change. This is a backdoor for phone app to call - * BluetoothHeadset since there is currently not a good way to get precise call state change - * outside of phone app. - * - * @hide - */ - @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) - @RequiresBluetoothConnectPermission - @RequiresPermission( - allOf = { - BLUETOOTH_CONNECT, - MODIFY_PHONE_STATE, - }) - public void phoneStateChanged( - int numActive, int numHeld, int callState, String number, int type, String name) { - final IBluetoothHeadset service = getService(); - if (service == null) { - Log.w(TAG, "Proxy not attached to service"); - if (DBG) log(Log.getStackTraceString(new Throwable())); - } else if (isEnabled()) { - try { - service.phoneStateChanged( - numActive, numHeld, callState, number, type, name, mAttributionSource); - } catch (RemoteException e) { - Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); - } - } - } - - /** * Sends a vendor-specific unsolicited result code to the headset. * * <p>The actual string to be sent is <code>command + ": " + arg</code>. For example, if {@code 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 0a4e829216..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; } /** diff --git a/framework/java/android/bluetooth/BluetoothHidDevice.java b/framework/java/android/bluetooth/BluetoothHidDevice.java index 8fd7dee6f7..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) { 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 09683a912a..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,29 +1331,7 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { 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; } private static boolean isValidDevice(@Nullable BluetoothDevice device) { 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 afa796b85e..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); 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/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/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/OWNERS b/framework/tests/bumble/src/android/bluetooth/sockets/OWNERS new file mode 100644 index 0000000000..f9b588d2e9 --- /dev/null +++ b/framework/tests/bumble/src/android/bluetooth/sockets/OWNERS @@ -0,0 +1,3 @@ +# Project owners +bhaktha@google.com +poahlo@google.com diff --git a/framework/tests/bumble/src/android/bluetooth/DckL2capTest.kt b/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt index aebaadaa5b..9f06aa6c18 100644 --- a/framework/tests/bumble/src/android/bluetooth/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 @@ -158,7 +160,7 @@ public class DckL2capTest() : Closeable { val waitFlow = flow { emit(waitConnection(dckSpsm, remoteDevice)) } val connectJob = scope.launch { - //give some time for Bumble to host the socket server + // give some time for Bumble to host the socket server Thread.sleep(200) bluetoothSocket.connect() Log.d(TAG, "testSend: Bluetooth socket connected") @@ -298,7 +300,7 @@ public class DckL2capTest() : Closeable { val waitFlow = flow { emit(waitConnection(dckSpsm, remoteDevice)) } val connectJob = scope.launch { - //give some time for Bumble to host the socket server + // give some time for Bumble to host the socket server Thread.sleep(200) bluetoothSocket.connect() Log.d(TAG, "testSendOverEncryptedOnlySocket: Bluetooth socket connected") @@ -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/ActiveLog.kt b/service/src/ActiveLog.kt index c504363d22..46e3a5570d 100644 --- a/service/src/ActiveLog.kt +++ b/service/src/ActiveLog.kt @@ -65,13 +65,12 @@ object ActiveLogs { } @JvmStatic - @JvmOverloads - fun add( - reason: Int, - enable: Boolean, - packageName: String = "BluetoothSystemServer", - isBle: Boolean = false - ) { + fun add(reason: Int, enable: Boolean) { + add(reason, enable, "BluetoothSystemServer", false) + } + + @JvmStatic + fun add(reason: Int, enable: Boolean, packageName: String, isBle: Boolean) { val last = activeLogs.lastOrNull() if (activeLogs.size == MAX_ENTRIES_STORED) { activeLogs.removeFirst() @@ -100,7 +99,7 @@ object ActiveLogs { reason, packageName, lastState, - timeSinceLastChanged + timeSinceLastChanged, ) } } diff --git a/system/audio/asrc/asrc_resampler.cc b/system/audio/asrc/asrc_resampler.cc index 7e44d9ade6..a0dc25995c 100644 --- a/system/audio/asrc/asrc_resampler.cc +++ b/system/audio/asrc/asrc_resampler.cc @@ -170,7 +170,7 @@ public: : state_{.id = StateId::RESET}, reference_timing_{0, 0, 0} { if (com::android::bluetooth::flags::run_clock_recovery_in_worker_thread()) { read_clock_timer_.SchedulePeriodic( - thread->GetWeakPtr(), FROM_HERE, + thread->GetWeakPtr(), base::BindRepeating( [](void*) { bluetooth::shim::GetHciLayer()->EnqueueCommand( @@ -183,7 +183,7 @@ public: std::chrono::milliseconds(100)); } else { read_clock_timer_.SchedulePeriodic( - get_main_thread()->GetWeakPtr(), FROM_HERE, + get_main_thread()->GetWeakPtr(), base::BindRepeating( [](void*) { bluetooth::shim::GetHciLayer()->EnqueueCommand( 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/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp index 64a85ddfe4..da0f17c726 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp @@ -92,7 +92,7 @@ void A2dpEncodingFuzzer::process(const uint8_t* data, size_t size) { bluetooth::common::MessageLoopThread messageLoopThread(name); messageLoopThread.StartUp(); - messageLoopThread.DoInThread(FROM_HERE, base::BindOnce(&source_init_delayed)); + messageLoopThread.DoInThread(base::BindOnce(&source_init_delayed)); uint16_t delayReport = fdp.ConsumeIntegral<uint16_t>(); bluetooth::audio::a2dp::set_remote_delay(delayReport); diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp index e382dbeb62..82f8b224a7 100644 --- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp +++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp @@ -51,7 +51,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { std::string name = fdp.ConsumeRandomLengthString(kRandomStringLength); bluetooth::common::MessageLoopThread messageLoopThread(name); messageLoopThread.StartUp(); - messageLoopThread.DoInThread(FROM_HERE, base::BindOnce(&source_init_delayed)); + messageLoopThread.DoInThread(base::BindOnce(&source_init_delayed)); LeAudioClientInterface* interface = LeAudioClientInterface::Get(); diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.cc b/system/audio_hal_interface/hidl/client_interface_hidl.cc index 4bea626d5b..4a633a47f1 100644 --- a/system/audio_hal_interface/hidl/client_interface_hidl.cc +++ b/system/audio_hal_interface/hidl/client_interface_hidl.cc @@ -163,7 +163,6 @@ public: if (bluetooth_audio_clientif_ != nullptr && message_loop_ != nullptr) { // restart the session on the correct thread message_loop_->DoInThread( - FROM_HERE, base::BindOnce(&BluetoothAudioClientInterface::RenewAudioProviderAndSession, base::Unretained(bluetooth_audio_clientif_))); } else { 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 b155260fb9..c578da63cf 100644 --- a/system/bta/gatt/bta_gattc_int.h +++ b/system/bta/gatt/bta_gattc_int.h @@ -366,6 +366,8 @@ extern tBTA_GATTC_CB bta_gattc_cb; /***************************************************************************** * Function prototypes ****************************************************************************/ +void bta_gatt_client_dump(int fd); + bool bta_gattc_hdl_event(const BT_HDR_RIGID* p_msg); bool bta_gattc_sm_execute(tBTA_GATTC_CLCB* p_clcb, uint16_t event, const tBTA_GATTC_DATA* p_data); @@ -480,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 ffb9ff9eef..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,19 +94,13 @@ 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); } wakelock_acquire(); - audio_timer.SchedulePeriodic(get_main_thread()->GetWeakPtr(), FROM_HERE, + audio_timer.SchedulePeriodic(get_main_thread()->GetWeakPtr(), base::BindRepeating(&send_audio_data), std::chrono::milliseconds(data_interval_ms)); log::info("running with 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/test/headless/android_namespace.cc b/system/bta/include/bta_gatts_co.h index 2c4eee7f74..00d33e8896 100644 --- a/system/test/headless/android_namespace.cc +++ b/system/bta/include/bta_gatts_co.h @@ -1,5 +1,5 @@ /* - * Copyright 2023 The Android Open Source Project + * Copyright 2025 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. @@ -14,6 +14,8 @@ * limitations under the License. */ -extern "C" { -struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; } -} // "C" +#pragma once + +#include "types/raw_address.h" + +void btif_gatts_add_bonded_dev_from_nv(const RawAddress& bda); 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 ba1560bb89..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; @@ -57,16 +55,13 @@ using namespace bluetooth; 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_thread.DoInThread(FROM_HERE, std::move(task))) { + if (!message_loop_thread.DoInThread(std::move(task))) { log::error("failed to post task to task runner!"); return BT_STATUS_FAIL; } 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 2ee512f1fc..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 @@ -264,7 +264,7 @@ void SourceImpl::StartAudioTicks() { worker_thread_, source_codec_config_.num_channels, source_codec_config_.sample_rate, source_codec_config_.bits_per_sample, source_codec_config_.data_interval_us); audio_timer_.SchedulePeriodic( - worker_thread_->GetWeakPtr(), FROM_HERE, + worker_thread_->GetWeakPtr(), base::BindRepeating(&SourceImpl::SendAudioData, weak_factory_.GetWeakPtr()), std::chrono::microseconds(source_codec_config_.data_interval_us)); } @@ -280,7 +280,7 @@ bool SourceImpl::OnSuspendReq() { if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) { if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr())); + base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr())); } else { StopAudioTicks(); } @@ -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, @@ -379,7 +382,7 @@ void SourceImpl::Stop() { if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) { if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr())); + base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr())); } else { StopAudioTicks(); } @@ -404,7 +407,7 @@ void SourceImpl::ConfirmStreamingRequest() { if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) { worker_thread_->DoInThread( - FROM_HERE, base::BindOnce(&SourceImpl::StartAudioTicks, weak_factory_.GetWeakPtr())); + base::BindOnce(&SourceImpl::StartAudioTicks, weak_factory_.GetWeakPtr())); } else { StartAudioTicks(); } 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.cc b/system/bta/le_audio/broadcaster/broadcaster.cc index e72757a129..5e96d73357 100644 --- a/system/bta/le_audio/broadcaster/broadcaster.cc +++ b/system/bta/le_audio/broadcaster/broadcaster.cc @@ -1186,24 +1186,18 @@ private: } void OnAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { - if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { - if (!instance) { - return; - } + if (!instance) { + return; + } - auto const& iter = - std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); - if (iter != instance->broadcasts_.cend()) { - iter->second->OnUpdateAnnouncement(status); - } else { - log::warn("Ignored OnAdvertisingDataSet callback advertiser_id:{}", advertiser_id); - } + auto const& iter = std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), + [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); + if (iter != instance->broadcasts_.cend()) { + iter->second->OnUpdateAnnouncement(status); } else { - log::warn("Not being used, ignored OnAdvertisingDataSet callback advertiser_id:{}", - advertiser_id); + log::warn("Ignored OnAdvertisingDataSet callback advertiser_id:{}", advertiser_id); } } @@ -1226,25 +1220,18 @@ private: } void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, uint8_t status) { - if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { - if (!instance) { - return; - } + if (!instance) { + return; + } - auto const& iter = - std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), - [advertiser_id](auto const& sm) { - return sm.second->GetAdvertisingSid() == advertiser_id; - }); - if (iter != instance->broadcasts_.cend()) { - iter->second->OnUpdateAnnouncement(status); - } else { - log::warn("Ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", - advertiser_id); - } + auto const& iter = std::find_if(instance->broadcasts_.cbegin(), instance->broadcasts_.cend(), + [advertiser_id](auto const& sm) { + return sm.second->GetAdvertisingSid() == advertiser_id; + }); + if (iter != instance->broadcasts_.cend()) { + iter->second->OnUpdateAnnouncement(status); } else { - log::warn("Not being used, ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", - advertiser_id); + log::warn("Ignored OnPeriodicAdvertisingDataSet callback advertiser_id:{}", advertiser_id); } } diff --git a/system/bta/le_audio/broadcaster/broadcaster_test.cc b/system/bta/le_audio/broadcaster/broadcaster_test.cc index 15ef0256f5..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 { @@ -96,13 +96,12 @@ void invoke_switch_buffer_size_cb(bool /*is_low_latency_buffer_size*/) {} bt_status_t do_in_main_thread(base::OnceClosure task) { // 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( - FROM_HERE, base::BindOnce( - [](base::OnceClosure task, std::atomic<int>& num_async_tasks) { - std::move(task).Run(); - num_async_tasks--; - }, - std::move(task), std::ref(num_async_tasks)))) { + if (!message_loop_thread.DoInThread(base::BindOnce( + [](base::OnceClosure task, std::atomic<int>& num_async_tasks) { + std::move(task).Run(); + num_async_tasks--; + }, + std::move(task), std::ref(num_async_tasks)))) { log::error("failed to post task to task runner!"); return BT_STATUS_FAIL; } @@ -110,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(); @@ -123,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 d8a51aa417..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*/) {} @@ -522,8 +520,6 @@ TEST_F(StateMachineTest, UpdateAnnouncement) { } TEST_F(StateMachineTest, UpdateBroadcastAnnouncementWithCallback) { - com::android::bluetooth::flags::provider_->leaudio_broadcast_update_metadata_callback(true); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); @@ -544,8 +540,6 @@ TEST_F(StateMachineTest, UpdateBroadcastAnnouncementWithCallback) { } TEST_F(StateMachineTest, UpdatePublicBroadcastAnnouncementWithCallback) { - com::android::bluetooth::flags::provider_->leaudio_broadcast_update_metadata_callback(true); - EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1); auto broadcast_id = InstantiateStateMachine(); 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 bb3d498714..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_ @@ -1184,7 +1212,9 @@ types::LeAudioLtvMap LeAudioDevice::GetMetadata(AudioContexts context_type, const std::vector<uint8_t>& ccid_list) { types::LeAudioLtvMap metadata; metadata.Add(types::kLeAudioMetadataTypeStreamingAudioContext, context_type.value()); - metadata.Add(types::kLeAudioMetadataTypeCcidList, ccid_list); + if (ccid_list.size()) { + metadata.Add(types::kLeAudioMetadataTypeCcidList, ccid_list); + } return metadata; } 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 6388d7141c..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,49 @@ 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( + bluetooth::le_audio::types::AudioContexts( + bluetooth::le_audio::types::LeAudioContextType::MEDIA), + std::vector<uint8_t>()); + ASSERT_EQ(metadata.Find(types::kLeAudioMetadataTypeCcidList), std::nullopt); + ASSERT_TRUE(metadata.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext) + .has_value()); + ASSERT_EQ(metadata.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext) + .value()[0], + uint8_t(LeAudioContextType::MEDIA)); + ASSERT_EQ(metadata.Find(bluetooth::le_audio::types::kLeAudioMetadataTypeStreamingAudioContext) + .value()[1], + uint8_t((uint16_t)LeAudioContextType::MEDIA >> 8)); +} + INSTANTIATE_TEST_CASE_P(Test, LeAudioAseConfigurationTest, ::testing::Values(kLeAudioCodingFormatLC3, kLeAudioCodingFormatVendorSpecific)); diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc index cfdf9f0df2..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,27 +106,22 @@ 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( - FROM_HERE, base::BindOnce( - [](base::OnceClosure task, std::atomic<int>& num_async_tasks) { - std::move(task).Run(); - num_async_tasks--; - }, - std::move(task), std::ref(num_async_tasks)))) { + if (!message_loop_thread.DoInThread(base::BindOnce( + [](base::OnceClosure task, std::atomic<int>& num_async_tasks) { + std::move(task).Run(); + num_async_tasks--; + }, + std::move(task), std::ref(num_async_tasks)))) { bluetooth::log::error("failed to post task to task runner!"); return BT_STATUS_FAIL; } @@ -140,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(); @@ -152,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}; @@ -172,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, @@ -240,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; @@ -257,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), @@ -1044,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; }); @@ -1335,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; } @@ -1408,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) { @@ -1947,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) { @@ -2027,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) { @@ -2248,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; @@ -2337,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; @@ -2359,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; @@ -2385,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); @@ -2474,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_) { @@ -2543,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 = { @@ -6692,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); @@ -8388,19 +8507,23 @@ 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 (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); } }); @@ -8421,6 +8544,110 @@ TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSinkSource) { 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 ((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_); + + // 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_); + 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); + + 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(); +} + TEST_F(UnicastTest, UpdateActiveAudioConfigForLocalSource) { uint8_t group_size = 2; int group_id = 2; @@ -8452,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); } }); @@ -8730,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); @@ -8946,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; @@ -8986,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); @@ -10543,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 @@ -10604,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. @@ -11162,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 @@ -12051,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 @@ -12089,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); @@ -12127,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 */ @@ -13261,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; @@ -13269,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/co/bta_gatts_co.cc b/system/btif/co/bta_gatts_co.cc index 28a24ad17a..b0dc95f514 100644 --- a/system/btif/co/bta_gatts_co.cc +++ b/system/btif/co/bta_gatts_co.cc @@ -16,6 +16,8 @@ * ******************************************************************************/ +#include "bta_gatts_co.h" + #include <stdlib.h> #include <string.h> @@ -25,9 +27,6 @@ #include "stack/include/gatt_api.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - /***************************************************************************** * Local type definitions ****************************************************************************/ diff --git a/system/btif/include/btif_dm.h b/system/btif/include/btif_dm.h index c14365ecfe..9d942d381d 100644 --- a/system/btif/include/btif_dm.h +++ b/system/btif/include/btif_dm.h @@ -155,8 +155,8 @@ void btif_update_remote_properties(const RawAddress& bd_addr, BD_NAME bd_name, D tBT_DEVICE_TYPE dev_type); bool btif_is_interesting_le_service(const bluetooth::Uuid& uuid); -bool check_cod_hid(const RawAddress& bd_addr); -bool check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod); +bool btif_check_cod_hid(const RawAddress& bd_addr); +bool btif_check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod); bool is_device_le_audio_capable(const RawAddress bd_addr); bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr); diff --git a/system/btif/include/btif_gatt.h b/system/btif/include/btif_gatt.h index 986873eadf..6a44518dd7 100644 --- a/system/btif/include/btif_gatt.h +++ b/system/btif/include/btif_gatt.h @@ -24,8 +24,7 @@ * *****************************************************************************/ -#ifndef BTIF_GATT_H -#define BTIF_GATT_H +#pragma once #include "include/hardware/bt_gatt.h" @@ -33,4 +32,4 @@ extern const btgatt_client_interface_t btgattClientInterface; extern const btgatt_server_interface_t btgattServerInterface; BleScannerInterface* get_ble_scanner_instance(); -#endif +const btgatt_interface_t* btif_gatt_get_interface(); 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_iot_config.h b/system/btif/include/btif_iot_config.h new file mode 100644 index 0000000000..72a2d68cd8 --- /dev/null +++ b/system/btif/include/btif_iot_config.h @@ -0,0 +1,23 @@ +/****************************************************************************** + * + * Copyright 2014 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. + * + ******************************************************************************/ + +#pragma once + +#include "bta/include/bta_sec_api.h" + +void btif_iot_update_remote_info(tBTA_DM_AUTH_CMPL* p_auth_cmpl, bool is_ble, bool is_ssp); diff --git a/system/btif/include/btif_le_audio.h b/system/btif/include/btif_le_audio.h new file mode 100644 index 0000000000..c587d35111 --- /dev/null +++ b/system/btif/include/btif_le_audio.h @@ -0,0 +1,28 @@ +/* + * Copyright 2025 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. + */ + +#pragma once + +#include "include/hardware/bt_csis.h" +#include "include/hardware/bt_has.h" +#include "include/hardware/bt_le_audio.h" +#include "include/hardware/bt_vc.h" + +bluetooth::le_audio::LeAudioClientInterface* btif_le_audio_get_interface(); +bluetooth::le_audio::LeAudioBroadcasterInterface* btif_le_audio_broadcaster_get_interface(); +bluetooth::vc::VolumeControlInterface* btif_volume_control_get_interface(); +bluetooth::csis::CsisClientInterface* btif_csis_client_get_interface(); +bluetooth::has::HasClientInterface* btif_has_client_get_interface(); diff --git a/system/btif/include/btif_profile_storage.h b/system/btif/include/btif_profile_storage.h index d6a3688741..d411a95e00 100644 --- a/system/btif/include/btif_profile_storage.h +++ b/system/btif/include/btif_profile_storage.h @@ -26,9 +26,21 @@ #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -/******************************************************************************* - * Functions - ******************************************************************************/ +struct HearingDevice; + +void btif_storage_add_hearing_aid(const HearingDevice& dev_info); + +void btif_storage_add_leaudio_has_device(const RawAddress& address, + std::vector<uint8_t> presets_bin, uint8_t features, + uint8_t active_preset); +bool btif_storage_get_leaudio_has_presets(const RawAddress& address, + std::vector<uint8_t>& presets_bin, + uint8_t& active_preset); +void btif_storage_set_leaudio_has_presets(const RawAddress& address, + std::vector<uint8_t> presets_bin); +void btif_storage_set_leaudio_has_active_preset(const RawAddress& address, uint8_t active_preset); +bool btif_storage_get_leaudio_has_features(const RawAddress& address, uint8_t& features); +void btif_storage_set_leaudio_has_features(const RawAddress& address, uint8_t features); /******************************************************************************* * @@ -112,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_sdp.h b/system/btif/include/btif_sdp.h index c1d719a388..b08e1b6591 100644 --- a/system/btif/include/btif_sdp.h +++ b/system/btif/include/btif_sdp.h @@ -24,8 +24,7 @@ * ******************************************************************************/ -#ifndef BTIF_SDP_H -#define BTIF_SDP_H +#pragma once #include <hardware/bt_sdp.h> @@ -35,4 +34,11 @@ bt_status_t btif_sdp_execute_service(bool b_enable); bt_status_t sdp_server_init(); void sdp_server_cleanup(); -#endif +int get_sdp_records_size(bluetooth_sdp_record* in_record, int count); +void copy_sdp_records(bluetooth_sdp_record* in_records, bluetooth_sdp_record* out_records, + int count); +bt_status_t create_sdp_record(bluetooth_sdp_record* record, int* record_handle); +bt_status_t remove_sdp_record(int record_handle); + +void on_create_record_event(int handle); +void on_remove_record_event(int handle); diff --git a/system/btif/include/btif_sock_rfc.h b/system/btif/include/btif_sock_rfc.h index eb5f22b82d..92245668db 100644 --- a/system/btif/include/btif_sock_rfc.h +++ b/system/btif/include/btif_sock_rfc.h @@ -32,8 +32,9 @@ #include "hardware/bt_sock.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" + bt_status_t btsock_rfc_init(int handle, uid_set_t* set); -bt_status_t btsock_rfc_cleanup(); +void btsock_rfc_cleanup(); bt_status_t btsock_rfc_control_req(uint8_t dlci, const RawAddress& bd_addr, uint8_t modem_signal, uint8_t break_signal, uint8_t discard_buffers, uint8_t break_signal_seq, bool fc); 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/include/stack_manager_t.h b/system/btif/include/stack_manager_t.h index f319fff7a7..c77bef001d 100644 --- a/system/btif/include/stack_manager_t.h +++ b/system/btif/include/stack_manager_t.h @@ -47,3 +47,7 @@ const stack_manager_t* stack_manager_get_interface(); future_t* stack_manager_get_hack_future(); bluetooth::core::CoreInterface* GetInterfaceToProfiles(); + +namespace bluetooth::legacy::testing { +void set_interface_to_profiles(bluetooth::core::CoreInterface* interfaceToProfiles); +} // namespace bluetooth::legacy::testing diff --git a/system/btif/src/bluetooth.cc b/system/btif/src/bluetooth.cc index 75898e0409..11b9d3ed69 100644 --- a/system/btif/src/bluetooth.cc +++ b/system/btif/src/bluetooth.cc @@ -40,6 +40,7 @@ #include <utility> #include <vector> +#include "bta/gatt/bta_gattc_int.h" #include "bta/hh/bta_hh_int.h" #include "bta/include/bta_api.h" #include "bta/include/bta_ar_api.h" @@ -61,16 +62,19 @@ #include "btif/include/btif_config.h" #include "btif/include/btif_debug_conn.h" #include "btif/include/btif_dm.h" +#include "btif/include/btif_gatt.h" #include "btif/include/btif_hd.h" #include "btif/include/btif_hearing_aid.h" #include "btif/include/btif_hf.h" #include "btif/include/btif_hf_client.h" #include "btif/include/btif_hh.h" #include "btif/include/btif_keystore.h" +#include "btif/include/btif_le_audio.h" #include "btif/include/btif_metrics_logging.h" #include "btif/include/btif_pan.h" #include "btif/include/btif_profile_storage.h" #include "btif/include/btif_rc.h" +#include "btif/include/btif_sdp.h" #include "btif/include/btif_sock.h" #include "btif/include/btif_sock_logging.h" #include "btif/include/btif_storage.h" @@ -162,40 +166,11 @@ tBT_TRANSPORT to_bt_transport(int val) { ******************************************************************************/ static bt_callbacks_t* bt_hal_cbacks = NULL; -bool restricted_mode = false; -bool common_criteria_mode = false; -const int CONFIG_COMPARE_ALL_PASS = 0b11; -int common_criteria_config_compare_result = CONFIG_COMPARE_ALL_PASS; -bool is_local_device_atv = false; - -/******************************************************************************* - * Externs - ******************************************************************************/ - -/* list all extended interfaces here */ - -/*rfc l2cap*/ -extern const btsock_interface_t* btif_sock_get_interface(); -/* gatt */ -extern const btgatt_interface_t* btif_gatt_get_interface(); -/* avrc controller */ -extern const btrc_ctrl_interface_t* btif_rc_ctrl_get_interface(); -/*SDP search client*/ -extern const btsdp_interface_t* btif_sdp_get_interface(); -/* Hearing Access client */ -extern HasClientInterface* btif_has_client_get_interface(); -/* LeAudio testi client */ -extern LeAudioClientInterface* btif_le_audio_get_interface(); -/* LeAudio Broadcaster */ -extern LeAudioBroadcasterInterface* btif_le_audio_broadcaster_get_interface(); -/* Coordinated Set Service Client */ -extern CsisClientInterface* btif_csis_client_get_interface(); -/* Volume Control client */ -extern VolumeControlInterface* btif_volume_control_get_interface(); - -bt_status_t btif_av_sink_execute_service(bool b_enable); - -extern void bta_gatt_client_dump(int fd); +static bool restricted_mode = false; +static bool common_criteria_mode = false; +static constexpr int CONFIG_COMPARE_ALL_PASS = 0b11; +static int common_criteria_config_compare_result = CONFIG_COMPARE_ALL_PASS; +static bool is_local_device_atv = false; /******************************************************************************* * Callbacks from bluetooth::core (see go/invisalign-bt) diff --git a/system/btif/src/btif_a2dp_sink.cc b/system/btif/src/btif_a2dp_sink.cc index 0328ba9cbc..e2258d35f2 100644 --- a/system/btif/src/btif_a2dp_sink.cc +++ b/system/btif/src/btif_a2dp_sink.cc @@ -207,8 +207,7 @@ bool btif_a2dp_sink_init() { log::fatal("Failed to increase A2DP decoder thread priority"); #endif } - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_init_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_init_delayed)); return true; } @@ -219,8 +218,7 @@ static void btif_a2dp_sink_init_delayed() { bool btif_a2dp_sink_startup() { log::info(""); - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_startup_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_startup_delayed)); return true; } @@ -305,9 +303,8 @@ static bool btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress& peer_ bool btif_a2dp_sink_start_session(const RawAddress& peer_address, std::promise<void> peer_ready_promise) { log::info("peer_address={}", peer_address); - if (btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_start_session_delayed, peer_address, - std::move(peer_ready_promise)))) { + if (btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce( + btif_a2dp_sink_start_session_delayed, peer_address, std::move(peer_ready_promise)))) { return true; } else { // cannot set promise but triggers crash @@ -353,8 +350,7 @@ bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address, bool btif_a2dp_sink_end_session(const RawAddress& peer_address) { log::info("peer_address={}", peer_address); - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_end_session_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_end_session_delayed)); return true; } @@ -366,8 +362,7 @@ static void btif_a2dp_sink_end_session_delayed() { void btif_a2dp_sink_shutdown() { log::info(""); - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_shutdown_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_shutdown_delayed)); } static void btif_a2dp_sink_shutdown_delayed() { @@ -401,8 +396,7 @@ void btif_a2dp_sink_cleanup() { alarm_free(decode_alarm); // Exit the thread - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_cleanup_delayed)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_cleanup_delayed)); btif_a2dp_sink_cb.worker_thread.ShutDown(); } @@ -460,15 +454,14 @@ void btif_a2dp_sink_update_decoder(const RawAddress& peer_address, const uint8_t p_buf->hdr.event = BTIF_MEDIA_SINK_DECODER_UPDATE; btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); + base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); } void btif_a2dp_sink_on_idle() { log::info(""); BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { return; @@ -481,8 +474,7 @@ void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) { log::info(""); BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { return; @@ -494,8 +486,7 @@ void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) { log::info(""); BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_SUSPEND; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) { return; @@ -508,8 +499,7 @@ bool btif_a2dp_sink_on_start() { BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_START; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); return true; } @@ -540,8 +530,7 @@ static void btif_a2dp_sink_audio_handle_stop_decoding() { } static void btif_decode_alarm_cb(void* /* context */) { - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_avk_handle_timer)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_avk_handle_timer)); } static void btif_a2dp_sink_clear_track_event() { @@ -767,8 +756,7 @@ void btif_a2dp_sink_audio_rx_flush_req() { BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); } void btif_a2dp_sink_debug_dump(int /* fd */) { @@ -782,7 +770,7 @@ void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) { p_buf->focus_state = state; p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE; btif_a2dp_sink_cb.worker_thread.DoInThread( - FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); + base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf)); } static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state) { @@ -815,8 +803,7 @@ static void btif_a2dp_sink_clear_track_event_req() { BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID))); p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK; - btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE, - base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); + btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf)); } static void btif_a2dp_sink_on_start_event() { diff --git a/system/btif/src/btif_a2dp_source.cc b/system/btif/src/btif_a2dp_source.cc index 70634b9984..25a5fe7093 100644 --- a/system/btif/src/btif_a2dp_source.cc +++ b/system/btif/src/btif_a2dp_source.cc @@ -343,7 +343,7 @@ bool btif_a2dp_source_init(void) { // Start A2DP Source media task btif_a2dp_source_thread.StartUp(); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_init_delayed)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_init_delayed)); return true; } @@ -441,7 +441,7 @@ static bool btif_a2dp_source_startup(void) { btif_a2dp_source_cb.tx_audio_queue = fixed_queue_new(SIZE_MAX); // Schedule the rest of the operations - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_startup_delayed)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_startup_delayed)); return true; } @@ -466,9 +466,8 @@ bool btif_a2dp_source_start_session(const RawAddress& peer_address, btif_a2dp_source_audio_tx_flush_req(); - if (local_thread()->DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_start_session_delayed, peer_address, - std::move(peer_ready_promise)))) { + if (local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_start_session_delayed, + peer_address, std::move(peer_ready_promise)))) { return true; } else { // cannot set promise but triggers crash @@ -535,9 +534,7 @@ bool btif_a2dp_source_end_session(const RawAddress& peer_address) { btif_a2dp_source_cleanup_codec(); btif_a2dp_source_end_session_delayed(peer_address); } else { - - local_thread()->DoInThread(FROM_HERE, - base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address)); btif_a2dp_source_cleanup_codec(); } return true; @@ -565,7 +562,6 @@ void btif_a2dp_source_allow_low_latency_audio(bool allowed) { log::info("allowed={}", allowed); local_thread()->DoInThread( - FROM_HERE, base::BindOnce(bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed, allowed)); } @@ -582,8 +578,8 @@ void btif_a2dp_source_shutdown(std::promise<void> shutdown_complete_promise) { // TODO(b/374166531) Remove the check for get_main_thread. if (local_thread() != get_main_thread()) { - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_shutdown_delayed, - std::move(shutdown_complete_promise))); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_shutdown_delayed, + std::move(shutdown_complete_promise))); } else { btif_a2dp_source_shutdown_delayed(std::move(shutdown_complete_promise)); } @@ -696,7 +692,7 @@ static void btif_a2dp_source_cleanup_codec() { log::info("state={}", btif_a2dp_source_cb.StateStr()); // Must stop media task first before cleaning up the encoder btif_a2dp_source_stop_audio_req(); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed)); } static void btif_a2dp_source_cleanup_codec_delayed() { @@ -710,13 +706,13 @@ static void btif_a2dp_source_cleanup_codec_delayed() { void btif_a2dp_source_start_audio_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_start_event)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_start_event)); } void btif_a2dp_source_stop_audio_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_stop_event)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_stop_event)); } void btif_a2dp_source_encoder_user_config_update_req( @@ -727,7 +723,6 @@ void btif_a2dp_source_encoder_user_config_update_req( btif_a2dp_source_cb.StateStr(), codec_user_preferences.size()); if (!local_thread()->DoInThread( - FROM_HERE, base::BindOnce(&btif_a2dp_source_encoder_user_config_update_event, peer_address, codec_user_preferences, std::move(peer_ready_promise)))) { // cannot set promise but triggers crash @@ -772,8 +767,8 @@ static void btif_a2dp_source_encoder_user_config_update_event( void btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t& codec_audio_config) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_feeding_update_event, - codec_audio_config)); + local_thread()->DoInThread( + base::BindOnce(&btif_a2dp_source_audio_feeding_update_event, codec_audio_config)); } static void btif_a2dp_source_audio_feeding_update_event( @@ -889,7 +884,7 @@ static void btif_a2dp_source_audio_tx_start_event(void) { btif_a2dp_source_cb.tx_flush = false; btif_a2dp_source_cb.sw_audio_is_encoding = true; btif_a2dp_source_cb.media_alarm.SchedulePeriodic( - btif_a2dp_source_thread.GetWeakPtr(), FROM_HERE, + btif_a2dp_source_thread.GetWeakPtr(), base::BindRepeating(&btif_a2dp_source_audio_handle_timer), std::chrono::milliseconds( btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms())); @@ -1086,7 +1081,7 @@ static void btif_a2dp_source_audio_tx_flush_event(void) { static bool btif_a2dp_source_audio_tx_flush_req(void) { log::info("state={}", btif_a2dp_source_cb.StateStr()); - local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_flush_event)); + local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_flush_event)); return true; } diff --git a/system/btif/src/btif_avrcp_audio_track.cc b/system/btif/src/btif_avrcp_audio_track.cc index fc24963681..9ba26d9be6 100644 --- a/system/btif/src/btif_avrcp_audio_track.cc +++ b/system/btif/src/btif_avrcp_audio_track.cc @@ -31,9 +31,6 @@ #include <cstdint> #include <thread> -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; typedef struct { @@ -57,9 +54,9 @@ struct AudioEngine { void* trackHandle = nullptr; } s_AudioEngine; -void ErrorCallback(AAudioStream* stream, void* userdata, aaudio_result_t error); +static void ErrorCallback(AAudioStream* stream, void* userdata, aaudio_result_t error); -void BtifAvrcpAudioErrorHandle() { +static void BtifAvrcpAudioErrorHandle() { AAudioStreamBuilder* builder; AAudioStream* stream; @@ -85,7 +82,7 @@ void BtifAvrcpAudioErrorHandle() { s_AudioEngine.thread = nullptr; } -void ErrorCallback(AAudioStream* /* stream */, void* /* userdata */, aaudio_result_t error) { +static void ErrorCallback(AAudioStream* /* stream */, void* /* userdata */, aaudio_result_t error) { if (error == AAUDIO_ERROR_DISCONNECTED) { if (s_AudioEngine.thread == nullptr) { s_AudioEngine.thread = new std::thread(BtifAvrcpAudioErrorHandle); diff --git a/system/btif/src/btif_ble_scanner.cc b/system/btif/src/btif_ble_scanner.cc index 3bfac0c305..7a612851e0 100644 --- a/system/btif/src/btif_ble_scanner.cc +++ b/system/btif/src/btif_ble_scanner.cc @@ -18,11 +18,9 @@ #include <hardware/ble_scanner.h> +#include "btif_gatt.h" #include "main/shim/le_scanning_manager.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - BleScannerInterface* get_ble_scanner_instance() { return bluetooth::shim::get_ble_scanner_instance(); } diff --git a/system/btif/src/btif_csis_client.cc b/system/btif/src/btif_csis_client.cc index 434368864b..cbaa9e7c53 100644 --- a/system/btif/src/btif_csis_client.cc +++ b/system/btif/src/btif_csis_client.cc @@ -26,14 +26,12 @@ #include "bind_helpers.h" #include "bta_csis_api.h" #include "btif_common.h" +#include "btif_le_audio.h" #include "btif_profile_storage.h" #include "stack/include/main_thread.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using base::Unretained; using bluetooth::csis::ConnectionState; diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc index 16e786d7d3..9ce8e1bfb5 100644 --- a/system/btif/src/btif_dm.cc +++ b/system/btif/src/btif_dm.cc @@ -479,7 +479,7 @@ static bool get_cached_remote_name(const RawAddress& bd_addr, bt_bdname_t* p_rem return false; } -static uint32_t get_cod(const RawAddress* remote_bdaddr) { +static uint32_t btif_get_cod(const RawAddress* remote_bdaddr) { uint32_t remote_cod = 0; if (!btif_storage_get_cod(*remote_bdaddr, &remote_cod)) { remote_cod = 0; @@ -488,22 +488,26 @@ static uint32_t get_cod(const RawAddress* remote_bdaddr) { return remote_cod; } -static bool check_cod(const RawAddress* remote_bdaddr, uint32_t cod) { - return (get_cod(remote_bdaddr) & COD_DEVICE_MASK) == cod; +static bool btif_check_cod(const RawAddress* remote_bdaddr, uint32_t cod) { + return (btif_get_cod(remote_bdaddr) & COD_DEVICE_MASK) == cod; } -bool check_cod_hid(const RawAddress& bd_addr) { - return (get_cod(&bd_addr) & COD_HID_MASK) == COD_HID_MAJOR; +static bool btif_check_cod_phone(const RawAddress& bd_addr) { + return (btif_get_cod(&bd_addr) & PHONE_COD_MAJOR_CLASS_MASK) == (BTM_COD_MAJOR_PHONE << 8); } -bool check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod) { - uint32_t remote_cod = get_cod(&bd_addr); +bool btif_check_cod_hid(const RawAddress& bd_addr) { + return (btif_get_cod(&bd_addr) & COD_HID_MASK) == COD_HID_MAJOR; +} + +bool btif_check_cod_hid_major(const RawAddress& bd_addr, uint32_t cod) { + uint32_t remote_cod = btif_get_cod(&bd_addr); return (remote_cod & COD_HID_MASK) == COD_HID_MAJOR && (remote_cod & COD_HID_SUB_MAJOR) == (cod & COD_HID_SUB_MAJOR); } -static bool check_cod_le_audio(const RawAddress& bd_addr) { - return (get_cod(&bd_addr) & COD_CLASS_LE_AUDIO) == COD_CLASS_LE_AUDIO; +static bool btif_check_cod_le_audio(const RawAddress& bd_addr) { + return (btif_get_cod(&bd_addr) & COD_CLASS_LE_AUDIO) == COD_CLASS_LE_AUDIO; } /***************************************************************************** @@ -655,7 +659,7 @@ void btif_update_remote_properties(const RawAddress& bdaddr, BD_NAME bd_name, DE ASSERTC(status == BT_STATUS_SUCCESS, "failed to save remote device name", status); } - uint32_t old_cod = get_cod(&bdaddr); + uint32_t old_cod = btif_get_cod(&bdaddr); /* class of device */ cod = devclass2uint(dev_class); @@ -706,7 +710,7 @@ bool is_device_le_audio_capable(const RawAddress bd_addr) { return false; } - if (!check_cod_le_audio(bd_addr) && !BTA_DmCheckLeAudioCapable(bd_addr)) { + if (!btif_check_cod_le_audio(bd_addr) && !BTA_DmCheckLeAudioCapable(bd_addr)) { /* LE Audio not present in CoD or in LE Advertisement, do nothing.*/ return false; } @@ -746,7 +750,7 @@ bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) { return false; } - if (check_cod_le_audio(bd_addr) || metadata_cb.le_audio_cache.contains(bd_addr) || + if (btif_check_cod_le_audio(bd_addr) || metadata_cb.le_audio_cache.contains(bd_addr) || metadata_cb.le_audio_cache.contains(pairing_cb.bd_addr) || BTA_DmCheckLeAudioCapable(bd_addr)) { return true; @@ -768,8 +772,9 @@ bool is_le_audio_capable_during_service_discovery(const RawAddress& bd_addr) { static void btif_dm_cb_create_bond(const RawAddress bd_addr, tBT_TRANSPORT transport) { bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING); - if (transport == BT_TRANSPORT_AUTO && is_device_le_audio_capable(bd_addr)) { - log::debug("LE Audio capable, forcing LE transport for Bonding"); + if (transport == BT_TRANSPORT_AUTO && is_device_le_audio_capable(bd_addr) && + !btif_check_cod_phone(bd_addr)) { + log::debug("LE Audio capable,forcing LE transport for Bonding"); transport = BT_TRANSPORT_LE; } @@ -937,9 +942,11 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { /* check for auto pair possiblity only if bond was initiated by local device */ if (pairing_cb.is_local_initiated && !p_pin_req->min_16_digit) { - if (check_cod(&bd_addr, COD_AV_HEADSETS) || check_cod(&bd_addr, COD_AV_HEADPHONES) || - check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) || check_cod(&bd_addr, COD_AV_HIFI_AUDIO) || - check_cod_hid_major(bd_addr, COD_HID_POINTING)) { + if (btif_check_cod(&bd_addr, COD_AV_HEADSETS) || + btif_check_cod(&bd_addr, COD_AV_HEADPHONES) || + btif_check_cod(&bd_addr, COD_AV_PORTABLE_AUDIO) || + btif_check_cod(&bd_addr, COD_AV_HIFI_AUDIO) || + btif_check_cod_hid_major(bd_addr, COD_HID_POINTING)) { /* Check if this device can be auto paired */ if (!interop_match_addr(INTEROP_DISABLE_AUTO_PAIRING, &bd_addr) && !interop_match_name(INTEROP_DISABLE_AUTO_PAIRING, (const char*)bd_name.name) && @@ -954,8 +961,8 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) { BTA_DmPinReply(bd_addr, true, 4, pin_code.pin); return; } - } else if (check_cod_hid_major(bd_addr, COD_HID_KEYBOARD) || - check_cod_hid_major(bd_addr, COD_HID_COMBO)) { + } else if (btif_check_cod_hid_major(bd_addr, COD_HID_KEYBOARD) || + btif_check_cod_hid_major(bd_addr, COD_HID_COMBO)) { if ((interop_match_addr(INTEROP_KEYBOARD_REQUIRES_FIXED_PIN, &bd_addr) == true) && (pairing_cb.autopair_attempts == 0)) { log::debug("Attempting auto pair w/ IOP"); @@ -1019,7 +1026,7 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) { /* if just_works and bonding bit is not set treat this as temporary */ if (p_ssp_cfm_req->just_works && !(p_ssp_cfm_req->loc_auth_req & BTM_AUTH_BONDS) && !(p_ssp_cfm_req->rmt_auth_req & BTM_AUTH_BONDS) && - !(check_cod_hid_major(p_ssp_cfm_req->bd_addr, COD_HID_POINTING))) { + !(btif_check_cod_hid_major(p_ssp_cfm_req->bd_addr, COD_HID_POINTING))) { pairing_cb.bond_type = BOND_TYPE_TEMPORARY; } else { pairing_cb.bond_type = BOND_TYPE_PERSISTENT; @@ -1171,7 +1178,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { state = BT_BOND_STATE_BONDED; bd_addr = p_auth_cmpl->bd_addr; - if (check_sdp_bl(&bd_addr) && check_cod_hid(bd_addr)) { + if (check_sdp_bl(&bd_addr) && btif_check_cod_hid(bd_addr)) { log::warn("skip SDP"); skip_sdp = true; } @@ -1283,7 +1290,7 @@ static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) { status = BT_STATUS_UNHANDLED; } /* Special Handling for HID Devices */ - if (check_cod_hid_major(bd_addr, COD_HID_POINTING)) { + if (btif_check_cod_hid_major(bd_addr, COD_HID_POINTING)) { /* Remove Device as bonded in nvram as authentication failed */ log::verbose("removing hid pointing device from nvram"); is_bonded_device_removed = false; @@ -1368,7 +1375,7 @@ static void btif_dm_search_devices_evt(tBTA_DM_SEARCH_EVT event, tBTA_DM_SEARCH* inferred device class based on the service uuids or appearance. We don't want this to replace the existing value below when we call btif_storage_add_remote_device */ - uint32_t old_cod = get_cod(&bdaddr); + uint32_t old_cod = btif_get_cod(&bdaddr); if (cod == COD_UNCLASSIFIED && old_cod != 0) { cod = old_cod; } @@ -1883,7 +1890,7 @@ static void btif_on_name_read(RawAddress bd_addr, tHCI_ERROR_CODE hci_status, co return; } - uint32_t cod = get_cod(&bd_addr); + uint32_t cod = btif_get_cod(&bd_addr); if (cod != 0) { properties.push_back(bt_property_t{BT_PROPERTY_BDADDR, sizeof(bd_addr), &bd_addr}); properties.push_back(bt_property_t{BT_PROPERTY_CLASS_OF_DEVICE, sizeof(uint32_t), &cod}); @@ -3841,7 +3848,7 @@ static void btif_stats_add_bond_event(const RawAddress& bd_addr, bt_bond_functio break; } - uint32_t cod = get_cod(&bd_addr); + uint32_t cod = btif_get_cod(&bd_addr); uint64_t ts = event->timestamp.tv_sec * 1000 + event->timestamp.tv_nsec / 1000000; bluetooth::common::BluetoothMetricsLogger::GetInstance()->LogPairEvent(0, ts, cod, device_type); } diff --git a/system/btif/src/btif_gatt.cc b/system/btif/src/btif_gatt.cc index 9bd0eba609..ed20db4821 100644 --- a/system/btif/src/btif_gatt.cc +++ b/system/btif/src/btif_gatt.cc @@ -39,9 +39,6 @@ #include "main/shim/distance_measurement_manager.h" #include "main/shim/le_advertising_manager.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - const btgatt_callbacks_t* bt_gatt_callbacks = NULL; /******************************************************************************* diff --git a/system/btif/src/btif_has_client.cc b/system/btif/src/btif_has_client.cc index ff9769c525..7e336810ca 100644 --- a/system/btif/src/btif_has_client.cc +++ b/system/btif/src/btif_has_client.cc @@ -28,13 +28,11 @@ #include "bta_has_api.h" #include "btif_common.h" +#include "btif_le_audio.h" #include "btif_profile_storage.h" #include "stack/include/main_thread.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using base::Unretained; using bluetooth::has::ConnectionState; diff --git a/system/btif/src/btif_hd.cc b/system/btif/src/btif_hd.cc index 321e57bc0d..d2a93a3405 100644 --- a/system/btif/src/btif_hd.cc +++ b/system/btif/src/btif_hd.cc @@ -226,7 +226,7 @@ static void btif_hd_upstreams_evt(uint16_t event, char* p_param) { RawAddress& addr = p_data->conn.bda; log::warn("BTA_HD_OPEN_EVT, address={}", addr); /* Check if the connection is from hid host and not hid device */ - if (check_cod_hid(addr)) { + if (btif_check_cod_hid(addr)) { /* Incoming connection from hid device, reject it */ log::warn("remote device is not hid host, disconnecting"); btif_hd_cb.forced_disc = TRUE; 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_hf_client.cc b/system/btif/src/btif_hf_client.cc index 30495459c1..842b5868aa 100644 --- a/system/btif/src/btif_hf_client.cc +++ b/system/btif/src/btif_hf_client.cc @@ -95,7 +95,8 @@ typedef struct { /****************************************************************************** * Local function declarations ******************************************************************************/ -static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& addr); +static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& bd_addr); +static btif_hf_client_cb_t* btif_hf_client_get_connected_device(const RawAddress& bd_addr); static bool is_connected(const btif_hf_client_cb_t* cb); /******************************************************************************* @@ -162,9 +163,9 @@ constexpr uint16_t BTIF_HF_CLIENT_CB_AUDIO_CONNECTING = 0x8501; static void btif_in_hf_client_generic_evt(uint16_t event, char* p_param) { log::verbose(""); RawAddress* bd_addr = (RawAddress*)p_param; - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { - log::error("failed to find block for bda"); + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { + log::error("failed to find block for bda:{}", *bd_addr); return; } @@ -188,8 +189,6 @@ static bool is_connected(const btif_hf_client_cb_t* cb) { (cb->state == BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED)) { return true; } - - log::error("not connected!"); return false; } @@ -212,8 +211,26 @@ static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& bd_ad return &btif_hf_client_cb_arr.cb[i]; } } - log::error("could not find block for bdaddr"); - return NULL; + return nullptr; +} + +/******************************************************************************* + * + * Function btif_hf_client_get_connected_device + * + * Description Get control block of connected device indexed by remote + * bluetooth address. + * + * Returns btif_hf_client_cb_t pointer if device connected, NULL + * otherwise + * + ******************************************************************************/ +static btif_hf_client_cb_t* btif_hf_client_get_connected_device(const RawAddress& bd_addr) { + btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(bd_addr); + if (cb == nullptr || !is_connected(cb)) { + return nullptr; + } + return cb; } /******************************************************************************* @@ -281,6 +298,7 @@ static bt_status_t connect_int(RawAddress* bd_addr, uint16_t /*uuid*/) { cb->peer_bda = *bd_addr; if (is_connected(cb)) { + log::warn("Peer is already connected remote:{}", *bd_addr); return BT_STATUS_BUSY; } @@ -331,8 +349,8 @@ static bt_status_t disconnect(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t connect_audio(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -362,8 +380,8 @@ static bt_status_t connect_audio(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t disconnect_audio(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -383,8 +401,8 @@ static bt_status_t disconnect_audio(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t start_voice_recognition(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -407,8 +425,8 @@ static bt_status_t start_voice_recognition(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -432,8 +450,8 @@ static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) { ******************************************************************************/ static bt_status_t volume_control(const RawAddress* bd_addr, bthf_client_volume_type_t type, int volume) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -463,8 +481,8 @@ static bt_status_t volume_control(const RawAddress* bd_addr, bthf_client_volume_ * ******************************************************************************/ static bt_status_t dial(const RawAddress* bd_addr, const char* number) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -488,8 +506,8 @@ static bt_status_t dial(const RawAddress* bd_addr, const char* number) { * ******************************************************************************/ static bt_status_t dial_memory(const RawAddress* bd_addr, int location) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -510,8 +528,8 @@ static bt_status_t dial_memory(const RawAddress* bd_addr, int location) { ******************************************************************************/ static bt_status_t handle_call_action(const RawAddress* bd_addr, bthf_client_call_action_t action, int idx) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -600,8 +618,8 @@ static bt_status_t handle_call_action(const RawAddress* bd_addr, bthf_client_cal * ******************************************************************************/ static bt_status_t query_current_calls(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -625,8 +643,8 @@ static bt_status_t query_current_calls(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t query_current_operator_name(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -646,8 +664,8 @@ static bt_status_t query_current_operator_name(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -667,8 +685,8 @@ static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) { * ******************************************************************************/ static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -688,8 +706,8 @@ static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) { * ******************************************************************************/ static bt_status_t request_last_voice_tag_number(const RawAddress* bd_addr) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -732,8 +750,8 @@ static void cleanup(void) { ******************************************************************************/ static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, int val2, const char* arg) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -755,8 +773,8 @@ static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, int * ******************************************************************************/ static bt_status_t send_android_at(const RawAddress* bd_addr, const char* arg) { - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr); + if (!cb) { return BT_STATUS_DEVICE_NOT_FOUND; } @@ -794,8 +812,8 @@ static const bthf_client_interface_t bthfClientInterface = { static void process_ind_evt(tBTA_HF_CLIENT_IND* ind) { log::verbose(""); - btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(ind->bd_addr); - if (cb == NULL || !is_connected(cb)) { + btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(ind->bd_addr); + if (!cb) { return; } diff --git a/system/btif/src/btif_hh.cc b/system/btif/src/btif_hh.cc index 6d4ae387a6..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; } @@ -650,8 +693,8 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { if (!com::android::bluetooth::flags::dont_send_hid_set_idle()) { // Send set_idle if the peer_device is a keyboard // TODO (b/307923455): clean this, set idle is deprecated in HID spec v1.1.1 - if (check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_KEYBOARD) || - check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_COMBO)) { + if (btif_check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_KEYBOARD) || + btif_check_cod_hid_major(conn.link_spec.addrt.bda, COD_HID_COMBO)) { BTA_HhSetIdle(conn.handle, 0); } } @@ -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; } @@ -888,7 +932,7 @@ static void hh_vc_unplug_handler(tBTA_HH_CBDATA& dev_status) { // Remove the HID device btif_hh_remove_device(p_dev->link_spec); - if (p_dev->local_vup || check_cod_hid(p_dev->link_spec.addrt.bda)) { + if (p_dev->local_vup || btif_check_cod_hid(p_dev->link_spec.addrt.bda)) { // Remove the bond if locally initiated or remote device has major class HID p_dev->local_vup = false; BTA_DmRemoveDevice(p_dev->link_spec.addrt.bda); @@ -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 = {}; } @@ -1004,12 +1050,10 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { btif_hh_device_t* p_dev; while ((p_dev = btif_hh_find_dev_by_link_spec(link_spec)) != nullptr) { announce_vup = true; - // Notify upper layers of disconnection to avoid getting states out of sync - do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); - }, - link_spec)); + // Notify service of disconnection to avoid state mismatch + do_in_jni_thread( + base::Bind([](tAclLinkSpec ls) { BTHH_STATE_UPDATE(ls, BTHH_CONN_STATE_DISCONNECTED); }, + p_dev->link_spec)); if (btif_hh_cb.device_num > 0) { btif_hh_cb.device_num--; @@ -1029,18 +1073,81 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { } } + // Remove pending connection if address matches + if (com::android::bluetooth::flags::vup_for_pending_connection()) { + size_t pending_connections = btif_hh_cb.new_connection_requests.remove_if( + [link_spec](auto ls) { return ls.addrt.bda == link_spec.addrt.bda; }); + if (pending_connections > 0) { + announce_vup = true; + } + } + if (!announce_vup) { + log::info("Device {} not found", link_spec); return; } + do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, &link_spec.addrt.bda, - link_spec.addrt.type, link_spec.transport, BTHH_OK); + [](tAclLinkSpec ls) { + HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, &ls.addrt.bda, ls.addrt.type, + ls.transport, BTHH_OK); }, link_spec)); } /******************************************************************************* + ** + ** Function btif_hh_remove_pending_connection + ** + ** Description Remove first time pending connection requests. + ** + ** Returns void + ******************************************************************************/ +static void btif_hh_remove_pending_connection(const tAclLinkSpec& link_spec) { + if (!com::android::bluetooth::flags::vup_for_pending_connection()) { + bool pending_connection = false; + for (auto ls : btif_hh_cb.new_connection_requests) { + if (ls.addrt.bda == link_spec.addrt.bda) { + pending_connection = true; + break; + } + } + + if (pending_connection) { + btif_hh_cb.new_connection_requests.remove_if( + [link_spec](auto ls) { return ls.addrt.bda == link_spec.addrt.bda; }); + + // Notify service of disconnection to avoid state mismatch + do_in_jni_thread(base::Bind( + [](tAclLinkSpec ls) { BTHH_STATE_UPDATE(ls, BTHH_CONN_STATE_DISCONNECTED); }, + link_spec)); + } + return; + } + + size_t pending_connections = btif_hh_cb.new_connection_requests.remove_if([link_spec](auto ls) { + if (ls.addrt.bda == link_spec.addrt.bda) { + // Notify service of disconnection to avoid state mismatch + do_in_jni_thread(base::Bind( + [](tAclLinkSpec ls) { BTHH_STATE_UPDATE(ls, BTHH_CONN_STATE_DISCONNECTED); }, ls)); + + return true; + } + return false; + }); + + if (pending_connections > 0) { + log::verbose("Removed pending connections to {}", link_spec); + do_in_jni_thread(base::Bind( + [](tAclLinkSpec ls) { + HAL_CBACK(bt_hh_callbacks, virtual_unplug_cb, &ls.addrt.bda, ls.addrt.type, + ls.transport, BTHH_OK); + }, + link_spec)); + } +} + +/******************************************************************************* * * Function btif_hh_virtual_unplug * @@ -1050,7 +1157,6 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { * Returns void * ******************************************************************************/ - bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec) { BTHH_LOG_LINK(link_spec); @@ -1074,36 +1180,17 @@ bt_status_t btif_hh_virtual_unplug(const tAclLinkSpec& link_spec) { // Remove the connecting or added device if (btif_hh_find_dev_by_link_spec(link_spec) != nullptr || btif_hh_find_added_dev(link_spec) != nullptr) { - // Remove pending connection if address matches - btif_hh_cb.new_connection_requests.remove_if( - [link_spec](auto ls) { return ls.addrt.bda == link_spec.addrt.bda; }); - + if (!com::android::bluetooth::flags::vup_for_pending_connection()) { + // Remove pending connection if address matches + btif_hh_cb.new_connection_requests.remove_if( + [link_spec](auto ls) { return ls.addrt.bda == link_spec.addrt.bda; }); + } btif_hh_remove_device(link_spec); BTA_DmRemoveDevice(link_spec.addrt.bda); return BT_STATUS_SUCCESS; } - // Abort outgoing initial connection attempt - bool pending_connection = false; - for (auto ls : btif_hh_cb.new_connection_requests) { - if (ls.addrt.bda == link_spec.addrt.bda) { - pending_connection = true; - break; - } - } - - if (pending_connection) { - btif_hh_cb.new_connection_requests.remove_if( - [link_spec](auto ls) { return ls.addrt.bda == link_spec.addrt.bda; }); - - /* need to notify up-layer device is disconnected to avoid - * state out of sync with up-layer */ - do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { - BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_DISCONNECTED); - }, - link_spec)); - } + btif_hh_remove_pending_connection(link_spec); return BT_STATUS_DEVICE_NOT_FOUND; } @@ -1169,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; } @@ -1532,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); @@ -2138,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_iot_config.cc b/system/btif/src/btif_iot_config.cc index ee857ef620..971c3723e4 100644 --- a/system/btif/src/btif_iot_config.cc +++ b/system/btif/src/btif_iot_config.cc @@ -16,6 +16,8 @@ * ******************************************************************************/ +#include "btif_iot_config.h" + #include <bluetooth/log.h> #include <cstdint> @@ -31,9 +33,6 @@ #include "stack/include/btm_client_interface.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; /******************************************************************************* diff --git a/system/btif/src/btif_jni_task.cc b/system/btif/src/btif_jni_task.cc index 3937dd1591..5eb7dcd50a 100644 --- a/system/btif/src/btif_jni_task.cc +++ b/system/btif/src/btif_jni_task.cc @@ -105,7 +105,7 @@ bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_ * the JNI message loop. **/ bt_status_t do_in_jni_thread(base::OnceClosure task) { - if (!jni_thread.DoInThread(FROM_HERE, std::move(task))) { + if (!jni_thread.DoInThread(std::move(task))) { log::error("Post task to task runner failed!"); return BT_STATUS_JNI_THREAD_ATTACH_ERROR; } diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc index 0e6d377698..10eb8f99fb 100644 --- a/system/btif/src/btif_le_audio.cc +++ b/system/btif/src/btif_le_audio.cc @@ -15,6 +15,8 @@ * limitations under the License. */ +#include "btif_le_audio.h" + #include <bluetooth/log.h> #include <hardware/bt_le_audio.h> @@ -29,9 +31,6 @@ #include "stack/include/main_thread.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using base::Unretained; using bluetooth::le_audio::btle_audio_codec_config_t; @@ -72,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_le_audio_broadcaster.cc b/system/btif/src/btif_le_audio_broadcaster.cc index 253c0e0d52..de7ff0c79c 100644 --- a/system/btif/src/btif_le_audio_broadcaster.cc +++ b/system/btif/src/btif_le_audio_broadcaster.cc @@ -28,11 +28,9 @@ #include "bta_le_audio_api.h" #include "bta_le_audio_broadcaster_api.h" #include "btif_common.h" +#include "btif_le_audio.h" #include "stack/include/main_thread.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using base::Unretained; using bluetooth::le_audio::BroadcastId; diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc index 22c46ecce1..6051de1415 100644 --- a/system/btif/src/btif_profile_storage.cc +++ b/system/btif/src/btif_profile_storage.cc @@ -54,9 +54,6 @@ #include "types/bt_transport.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using bluetooth::Uuid; using bluetooth::csis::CsisClient; @@ -109,6 +106,7 @@ static void btif_storage_hid_device_info(std::string bdstr, uint16_t attr_mask, btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HID_DESCRIPTOR, dsc_list, dl_len); } } + static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, uint8_t sub_class, uint8_t app_id, uint16_t vendor_id, uint16_t product_id, uint16_t version, uint8_t ctry_code, uint16_t dl_len, @@ -124,6 +122,7 @@ static void btif_storage_hogp_device_info(std::string bdstr, uint16_t attr_mask, btif_config_set_bin(bdstr, BTIF_STORAGE_KEY_HOGP_DESCRIPTOR, dsc_list, dl_len); } } + /******************************************************************************* * * Function btif_storage_add_hid_device_info @@ -684,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 */ @@ -730,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/src/btif_sdp.cc b/system/btif/src/btif_sdp.cc index a7e61c3c03..54ace11bc2 100644 --- a/system/btif/src/btif_sdp.cc +++ b/system/btif/src/btif_sdp.cc @@ -46,21 +46,6 @@ using bluetooth::Uuid; using namespace bluetooth; /***************************************************************************** - * Functions implemented in sdp_server.c - *****************************************************************************/ -bt_status_t sdp_server_init(); -void sdp_server_cleanup(); -bt_status_t create_sdp_record(bluetooth_sdp_record* records, int* record_handles); -bt_status_t remove_sdp_record(int record_handle); -void on_create_record_event(int handle); -void on_remove_record_event(int handle); - -// Utility functions: -int get_sdp_records_size(bluetooth_sdp_record* in_record, int count); -void copy_sdp_records(bluetooth_sdp_record* in_records, bluetooth_sdp_record* out_records, - int count); - -/***************************************************************************** * Static variables *****************************************************************************/ diff --git a/system/btif/src/btif_sdp_server.cc b/system/btif/src/btif_sdp_server.cc index 6d3dfd4e03..6c073daf61 100644 --- a/system/btif/src/btif_sdp_server.cc +++ b/system/btif/src/btif_sdp_server.cc @@ -40,6 +40,7 @@ #include "bta/include/bta_sdp_api.h" #include "bta/sys/bta_sys.h" #include "btif_common.h" +#include "btif_sdp.h" #include "btif_sock_sdp.h" #include "osi/include/allocator.h" #include "stack/include/bt_types.h" @@ -48,9 +49,6 @@ #include "types/bluetooth/uuid.h" #include "utl.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth::legacy::stack::sdp; using namespace bluetooth; @@ -90,7 +88,6 @@ static int add_pbaps_sdp(const bluetooth_sdp_pse_record* rec); static int add_opps_sdp(const bluetooth_sdp_ops_record* rec); static int add_saps_sdp(const bluetooth_sdp_sap_record* rec); static int add_mps_sdp(const bluetooth_sdp_mps_record* rec); -bt_status_t remove_sdp_record(int record_id); static int free_sdp_slot(int id); /****************************************************************************** diff --git a/system/btif/src/btif_sock_l2cap.cc b/system/btif/src/btif_sock_l2cap.cc index 2a8e4e4f9a..ac1099fec4 100644 --- a/system/btif/src/btif_sock_l2cap.cc +++ b/system/btif/src/btif_sock_l2cap.cc @@ -15,6 +15,8 @@ * limitations under the License. */ +#include "btif_sock_l2cap.h" + #include <bluetooth/log.h> #include <com_android_bluetooth_flags.h> #include <sys/ioctl.h> @@ -44,9 +46,6 @@ #include "stack/include/l2cdefs.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; struct packet { @@ -102,7 +101,7 @@ static void on_srv_l2cap_psm_connect_offload_l(tBTA_JV_L2CAP_OPEN* p_open, l2cap static std::mutex state_lock; -l2cap_socket* socks = NULL; +static l2cap_socket* socks = NULL; static uint32_t last_sock_id = 0; static uid_set_t* uid_set = NULL; static int pth = -1; @@ -1087,8 +1086,8 @@ inline uint8_t* get_l2cap_sdu_start_ptr(BT_HDR* msg) { } // state_lock taken by caller -bool btsock_l2cap_read_signaled_on_connected_socket(int fd, int flags, uint32_t user_id, - l2cap_socket* sock) { +static bool btsock_l2cap_read_signaled_on_connected_socket(int fd, int flags, uint32_t user_id, + l2cap_socket* sock) { if (!sock->connected) { return false; } @@ -1129,8 +1128,9 @@ bool btsock_l2cap_read_signaled_on_connected_socket(int fd, int flags, uint32_t } // state_lock taken by caller -bool btsock_l2cap_read_signaled_on_listen_socket(int fd, int /* flags */, uint32_t /* user_id */, - l2cap_socket* sock) { +static bool btsock_l2cap_read_signaled_on_listen_socket(int fd, int /* flags */, + uint32_t /* user_id */, + l2cap_socket* sock) { int size = 0; bool ioctl_success = ioctl(sock->our_fd, FIONREAD, &size) == 0; if (ioctl_success && size) { @@ -1149,7 +1149,7 @@ bool btsock_l2cap_read_signaled_on_listen_socket(int fd, int /* flags */, uint32 return true; } -void btsock_l2cap_signaled_flagged(int fd, int flags, uint32_t user_id) { +static void btsock_l2cap_signaled_flagged(int fd, int flags, uint32_t user_id) { char drop_it = false; /* We use MSG_DONTWAIT when sending data to JAVA, hence it can be accepted to diff --git a/system/btif/src/btif_sock_rfc.cc b/system/btif/src/btif_sock_rfc.cc index 1a115c4cac..8af6a1bcf6 100644 --- a/system/btif/src/btif_sock_rfc.cc +++ b/system/btif/src/btif_sock_rfc.cc @@ -18,6 +18,8 @@ #define LOG_TAG "bt_btif_sock_rfcomm" +#include "btif_sock_rfc.h" + #include <bluetooth/log.h> #include <com_android_bluetooth_flags.h> #include <sys/ioctl.h> @@ -28,6 +30,7 @@ #include <mutex> #include "bta/include/bta_jv_api.h" +#include "bta/include/bta_jv_co.h" #include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_rfcomm_scn.h" #include "btif/include/btif_metrics_logging.h" @@ -51,9 +54,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; @@ -1087,6 +1087,7 @@ static void jv_dm_cback(tBTA_JV_EVT event, tBTA_JV* p_data, uint32_t id) { cfg.init_credit = 0; cfg.rx_mtu_present = slot->mtu > 0; cfg.rx_mtu = slot->mtu; + cfg.data_path = slot->data_path; } } // Start the rfcomm server after sdp & channel # assigned. @@ -1152,6 +1153,7 @@ static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) { cfg.init_credit = 0; cfg.rx_mtu_present = slot->mtu > 0; cfg.rx_mtu = slot->mtu; + cfg.data_path = slot->data_path; } } diff --git a/system/btif/src/btif_sock_sco.cc b/system/btif/src/btif_sock_sco.cc index a03d176e6f..45e2fb1ef5 100644 --- a/system/btif/src/btif_sock_sco.cc +++ b/system/btif/src/btif_sock_sco.cc @@ -18,6 +18,8 @@ #define LOG_TAG "bt_btif_sock_sco" +#include "btif_sock_sco.h" + #include <bluetooth/log.h> #include <sys/socket.h> #include <sys/types.h> @@ -54,9 +56,6 @@ // socket_read_ready_cb() - local host closed SCO socket // disconnect_completed_cb() - connection terminated -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using namespace bluetooth; typedef struct { @@ -175,7 +174,7 @@ static sco_socket_t* sco_socket_establish_locked(bool is_listening, const RawAdd socket_register(socket, thread_get_reactor(thread), sco_socket, socket_read_ready_cb, NULL); return sco_socket; -error:; +error: if (pair[0] != INVALID_FD) { close(pair[0]); } @@ -282,7 +281,7 @@ static void connection_request_cb(tBTM_ESCO_EVT event, tBTM_ESCO_EVT_DATA* data) return; -error:; +error: if (client_fd != INVALID_FD) { close(client_fd); } diff --git a/system/btif/src/btif_storage.cc b/system/btif/src/btif_storage.cc index fb2a716516..6a321f6405 100644 --- a/system/btif/src/btif_storage.cc +++ b/system/btif/src/btif_storage.cc @@ -45,6 +45,7 @@ #include <unordered_set> #include <vector> +#include "bta/include/bta_gatts_co.h" #include "btif/include/btif_api.h" #include "btif/include/btif_config.h" #include "btif/include/btif_dm.h" @@ -68,9 +69,6 @@ // Default user ID to use when real user ID is not available #define BTIF_STORAGE_RESTRICTED_USER_ID_DEFAULT 1 -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using bluetooth::Uuid; using namespace bluetooth; @@ -100,12 +98,6 @@ static const BtifStorageKey BTIF_STORAGE_LOCAL_LE_KEYS[] = { }; /******************************************************************************* - * External functions - ******************************************************************************/ - -void btif_gatts_add_bonded_dev_from_nv(const RawAddress& bda); - -/******************************************************************************* * Internal Functions ******************************************************************************/ @@ -584,8 +576,8 @@ size_t btif_split_uuids_string(const char* str, bluetooth::Uuid* p_uuid, size_t } /** Helper function for fetching a bt_property of the adapter. */ -bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size, - bt_property_t* property) { +static bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size, + bt_property_t* property) { property->type = type; property->val = buf; property->len = size; @@ -715,8 +707,8 @@ bt_status_t btif_storage_set_adapter_property(bt_property_t* property) { } /** Helper function for fetching a bt_property of a remote device. */ -bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type, - void* buf, int size, bt_property_t* property) { +static bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type, + void* buf, int size, bt_property_t* property) { property->type = type; property->val = buf; property->len = size; @@ -1258,8 +1250,9 @@ bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, i return BT_STATUS_DEVICE_NOT_FOUND; } -void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, - const tBLE_ADDR_TYPE& addr_type) { +#if TARGET_FLOSS +static void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, + const tBLE_ADDR_TYPE& addr_type) { bt_property_t prop; prop.type = BT_PROPERTY_REMOTE_ADDR_TYPE; prop.val = const_cast<tBLE_ADDR_TYPE*>(reinterpret_cast<const tBLE_ADDR_TYPE*>(&addr_type)); @@ -1267,6 +1260,7 @@ void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr, GetInterfaceToProfiles()->events->invoke_remote_device_properties_cb(BT_STATUS_SUCCESS, remote_bd_addr, 1, &prop); } +#endif // TARGET_FLOSS bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, tBLE_ADDR_TYPE addr_type) { @@ -1281,7 +1275,7 @@ bt_status_t btif_storage_set_remote_addr_type(const RawAddress* remote_bd_addr, return ret ? BT_STATUS_SUCCESS : BT_STATUS_FAIL; } -bool btif_has_ble_keys(const std::string& bdstr) { +static bool btif_has_ble_keys(const std::string& bdstr) { return btif_config_exist(bdstr, BTIF_STORAGE_KEY_LE_KEY_PENC); } diff --git a/system/btif/src/btif_vc.cc b/system/btif/src/btif_vc.cc index 99fad72810..51e0f1a2a6 100644 --- a/system/btif/src/btif_vc.cc +++ b/system/btif/src/btif_vc.cc @@ -33,12 +33,10 @@ #include "bta/include/bta_vc_api.h" #include "btif/include/btif_common.h" #include "btif/include/btif_profile_storage.h" +#include "btif_le_audio.h" #include "stack/include/main_thread.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using base::Bind; using base::Unretained; using bluetooth::aics::GainMode; @@ -48,8 +46,8 @@ using bluetooth::vc::VolumeControlCallbacks; using bluetooth::vc::VolumeControlInterface; namespace { -std::unique_ptr<VolumeControlInterface> vc_instance; -std::atomic_bool initialized = false; +static std::unique_ptr<VolumeControlInterface> vc_instance; +static std::atomic_bool initialized = false; class VolumeControlInterfaceImpl : public VolumeControlInterface, public VolumeControlCallbacks { ~VolumeControlInterfaceImpl() override = default; diff --git a/system/btif/src/stack_manager.cc b/system/btif/src/stack_manager.cc index 4ba403586e..935dbd7de2 100644 --- a/system/btif/src/stack_manager.cc +++ b/system/btif/src/stack_manager.cc @@ -99,9 +99,6 @@ static_assert(BTA_HH_INCLUDED, " Host interface device profile is always enabled in the bluetooth stack" "*** Conditional Compilation Directive error"); -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::common::MessageLoopThread; using bluetooth::log::error; using bluetooth::log::fatal; @@ -146,8 +143,8 @@ static void init_stack(bluetooth::core::CoreInterface* interface) { // and do not overlap. std::promise<void> promise; auto future = promise.get_future(); - management_thread.DoInThread(FROM_HERE, base::BindOnce(event_init_stack, std::move(promise), - base::Unretained(interface))); + management_thread.DoInThread( + base::BindOnce(event_init_stack, std::move(promise), base::Unretained(interface))); future.wait(); } @@ -155,11 +152,11 @@ static void start_up_stack_async(bluetooth::core::CoreInterface* interface, ProfileStartCallback startProfiles, ProfileStopCallback stopProfiles) { management_thread.DoInThread( - FROM_HERE, base::BindOnce(event_start_up_stack, interface, startProfiles, stopProfiles)); + base::BindOnce(event_start_up_stack, interface, startProfiles, stopProfiles)); } static void shut_down_stack_async(ProfileStopCallback stopProfiles) { - management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_stack, stopProfiles)); + management_thread.DoInThread(base::BindOnce(event_shut_down_stack, stopProfiles)); } static void clean_up_stack(ProfileStopCallback stopProfiles) { @@ -168,7 +165,7 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) { std::promise<void> promise; auto future = promise.get_future(); management_thread.DoInThread( - FROM_HERE, base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles)); + base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles)); auto status = future.wait_for(std::chrono::milliseconds( bluetooth::os::GetSystemPropertyUint32("bluetooth.cleanup_timeout", @@ -181,12 +178,11 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) { } static void start_up_rust_module_async(std::promise<void> promise) { - management_thread.DoInThread(FROM_HERE, - base::BindOnce(event_start_up_rust_module, std::move(promise))); + management_thread.DoInThread(base::BindOnce(event_start_up_rust_module, std::move(promise))); } static void shut_down_rust_module_async() { - management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_rust_module)); + management_thread.DoInThread(base::BindOnce(event_shut_down_rust_module)); } static bool get_stack_is_running() { return stack_is_running; } diff --git a/system/btif/test/btif_core_test.cc b/system/btif/test/btif_core_test.cc index 1bffc9ce3a..7342a17b99 100644 --- a/system/btif/test/btif_core_test.cc +++ b/system/btif/test/btif_core_test.cc @@ -57,9 +57,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::testing { void set_hal_cbacks(bt_callbacks_t* callbacks); } // namespace bluetooth::testing @@ -256,7 +253,7 @@ protected: }; std::promise<int> promise0; -void callback0(int val) { promise0.set_value(val); } +static void callback0(int val) { promise0.set_value(val); } TEST_F(BtifCoreTest, test_nop) {} diff --git a/system/btif/test/btif_dm_test.cc b/system/btif/test/btif_dm_test.cc index 068740472f..6f4447fa66 100644 --- a/system/btif/test/btif_dm_test.cc +++ b/system/btif/test/btif_dm_test.cc @@ -24,6 +24,7 @@ #include "bta/include/bta_api_data_types.h" #include "btif/include/mock_core_callbacks.h" +#include "btif/include/stack_manager_t.h" #include "main/shim/entry.h" #include "main/shim/shim.h" #include "main/shim/stack.h" @@ -42,10 +43,6 @@ const RawAddress kRawAddress = {{0x11, 0x22, 0x33, 0x44, 0x55, 0x66}}; constexpr char kBdName[] = {'k', 'B', 'd', 'N', 'a', 'm', 'e', '\0'}; } // namespace -namespace bluetooth::legacy::testing { -void set_interface_to_profiles(bluetooth::core::CoreInterface* interfaceToProfiles); -} // namespace bluetooth::legacy::testing - namespace { constexpr tBTM_BLE_TX_TIME_MS tx_time = 0x12345678; constexpr tBTM_BLE_RX_TIME_MS rx_time = 0x87654321; 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/btif/test/btif_profile_queue_test.cc b/system/btif/test/btif_profile_queue_test.cc index 489ba79660..0420b00622 100644 --- a/system/btif/test/btif_profile_queue_test.cc +++ b/system/btif/test/btif_profile_queue_test.cc @@ -22,19 +22,17 @@ #include <base/location.h> #include <gtest/gtest.h> +#include "btif/include/btif_common.h" #include "btif/include/stack_manager_t.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - typedef void(tBTIF_CBACK)(uint16_t event, char* p_param); typedef void(tBTIF_COPY_CBACK)(uint16_t event, char* p_dest, const char* p_src); // NOTE: Local re-implementation of functions to avoid thread context switching static bool sStackRunning; -bool get_stack_is_running(void) { return sStackRunning; } +static bool get_stack_is_running(void) { return sStackRunning; } static stack_manager_t sStackManager = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, get_stack_is_running}; const stack_manager_t* stack_manager_get_interface() { return &sStackManager; } diff --git a/system/btif/test/btif_rc_test.cc b/system/btif/test/btif_rc_test.cc index b537e06e04..64a899baae 100644 --- a/system/btif/test/btif_rc_test.cc +++ b/system/btif/test/btif_rc_test.cc @@ -99,7 +99,7 @@ bool btif_av_both_enable(void) { return true; } static bluetooth::common::MessageLoopThread jni_thread("bt_jni_thread"); bt_status_t do_in_jni_thread(base::OnceClosure task) { - if (!jni_thread.DoInThread(FROM_HERE, std::move(task))) { + if (!jni_thread.DoInThread(std::move(task))) { log::error("Post task to task runner failed!"); return BT_STATUS_JNI_THREAD_ATTACH_ERROR; } diff --git a/system/common/benchmark/thread_performance_benchmark.cc b/system/common/benchmark/thread_performance_benchmark.cc index 97f0c93b2d..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++; @@ -329,8 +326,7 @@ protected: std::future<void> set_up_future = set_up_promise_->get_future(); message_loop_thread_ = new MessageLoopThread("BM_MessageLooopThread thread"); message_loop_thread_->StartUp(); - message_loop_thread_->DoInThread(FROM_HERE, - base::BindOnce(&std::promise<void>::set_value, + message_loop_thread_->DoInThread(base::BindOnce(&std::promise<void>::set_value, base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -352,8 +348,7 @@ BENCHMARK_F(BM_MessageLooopThread, batch_enque_dequeue)(State& state) { std::future<void> counter_future = g_counter_promise->get_future(); for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - message_loop_thread_->DoInThread(FROM_HERE, - base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + message_loop_thread_->DoInThread(base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); } @@ -364,7 +359,7 @@ BENCHMARK_F(BM_MessageLooopThread, sequential_execution)(State& state) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { g_counter_promise = std::make_unique<std::promise<void>>(); std::future<void> counter_future = g_counter_promise->get_future(); - message_loop_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_sequential, nullptr)); + message_loop_thread_->DoInThread(base::BindOnce(&callback_sequential, nullptr)); counter_future.wait(); } } diff --git a/system/common/message_loop_thread.cc b/system/common/message_loop_thread.cc index 1de1ff036e..a6dd211d77 100644 --- a/system/common/message_loop_thread.cc +++ b/system/common/message_loop_thread.cc @@ -70,22 +70,20 @@ void MessageLoopThread::StartUp() { start_up_future.wait(); } -bool MessageLoopThread::DoInThread(const base::Location& from_here, base::OnceClosure task) { - return DoInThreadDelayed(from_here, std::move(task), std::chrono::microseconds(0)); +bool MessageLoopThread::DoInThread(base::OnceClosure task) { + return DoInThreadDelayed(std::move(task), std::chrono::microseconds(0)); } -bool MessageLoopThread::DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task, - std::chrono::microseconds delay) { +bool MessageLoopThread::DoInThreadDelayed(base::OnceClosure task, std::chrono::microseconds delay) { std::lock_guard<std::recursive_mutex> api_lock(api_mutex_); if (message_loop_ == nullptr) { - log::error("message loop is null for thread {}, from {}", *this, from_here.ToString()); + log::error("message loop is null for thread {}", *this); return false; } - if (!message_loop_->task_runner()->PostDelayedTask(from_here, std::move(task), + if (!message_loop_->task_runner()->PostDelayedTask(FROM_HERE, std::move(task), timeDeltaFromMicroseconds(delay))) { - log::error("failed to post task to message loop for thread {}, from {}", *this, - from_here.ToString()); + log::error("failed to post task to message loop for thread {}", *this); return false; } return true; @@ -199,9 +197,7 @@ void MessageLoopThread::Run(std::promise<void> start_up_promise) { } } -void MessageLoopThread::Post(base::OnceClosure closure) { - DoInThread(FROM_HERE, std::move(closure)); -} +void MessageLoopThread::Post(base::OnceClosure closure) { DoInThread(std::move(closure)); } PostableContext* MessageLoopThread::Postable() { return this; } diff --git a/system/common/message_loop_thread.h b/system/common/message_loop_thread.h index 301a4848a7..f51e2c9595 100644 --- a/system/common/message_loop_thread.h +++ b/system/common/message_loop_thread.h @@ -67,12 +67,11 @@ public: /** * Post a task to run on this thread * - * @param from_here location where this task is originated * @param task task created through base::Bind() * @return true if task is successfully scheduled, false if task cannot be * scheduled */ - bool DoInThread(const base::Location& from_here, base::OnceClosure task); + bool DoInThread(base::OnceClosure task); /** * Shutdown the current thread as if it is never started. IsRunning() and @@ -147,26 +146,22 @@ public: * <code> * base::CancelableClosure cancelable_task; * cancelable_task.Reset(base::Bind(...)); // bind the task - * same_thread->DoInThreadDelayed(FROM_HERE, - * cancelable_task.callback(), delay); + * same_thread->DoInThreadDelayed(cancelable_task.callback(), delay); * ... * // Cancel the task closure - * same_thread->DoInThread(FROM_HERE, - * base::Bind(&base::CancelableClosure::Cancel, - * base::Unretained(&cancelable_task))); + * same_thread->DoInThread(base::Bind(&base::CancelableClosure::Cancel, + * base::Unretained(&cancelable_task))); * </code> * * Warning: base::CancelableClosure objects must be created on, posted to, * cancelled on, and destroyed on the same thread. * - * @param from_here location where this task is originated * @param task task created through base::Bind() * @param delay delay for the task to be executed * @return true if task is successfully scheduled, false if task cannot be * scheduled */ - bool DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task, - std::chrono::microseconds delay); + bool DoInThreadDelayed(base::OnceClosure task, std::chrono::microseconds delay); /** * Wrapper around DoInThread without a location. */ diff --git a/system/common/message_loop_thread_unittest.cc b/system/common/message_loop_thread_unittest.cc index 8b6d598aaf..160f61e2c8 100644 --- a/system/common/message_loop_thread_unittest.cc +++ b/system/common/message_loop_thread_unittest.cc @@ -115,7 +115,6 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_before_start) { std::string name = "test_thread"; MessageLoopThread message_loop_thread(name); ASSERT_FALSE(message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this)))); } @@ -125,7 +124,6 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_after_shutdown) { message_loop_thread.StartUp(); message_loop_thread.ShutDown(); ASSERT_FALSE(message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this)))); } @@ -136,9 +134,8 @@ TEST_F(MessageLoopThreadTest, test_name) { ASSERT_GE(message_loop_thread.GetThreadId(), 0); std::promise<std::string> name_promise; std::future<std::string> name_future = name_promise.get_future(); - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetName, base::Unretained(this), - std::move(name_promise))); + message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetName, + base::Unretained(this), std::move(name_promise))); std::string my_name = name_future.get(); ASSERT_EQ(name, my_name); ASSERT_EQ(name, message_loop_thread.GetName()); @@ -152,9 +149,9 @@ TEST_F(MessageLoopThreadTest, test_thread_id) { ASSERT_GE(thread_id, 0); std::promise<base::PlatformThreadId> thread_id_promise; std::future<base::PlatformThreadId> thread_id_future = thread_id_promise.get_future(); - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetThreadId, base::Unretained(this), - std::move(thread_id_promise))); + message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetThreadId, + base::Unretained(this), + std::move(thread_id_promise))); base::PlatformThreadId my_thread_id = thread_id_future.get(); ASSERT_EQ(thread_id, my_thread_id); } @@ -189,19 +186,17 @@ TEST_F(MessageLoopThreadTest, test_set_realtime_priority_success) { std::future<void> execution_future = execution_promise.get_future(); int scheduling_policy = -1; int scheduling_priority = -1; - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetSchedulingPolicyAndPriority, - base::Unretained(this), &scheduling_policy, - &scheduling_priority, std::move(execution_promise))); + message_loop_thread.DoInThread(base::BindOnce( + &MessageLoopThreadTest::GetSchedulingPolicyAndPriority, base::Unretained(this), + &scheduling_policy, &scheduling_priority, std::move(execution_promise))); execution_future.wait(); ASSERT_EQ(scheduling_policy, SCHED_FIFO); // Internal implementation verified here ASSERT_EQ(scheduling_priority, 1); std::promise<pid_t> tid_promise; std::future<pid_t> tid_future = tid_promise.get_future(); - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetLinuxTid, base::Unretained(this), - std::move(tid_promise))); + message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetLinuxTid, + base::Unretained(this), std::move(tid_promise))); pid_t linux_tid = tid_future.get(); ASSERT_GT(linux_tid, 0); ASSERT_EQ(sched_getscheduler(linux_tid), SCHED_FIFO); @@ -260,9 +255,9 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback) { std::promise<std::string> name_promise; std::future<std::string> name_future = name_promise.get_future(); uint32_t delay_ms = 5; - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce(&MessageLoopThreadTest::SleepAndGetName, base::Unretained(this), - std::move(name_promise), delay_ms)); + message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::SleepAndGetName, + base::Unretained(this), std::move(name_promise), + delay_ms)); message_loop_thread.ShutDown(); std::string my_name = name_future.get(); ASSERT_EQ(name, my_name); @@ -273,9 +268,8 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback_check_lock) { std::string name = "test_thread"; MessageLoopThread message_loop_thread(name); message_loop_thread.StartUp(); - message_loop_thread.DoInThread( - FROM_HERE, base::BindOnce([](MessageLoopThread* thread) { thread->IsRunning(); }, - &message_loop_thread)); + message_loop_thread.DoInThread(base::BindOnce( + [](MessageLoopThread* thread) { thread->IsRunning(); }, &message_loop_thread)); message_loop_thread.ShutDown(); } 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/repeating_timer.cc b/system/common/repeating_timer.cc index f1e645182a..98ff8c442a 100644 --- a/system/common/repeating_timer.cc +++ b/system/common/repeating_timer.cc @@ -37,7 +37,7 @@ RepeatingTimer::~RepeatingTimer() { // This runs on user thread bool RepeatingTimer::SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread, - const base::Location& from_here, base::RepeatingClosure task, + base::RepeatingClosure task, std::chrono::microseconds period) { if (period < kMinimumPeriod) { log::error("period must be at least {}", kMinimumPeriod.count()); @@ -58,10 +58,9 @@ bool RepeatingTimer::SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& th message_loop_thread_ = thread; period_ = period; uint64_t time_until_next_us = time_next_task_us - clock_tick_us_(); - if (!thread->DoInThreadDelayed(from_here, task_wrapper_.callback(), + if (!thread->DoInThreadDelayed(task_wrapper_.callback(), std::chrono::microseconds(time_until_next_us))) { - log::error("failed to post task to message loop for thread {}, from {}", *thread, - from_here.ToString()); + log::error("failed to post task to message loop for thread {}", *thread); expected_time_next_task_us_ = 0; task_wrapper_.Cancel(); message_loop_thread_ = nullptr; @@ -97,9 +96,8 @@ void RepeatingTimer::CancelHelper(std::promise<void> promise) { CancelClosure(std::move(promise)); return; } - scheduled_thread->DoInThread( - FROM_HERE, base::BindOnce(&RepeatingTimer::CancelClosure, base::Unretained(this), - std::move(promise))); + scheduled_thread->DoInThread(base::BindOnce(&RepeatingTimer::CancelClosure, + base::Unretained(this), std::move(promise))); } // This runs on message loop thread @@ -140,7 +138,7 @@ void RepeatingTimer::RunTask() { // multiple of period remaining_time_us = (remaining_time_us % period_us + period_us) % period_us; } - message_loop_thread_->DoInThreadDelayed(FROM_HERE, task_wrapper_.callback(), + message_loop_thread_->DoInThreadDelayed(task_wrapper_.callback(), std::chrono::microseconds(remaining_time_us)); uint64_t time_before_task_us = clock_tick_us_(); diff --git a/system/common/repeating_timer.h b/system/common/repeating_timer.h index 6c22f0d467..c7d0505e86 100644 --- a/system/common/repeating_timer.h +++ b/system/common/repeating_timer.h @@ -54,13 +54,11 @@ public: * blocks until the previous task is cancelled. * * @param thread thread to run the task - * @param from_here location where this task is originated * @param task task created through base::Bind() * @param period period for the task to be executed * @return true iff task is scheduled successfully */ - bool SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread, - const base::Location& from_here, base::RepeatingClosure task, + bool SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread, base::RepeatingClosure task, std::chrono::microseconds period); /** diff --git a/system/common/repeating_timer_unittest.cc b/system/common/repeating_timer_unittest.cc index 817f3e9bb0..a8a7a4cd80 100644 --- a/system/common/repeating_timer_unittest.cc +++ b/system/common/repeating_timer_unittest.cc @@ -81,7 +81,7 @@ public: auto future = promise_->get_future(); auto start_time = std::chrono::steady_clock::now(); timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, + message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::VerifyDelayTimeAndSleep, base::Unretained(this), start_time, interval_between_tasks_ms, scheduled_tasks, task_length_ms, promise_), @@ -136,7 +136,7 @@ TEST_F(RepeatingTimerTest, periodic_run) { uint32_t delay_ms = 5; int num_tasks = 200; - timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, base::Unretained(this), num_tasks, promise_), std::chrono::milliseconds(delay_ms)); @@ -152,7 +152,7 @@ TEST_F(RepeatingTimerTest, schedule_periodic_task_zero_interval) { uint32_t interval_ms = 0; ASSERT_FALSE(timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, + message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)), std::chrono::milliseconds(interval_ms))); std::this_thread::sleep_for(std::chrono::milliseconds(delay_error_ms)); @@ -165,7 +165,7 @@ TEST_F(RepeatingTimerTest, periodic_delete_without_cancel) { message_loop_thread.StartUp(); uint32_t delay_ms = 5; timer_->SchedulePeriodic( - message_loop_thread.GetWeakPtr(), FROM_HERE, + message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)), std::chrono::milliseconds(delay_ms)); delete timer_; @@ -178,7 +178,7 @@ TEST_F(RepeatingTimerTest, cancel_single_task_near_fire_no_race_condition) { MessageLoopThread message_loop_thread(name); message_loop_thread.StartUp(); uint32_t delay_ms = 5; - timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, base::DoNothing(), + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), base::DoNothing(), std::chrono::milliseconds(delay_ms)); std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms)); timer_->CancelAndWait(); @@ -192,7 +192,7 @@ TEST_F(RepeatingTimerTest, cancel_periodic_task) { int num_tasks = 5; auto future = promise_->get_future(); - timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, base::Unretained(this), num_tasks, promise_), std::chrono::milliseconds(delay_ms)); @@ -225,7 +225,7 @@ TEST_F(RepeatingTimerTest, message_loop_thread_down_cancel_scheduled_periodic_ta uint32_t delay_ms = 5; int num_tasks = 5; - timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, + timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter, base::Unretained(this), num_tasks, promise_), std::chrono::milliseconds(delay_ms)); diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc index d6a0ea32ec..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); } @@ -264,8 +261,8 @@ protected: std::future<void> set_up_future = set_up_promise_->get_future(); worker_thread_ = new MessageLoopThread("WorkerThreadPerformanceTest thread"); worker_thread_->StartUp(); - worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&std::promise<void>::set_value, - base::Unretained(set_up_promise_.get()))); + worker_thread_->DoInThread(base::BindOnce(&std::promise<void>::set_value, + base::Unretained(set_up_promise_.get()))); set_up_future.wait(); } @@ -288,7 +285,7 @@ TEST_F(WorkerThreadPerformanceTest, worker_thread_speed_test) { for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) { fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter); - worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); + worker_thread_->DoInThread(base::BindOnce(&callback_batch, bt_msg_queue_, nullptr)); } counter_future.wait(); 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/le_advertising_manager.cc b/system/main/shim/le_advertising_manager.cc index 6fcae663c0..dfe7ba5f59 100644 --- a/system/main/shim/le_advertising_manager.cc +++ b/system/main/shim/le_advertising_manager.cc @@ -269,16 +269,14 @@ public: // bluetooth::hci::AdvertisingCallback void OnAdvertisingDataSet(uint8_t advertiser_id, AdvertisingCallback::AdvertisingStatus status) override { - if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { - int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); - uint8_t client_id = is_native_advertiser(reg_id); - if (client_id != kAdvertiserClientIdJni) { - // Invoke callback for native client - do_in_main_thread(base::Bind(&::AdvertisingCallbacks::OnAdvertisingDataSet, - base::Unretained(native_adv_callbacks_map_[client_id]), - advertiser_id, status)); - return; - } + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + uint8_t client_id = is_native_advertiser(reg_id); + if (client_id != kAdvertiserClientIdJni) { + // Invoke callback for native client + do_in_main_thread(base::Bind(&::AdvertisingCallbacks::OnAdvertisingDataSet, + base::Unretained(native_adv_callbacks_map_[client_id]), + advertiser_id, status)); + return; } do_in_jni_thread(base::BindOnce(&::AdvertisingCallbacks::OnAdvertisingDataSet, base::Unretained(advertising_callbacks_), advertiser_id, @@ -312,16 +310,14 @@ public: // bluetooth::hci::AdvertisingCallback void OnPeriodicAdvertisingDataSet(uint8_t advertiser_id, AdvertisingCallback::AdvertisingStatus status) override { - if (com::android::bluetooth::flags::leaudio_broadcast_update_metadata_callback()) { - int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); - uint8_t client_id = is_native_advertiser(reg_id); - if (client_id != kAdvertiserClientIdJni) { - // Invoke callback for native client - do_in_main_thread(base::Bind(&::AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, - base::Unretained(native_adv_callbacks_map_[client_id]), - advertiser_id, status)); - return; - } + int reg_id = bluetooth::shim::GetAdvertising()->GetAdvertiserRegId(advertiser_id); + uint8_t client_id = is_native_advertiser(reg_id); + if (client_id != kAdvertiserClientIdJni) { + // Invoke callback for native client + do_in_main_thread(base::Bind(&::AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, + base::Unretained(native_adv_callbacks_map_[client_id]), + advertiser_id, status)); + return; } do_in_jni_thread(base::BindOnce(&::AdvertisingCallbacks::OnPeriodicAdvertisingDataSet, base::Unretained(advertising_callbacks_), advertiser_id, 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/osi/src/alarm.cc b/system/osi/src/alarm.cc index fa5072474d..6aaf4354ae 100644 --- a/system/osi/src/alarm.cc +++ b/system/osi/src/alarm.cc @@ -654,7 +654,7 @@ static void callback_dispatch(void* /* context */) { } alarm->closure.i.Reset(Bind(alarm_ready_mloop, alarm)); - get_main_thread()->DoInThread(FROM_HERE, alarm->closure.i.callback()); + get_main_thread()->DoInThread(alarm->closure.i.callback()); } else { fixed_queue_enqueue(alarm->queue, alarm); } diff --git a/system/osi/test/future_test.cc b/system/osi/test/future_test.cc index a3ed620302..4acf389be4 100644 --- a/system/osi/test/future_test.cc +++ b/system/osi/test/future_test.cc @@ -41,7 +41,7 @@ TEST_F(FutureTest, test_future_non_immediate) { MessageLoopThread worker_thread("worker_thread"); worker_thread.StartUp(); - worker_thread.DoInThread(FROM_HERE, base::BindOnce(post_to_future, future)); + worker_thread.DoInThread(base::BindOnce(post_to_future, future)); EXPECT_EQ(pass_back_data0, future_await(future)); diff --git a/system/osi/test/internal/semaphore_test.cc b/system/osi/test/internal/semaphore_test.cc index 612804749f..92c0194976 100644 --- a/system/osi/test/internal/semaphore_test.cc +++ b/system/osi/test/internal/semaphore_test.cc @@ -83,7 +83,7 @@ TEST_F(SemaphoreTest, test_ensure_wait) { EXPECT_FALSE(semaphore_try_wait(semaphore)); SemaphoreTestSequenceHelper sequence_helper = {semaphore, 0}; - thread.DoInThread(FROM_HERE, base::BindOnce(sleep_then_increment_counter, &sequence_helper)); + thread.DoInThread(base::BindOnce(sleep_then_increment_counter, &sequence_helper)); semaphore_wait(semaphore); EXPECT_EQ(sequence_helper.counter, 1) << "semaphore_wait() did not wait for counter to increment"; 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/btm/btm_ble.cc b/system/stack/btm/btm_ble.cc index b612b684b3..2251835c7d 100644 --- a/system/stack/btm/btm_ble.cc +++ b/system/stack/btm/btm_ble.cc @@ -182,8 +182,7 @@ void BTM_BleReadPhy(const RawAddress& bd_addr, uint8_t data[len]; uint8_t* pp = data; UINT16_TO_STREAM(pp, handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_READ_PHY, data, len, - base::Bind(&read_phy_cb, std::move(cb))); + btu_hcif_send_cmd_with_cb(HCI_BLE_READ_PHY, data, len, base::Bind(&read_phy_cb, std::move(cb))); } void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, @@ -229,6 +228,5 @@ void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys, UINT8_TO_STREAM(pp, tx_phys); UINT8_TO_STREAM(pp, rx_phys); UINT16_TO_STREAM(pp, phy_options); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_SET_PHY, data, len, - base::Bind([](uint8_t*, uint16_t) {})); + btu_hcif_send_cmd_with_cb(HCI_BLE_SET_PHY, data, len, base::Bind([](uint8_t*, uint16_t) {})); } diff --git a/system/stack/btm/btm_ble_adv_filter.cc b/system/stack/btm/btm_ble_adv_filter.cc index 73050b5047..7f064132b8 100644 --- a/system/stack/btm/btm_ble_adv_filter.cc +++ b/system/stack/btm/btm_ble_adv_filter.cc @@ -382,7 +382,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I BTM_BLE_ADV_FILT_TRACK_NUM; } - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, len, + btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param, len, base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); } else if (BTM_BLE_SCAN_COND_DELETE == action) { /* select feature based on control block settings */ @@ -391,7 +391,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I /* Filter index */ UINT8_TO_STREAM(p, filt_index); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, + btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param, (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH), base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); @@ -403,7 +403,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I UINT8_TO_STREAM(p, BTM_BLE_META_PF_FEAT_SEL); UINT8_TO_STREAM(p, BTM_BLE_SCAN_COND_CLEAR); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, + btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param, (uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH - 1), base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb)); } diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc index 7d8a0cd618..7a4b6d1256 100644 --- a/system/stack/btu/btu_hcif.cc +++ b/system/stack/btu/btu_hcif.cc @@ -64,7 +64,6 @@ #include "types/raw_address.h" using namespace bluetooth; -using base::Location; using bluetooth::hci::IsoManager; /******************************************************************************/ @@ -574,18 +573,13 @@ using hci_cmd_cb = base::OnceCallback<void(uint8_t* /* return_parameters */, struct cmd_with_cb_data { hci_cmd_cb cb; - base::Location posted_from; }; static void cmd_with_cb_data_init(cmd_with_cb_data* cb_wrapper) { new (&cb_wrapper->cb) hci_cmd_cb; - new (&cb_wrapper->posted_from) Location; } -static void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) { - cb_wrapper->cb.~hci_cmd_cb(); - cb_wrapper->posted_from.~Location(); -} +static void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) { cb_wrapper->cb.~hci_cmd_cb(); } /** * Log command complete events that is not handled individually in this file @@ -646,7 +640,6 @@ static void btu_hcif_command_complete_evt_with_cb_on_task(BT_HDR* event, void* c btu_hcif_log_command_complete_metrics(opcode, stream); cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context; - log::verbose("command complete for: {}", cb_wrapper->posted_from.ToString()); // 2 for event header: event code (1) + parameter length (1) // 3 for command complete header: num_hci_pkt (1) + opcode (2) uint16_t param_len = static_cast<uint16_t>(event->len - 5); @@ -676,7 +669,6 @@ static void btu_hcif_command_status_evt_with_cb_on_task(uint8_t status, BT_HDR* // report command status error cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context; - log::verbose("command status for: {}", cb_wrapper->posted_from.ToString()); std::move(cb_wrapper->cb).Run(&status, sizeof(uint16_t)); cmd_with_cb_data_cleanup(cb_wrapper); osi_free(cb_wrapper); @@ -698,8 +690,8 @@ static void btu_hcif_command_status_evt_with_cb(uint8_t status, BT_HDR* command, /* This function is called to send commands to the Host Controller. |cb| is * called when command status event is called with error code, or when the * command complete event is received. */ -void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params, - uint8_t params_len, hci_cmd_cb cb) { +void btu_hcif_send_cmd_with_cb(uint16_t opcode, uint8_t* params, uint8_t params_len, + hci_cmd_cb cb) { BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE); uint8_t* pp = (uint8_t*)(p + 1); @@ -718,7 +710,6 @@ void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcod cmd_with_cb_data_init(cb_wrapper); cb_wrapper->cb = std::move(cb); - cb_wrapper->posted_from = posted_from; bluetooth::shim::hci_layer_get_interface()->transmit_command( p, btu_hcif_command_complete_evt_with_cb, btu_hcif_command_status_evt_with_cb, diff --git a/system/stack/btu/main_thread.cc b/system/stack/btu/main_thread.cc index 6223e66716..6364f81e8b 100644 --- a/system/stack/btu/main_thread.cc +++ b/system/stack/btu/main_thread.cc @@ -37,7 +37,7 @@ bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; } bluetooth::common::PostableContext* get_main() { return main_thread.Postable(); } bt_status_t do_in_main_thread(base::OnceClosure task) { - if (!main_thread.DoInThread(FROM_HERE, std::move(task))) { + if (!main_thread.DoInThread(std::move(task))) { log::error("failed to post task to task runner!"); return BT_STATUS_JNI_THREAD_ATTACH_ERROR; } @@ -45,7 +45,7 @@ bt_status_t do_in_main_thread(base::OnceClosure task) { } bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::microseconds delay) { - if (!main_thread.DoInThreadDelayed(FROM_HERE, std::move(task), delay)) { + if (!main_thread.DoInThreadDelayed(std::move(task), delay)) { log::error("failed to post task to task runner!"); return BT_STATUS_JNI_THREAD_ATTACH_ERROR; } diff --git a/system/stack/connection_manager/connection_manager.cc b/system/stack/connection_manager/connection_manager.cc index 3b13c63adc..ff878d84ac 100644 --- a/system/stack/connection_manager/connection_manager.cc +++ b/system/stack/connection_manager/connection_manager.cc @@ -53,25 +53,20 @@ constexpr char kBtmLogTagTA[] = "TA"; struct closure_data { base::OnceClosure user_task; - base::Location posted_from; }; extern std::string get_client_name(uint8_t gatt_if); static void alarm_closure_cb(void* p) { closure_data* data = (closure_data*)p; - log::verbose("executing timer scheduled at {}", data->posted_from.ToString()); std::move(data->user_task).Run(); delete data; } // Periodic alarms are not supported, because we clean up data in callback -static void alarm_set_closure(const base::Location& posted_from, alarm_t* alarm, - uint64_t interval_ms, base::OnceClosure user_task) { +static void alarm_set_closure(alarm_t* alarm, uint64_t interval_ms, base::OnceClosure user_task) { closure_data* data = new closure_data; - data->posted_from = posted_from; data->user_task = std::move(user_task); - log::verbose("scheduling timer {}", data->posted_from.ToString()); alarm_set_on_mloop(alarm, interval_ms, alarm_closure_cb, data); } @@ -561,7 +556,7 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address, tBLE_ADDR_TYP // Setup a timer alarm_t* timeout = alarm_new("wl_conn_params_30s"); - alarm_set_closure(FROM_HERE, timeout, DIRECT_CONNECT_TIMEOUT, + alarm_set_closure(timeout, DIRECT_CONNECT_TIMEOUT, base::BindOnce(&wl_direct_connect_timeout_cb, app_id, address)); bgconn_dev[address].doing_direct_conn.emplace(app_id, unique_alarm_ptr(timeout, &alarm_free)); 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/hcic/hciblecmds.cc b/system/stack/hcic/hciblecmds.cc index 10d283af90..27be452ce5 100644 --- a/system/stack/hcic/hciblecmds.cc +++ b/system/stack/hcic/hciblecmds.cc @@ -238,7 +238,7 @@ void btsnd_hcic_ble_read_remote_feat(uint16_t handle) { void btsnd_hcic_ble_rand(base::Callback<void(BT_OCTET8)> cb) { btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_BLE_RAND, nullptr, 0, + HCI_BLE_RAND, nullptr, 0, base::Bind( [](base::Callback<void(BT_OCTET8)> cb, uint8_t* param, uint16_t /* param_len */) { bluetooth::log::assert_that(param[0] == 0, @@ -466,7 +466,7 @@ void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t s UINT8_TO_STREAM(pp, cis_cfg[i].rtn_stom); } - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_CIG_PARAMS, param, params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_SET_CIG_PARAMS, param, params_len, std::move(cb)); } void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, @@ -482,7 +482,7 @@ void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg, UINT16_TO_STREAM(pp, cis_cfg[i].acl_conn_handle); } - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_CREATE_CIS, param, params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_CREATE_CIS, param, params_len, std::move(cb)); } void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback<void(uint8_t*, uint16_t)> cb) { @@ -492,7 +492,7 @@ void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback<void(uint8_t*, uin UINT8_TO_STREAM(pp, cig_id); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_CIG, param, params_len, std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_REMOVE_CIG, param, params_len, std::move(cb)); } void btsnd_hcic_req_peer_sca(uint16_t conn_handle) { @@ -578,8 +578,7 @@ void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, UINT8_TO_STREAM(pp, codec_conf.size()); ARRAY_TO_STREAM(pp, codec_conf.data(), static_cast<int>(codec_conf.size())); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SETUP_ISO_DATA_PATH, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_SETUP_ISO_DATA_PATH, param, params_len, std::move(cb)); } void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, @@ -591,8 +590,7 @@ void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir, UINT16_TO_STREAM(pp, iso_handle); UINT8_TO_STREAM(pp, data_path_dir); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_ISO_DATA_PATH, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_REMOVE_ISO_DATA_PATH, param, params_len, std::move(cb)); } void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, @@ -603,8 +601,7 @@ void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle, UINT16_TO_STREAM(pp, iso_handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_READ_ISO_LINK_QUALITY, param, params_len, - std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_READ_ISO_LINK_QUALITY, param, params_len, std::move(cb)); } void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t adv_sid, @@ -632,7 +629,7 @@ void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t ad void btsnd_hcic_ble_periodic_advertising_create_sync_cancel( base::OnceCallback<void(uint8_t*, uint16_t)> cb) { - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr, + btu_hcif_send_cmd_with_cb(HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr, HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, std::move(cb)); } @@ -643,7 +640,7 @@ void btsnd_hcic_ble_periodic_advertising_terminate_sync( UINT16_TO_STREAM(pp, sync_handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param, + btu_hcif_send_cmd_with_cb(HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param, HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_TERMINATE_SYNC, std::move(cb)); } @@ -657,7 +654,7 @@ void btsnd_hci_ble_add_device_to_periodic_advertiser_list( BDADDR_TO_STREAM(pp, adv_addr); UINT8_TO_STREAM(pp, adv_sid); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param, + btu_hcif_send_cmd_with_cb(HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param, HCIC_PARAM_SIZE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, std::move(cb)); } @@ -671,13 +668,13 @@ void btsnd_hci_ble_remove_device_from_periodic_advertiser_list( BDADDR_TO_STREAM(pp, adv_addr); UINT8_TO_STREAM(pp, adv_sid); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param, + btu_hcif_send_cmd_with_cb(HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param, HCIC_PARAM_SIZE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, std::move(cb)); } void btsnd_hci_ble_clear_periodic_advertiser_list(base::OnceCallback<void(uint8_t*, uint16_t)> cb) { - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr, + btu_hcif_send_cmd_with_cb(HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr, HCIC_PARAM_SIZE_CLEAR_PERIODIC_ADVERTISER_LIST, std::move(cb)); } @@ -689,7 +686,7 @@ void btsnd_hcic_ble_set_periodic_advertising_receive_enable( UINT16_TO_STREAM(pp, sync_handle); UINT8_TO_STREAM(pp, (enable ? 0x01 : 0x00)); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param, + btu_hcif_send_cmd_with_cb(HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param, HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, std::move(cb)); } @@ -703,7 +700,7 @@ void btsnd_hcic_ble_periodic_advertising_sync_transfer( UINT16_TO_STREAM(pp, service_data); UINT16_TO_STREAM(pp, sync_handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param, + btu_hcif_send_cmd_with_cb(HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param, HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SYNC_TRANSFER, std::move(cb)); } @@ -717,7 +714,7 @@ void btsnd_hcic_ble_periodic_advertising_set_info_transfer( UINT16_TO_STREAM(pp, service_data); UINT8_TO_STREAM(pp, adv_handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param, + btu_hcif_send_cmd_with_cb(HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param, HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, std::move(cb)); } @@ -733,7 +730,7 @@ void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params( UINT16_TO_STREAM(pp, sync_timeout); UINT8_TO_STREAM(pp, cte_type); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, + btu_hcif_send_cmd_with_cb(HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, std::move(cb)); } @@ -750,7 +747,7 @@ void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params( UINT16_TO_STREAM(pp, sync_timeout); UINT8_TO_STREAM(pp, cte_type); - btu_hcif_send_cmd_with_cb( - FROM_HERE, HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, - HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, std::move(cb)); + btu_hcif_send_cmd_with_cb(HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param, + HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, + std::move(cb)); } diff --git a/system/stack/hcic/hcicmds.cc b/system/stack/hcic/hcicmds.cc index 4183df86c2..257be53656 100644 --- a/system/stack/hcic/hcicmds.cc +++ b/system/stack/hcic/hcicmds.cc @@ -1472,7 +1472,7 @@ void btsnd_hcic_read_encryption_key_size(uint16_t handle, ReadEncKeySizeCb cb) { uint8_t* p = param; UINT16_TO_STREAM(p, handle); - btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_READ_ENCR_KEY_SIZE, param, len, + btu_hcif_send_cmd_with_cb(HCI_READ_ENCR_KEY_SIZE, param, len, base::Bind(&read_encryption_key_size_complete, base::Passed(&cb))); } @@ -1566,7 +1566,7 @@ void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data, tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) { uint16_t v_opcode = HCI_GRP_VENDOR_SPECIFIC | opcode; - btu_hcif_send_cmd_with_cb(FROM_HERE, v_opcode, p_data, len, + btu_hcif_send_cmd_with_cb(v_opcode, p_data, len, base::BindOnce(&btsnd_hcic_vendor_spec_complete, base::Unretained(p_cmd_cplt_cback), v_opcode)); } 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/include/bt_dev_class.h b/system/stack/include/bt_dev_class.h index 333376c071..b966836731 100644 --- a/system/stack/include/bt_dev_class.h +++ b/system/stack/include/bt_dev_class.h @@ -24,6 +24,9 @@ constexpr size_t kDevClassLength = 3; typedef std::array<uint8_t, kDevClassLength> DEV_CLASS; /* Device class */ +/* major class mask */ +#define PHONE_COD_MAJOR_CLASS_MASK 0x1F00 + /*************************** * major device class field * Note: All values are deduced by basing BIT_X to BIT_8, values as per diff --git a/system/stack/include/btu_hcif.h b/system/stack/include/btu_hcif.h index 13ee0f1493..0d1bceba63 100644 --- a/system/stack/include/btu_hcif.h +++ b/system/stack/include/btu_hcif.h @@ -27,8 +27,8 @@ *********************************** */ void btu_hcif_send_cmd(uint8_t controller_id, const BT_HDR* p_msg); -void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params, - uint8_t params_len, base::OnceCallback<void(uint8_t*, uint16_t)> cb); +void btu_hcif_send_cmd_with_cb(uint16_t opcode, uint8_t* params, uint8_t params_len, + base::OnceCallback<void(uint8_t*, uint16_t)> cb); void btu_hci_msg_process(BT_HDR* p_msg); namespace bluetooth::legacy::testing { diff --git a/system/stack/include/port_api.h b/system/stack/include/port_api.h index 5efdc30205..57d1220c17 100644 --- a/system/stack/include/port_api.h +++ b/system/stack/include/port_api.h @@ -24,6 +24,8 @@ #ifndef PORT_API_H #define PORT_API_H +#include <hardware/bt_sock.h> + #include <cstdint> #include "include/macros.h" @@ -188,6 +190,7 @@ struct RfcommCfgInfo { uint16_t init_credit; bool rx_mtu_present; uint16_t rx_mtu; + btsock_data_path_t data_path{BTSOCK_DATA_PATH_NO_OFFLOAD}; }; namespace std { diff --git a/system/stack/mmc/daemon/service.cc b/system/stack/mmc/daemon/service.cc index d2dee226d2..0ac49a5746 100644 --- a/system/stack/mmc/daemon/service.cc +++ b/system/stack/mmc/daemon/service.cc @@ -286,9 +286,9 @@ bool Service::StartWorkerThread(int fd, struct sockaddr_un addr, log::warn("Failed to enable real time scheduling"); } - if (!thread_pool_.back().first->DoInThread( - FROM_HERE, base::BindOnce(&StartSocketListener, fd, std::move(addr), - std::move(task_ended), std::move(codec_server)))) { + if (!thread_pool_.back().first->DoInThread(base::BindOnce(&StartSocketListener, fd, + std::move(addr), std::move(task_ended), + std::move(codec_server)))) { log::error("Failed to run task"); return false; } diff --git a/system/stack/rfcomm/port_int.h b/system/stack/rfcomm/port_int.h index 19364dfc19..deedced477 100644 --- a/system/stack/rfcomm/port_int.h +++ b/system/stack/rfcomm/port_int.h @@ -197,6 +197,8 @@ typedef struct { #define PORT_CTRL_REQ_CONFIRMED 0x02 #define PORT_CTRL_IND_RECEIVED 0x04 #define PORT_CTRL_IND_RESPONDED 0x08 +#define PORT_CTRL_SETUP_COMPLETED \ + (PORT_CTRL_REQ_SENT | PORT_CTRL_REQ_CONFIRMED | PORT_CTRL_IND_RECEIVED | PORT_CTRL_IND_RESPONDED) uint8_t port_ctrl; /* Modem Status Command */ diff --git a/system/stack/rfcomm/port_rfc.cc b/system/stack/rfcomm/port_rfc.cc index ac206257bf..860fdf0450 100644 --- a/system/stack/rfcomm/port_rfc.cc +++ b/system/stack/rfcomm/port_rfc.cc @@ -453,10 +453,19 @@ void PORT_DlcEstablishInd(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu) { (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle); } - if (p_port->p_mgmt_callback) { - p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_IND, - 1); + if (com::android::bluetooth::flags::indicate_rfcomm_connection_complete_after_msc()) { + if (p_port->rfc_cfg_info.data_path != BTSOCK_DATA_PATH_HARDWARE_OFFLOAD && + p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_IND, + 1); + } + } else { + if (p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_IND, + 1); + } } p_port->state = PORT_CONNECTION_STATE_OPENED; @@ -500,11 +509,21 @@ void PORT_DlcEstablishCnf(tRFC_MCB* p_mcb, uint8_t dlci, uint16_t mtu, uint16_t (p_port->p_callback)(PORT_EV_CONNECTED, p_port->handle); } - if (p_port->p_mgmt_callback) { - p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); - log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_CNF, - 1); + if (com::android::bluetooth::flags::indicate_rfcomm_connection_complete_after_msc()) { + if (p_port->rfc_cfg_info.data_path != BTSOCK_DATA_PATH_HARDWARE_OFFLOAD && + p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_CNF, + 1); + } + } else { + if (p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics(android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_CNF, + 1); + } } + p_port->state = PORT_CONNECTION_STATE_OPENED; /* RPN is required only if we want to tell DTE how the port should be opened @@ -637,6 +656,16 @@ void PORT_ControlInd(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* p_pars) { (p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RTSCTS) ? 1 : 0, (p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_RI) ? 1 : 0, (p_port->peer_ctrl.modem_signal & MODEM_SIGNAL_DCD) ? 1 : 0); + + if (com::android::bluetooth::flags::indicate_rfcomm_connection_complete_after_msc()) { + if (p_port->rfc_cfg_info.data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) { + if (p_port->port_ctrl == PORT_CTRL_SETUP_COMPLETED && p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_IND, 1); + } + } + } } /******************************************************************************* @@ -674,6 +703,16 @@ void PORT_ControlCnf(tRFC_MCB* p_mcb, uint8_t dlci, tPORT_CTRL* /* p_pars */) { if (event && p_port->p_callback) { (p_port->p_callback)(event, p_port->handle); } + + if (com::android::bluetooth::flags::indicate_rfcomm_connection_complete_after_msc()) { + if (p_port->rfc_cfg_info.data_path == BTSOCK_DATA_PATH_HARDWARE_OFFLOAD) { + if (p_port->port_ctrl == PORT_CTRL_SETUP_COMPLETED && p_port->p_mgmt_callback) { + p_port->p_mgmt_callback(PORT_SUCCESS, p_port->handle); + log_counter_metrics( + android::bluetooth::CodePathCounterKeyEnum::RFCOMM_CONNECTION_SUCCESS_CNF, 1); + } + } + } } /******************************************************************************* 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/common/main_handler.cc b/system/test/common/main_handler.cc index c6e792c4dc..87e97d9c49 100644 --- a/system/test/common/main_handler.cc +++ b/system/test/common/main_handler.cc @@ -42,13 +42,13 @@ void do_post_on_bt_main(BtMainClosure closure) { closure(); } } // namespace bt_status_t do_in_main_thread(base::OnceClosure task) { - bluetooth::log::assert_that(main_thread.DoInThread(FROM_HERE, std::move(task)), + bluetooth::log::assert_that(main_thread.DoInThread(std::move(task)), "Unable to run on main thread"); return BT_STATUS_SUCCESS; } bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::microseconds delay) { - bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(FROM_HERE, std::move(task), delay), + bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(std::move(task), delay), "Unable to run on main thread delayed"); return BT_STATUS_SUCCESS; } 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_jni_thread.cc b/system/test/mock/mock_jni_thread.cc index eb8b6db093..2a9365b748 100644 --- a/system/test/mock/mock_jni_thread.cc +++ b/system/test/mock/mock_jni_thread.cc @@ -46,8 +46,3 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) { do_in_jni_thread_task_queue.push(std::move(task)); return BT_STATUS_SUCCESS; } -bt_status_t do_in_jni_thread(const base::Location& /* from_here */, base::OnceClosure task) { - inc_func_call_count(__func__); - do_in_jni_thread_task_queue.push(std::move(task)); - return BT_STATUS_SUCCESS; -} 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_btu_hcif.cc b/system/test/mock/mock_stack_btu_hcif.cc index 0a4da4bc03..1d27c8a0b7 100644 --- a/system/test/mock/mock_stack_btu_hcif.cc +++ b/system/test/mock/mock_stack_btu_hcif.cc @@ -34,9 +34,8 @@ using hci_cmd_cb = base::OnceCallback<void(uint8_t* /* return_parameters */, void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* /* p_buf */) { inc_func_call_count(__func__); } -void btu_hcif_send_cmd_with_cb(const base::Location& /* posted_from */, uint16_t /* opcode */, - uint8_t* /* params */, uint8_t /* params_len */, - hci_cmd_cb /* cb */) { +void btu_hcif_send_cmd_with_cb(uint16_t /* opcode */, uint8_t* /* params */, + uint8_t /* params_len */, hci_cmd_cb /* cb */) { inc_func_call_count(__func__); } void btu_hci_msg_process(BT_HDR* /* p_msg */) { 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 |