diff options
708 files changed, 9683 insertions, 14682 deletions
diff --git a/Android.bp b/Android.bp index 3ea90eb91b..93d31a7b63 100644 --- a/Android.bp +++ b/Android.bp @@ -121,6 +121,7 @@ java_defaults { javacflags: [ "-Xep:AlmostJavadoc:ERROR", "-Xep:AlreadyChecked:ERROR", + "-Xep:ArrayRecordComponent:ERROR", "-Xep:BadImport:ERROR", "-Xep:CatchAndPrintStackTrace:ERROR", "-Xep:CatchFail:ERROR", @@ -137,6 +138,7 @@ java_defaults { "-Xep:EqualsIncompatibleType:ERROR", "-Xep:FallThrough:ERROR", "-Xep:Finalize:ERROR", + "-Xep:ForEachIterable:ERROR", "-Xep:FutureReturnValueIgnored:ERROR", "-Xep:GuardedBy:ERROR", "-Xep:HidingField:ERROR", @@ -151,6 +153,7 @@ java_defaults { "-Xep:LockOnNonEnclosingClassLiteral:ERROR", "-Xep:LongFloatConversion:ERROR", "-Xep:LoopOverCharArray:ERROR", + "-Xep:MethodCanBeStatic:ERROR", "-Xep:MissingCasesInEnumSwitch:ERROR", "-Xep:MixedMutabilityReturnType:ERROR", "-Xep:MockNotUsedInProduction:ERROR", diff --git a/TEST_MAPPING b/TEST_MAPPING index 8c32e97a23..34772b59b0 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -4,6 +4,9 @@ "name": "CtsBluetoothTestCases" }, { + "name": "BluetoothJavaUnitTests" + }, + { "name": "GoogleBluetoothInstrumentationTests" }, { @@ -18,9 +21,6 @@ // "name": "bluetooth-test-audio-hal-interface" //}, { - "name": "net_test_audio_hearing_aid_hw" - }, - { "name": "net_test_bluetooth" }, { @@ -235,6 +235,9 @@ "name": "CtsStrictJavaPackagesTestCases" }, { + "name": "BluetoothJavaUnitTests" + }, + { "name": "BluetoothInstrumentationTests" }, { @@ -253,9 +256,6 @@ // "name": "bluetooth-test-audio-hal-interface" //}, { - "name": "net_test_audio_hearing_aid_hw" - }, - { "name": "net_test_bluetooth" }, { @@ -467,6 +467,9 @@ "name": "CtsBluetoothTestCases" }, { + "name": "BluetoothJavaUnitTests" + }, + { "name": "BluetoothInstrumentationTests" }, { @@ -484,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 1a1b0cd950..b7e4929cbb 100644 --- a/android/app/Android.bp +++ b/android/app/Android.bp @@ -140,6 +140,7 @@ cc_library_shared { "libmodpb64", "libopus", "libosi", + "libperfetto_client_experimental", "libprotobuf-cpp-lite", "libstatslog_bt", "libstatslog_express", @@ -202,6 +203,7 @@ cc_library { android_library { name: "BluetoothLib", defaults: ["bluetooth_framework_errorprone_rules"], + manifest: "LibAndroidManifest.xml", srcs: [ ":statslog-bluetooth-java-gen", @@ -221,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", @@ -341,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/LibAndroidManifest.xml b/android/app/LibAndroidManifest.xml new file mode 100644 index 0000000000..ee17512047 --- /dev/null +++ b/android/app/LibAndroidManifest.xml @@ -0,0 +1,200 @@ +<?xml version="1.0" encoding="utf-8"?> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + package="com.android.bluetooth"> + <uses-sdk android:minSdkVersion="14"/> + <!-- For PBAP Owner Vcard Info --> + <uses-permission android:name="android.permission.READ_PROFILE"/> + <application android:name="com.android.bluetooth.btservice.AdapterApp" + android:icon="@mipmap/bt_share" + android:persistent="false" + android:label="@string/app_name" + android:supportsRtl="true" + android:usesCleartextTraffic="false" + android:directBootAware="true" + android:defaultToDeviceProtectedStorage="true" + android:memtagMode="async"> + <service android:process="@string/process" + android:name="com.android.bluetooth.btservice.AdapterService" + android:exported="true" + android:permission="android.permission.ACCESS_BLUETOOTH_SHARE"> + <intent-filter> + <action android:name="android.bluetooth.IBluetooth"/> + </intent-filter> + </service> + <service android:process="@string/process" + android:name="com.android.bluetooth.notification.NotificationHelperService" + android:label="Notification Helper" + android:exported="true" + android:permission="android.permission.BLUETOOTH_PRIVILEGED"> + <intent-filter> + <action android:name="android.bluetooth.notification.action.SEND_TOGGLE_NOTIFICATION"/> + </intent-filter> + </service> + <service android:process="@string/process" + android:name="com.android.bluetooth.avrcpcontroller.BluetoothMediaBrowserService" + android:enabled="true" + android:exported="true" + android:label="@string/a2dp_sink_mbs_label"> + <intent-filter> + <action android:name="android.media.browse.MediaBrowserService"/> + </intent-filter> + <meta-data android:name="androidx.car.app.launchable" android:value="true" /> + </service> + <activity android:name="com.android.bluetooth.BluetoothPrefs" + android:exported="true" + android:enabled="false"> + <intent-filter> + <action android:name="android.intent.action.APPLICATION_PREFERENCES"/> + </intent-filter> + <meta-data android:name="distractionOptimized" android:value="true"/> + </activity> + <service + android:name="com.android.bluetooth.telephony.BluetoothInCallService" + android:permission="android.permission.BIND_INCALL_SERVICE" + android:process="@string/process" + android:enabled="false" + android:exported="true"> + <meta-data android:name="android.telecom.INCLUDE_SELF_MANAGED_CALLS" + android:value="true" /> + <intent-filter> + <action android:name="android.telecom.InCallService"/> + </intent-filter> + </service> + <service android:process="@string/process" + android:name="com.android.bluetooth.hfpclient.HfpClientConnectionService" + android:permission="android.permission.BIND_CONNECTION_SERVICE" + android:enabled="true" + android:exported="true"> + <intent-filter> + <action android:name="android.telecom.ConnectionService"/> + </intent-filter> + </service> + <receiver android:process="@string/process" + android:name="com.android.bluetooth.opp.BluetoothOppReceiver" + android:exported="true" + android:enabled="false"> + </receiver> + <receiver android:process="@string/process" + android:name="com.android.bluetooth.opp.BluetoothOppHandoverReceiver" + android:permission="com.android.permission.ALLOWLIST_BLUETOOTH_DEVICE" + android:exported="true" + android:enabled="false"> + <intent-filter> + <action android:name="android.btopp.intent.action.ACCEPTLIST_DEVICE"/> + <action android:name="android.btopp.intent.action.STOP_HANDOVER_TRANSFER"/> + </intent-filter> + <intent-filter> + <action android:name="android.nfc.handover.intent.action.HANDOVER_SEND"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="*/*"/> + </intent-filter> + <intent-filter> + <action android:name="android.nfc.handover.intent.action.HANDOVER_SEND_MULTIPLE"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="*/*"/> + </intent-filter> + </receiver> + <activity android:name="com.android.bluetooth.opp.BluetoothOppLauncherActivity" + android:process="@string/process" + android:theme="@android:style/Theme.Translucent.NoTitleBar" + android:label="@string/bt_share_picker_label" + android:enabled="false" + android:exported="true"> + <intent-filter> + <action android:name="android.intent.action.SEND"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="image/*"/> + <data android:mimeType="video/*"/> + <data android:mimeType="audio/*"/> + <data android:mimeType="text/x-vcard"/> + <data android:mimeType="text/x-vcalendar"/> + <data android:mimeType="text/calendar"/> + <data android:mimeType="text/plain"/> + <data android:mimeType="text/html"/> + <data android:mimeType="text/xml"/> + <data android:mimeType="application/zip"/> + <data android:mimeType="application/vnd.ms-excel"/> + <data android:mimeType="application/msword"/> + <data android:mimeType="application/vnd.ms-powerpoint"/> + <data android:mimeType="application/pdf"/> + <data android:mimeType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/> + <data android:mimeType="application/vnd.openxmlformats-officedocument.wordprocessingml.document"/> + <data android:mimeType="application/vnd.openxmlformats-officedocument.presentationml.presentation"/> + <data android:mimeType="application/x-hwp"/> + </intent-filter> + <intent-filter> + <action android:name="android.intent.action.SEND_MULTIPLE"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="image/*"/> + <data android:mimeType="video/*"/> + <data android:mimeType="x-mixmedia/*"/> + <data android:mimeType="text/x-vcard"/> + </intent-filter> + <intent-filter> + <action android:name="android.btopp.intent.action.OPEN"/> + <category android:name="android.intent.category.DEFAULT"/> + <data android:mimeType="vnd.android.cursor.item/vnd.android.btopp"/> + </intent-filter> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppBtEnableActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppBtErrorActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppBtEnablingActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppIncomingFileConfirmActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppTransferActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <activity android:name="com.android.bluetooth.opp.BluetoothOppTransferHistory" + android:process="@string/process" + android:label="" + android:excludeFromRecents="true" + android:configChanges="orientation|keyboardHidden" + android:enabled="false" + android:theme="@android:style/Theme.DeviceDefault.Settings" + android:exported="true"> + <intent-filter> + <action android:name="com.android.bluetooth.action.TransferHistory"/> + <category android:name="android.intent.category.DEFAULT"/> + </intent-filter> + </activity> + <activity android:name="com.android.bluetooth.pbap.BluetoothPbapActivity" + android:process="@string/process" + android:excludeFromRecents="true" + android:theme="@style/dialog" + android:enabled="false"> + </activity> + <service android:process="@string/process" + android:name="com.android.bluetooth.pbapclient.PbapClientAccountAuthenticatorService" + android:enabled="false" + android:exported="true"> + <intent-filter> + <action android:name="android.accounts.AccountAuthenticator"/> + </intent-filter> + <meta-data android:name="android.accounts.AccountAuthenticator" + android:resource="@xml/authenticator"/> + </service> + </application> +</manifest> + diff --git a/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl index 9f63f37dc0..49a5cd6650 100644 --- a/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl +++ b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl @@ -71,8 +71,6 @@ interface IBluetoothHeadset { @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})") - void clccResponse(int index, int direction, int status, int mode, boolean mpty, String number, int type, 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_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp index 9f6c5c45ed..357e23f5d0 100644 --- a/android/app/jni/com_android_bluetooth_gatt.cpp +++ b/android/app/jni/com_android_bluetooth_gatt.cpp @@ -49,6 +49,7 @@ #include "hardware/distance_measurement_interface.h" #include "main/shim/le_scanning_manager.h" #include "rust/cxx.h" +#include "src/core/ffi/module.h" #include "src/gatt/ffi.rs.h" #include "types/bluetooth/uuid.h" #include "types/raw_address.h" @@ -586,6 +587,11 @@ static const btgatt_client_callbacks_t sGattClientCallbacks = { */ void btgatts_register_app_cb(int status, int server_if, const Uuid& uuid) { + // TODO(b/356462170): Remove this when we have fixed the bug + if (!is_module_started(&rust_module)) { + log::error("Rust module isn't started! scan_manager_refactor={}", + com::android::bluetooth::flags::scan_manager_refactor()); + } bluetooth::gatt::open_server(server_if); std::shared_lock<std::shared_mutex> lock(callbacks_mutex); CallbackEnv sCallbackEnv(__func__); diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp index 3a3d8ceed6..3b0411135c 100644 --- a/android/app/jni/com_android_bluetooth_le_audio.cpp +++ b/android/app/jni/com_android_bluetooth_le_audio.cpp @@ -130,6 +130,8 @@ static std::shared_timed_mutex interface_mutex; static jobject mCallbacksObj = nullptr; static std::shared_timed_mutex callbacks_mutex; +static jclass class_LeAudioNativeInterface; + jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig) { log::info( "ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, " @@ -174,7 +176,7 @@ public: if (!sCallbackEnv.valid() || mCallbacksObj == nullptr) { return; } - sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onInitialized); + sCallbackEnv->CallStaticVoidMethod(class_LeAudioNativeInterface, method_onInitialized); } void OnConnectionState(ConnectionState state, const RawAddress& bd_addr) override { @@ -430,6 +432,10 @@ static void initNative(JNIEnv* env, jobject object, jobjectArray codecOffloading return; } + jclass tmpControllerInterface = + env->FindClass("com/android/bluetooth/le_audio/LeAudioNativeInterface"); + class_LeAudioNativeInterface = (jclass)env->NewGlobalRef(tmpControllerInterface); + if (mCallbacksObj != nullptr) { log::info("Cleaning up LeAudio callback object"); env->DeleteGlobalRef(mCallbacksObj); @@ -1573,7 +1579,7 @@ int register_com_android_bluetooth_le_audio(JNIEnv* env) { {"onGroupNodeStatus", "([BII)V", &method_onGroupNodeStatus}, {"onAudioConf", "(IIIII)V", &method_onAudioConf}, {"onSinkAudioLocationAvailable", "([BI)V", &method_onSinkAudioLocationAvailable}, - {"onInitialized", "()V", &method_onInitialized}, + {"onInitialized", "()V", &method_onInitialized, true}, {"onConnectionStateChanged", "(I[B)V", &method_onConnectionStateChanged}, {"onAudioLocalCodecCapabilities", "([Landroid/bluetooth/BluetoothLeAudioCodecConfig;" diff --git a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapContract.java b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapContract.java index dd7493a1ae..8b5b8ddb59 100644 --- a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapContract.java +++ b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapContract.java @@ -47,7 +47,7 @@ import android.net.Uri; * android:permission="android.permission.BLUETOOTH_MAP"> * ... * <intent-filter> - * <action android:name="android.content.action.BLEUETOOT_MAP_PROVIDER" /> + * <action android:name="android.content.action.BLUETOOTH_MAP_PROVIDER" /> * </intent-filter> * ... * </provider> @@ -165,7 +165,7 @@ public final class BluetoothMapContract { * Build URI representing the given Account data-set with specific Id in a Bluetooth provider. * When queried, the direct URI for the account with the given accountID is returned. */ - public static Uri buildAccountUriwithId(String authority, String accountId) { + public static Uri buildAccountUriWithId(String authority, String accountId) { return new Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority(authority) @@ -505,7 +505,7 @@ public final class BluetoothMapContract { String _ID = "_id"; /** - * The date the message was received as a unix timestamp (miliseconds since 00:00:00 UTC + * The date the message was received as a unix timestamp (milliseconds since 00:00:00 UTC * 1/1-1970). * * <p>Type: INTEGER (long) read-only @@ -553,7 +553,7 @@ public final class BluetoothMapContract { * * <p>Type: TEXT see DELIVERY_STATE_* constants below read-only */ - String DEVILERY_STATE = "delivery_state"; + String DELIVERY_STATE = "delivery_state"; /** * To be able to filter messages with attachments, we need this flag. @@ -779,7 +779,7 @@ public final class BluetoothMapContract { String THREAD_NAME = "thread_name"; /** - * The time stamp of the last activity in the conversation as a unix timestamp (miliseconds + * The time stamp of the last activity in the conversation as a unix timestamp (milliseconds * since 00:00:00 UTC 1/1-1970) * * <p>Type: INTEGER (long) read-only @@ -798,7 +798,7 @@ public final class BluetoothMapContract { * * <p>Type: INTEGER (long) read-only */ - // TODO: IS THIS NECESSARY - skal den ligge i databasen? + // TODO: IS THIS NECESSARY - should it be in the database? // CB: If we need it, it must be in the database, or initialized with a random value at // BT-ON // UPDATE: TODO: Change to the last_activity time stamp (as a long value). This will @@ -883,13 +883,13 @@ public final class BluetoothMapContract { /** * Time in ms since epoch. For conversations this will be for last activity as a unix timestamp - * (miliseconds since 00:00:00 UTC 1/1-1970) + * (milliseconds since 00:00:00 UTC 1/1-1970) */ public static final String FILTER_PERIOD_BEGIN = "t_begin"; /** * Time in ms since epoch. For conversations this will be for last activity as a unix timestamp - * (miliseconds since 00:00:00 UTC 1/1-1970) + * (milliseconds since 00:00:00 UTC 1/1-1970) */ public static final String FILTER_PERIOD_END = "t_end"; @@ -898,8 +898,8 @@ public final class BluetoothMapContract { public interface ChatState { int UNKNOWN = 0; - int INACITVE = 1; - int ACITVE = 2; + int INACTIVE = 1; + int ACTIVE = 2; int COMPOSING = 3; int PAUSED = 4; int GONE = 5; @@ -931,7 +931,7 @@ public final class BluetoothMapContract { /** * The chat state of contact in conversation, see {@link ChatState} * - * <p>Type: INTERGER read-only + * <p>Type: INTEGER read-only */ String CHAT_STATE = "chat_state"; @@ -979,14 +979,14 @@ public final class BluetoothMapContract { /** * The presence state of contact, see {@link PresenceState} * - * <p>Type: INTERGER read-only + * <p>Type: INTEGER read-only */ String PRESENCE_STATE = "presence_state"; /** * The priority of contact presence * - * <p>Type: INTERGER read-only + * <p>Type: INTEGER read-only */ // TODO: IS THIS NEEDED - not in latest specification String PRIORITY = "priority"; @@ -1027,7 +1027,7 @@ public final class BluetoothMapContract { MessageColumns.BCC_LIST, MessageColumns.REPLY_TO_LIST, MessageColumns.RECEPTION_STATE, - MessageColumns.DEVILERY_STATE, + MessageColumns.DELIVERY_STATE, MessageColumns.THREAD_ID }; @@ -1047,7 +1047,7 @@ public final class BluetoothMapContract { MessageColumns.FROM_LIST, MessageColumns.TO_LIST, MessageColumns.RECEPTION_STATE, - MessageColumns.DEVILERY_STATE, + MessageColumns.DELIVERY_STATE, MessageColumns.THREAD_ID, MessageColumns.THREAD_NAME }; diff --git a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapEmailProvider.java b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapEmailProvider.java index a5ee32357f..36cc6f037d 100644 --- a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapEmailProvider.java +++ b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapEmailProvider.java @@ -42,8 +42,8 @@ import java.util.Map; * allows access to Email messages from a Bluetooth device through the Message Access Profile. */ public abstract class BluetoothMapEmailProvider extends ContentProvider { + private static final String TAG = BluetoothMapEmailProvider.class.getSimpleName(); - private static final String TAG = "BluetoothMapEmailProvider"; private static final boolean D = true; private static final int MATCH_ACCOUNT = 1; @@ -68,7 +68,7 @@ public abstract class BluetoothMapEmailProvider extends ContentProvider { * @param download true if any missing part of the message shall be downloaded before written to * the stream. The download flag will determine whether or not attachments shall be * downloaded or only the message content. - * @param out the FileOurputStream to write to. + * @param out the FileOutputStream to write to. * @throws IOException */ protected abstract void WriteMessageToStream( @@ -248,7 +248,7 @@ public abstract class BluetoothMapEmailProvider extends ContentProvider { if (accountId == null) { newUri = BluetoothMapContract.buildAccountUri(mAuthority); } else { - newUri = BluetoothMapContract.buildAccountUriwithId(mAuthority, accountId); + newUri = BluetoothMapContract.buildAccountUriWithId(mAuthority, accountId); } if (D) { Log.d(TAG, "onAccountChanged() accountId = " + accountId + " URI: " + newUri); @@ -745,7 +745,7 @@ public abstract class BluetoothMapEmailProvider extends ContentProvider { public static String getAccountId(Uri uri) { final List<String> segments = uri.getPathSegments(); if (segments.size() < 1) { - throw new IllegalArgumentException("No AccountId pressent in URI: " + uri); + throw new IllegalArgumentException("No AccountId present in URI: " + uri); } return segments.get(0); } diff --git a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapIMProvider.java b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapIMProvider.java index 7e4e8d7640..395f82a651 100644 --- a/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapIMProvider.java +++ b/android/app/lib/mapapi/com/android/bluetooth/mapapi/BluetoothMapIMProvider.java @@ -37,8 +37,8 @@ import java.util.Set; * access to Instant messages from a Bluetooth device through the Message Access Profile. */ public abstract class BluetoothMapIMProvider extends ContentProvider { + private static final String TAG = BluetoothMapIMProvider.class.getSimpleName(); - private static final String TAG = "BluetoothMapIMProvider"; private static final boolean D = true; private static final int MATCH_ACCOUNT = 1; @@ -103,7 +103,7 @@ public abstract class BluetoothMapIMProvider extends ContentProvider { if (accountId == null) { newUri = BluetoothMapContract.buildAccountUri(mAuthority); } else { - newUri = BluetoothMapContract.buildAccountUriwithId(mAuthority, accountId); + newUri = BluetoothMapContract.buildAccountUriWithId(mAuthority, accountId); } if (D) { @@ -447,7 +447,7 @@ public abstract class BluetoothMapIMProvider extends ContentProvider { /** * Query for conversations with contact information. The expected result is a cursor pointing to * one row for each contact in a conversation. E.g.: ThreadId | ThreadName | ... | ContactName | - * ContactPrecence | ... | 1 | "Bowling" | ... | Hans | 1 | ... | 1 | "Bowling" | ... | Peter | + * ContactPresence | ... | 1 | "Bowling" | ... | Hans | 1 | ... | 1 | "Bowling" | ... | Peter | * 2 | ... | 2 | "" | ... | Peter | 2 | ... | 3 | "" | ... | Hans | 1 | ... | * * @param accountId the ID of the account @@ -734,7 +734,7 @@ public abstract class BluetoothMapIMProvider extends ContentProvider { public static String getAccountId(Uri uri) { final List<String> segments = uri.getPathSegments(); if (segments.size() < 1) { - throw new IllegalArgumentException("No AccountId pressent in URI: " + uri); + throw new IllegalArgumentException("No AccountId present in URI: " + uri); } return segments.get(0); } diff --git a/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java b/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java index e73c4f99ba..c87481853a 100644 --- a/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java +++ b/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java @@ -59,6 +59,7 @@ import java.util.Set; // should be avoided public class BluetoothMethodProxy { private static final String TAG = BluetoothMethodProxy.class.getSimpleName(); + private static final Object INSTANCE_LOCK = new Object(); private static BluetoothMethodProxy sInstance; diff --git a/android/app/src/com/android/bluetooth/ObexRejectServer.java b/android/app/src/com/android/bluetooth/ObexRejectServer.java index cc38c2d1db..3b24dfa6de 100644 --- a/android/app/src/com/android/bluetooth/ObexRejectServer.java +++ b/android/app/src/com/android/bluetooth/ObexRejectServer.java @@ -35,8 +35,8 @@ import java.io.IOException; * <p>Will reject the OBEX connection, start a timer, and at timeout close the socket. */ public class ObexRejectServer extends ServerRequestHandler implements Handler.Callback { + private static final String TAG = ObexRejectServer.class.getSimpleName(); - private static final String TAG = "ObexRejectServer"; private final int mResult; private final HandlerThread mHandlerThread; private final Handler mMessageHandler; diff --git a/android/app/src/com/android/bluetooth/ObexServerSockets.java b/android/app/src/com/android/bluetooth/ObexServerSockets.java index b6af0a59bd..afa2f8b646 100644 --- a/android/app/src/com/android/bluetooth/ObexServerSockets.java +++ b/android/app/src/com/android/bluetooth/ObexServerSockets.java @@ -46,7 +46,7 @@ import java.io.IOException; * In both cases the {@link ObexServerSockets} object have terminated, and a new must be created. */ public class ObexServerSockets { - private static final String TAG = "ObexServerSockets"; + private static final String TAG = ObexServerSockets.class.getSimpleName(); private final IObexConnectionHandler mConHandler; /* The wrapped sockets */ diff --git a/android/app/src/com/android/bluetooth/Utils.java b/android/app/src/com/android/bluetooth/Utils.java index 946adbfebe..dc2fdc12ec 100644 --- a/android/app/src/com/android/bluetooth/Utils.java +++ b/android/app/src/com/android/bluetooth/Utils.java @@ -98,7 +98,9 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public final class Utils { - private static final String TAG = "BluetoothUtils"; + public static final String TAG_PREFIX_BLUETOOTH = "Bluetooth"; + private static final String TAG = TAG_PREFIX_BLUETOOTH + Utils.class.getSimpleName(); + private static final int MICROS_PER_UNIT = 625; private static final String PTS_TEST_MODE_PROPERTY = "persist.bluetooth.pts"; @@ -1032,7 +1034,7 @@ public final class Utils { if (!sIsInstrumentationTestModeCacheSet) { try { sInstrumentationTestModeCache = - Class.forName("com.android.bluetooth.FileSystemWriteTest") != null; + Class.forName("com.android.bluetooth.TestUtils") != null; } catch (ClassNotFoundException exception) { sInstrumentationTestModeCache = false; } diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java index 6c7d53c8e6..31549ea3fd 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java @@ -168,7 +168,7 @@ class A2dpCodecConfig { } // Get the codec type of the highest priority of selectableCodecs and codecConfig. - private int getPrioitizedCodecType( + private static int getPrioitizedCodecType( BluetoothCodecConfig codecConfig, List<BluetoothCodecConfig> selectableCodecs) { BluetoothCodecConfig prioritizedCodecConfig = codecConfig; for (BluetoothCodecConfig config : selectableCodecs) { diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeCallback.java b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeCallback.java index 4ea0fbe96e..314811f71c 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpNativeCallback.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpNativeCallback.java @@ -31,7 +31,7 @@ import com.android.internal.annotations.VisibleForTesting; import java.util.Arrays; class A2dpNativeCallback { - static final String TAG = A2dpNativeCallback.class.getSimpleName(); + private static final String TAG = A2dpNativeCallback.class.getSimpleName(); private final AdapterService mAdapterService; private final A2dpService mA2dpService; diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java index 89174b84ec..bae84611d1 100644 --- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java +++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java @@ -20,6 +20,8 @@ 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 com.android.bluetooth.Utils.checkCallerTargetSdk; @@ -235,9 +237,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 +306,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 } @@ -391,7 +391,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 +427,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 +532,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(" @@ -1166,9 +1166,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 +1181,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 +1303,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 +1437,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); diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java index 106d2699a1..e26624b614 100644 --- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java +++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkNativeInterface.java @@ -30,6 +30,7 @@ import com.android.internal.annotations.VisibleForTesting; /** A2DP Sink Native Interface to/from JNI. */ public class A2dpSinkNativeInterface { private static final String TAG = A2dpSinkNativeInterface.class.getSimpleName(); + private AdapterService mAdapterService; @GuardedBy("INSTANCE_LOCK") @@ -137,7 +138,7 @@ public class A2dpSinkNativeInterface { } /** Send a stack event up to the A2DP Sink Service */ - private void sendMessageToService(StackEvent event) { + private static void sendMessageToService(StackEvent event) { A2dpSinkService service = A2dpSinkService.getA2dpSinkService(); if (service != null) { service.messageFromNative(event); diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java index 7ad03639a7..87cce542b2 100644 --- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java +++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java @@ -17,6 +17,8 @@ package com.android.bluetooth.a2dpsink; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -249,7 +251,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); } @@ -354,8 +356,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 +438,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(); } /** diff --git a/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java b/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java index 6386a0ce89..9092efa879 100644 --- a/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java +++ b/android/app/src/com/android/bluetooth/audio_util/BrowsablePlayerConnector.java @@ -24,6 +24,7 @@ import android.os.Message; import android.util.Log; import com.android.bluetooth.Utils; +import com.android.bluetooth.avrcpcontroller.AvrcpControllerUtils; import com.android.internal.annotations.VisibleForTesting; import java.util.ArrayList; @@ -41,7 +42,9 @@ import java.util.Set; * BrowsedPlayerWrappers by hand. */ public class BrowsablePlayerConnector extends Handler { - private static final String TAG = "AvrcpBrowsablePlayerConnector"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP + BrowsablePlayerConnector.class.getSimpleName(); + private static final long CONNECT_TIMEOUT_MS = 10000; // Time in ms to wait for a connection private static final int MSG_GET_FOLDER_ITEMS_CB = 0; diff --git a/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java b/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java index 33c680e7df..a69a6be6f9 100644 --- a/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java +++ b/android/app/src/com/android/bluetooth/audio_util/GPMWrapper.java @@ -21,13 +21,16 @@ import android.media.session.MediaSession; import android.os.Looper; import android.util.Log; +import com.android.bluetooth.avrcpcontroller.AvrcpControllerUtils; + /** * Google Play Music hides some of the metadata behind a specific key in the Extras of the * MediaDescription in the MediaSession.QueueItem. This class exists to provide alternate methods to * allow Google Play Music to match the default behaviour of MediaPlayerWrapper. */ class GPMWrapper extends MediaPlayerWrapper { - private static final String TAG = "AvrcpGPMWrapper"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP + GPMWrapper.class.getSimpleName(); GPMWrapper(Context context, MediaController controller, Looper looper) { super(context, controller, looper); diff --git a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java index e062814766..248fd20c14 100644 --- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java +++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java @@ -59,6 +59,7 @@ import java.util.regex.Pattern; */ public class MediaPlayerList { private static final String TAG = MediaPlayerList.class.getSimpleName(); + static boolean sTesting = false; private static final String PACKAGE_SCHEME = "package"; diff --git a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java index 18b3d2979e..36a9ee9793 100644 --- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java +++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java @@ -41,7 +41,8 @@ import java.util.Objects; * with that. */ public class MediaPlayerWrapper { - private static final String TAG = "AudioMediaPlayerWrapper"; + private static final String TAG = MediaPlayerWrapper.class.getSimpleName(); + static boolean sTesting = false; private static final int PLAYBACK_STATE_CHANGE_EVENT_LOGGER_SIZE = 5; private static final String PLAYBACK_STATE_CHANGE_LOGGER_EVENT_TITLE = diff --git a/android/app/src/com/android/bluetooth/audio_util/helpers/Image.java b/android/app/src/com/android/bluetooth/audio_util/helpers/Image.java index d89a6afddf..6c686b9126 100644 --- a/android/app/src/com/android/bluetooth/audio_util/helpers/Image.java +++ b/android/app/src/com/android/bluetooth/audio_util/helpers/Image.java @@ -34,7 +34,7 @@ import java.io.InputStream; * determine image equality in an application/folder/item agnostic way. */ public class Image { - private static final String TAG = "Image"; + private static final String TAG = Image.class.getSimpleName(); public static int SOURCE_NONE = 0; public static int SOURCE_URI = 1; diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java index 9e76df75c3..3ab495fdb0 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java @@ -178,7 +178,7 @@ public class AvrcpBipObexServer extends ServerRequestHandler { * * @return True if the image handle is valid, false otherwise. */ - private boolean isImageHandleValid(String handle) { + private static boolean isImageHandleValid(String handle) { if (handle == null || handle.length() != 7) return false; for (int i = 0; i < 7; i++) { char c = handle.charAt(i); @@ -305,7 +305,7 @@ public class AvrcpBipObexServer extends ServerRequestHandler { } /** Send a response to the given operation using the given headers and bytes. */ - private int sendResponse(Operation op, HeaderSet replyHeaders, byte[] bytes) { + private static int sendResponse(Operation op, HeaderSet replyHeaders, byte[] bytes) { if (op != null && bytes != null && replyHeaders != null) { OutputStream outStream = null; int maxChunkSize = 0; @@ -344,11 +344,11 @@ public class AvrcpBipObexServer extends ServerRequestHandler { return ResponseCodes.OBEX_HTTP_NOT_FOUND; } - private void warn(String msg) { + private static void warn(String msg) { Log.w(TAG, msg); } - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java index 46805f404c..232bdfa56a 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java @@ -273,12 +273,12 @@ public class AvrcpCoverArtService { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java index 1ad024ab80..cd97e9970c 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtStorage.java @@ -182,12 +182,12 @@ final class AvrcpCoverArtStorage { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java index 2436bc6bb4..82f4fa4b7b 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java @@ -16,11 +16,12 @@ package com.android.bluetooth.avrcp; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static java.util.Objects.requireNonNull; import android.annotation.NonNull; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothUtils; import android.content.BroadcastReceiver; import android.content.Context; @@ -294,7 +295,7 @@ public class AvrcpTargetService extends ProfileService { * <p>This will be called by the native stack when a play event is received from a remote * device. See packages/modules/Bluetooth/system/profile/avrcp/device.cc. */ - private void setA2dpActiveDevice(@NonNull BluetoothDevice device) { + private static void setA2dpActiveDevice(@NonNull BluetoothDevice device) { A2dpService service = A2dpService.getA2dpService(); if (service == null) { Log.d(TAG, "setA2dpActiveDevice: A2dp service not found"); @@ -341,7 +342,7 @@ public class AvrcpTargetService extends ProfileService { */ public void handleA2dpConnectionStateChanged(BluetoothDevice device, int newState) { if (device == null) return; - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { // If there is no connection, disconnectDevice() will do nothing if (mNativeInterface.disconnectDevice(device)) { Log.d(TAG, "request to disconnect device " + device); diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java index b11aeebe24..91f602815a 100644 --- a/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java +++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpVolumeManager.java @@ -54,7 +54,7 @@ import java.util.concurrent.CompletableFuture; * device connection. */ class AvrcpVolumeManager extends AudioDeviceCallback { - public static final String TAG = AvrcpVolumeManager.class.getSimpleName(); + private static final String TAG = AvrcpVolumeManager.class.getSimpleName(); // All volumes are stored at system volume values, not AVRCP values private static final String VOLUME_MAP = "bluetooth_volume_map"; diff --git a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java index dd720077a0..d2e34c64ac 100644 --- a/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java +++ b/android/app/src/com/android/bluetooth/avrcp/helpers/CoverArt.java @@ -77,7 +77,7 @@ public class CoverArt { } /** Covert a Bitmap to a byte array with an image format without lossy compression */ - private byte[] toByteArray(Bitmap bitmap) { + private static byte[] toByteArray(Bitmap bitmap) { if (bitmap == null) return null; ByteArrayOutputStream buffer = new ByteArrayOutputStream(bitmap.getWidth() * bitmap.getHeight()); @@ -131,7 +131,7 @@ public class CoverArt { } /** Determine if a given image descriptor is valid */ - private boolean isDescriptorValid(BipImageDescriptor descriptor) { + private static boolean isDescriptorValid(BipImageDescriptor descriptor) { debug("isDescriptorValid(descriptor=" + descriptor + ")"); if (descriptor == null) return false; @@ -196,12 +196,12 @@ public class CoverArt { } /** Print a message to DEBUG if debug output is enabled */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print a message to ERROR */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java index 1407b9292f..c86d35c0cf 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java @@ -16,9 +16,13 @@ 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 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 +83,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 +189,7 @@ public class AvrcpBipClient { * @return True if connected, False otherwise */ public boolean isConnected() { - return getState() == BluetoothProfile.STATE_CONNECTED; + return getState() == STATE_CONNECTED; } /** @@ -247,7 +251,7 @@ public class AvrcpBipClient { } try { - setConnectionState(BluetoothProfile.STATE_CONNECTING); + setConnectionState(STATE_CONNECTING); mSocket = mDevice.createL2capSocket(mPsm); mSocket.connect(); @@ -261,7 +265,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 +282,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 +292,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 +300,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 +323,7 @@ public class AvrcpBipClient { */ private synchronized void disconnect() { if (mSession != null) { - setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + setConnectionState(STATE_DISCONNECTING); try { mSession.disconnect(null); @@ -341,7 +345,7 @@ public class AvrcpBipClient { mTransport = null; mSocket = null; } - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); } private void executeRequest(BipRequest request) { @@ -427,13 +431,13 @@ public class AvrcpBipClient { String getStateName() { int state = getState(); switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return "Disconnected"; - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: return "Connecting"; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: return "Connected"; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: return "Disconnecting"; } return "Unknown"; diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java index 778a7ee2e8..b01dbc3ec0 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java @@ -29,7 +29,7 @@ import java.util.UUID; /** Provides Bluetooth AVRCP Controller native interface for the AVRCP Controller service */ public class AvrcpControllerNativeInterface { - static final String TAG = AvrcpControllerNativeInterface.class.getSimpleName(); + private static final String TAG = AvrcpControllerNativeInterface.class.getSimpleName(); private AvrcpControllerService mAvrcpController; diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java index 197b37c9f1..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; @@ -52,7 +54,7 @@ import java.util.concurrent.ConcurrentHashMap; /** Provides Bluetooth AVRCP Controller profile, as a service in the Bluetooth application. */ public class AvrcpControllerService extends ProfileService { - static final String TAG = AvrcpControllerService.class.getSimpleName(); + private static final String TAG = AvrcpControllerService.class.getSimpleName(); static final int MAXIMUM_CONNECTED_DEVICES = 5; @@ -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 dff27a46cd..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; @@ -55,7 +59,7 @@ import java.util.Set; * and interactions with a remote controllable device. */ class AvrcpControllerStateMachine extends StateMachine { - static final String TAG = AvrcpControllerStateMachine.class.getSimpleName(); + private static final String TAG = AvrcpControllerStateMachine.class.getSimpleName(); // 0->99 Events from Outside public static final int CONNECT = 1; @@ -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; @@ -183,7 +187,7 @@ class AvrcpControllerStateMachine extends StateMachine { mGetFolderList = new GetFolderList(); addState(mGetFolderList, mConnected); - mAudioManager = service.getSystemService(AudioManager.class); + mAudioManager = mAdapterService.getSystemService(AudioManager.class); mIsVolumeFixed = mAudioManager.isVolumeFixed() || isControllerAbsoluteVolumeEnabled; setInitialState(mDisconnected); @@ -256,9 +260,7 @@ class AvrcpControllerStateMachine extends StateMachine { ProfileService.println(sb, "Control: " + mRemoteControlConnected); ProfileService.println(sb, "Browsing: " + mBrowsingConnected); ProfileService.println( - sb, - "Cover Art: " - + (mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED)); + sb, "Cover Art: " + (mCoverArtManager.getState(mDevice) == STATE_CONNECTED)); ProfileService.println(sb, "Addressed Player ID: " + mAddressedPlayerId); ProfileService.println(sb, "Browsed Player ID: " + mBrowseTree.getCurrentBrowsedPlayer()); @@ -321,7 +323,7 @@ class AvrcpControllerStateMachine extends StateMachine { // Called from "connected" state, which assumes either control or browse is connected if (mCoverArtManager != null && mCoverArtPsm != 0 - && mCoverArtManager.getState(mDevice) != BluetoothProfile.STATE_CONNECTED) { + && mCoverArtManager.getState(mDevice) != STATE_CONNECTED) { debug("Attempting to connect to AVRCP BIP, psm: " + mCoverArtPsm); mCoverArtManager.connect(mDevice, /* psm */ mCoverArtPsm); } @@ -330,7 +332,7 @@ class AvrcpControllerStateMachine extends StateMachine { synchronized void refreshCoverArt() { if (mCoverArtManager != null && mCoverArtPsm != 0 - && mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED) { + && mCoverArtManager.getState(mDevice) == STATE_CONNECTED) { debug("Attempting to refresh AVRCP BIP OBEX session, psm: " + mCoverArtPsm); mCoverArtManager.refreshSession(mDevice); } @@ -415,10 +417,10 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { debug("Disconnected: Entered"); - if (mMostRecentState != BluetoothProfile.STATE_DISCONNECTED) { + if (mMostRecentState != STATE_DISCONNECTED) { sendMessage(CLEANUP); } - broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED); + broadcastConnectionStateChanged(STATE_DISCONNECTED); } @Override @@ -448,7 +450,7 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { debug("Connecting: Enter Connecting"); - broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTING); + broadcastConnectionStateChanged(STATE_CONNECTING); transitionTo(mConnected); } } @@ -458,8 +460,8 @@ class AvrcpControllerStateMachine extends StateMachine { @Override public void enter() { - if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) { - broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTED); + if (mMostRecentState == STATE_CONNECTING) { + broadcastConnectionStateChanged(STATE_CONNECTED); mService.getBrowseTree().mRootNode.addChild(mBrowseTree.mRootNode); BluetoothMediaBrowserService.onBrowseNodeChanged( mService.getBrowseTree().mRootNode); @@ -802,7 +804,7 @@ class AvrcpControllerStateMachine extends StateMachine { } } - private boolean isHoldableKey(int cmd) { + private static boolean isHoldableKey(int cmd) { return (cmd == AvrcpControllerService.PASS_THRU_CMD_ID_REWIND) || (cmd == AvrcpControllerService.PASS_THRU_CMD_ID_FF); } @@ -1051,7 +1053,7 @@ class AvrcpControllerStateMachine extends StateMachine { * @return true: a new folder in the same scope a new player while fetching contents of a * folder false: other cases, specifically Now Playing while fetching a folder */ - private boolean shouldAbort(int currentScope, int fetchScope) { + private static boolean shouldAbort(int currentScope, int fetchScope) { if ((currentScope == fetchScope) || (currentScope == AvrcpControllerService.BROWSE_SCOPE_VFS && fetchScope == AvrcpControllerService.BROWSE_SCOPE_PLAYER_LIST)) { @@ -1192,7 +1194,7 @@ class AvrcpControllerStateMachine extends StateMachine { onBrowsingDisconnected(); mService.getBrowseTree().mRootNode.removeChild(mBrowseTree.mRootNode); BluetoothMediaBrowserService.onBrowseNodeChanged(mService.getBrowseTree().mRootNode); - broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING); + broadcastConnectionStateChanged(STATE_DISCONNECTING); transitionTo(mDisconnected); } } @@ -1276,7 +1278,7 @@ class AvrcpControllerStateMachine extends StateMachine { } } - private int getFocusState() { + private static int getFocusState() { int focusState = AudioManager.ERROR; A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService(); if (a2dpSinkService != null) { @@ -1403,7 +1405,7 @@ class AvrcpControllerStateMachine extends StateMachine { if (mMostRecentState == currentState) { return; } - if (currentState == BluetoothProfile.STATE_CONNECTED) { + if (currentState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent( BluetoothMetricsProto.ProfileId.AVRCP_CONTROLLER); } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java index e583ce80e1..f06fbc8afa 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerUtils.java @@ -20,6 +20,8 @@ import android.support.v4.media.session.PlaybackStateCompat; /** A package global set of utilities for the AVRCP Controller implementation to leverage */ public final class AvrcpControllerUtils { + public static final String TAG_PREFIX_AVRCP = "Avrcp"; + public static final String TAG_PREFIX_AVRCP_CONTROLLER = TAG_PREFIX_AVRCP + "Controller."; /** Convert an AVRCP Passthrough command id to a human readable version of the key */ public static String passThruIdToString(int id) { diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java index a48b2d5ea2..826361a36b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java @@ -16,8 +16,10 @@ package com.android.bluetooth.avrcpcontroller; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.graphics.Bitmap; import android.net.Uri; import android.os.SystemProperties; @@ -215,11 +217,11 @@ public class AvrcpCoverArtManager { * Get the client connection state for a particular device's BIP Client * * @param device The Bluetooth device you want connection status for - * @return Connection status, based on BluetoothProfile.STATE_* constants + * @return Connection status, based on STATE_* constants */ public int getState(BluetoothDevice device) { AvrcpBipClient client = getClient(device); - if (client == null) return BluetoothProfile.STATE_DISCONNECTED; + if (client == null) return STATE_DISCONNECTED; return client.getState(); } @@ -403,14 +405,14 @@ public class AvrcpCoverArtManager { @Override public void onConnectionStateChanged(int oldState, int newState) { debug(mDevice + ": " + oldState + " -> " + newState); - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { // Ensure the handle map is cleared since old ones are invalid on a new connection clearHandleUuids(mDevice); // Once we're connected fetch the current metadata again in case the target has an // image handle they can now give us. Only do this if we don't already have one. mService.getCurrentMetadataIfNoCoverArt(mDevice); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { AvrcpBipClient client = getClient(mDevice); boolean shouldReconnect = (client != null); disconnect(mDevice); @@ -501,17 +503,17 @@ public class AvrcpCoverArtManager { } /** Print to debug if debug is enabled for this class */ - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } /** Print to warn */ - private void warn(String msg) { + private static void warn(String msg) { Log.w(TAG, msg); } /** Print to error */ - private void error(String msg) { + private static void error(String msg) { Log.e(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java index 71728e29db..d3c97b8cb1 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtProvider.java @@ -74,7 +74,7 @@ public class AvrcpCoverArtProvider extends ContentProvider { return uri; } - private Bitmap getImage(BluetoothDevice device, String imageUuid) { + private static Bitmap getImage(BluetoothDevice device, String imageUuid) { AvrcpControllerService service = AvrcpControllerService.getAvrcpControllerService(); if (service == null) { debug("Failed to get service, cover art not available"); @@ -89,7 +89,7 @@ public class AvrcpCoverArtProvider extends ContentProvider { return manager.getImage(device, imageUuid); } - private ParcelFileDescriptor getImageDescriptor(BluetoothDevice device, String imageUuid) + private static ParcelFileDescriptor getImageDescriptor(BluetoothDevice device, String imageUuid) throws FileNotFoundException, IOException { debug("getImageDescriptor(" + device + ", " + imageUuid + ")"); Bitmap image = getImage(device, imageUuid); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java index ff9e69cc4d..a188eb5494 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java @@ -157,7 +157,7 @@ public class AvrcpCoverArtStorage { return sb.toString(); } - private void debug(String msg) { + private static void debug(String msg) { Log.d(TAG, msg); } } diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java index bf34581d96..3722796f37 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpItem.java @@ -299,7 +299,7 @@ public class AvrcpItem { /** Builder for an AvrcpItem */ public static class Builder { - private static final String TAG = "AvrcpItem.Builder"; + private static final String TAG = AvrcpItem.TAG + "." + Builder.class.getSimpleName(); // Attribute ID Values from AVRCP Specification private static final int MEDIA_ATTRIBUTE_TITLE = 0x01; diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java index 5fa4852246..8c498f6a7b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/BluetoothMediaBrowserService.java @@ -262,7 +262,7 @@ public class BluetoothMediaBrowserService extends MediaBrowserServiceCompat { mSession.setPlaybackState(errorState); } - private Bundle getDefaultStyle() { + private static Bundle getDefaultStyle() { Bundle style = new Bundle(); style.putBoolean(CONTENT_STYLE_SUPPORTED, true); style.putInt(CONTENT_STYLE_BROWSABLE_HINT, CONTENT_STYLE_GRID_ITEM_HINT_VALUE); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java index f39f36d210..4a27b1582c 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java @@ -29,7 +29,7 @@ import java.util.ArrayList; * Contains information Player Application Setting extended from BluetootAvrcpPlayerSettings */ class PlayerApplicationSettings { - private static final String TAG = "PlayerApplicationSettings"; + private static final String TAG = PlayerApplicationSettings.class.getSimpleName(); /* * Values for SetPlayerApplicationSettings from AVRCP Spec V1.6 Appendix F. diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormat.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormat.java index 222681afcd..9f65b69a1c 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormat.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormat.java @@ -32,7 +32,9 @@ import java.util.Objects; * content-type="audio/basic" name="ABCD1234.wav" size="102400"/> */ public class BipAttachmentFormat { - private static final String TAG = "avrcpcontroller.BipAttachmentFormat"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + + BipAttachmentFormat.class.getSimpleName(); /** * MIME content type of the image attachment, i.e. "text/plain" diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipDateTime.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipDateTime.java index 98f8e67ff0..fae140a702 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipDateTime.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipDateTime.java @@ -41,7 +41,8 @@ import java.util.regex.Pattern; * <p>Example date-time values: 20000101T000000Z 20000101T235959Z 20000101T000000 */ public class BipDateTime { - private static final String TAG = "avrcpcontroller.BipDateTime"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + BipDateTime.class.getSimpleName(); private Date mDate = null; private boolean mIsUtc = false; diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java index 1e3be0184a..504f9e92c6 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java @@ -51,7 +51,10 @@ import java.util.Objects; * size=“500000”/> < /image-descriptor > */ public class BipImageDescriptor { - private static final String TAG = "avrcpcontroller.BipImageDescriptor"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + + BipImageDescriptor.class.getSimpleName(); + private static final String sVersion = "1.0"; /** A Builder for an ImageDescriptor object */ diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormat.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormat.java index eaab6cb819..9569c8cc12 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormat.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormat.java @@ -38,7 +38,8 @@ import java.util.Objects; * pixel="80*60-640*480"/> */ public class BipImageFormat { - private static final String TAG = "avrcpcontroller.BipImageFormat"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + BipImageFormat.class.getSimpleName(); public static final int FORMAT_NATIVE = 0; public static final int FORMAT_VARIANT = 1; diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java index 31bb1fde61..7e389ff45f 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageProperties.java @@ -58,7 +58,10 @@ import java.util.List; * </image-properties> */ public class BipImageProperties { - private static final String TAG = "avrcpcontroller.BipImageProperties"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + + BipImageProperties.class.getSimpleName(); + private static final String sVersion = "1.0"; /** A Builder for a BipImageProperties object */ @@ -275,7 +278,7 @@ public class BipImageProperties { } } - private boolean isThumbnailFormat(BipImageFormat format) { + private static boolean isThumbnailFormat(BipImageFormat format) { if (format == null) return false; BipEncoding encoding = format.getEncoding(); diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipPixel.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipPixel.java index e36198fdad..a00aacc2c5 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipPixel.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipPixel.java @@ -46,7 +46,8 @@ import java.util.regex.Pattern; * <p>H=(W*H2)/W2 */ public class BipPixel { - private static final String TAG = "avrcpcontroller.BipPixel"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + BipPixel.class.getSimpleName(); // The BIP specification declares this as the max size to be transferred. You can optionally // use this value to indicate there is no upper bound on pixel size. diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java index a2395e9feb..2e2818d97b 100644 --- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java +++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipTransformation.java @@ -39,7 +39,9 @@ import java.util.Objects; * pixel=“1280*960” size=“500000” transformation="stretch"/> </image-descriptor> */ public class BipTransformation { - private static final String TAG = "avrcpcontroller.BipTransformation"; + private static final String TAG = + AvrcpControllerUtils.TAG_PREFIX_AVRCP_CONTROLLER + + BipTransformation.class.getSimpleName(); public static final int UNKNOWN = -1; public static final int STRETCH = 0; @@ -120,7 +122,7 @@ public class BipTransformation { * BipTransformation.* constants, but doesn't *have* to be * @return True if the transformation constant is valid, False otherwise */ - private boolean isValid(int transformation) { + private static boolean isValid(int transformation) { return transformation >= STRETCH && transformation <= CROP; } diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java index 23cda4bd5c..4f12dcb3da 100644 --- a/android/app/src/com/android/bluetooth/bas/BatteryService.java +++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java @@ -16,6 +16,8 @@ package com.android.bluetooth.bas; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static java.util.Objects.requireNonNull; import android.bluetooth.BluetoothDevice; @@ -239,7 +241,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 +261,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 +298,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(); } @@ -370,7 +372,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 7b4d7fe3b4..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) { @@ -224,7 +228,8 @@ public class BatteryStateMachine extends StateMachine { @VisibleForTesting class Disconnected extends State { - private static final String TAG = "BASM_Disconnected"; + private static final String TAG = + BatteryStateMachine.TAG + "." + Disconnected.class.getSimpleName(); @Override public void enter() { @@ -235,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 @@ -279,13 +284,14 @@ public class BatteryStateMachine extends StateMachine { @VisibleForTesting class Connecting extends State { - private static final String TAG = "BASM_Connecting"; + private static final String TAG = + BatteryStateMachine.TAG + "." + Connecting.class.getSimpleName(); @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 @@ -316,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); } } @@ -328,14 +334,15 @@ public class BatteryStateMachine extends StateMachine { @VisibleForTesting class Disconnecting extends State { - private static final String TAG = "BASM_Disconnecting"; + private static final String TAG = + BatteryStateMachine.TAG + "." + Disconnecting.class.getSimpleName(); @Override 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 @@ -367,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. @@ -388,13 +395,14 @@ public class BatteryStateMachine extends StateMachine { @VisibleForTesting class Connected extends State { - private static final String TAG = "BASM_Connected"; + private static final String TAG = + BatteryStateMachine.TAG + "." + Connected.class.getSimpleName(); @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(); } @@ -430,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/BaseData.java b/android/app/src/com/android/bluetooth/bass_client/BaseData.java index c15277eedd..948abff89c 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BaseData.java +++ b/android/app/src/com/android/bluetooth/bass_client/BaseData.java @@ -28,7 +28,8 @@ import java.util.MissingResourceException; /** Helper class to parse the Broadcast Announcement BASE data */ class BaseData { - private static final String TAG = "Bassclient-BaseData"; + private static final String TAG = BassClientService.TAG + "." + BaseData.class.getSimpleName(); + private static final int METADATA_LEVEL1 = 1; private static final int METADATA_LEVEL2 = 2; private static final int METADATA_LEVEL3 = 3; diff --git a/android/app/src/com/android/bluetooth/bass_client/BassClientPeriodicAdvertisingManager.java b/android/app/src/com/android/bluetooth/bass_client/BassClientPeriodicAdvertisingManager.java index 73e51a5552..28d9f79d12 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientPeriodicAdvertisingManager.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientPeriodicAdvertisingManager.java @@ -22,7 +22,7 @@ import android.util.Log; /** Bass Client Periodic Advertising object handler */ public class BassClientPeriodicAdvertisingManager { - private static final String TAG = "BassClientPeriodicAdvertisingManager"; + private static final String TAG = BassClientPeriodicAdvertisingManager.class.getSimpleName(); private static PeriodicAdvertisingManager sPeriodicAdvertisingManager; 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 a57666f105..0c0c3f317b 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java @@ -20,14 +20,12 @@ 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 android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID; -import static com.android.bluetooth.flags.Flags.leaudioAllowedContextMask; 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.leaudioBroadcastExtractPeriodicScannerFromStateMachine; import static com.android.bluetooth.flags.Flags.leaudioBroadcastPreventResumeInterruption; import static com.android.bluetooth.flags.Flags.leaudioBroadcastResyncHelper; import static com.android.bluetooth.flags.Flags.leaudioMonitorUnicastSourceWhenManagedByBroadcastDelegator; @@ -86,12 +84,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; @@ -107,7 +103,8 @@ import java.util.stream.Collectors; /** Broadcast Assistant Scan Service */ public class BassClientService extends ProfileService { - private static final String TAG = BassClientService.class.getSimpleName(); + static final String TAG = BassClientService.class.getSimpleName(); + private static final int MAX_ACTIVE_SYNCED_SOURCES_NUM = 4; private static final int MAX_BIS_DISCOVERY_TRIES_NUM = 5; @@ -177,7 +174,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(); @@ -268,6 +264,7 @@ public class BassClientService extends ProfileService { } controller.stopScanInternal(mScannerId); controller.unregisterScannerInternal(mScannerId); + mBaasUuidFilters.clear(); mScannerId = SCANNER_ID_NOT_INITIALIZED; } } @@ -405,10 +402,10 @@ public class BassClientService extends ProfileService { case MESSAGE_BROADCAST_MONITOR_TIMEOUT: { log("MESSAGE_BROADCAST_MONITOR_TIMEOUT"); - List<Integer> activeSyncedSrc = - new ArrayList<>(getActiveSyncedSources()); - if (activeSyncedSrc.contains( - getSyncHandleForBroadcastId(broadcastId))) { + if (getActiveSyncedSources() + .contains( + getSyncHandleForBroadcastId( + broadcastId))) { break; } // Clear from cache to make possible sync again @@ -494,7 +491,7 @@ public class BassClientService extends ProfileService { } @SuppressLint("NewApi") // Api is protected by flag check and the lint is wrong - private boolean hasAnyMessagesOrCallbacks(Handler handler) { + private static boolean hasAnyMessagesOrCallbacks(Handler handler) { if (android.os.Flags.mainlineVcnPlatformApi()) { return handler.hasMessagesOrCallbacks(); } else { @@ -640,40 +637,24 @@ public class BassClientService extends ProfileService { log("PAResmap: update >>>"); if (bId == BassConstants.INVALID_BROADCAST_ID) { // Update when onSyncEstablished, try to retrieve valid broadcast id - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - bId = getBroadcastIdForSyncHandle(BassConstants.PENDING_SYNC_HANDLE); + bId = getBroadcastIdForSyncHandle(BassConstants.PENDING_SYNC_HANDLE); - if (bId == BassConstants.INVALID_BROADCAST_ID || !paResMap.containsKey(bId)) { - Log.e(TAG, "PAResmap: error! no valid broadcast id found>>>"); - return; - } + if (bId == BassConstants.INVALID_BROADCAST_ID || !paResMap.containsKey(bId)) { + Log.e(TAG, "PAResmap: error! no valid broadcast id found>>>"); + return; + } - int oldBroadcastId = getBroadcastIdForSyncHandle(syncHandle); - if (oldBroadcastId != BassConstants.INVALID_BROADCAST_ID - && oldBroadcastId != bId) { - log( - "updatePeriodicAdvertisementResultMap: SyncEstablished on the" - + " same syncHandle=" - + syncHandle - + ", before syncLost"); - log("Notify broadcast source lost, broadcast id: " + oldBroadcastId); - mCallbacks.notifySourceLost(oldBroadcastId); - clearAllDataForSyncHandle(syncHandle); - mCachedBroadcasts.remove(oldBroadcastId); - } - } else { - for (Map.Entry<Integer, PeriodicAdvertisementResult> entry : - paResMap.entrySet()) { - PeriodicAdvertisementResult value = entry.getValue(); - if (value.getBroadcastId() != BassConstants.INVALID_BROADCAST_ID) { - bId = value.getBroadcastId(); - break; - } - } - if (bId == BassConstants.INVALID_BROADCAST_ID) { - log("PAResmap: error! no valid broadcast id found>>>"); - return; - } + int oldBroadcastId = getBroadcastIdForSyncHandle(syncHandle); + if (oldBroadcastId != BassConstants.INVALID_BROADCAST_ID && oldBroadcastId != bId) { + log( + "updatePeriodicAdvertisementResultMap: SyncEstablished on the" + + " same syncHandle=" + + syncHandle + + ", before syncLost"); + log("Notify broadcast source lost, broadcast id: " + oldBroadcastId); + mCallbacks.notifySourceLost(oldBroadcastId); + clearAllDataForSyncHandle(syncHandle); + mCachedBroadcasts.remove(oldBroadcastId); } } PeriodicAdvertisementResult paRes = paResMap.get(bId); @@ -750,87 +731,6 @@ public class BassClientService extends ProfileService { return base; } - void removeActiveSyncedSource(BluetoothDevice scanDelegator, Integer syncHandle) { - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - - log( - "removeActiveSyncedSource, scanDelegator: " - + scanDelegator - + ", syncHandle: " - + syncHandle); - if (syncHandle == null) { - // remove all sources for this scanDelegator - mActiveSourceMap.remove(scanDelegator); - } else { - List<Integer> sources = mActiveSourceMap.get(scanDelegator); - if (sources != null) { - sources.removeIf(e -> e.equals(syncHandle)); - if (sources.isEmpty()) { - mActiveSourceMap.remove(scanDelegator); - } - } - } - sEventLogger.logd( - TAG, - "Broadcast Source Unsynced: scanDelegator= " - + scanDelegator - + ", syncHandle= " - + syncHandle); - } - - void addActiveSyncedSource(BluetoothDevice scanDelegator, Integer syncHandle) { - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - - log( - "addActiveSyncedSource, scanDelegator: " - + scanDelegator - + ", syncHandle: " - + syncHandle); - if (syncHandle != BassConstants.INVALID_SYNC_HANDLE) { - mActiveSourceMap.putIfAbsent(scanDelegator, new ArrayList<>()); - if (!mActiveSourceMap.get(scanDelegator).contains(syncHandle)) { - mActiveSourceMap.get(scanDelegator).add(syncHandle); - } - } - sEventLogger.logd( - TAG, - "Broadcast Source Synced: scanDelegator= " - + scanDelegator - + ", syncHandle= " - + syncHandle); - } - - List<Integer> getActiveSyncedSources(BluetoothDevice scanDelegator) { - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - - List<Integer> currentSources = mActiveSourceMap.get(scanDelegator); - if (currentSources != null) { - log( - "getActiveSyncedSources: scanDelegator: " - + scanDelegator - + ", sources num: " - + currentSources.size()); - } else { - log( - "getActiveSyncedSources: scanDelegator: " - + scanDelegator - + ", currentSources is null"); - } - return currentSources; - } - void removeActiveSyncedSource(Integer syncHandle) { log("removeActiveSyncedSource, syncHandle: " + syncHandle); if (syncHandle == null) { @@ -912,37 +812,25 @@ public class BassClientService extends ProfileService { mTimeoutHandler.stopAll(); setBassClientService(null); - if (!leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - mSyncHandleToDeviceMap.clear(); - mPeriodicAdvertisementResultMap.clear(); - mActiveSourceMap.clear(); - mLocalBroadcastReceivers.clear(); - mPendingGroupOp.clear(); - mCachedBroadcasts.clear(); - mBroadcastMetadataMap.clear(); - mSyncHandleToBroadcastIdMap.clear(); - mSyncHandleToBaseDataMap.clear(); - } else { - synchronized (mSearchScanCallbackLock) { - if (leaudioBassScanWithInternalScanController()) { - if (isSearchInProgress()) { - mBassScanCallback.stopScanAndUnregister(); - } - } else { - if (mBluetoothLeScannerWrapper != null && mSearchScanCallback != null) { - mBluetoothLeScannerWrapper.stopScan(mSearchScanCallback); - } - mBluetoothLeScannerWrapper = null; - mSearchScanCallback = null; + synchronized (mSearchScanCallbackLock) { + if (leaudioBassScanWithInternalScanController()) { + if (isSearchInProgress()) { + mBassScanCallback.stopScanAndUnregister(); } - clearAllSyncData(); + } else { + if (mBluetoothLeScannerWrapper != null && mSearchScanCallback != null) { + mBluetoothLeScannerWrapper.stopScan(mSearchScanCallback); + } + mBluetoothLeScannerWrapper = null; + mSearchScanCallback = null; } - - mLocalBroadcastReceivers.clear(); - mPendingGroupOp.clear(); - mBroadcastMetadataMap.clear(); - mPausedBroadcastSinks.clear(); + clearAllSyncData(); } + + mLocalBroadcastReceivers.clear(); + mPendingGroupOp.clear(); + mBroadcastMetadataMap.clear(); + mPausedBroadcastSinks.clear(); } BluetoothDevice getDeviceForSyncHandle(int syncHandle) { @@ -994,7 +882,7 @@ public class BassClientService extends ProfileService { }); } - private boolean isSuccess(int status) { + private static boolean isSuccess(int status) { boolean ret = false; switch (status) { case BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST: @@ -1088,13 +976,13 @@ public class BassClientService extends ProfileService { } } - private boolean removeMatchingOperation( + private static boolean removeMatchingOperation( List<Pair<Integer, Object>> operations, int reqMsg, Object obj) { return operations.removeIf( m -> m.first.equals(reqMsg) && isMatchingOperation(m.second, obj)); } - private boolean isMatchingOperation(Object operationData, Object obj) { + private static boolean isMatchingOperation(Object operationData, Object obj) { if (obj instanceof BluetoothLeBroadcastReceiveState) { return ((BluetoothLeBroadcastMetadata) operationData).getBroadcastId() == ((BluetoothLeBroadcastReceiveState) obj).getBroadcastId(); @@ -1117,7 +1005,7 @@ public class BassClientService extends ProfileService { && (leAudioService.getActiveDevices().contains(device)); } - private boolean isEmptyBluetoothDevice(BluetoothDevice device) { + private static boolean isEmptyBluetoothDevice(BluetoothDevice device) { if (device == null) { Log.e(TAG, "Device is null!"); return true; @@ -1160,15 +1048,13 @@ public class BassClientService extends ProfileService { return; } - if (leaudioAllowedContextMask()) { - /* Don't bother active group (external broadcaster scenario) with SOUND EFFECTS */ - if (!mIsAllowedContextOfActiveGroupModified && isDevicePartOfActiveUnicastGroup(sink)) { - leAudioService.setActiveGroupAllowedContextMask( - BluetoothLeAudio.CONTEXTS_ALL - & ~BluetoothLeAudio.CONTEXT_TYPE_SOUND_EFFECTS, - BluetoothLeAudio.CONTEXTS_ALL); - mIsAllowedContextOfActiveGroupModified = true; - } + /* Don't bother active group (external broadcaster scenario) with SOUND EFFECTS */ + if (!mIsAllowedContextOfActiveGroupModified && isDevicePartOfActiveUnicastGroup(sink)) { + leAudioService.setActiveGroupAllowedContextMask( + BluetoothLeAudio.CONTEXTS_ALL + & ~BluetoothLeAudio.CONTEXT_TYPE_SOUND_EFFECTS, + BluetoothLeAudio.CONTEXTS_ALL); + mIsAllowedContextOfActiveGroupModified = true; } } @@ -1178,15 +1064,13 @@ public class BassClientService extends ProfileService { return; } - if (leaudioAllowedContextMask()) { - /* Restore allowed context mask for Unicast */ - if (mIsAllowedContextOfActiveGroupModified - && !hasAnyConnectedDeviceExternalBroadcastSource() - && !isAnyConnectedDeviceSwitchingSource()) { - leAudioService.setActiveGroupAllowedContextMask( - BluetoothLeAudio.CONTEXTS_ALL, BluetoothLeAudio.CONTEXTS_ALL); - mIsAllowedContextOfActiveGroupModified = false; - } + /* Restore allowed context mask for Unicast */ + if (mIsAllowedContextOfActiveGroupModified + && !hasAnyConnectedDeviceExternalBroadcastSource() + && !isAnyConnectedDeviceSwitchingSource()) { + leAudioService.setActiveGroupAllowedContextMask( + BluetoothLeAudio.CONTEXTS_ALL, BluetoothLeAudio.CONTEXTS_ALL); + mIsAllowedContextOfActiveGroupModified = false; } } @@ -1731,7 +1615,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) { @@ -1791,7 +1675,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; @@ -1894,7 +1778,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(); } @@ -1921,7 +1805,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(); @@ -2034,8 +1918,7 @@ public class BassClientService extends ProfileService { synchronized (mSearchScanCallbackLock) { if (!leaudioBassScanWithInternalScanController()) { - if (!leaudioBroadcastExtractPeriodicScannerFromStateMachine() - || mBluetoothLeScannerWrapper == null) { + if (mBluetoothLeScannerWrapper == null) { mBluetoothLeScannerWrapper = BassObjectsFactory.getInstance() .getBluetoothLeScannerWrapper(mBluetoothAdapter); @@ -2085,19 +1968,8 @@ public class BassClientService extends ProfileService { if (!mCachedBroadcasts.containsKey(broadcastId)) { log("selectBroadcastSource: broadcastId " + broadcastId); mCachedBroadcasts.put(broadcastId, result); - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - addSelectSourceRequest( - broadcastId, /* hasPriority */ false); - } else { - synchronized (mStateMachines) { - for (BassClientStateMachine sm : - mStateMachines.values()) { - if (sm.isConnected()) { - selectSource(sm.getDevice(), result, false); - } - } - } - } + addSelectSourceRequest( + broadcastId, /* hasPriority */ false); } else { if (leaudioBroadcastResyncHelper() && mTimeoutHandler.isStarted( @@ -2234,116 +2106,89 @@ public class BassClientService extends ProfileService { /** Stops an ongoing search for nearby Broadcast Sources */ public void stopSearchingForSources() { log("stopSearchingForSources"); - if (!leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - BluetoothLeScannerWrapper scanner = - BassObjectsFactory.getInstance() - .getBluetoothLeScannerWrapper(mBluetoothAdapter); - if (scanner == null) { - Log.e(TAG, "startLeScan: cannot get BluetoothLeScanner"); - return; - } - synchronized (mSearchScanCallbackLock) { + synchronized (mSearchScanCallbackLock) { + if (leaudioBassScanWithInternalScanController()) { if (!isSearchInProgress()) { Log.e(TAG, "stopSearchingForSources: Scan not started yet"); mCallbacks.notifySearchStopFailed( BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); return; } - informConnectedDeviceAboutScanOffloadStop(); - if (leaudioBassScanWithInternalScanController()) { - mBassScanCallback.stopScanAndUnregister(); - } else { - scanner.stopScan(mSearchScanCallback); - mSearchScanCallback = null; + mBassScanCallback.stopScanAndUnregister(); + } else { + if (mBluetoothLeScannerWrapper == null || mSearchScanCallback == null) { + Log.e(TAG, "stopSearchingForSources: Scan not started yet"); + mCallbacks.notifySearchStopFailed( + BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); + return; } - sEventLogger.logd(TAG, "stopSearchingForSources"); - mCallbacks.notifySearchStopped(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); + mBluetoothLeScannerWrapper.stopScan(mSearchScanCallback); + mBluetoothLeScannerWrapper = null; + mSearchScanCallback = null; } - } else { - synchronized (mSearchScanCallbackLock) { - if (leaudioBassScanWithInternalScanController()) { - if (!isSearchInProgress()) { - Log.e(TAG, "stopSearchingForSources: Scan not started yet"); - mCallbacks.notifySearchStopFailed( - BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); - return; - } - mBassScanCallback.stopScanAndUnregister(); - } else { - if (mBluetoothLeScannerWrapper == null || mSearchScanCallback == null) { - Log.e(TAG, "stopSearchingForSources: Scan not started yet"); - mCallbacks.notifySearchStopFailed( - BluetoothStatusCodes.ERROR_ALREADY_IN_TARGET_STATE); - return; - } - mBluetoothLeScannerWrapper.stopScan(mSearchScanCallback); - mBluetoothLeScannerWrapper = null; - mSearchScanCallback = null; - } - if (leaudioBroadcastPreventResumeInterruption()) { - printAllSyncData(); + if (leaudioBroadcastPreventResumeInterruption()) { + printAllSyncData(); - // Collect broadcasts which should stay synced after search stops - HashSet<Integer> broadcastsToKeepSynced = new HashSet<>(); + // Collect broadcasts which should stay synced after search stops + HashSet<Integer> broadcastsToKeepSynced = new HashSet<>(); - // Keep broadcasts waiting for PAST - broadcastsToKeepSynced.addAll(getBroadcastIdsWaitingForPAST()); + // Keep broadcasts waiting for PAST + broadcastsToKeepSynced.addAll(getBroadcastIdsWaitingForPAST()); - // Keep broadcasts waiting for adding source (could be by resume too) - broadcastsToKeepSynced.addAll(getBroadcastIdsWaitingForAddSource()); + // Keep broadcasts waiting for adding source (could be by resume too) + broadcastsToKeepSynced.addAll(getBroadcastIdsWaitingForAddSource()); - // Keep broadcast unintentionally paused - broadcastsToKeepSynced.addAll(getUnintentionallyPausedBroadcastIds()); + // Keep broadcast unintentionally paused + broadcastsToKeepSynced.addAll(getUnintentionallyPausedBroadcastIds()); - log("Broadcasts to keep on stop: " + broadcastsToKeepSynced); + log("Broadcasts to keep on stop: " + broadcastsToKeepSynced); - // Remove all other broadcasts from sync queue if not in broadcastsToKeepSynced - synchronized (mSourceSyncRequestsQueue) { - Iterator<SourceSyncRequest> iterator = mSourceSyncRequestsQueue.iterator(); - while (iterator.hasNext()) { - SourceSyncRequest sourceSyncRequest = iterator.next(); - Integer queuedBroadcastId = - BassUtils.getBroadcastId(sourceSyncRequest.getScanResult()); - if (!broadcastsToKeepSynced.contains(queuedBroadcastId)) { - iterator.remove(); - } + // Remove all other broadcasts from sync queue if not in broadcastsToKeepSynced + synchronized (mSourceSyncRequestsQueue) { + Iterator<SourceSyncRequest> iterator = mSourceSyncRequestsQueue.iterator(); + while (iterator.hasNext()) { + SourceSyncRequest sourceSyncRequest = iterator.next(); + Integer queuedBroadcastId = + BassUtils.getBroadcastId(sourceSyncRequest.getScanResult()); + if (!broadcastsToKeepSynced.contains(queuedBroadcastId)) { + iterator.remove(); } } + } - // Collect broadcasts (sync handles) which should be unsynced (not in keep list) - List<Integer> syncHandlesToRemove = - new ArrayList<>(mSyncHandleToBroadcastIdMap.keySet()); - for (int broadcastId : broadcastsToKeepSynced) { - syncHandlesToRemove.remove(getSyncHandleForBroadcastId(broadcastId)); - // Add again, as unintentionally paused broadcasts were monitored in - // onScanResult during scanning, now need to be monitored in the sync loop - addSelectSourceRequest(broadcastId, /* hasPriority */ true); - } + // Collect broadcasts (sync handles) which should be unsynced (not in keep list) + List<Integer> syncHandlesToRemove = + new ArrayList<>(mSyncHandleToBroadcastIdMap.keySet()); + for (int broadcastId : broadcastsToKeepSynced) { + syncHandlesToRemove.remove(getSyncHandleForBroadcastId(broadcastId)); + // Add again, as unintentionally paused broadcasts were monitored in + // onScanResult during scanning, now need to be monitored in the sync loop + addSelectSourceRequest(broadcastId, /* hasPriority */ true); + } - // Unsync not needed broadcasts - for (int syncHandleToRemove : syncHandlesToRemove) { - cancelActiveSync(syncHandleToRemove); - } + // Unsync not needed broadcasts + for (int syncHandleToRemove : syncHandlesToRemove) { + cancelActiveSync(syncHandleToRemove); + } - mSyncFailureCounter.clear(); + mSyncFailureCounter.clear(); - printAllSyncData(); - } else { - clearAllSyncData(); - } + printAllSyncData(); + } else { + clearAllSyncData(); + } - informConnectedDeviceAboutScanOffloadStop(); - sEventLogger.logd(TAG, "stopSearchingForSources"); - mCallbacks.notifySearchStopped(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); + informConnectedDeviceAboutScanOffloadStop(); + sEventLogger.logd(TAG, "stopSearchingForSources"); + mCallbacks.notifySearchStopped(BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST); - if (!leaudioBroadcastPreventResumeInterruption()) { - for (Map.Entry<Integer, PauseType> entry : mPausedBroadcastIds.entrySet()) { - Integer broadcastId = entry.getKey(); - PauseType pauseType = entry.getValue(); - if (pauseType != PauseType.HOST_INTENTIONAL) { - addSelectSourceRequest(broadcastId, /* hasPriority */ true); - } + if (!leaudioBroadcastPreventResumeInterruption()) { + for (Map.Entry<Integer, PauseType> entry : mPausedBroadcastIds.entrySet()) { + Integer broadcastId = entry.getKey(); + PauseType pauseType = entry.getValue(); + if (pauseType != PauseType.HOST_INTENTIONAL) { + addSelectSourceRequest(broadcastId, /* hasPriority */ true); } } } @@ -2728,11 +2573,6 @@ public class BassClientService extends ProfileService { resumeReceiversSourceSynchronization(); } } - - @Override - public void onSyncTransferred(BluetoothDevice device, int status) { - log("onSyncTransferred: device=" + device + ", status =" + status); - } } private void clearAllDataForSyncHandle(Integer syncHandle) { @@ -2963,6 +2803,11 @@ public class BassClientService extends ProfileService { + ", hasPriority: " + hasPriority); + if (getActiveSyncedSources().contains(getSyncHandleForBroadcastId(broadcastId))) { + log("addSelectSourceRequest: Already synced"); + return; + } + if (isAddedToSelectSourceRequest(broadcastId, hasPriority)) { log("addSelectSourceRequest: Already added"); return; @@ -3092,47 +2937,6 @@ public class BassClientService extends ProfileService { } } - void selectSource(BluetoothDevice sink, ScanResult result, boolean autoTrigger) { - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - List<Integer> activeSyncedSrc = getActiveSyncedSources(sink); - if (activeSyncedSrc != null && activeSyncedSrc.size() >= MAX_ACTIVE_SYNCED_SOURCES_NUM) { - log("selectSource : reached max allowed active source"); - int syncHandle = activeSyncedSrc.get(0); - // removing the 1st synced source before proceeding to add new - synchronized (mStateMachines) { - BassClientStateMachine stateMachine = getOrCreateStateMachine(sink); - if (stateMachine == null) { - Log.e(TAG, "Can't get state machine for device: " + sink); - return; - } - Message message = - stateMachine.obtainMessage(BassClientStateMachine.REACHED_MAX_SOURCE_LIMIT); - message.arg1 = syncHandle; - stateMachine.sendMessage(message); - } - } - - synchronized (mStateMachines) { - sEventLogger.logd( - TAG, "Select Broadcast Source: sink: " + sink + ", result: " + result); - - BassClientStateMachine stateMachine = getOrCreateStateMachine(sink); - if (stateMachine == null) { - Log.e(TAG, "Can't get state machine for device: " + sink); - return; - } - Message message = - stateMachine.obtainMessage(BassClientStateMachine.SELECT_BCAST_SOURCE); - message.obj = result; - message.arg1 = autoTrigger ? BassConstants.AUTO : BassConstants.USER; - stateMachine.sendMessage(message); - } - } - private void storeSinkMetadata( BluetoothDevice device, int broadcastId, BluetoothLeBroadcastMetadata metadata) { if (device == null @@ -3355,43 +3159,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. @@ -3399,44 +3194,38 @@ public class BassClientService extends ProfileService { logPausedBroadcastsAndSinks(); for (BluetoothDevice device : devices) { - if (leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - List<Integer> activeSyncedSrc = getActiveSyncedSources(); - BluetoothDevice sourceDevice = sourceMetadata.getSourceDevice(); - if (!isLocalBroadcast(sourceMetadata) - && (!activeSyncedSrc.contains( - getSyncHandleForBroadcastId(sourceMetadata.getBroadcastId())))) { - log("Adding inactive source: " + sourceDevice); - int broadcastId = sourceMetadata.getBroadcastId(); - if (broadcastId != BassConstants.INVALID_BROADCAST_ID) { - // Check if not added already - if (isAddedToSelectSourceRequest( - broadcastId, /* priorityImportant */ true)) { - mPendingSourcesToAdd.add( - new AddSourceData(device, sourceMetadata, isGroupOp)); - // If the source has been synced before, try to re-sync - // with the source by previously cached scan result. - } else if (getCachedBroadcast(broadcastId) != null) { - mPendingSourcesToAdd.add( - new AddSourceData(device, sourceMetadata, isGroupOp)); - addSelectSourceRequest(broadcastId, /* hasPriority */ true); - } else { - Log.w( - TAG, - "AddSource: broadcast not cached, broadcastId: " + broadcastId); - mCallbacks.notifySourceAddFailed( - sink, - sourceMetadata, - BluetoothStatusCodes.ERROR_BAD_PARAMETERS); - return; - } + BluetoothDevice sourceDevice = sourceMetadata.getSourceDevice(); + if (!isLocalBroadcast(sourceMetadata) + && (!getActiveSyncedSources() + .contains( + getSyncHandleForBroadcastId( + sourceMetadata.getBroadcastId())))) { + log("Adding inactive source: " + sourceDevice); + int broadcastId = sourceMetadata.getBroadcastId(); + if (broadcastId != BassConstants.INVALID_BROADCAST_ID) { + // Check if not added already + if (isAddedToSelectSourceRequest(broadcastId, /* priorityImportant */ true)) { + mPendingSourcesToAdd.add( + new AddSourceData(device, sourceMetadata, isGroupOp)); + // If the source has been synced before, try to re-sync + // with the source by previously cached scan result. + } else if (getCachedBroadcast(broadcastId) != null) { + mPendingSourcesToAdd.add( + new AddSourceData(device, sourceMetadata, isGroupOp)); + addSelectSourceRequest(broadcastId, /* hasPriority */ true); } else { - Log.w(TAG, "AddSource: invalid broadcastId"); + Log.w(TAG, "AddSource: broadcast not cached, broadcastId: " + broadcastId); mCallbacks.notifySourceAddFailed( sink, sourceMetadata, BluetoothStatusCodes.ERROR_BAD_PARAMETERS); return; } - continue; + } else { + Log.w(TAG, "AddSource: invalid broadcastId"); + mCallbacks.notifySourceAddFailed( + sink, sourceMetadata, BluetoothStatusCodes.ERROR_BAD_PARAMETERS); + return; } + continue; } BassClientStateMachine stateMachine = getOrCreateStateMachine(device); @@ -3927,13 +3716,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<>(); @@ -3953,10 +3741,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()); } @@ -3978,12 +3764,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); } } } @@ -4004,25 +3786,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); @@ -4178,9 +3941,7 @@ public class BassClientService extends ProfileService { if (pendingSourcesToAdd.mSink.equals(sink)) { Log.d(TAG, "handleBassStateReady: retry adding source with device, " + sink); addSource( - pendingSourcesToAdd.mSink, - pendingSourcesToAdd.mSourceMetadata, - pendingSourcesToAdd.mIsGroupOp); + pendingSourcesToAdd.mSink, pendingSourcesToAdd.mSourceMetadata, false); iterator.remove(); return; } @@ -4328,25 +4089,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 */ @@ -4362,8 +4121,7 @@ public class BassClientService extends ProfileService { for (BluetoothLeBroadcastMetadata metadata : entry.values()) { - if (leaudioBroadcastAssistantPeripheralEntrustment() - || leaudioBroadcastResyncHelper()) { + if (leaudioBroadcastResyncHelper()) { if (metadata == null) { Log.w( TAG, @@ -4394,14 +4152,13 @@ public class BassClientService extends ProfileService { continue; } - List<Integer> activeSyncedSrc = getActiveSyncedSources(); - if (receiveState.isPresent() && (!leaudioBroadcastResyncHelper() || isLocalBroadcast(metadata) - || activeSyncedSrc.contains( - getSyncHandleForBroadcastId( - metadata.getBroadcastId())))) { + || getActiveSyncedSources() + .contains( + getSyncHandleForBroadcastId( + metadata.getBroadcastId())))) { int sourceId = receiveState.get().getSourceId(); updateSourceToResumeBroadcast(sink, sourceId, metadata); } else { @@ -4473,17 +4230,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()) { @@ -4500,18 +4253,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) { @@ -4592,7 +4333,7 @@ public class BassClientService extends ProfileService { return false; } - private boolean isReceiverActive(BluetoothLeBroadcastReceiveState receiveState) { + private static boolean isReceiverActive(BluetoothLeBroadcastReceiveState receiveState) { if (receiveState.getPaSyncState() == BluetoothLeBroadcastReceiveState.PA_SYNC_STATE_SYNCHRONIZED) { return true; @@ -4648,7 +4389,9 @@ public class BassClientService extends ProfileService { .anyMatch( receiveState -> (receiveState.getBisSyncState().stream() - .anyMatch(this::isSyncedToBroadcastStream)))) { + .anyMatch( + BassClientService + ::isSyncedToBroadcastStream)))) { activeSinks.add(device); } } @@ -4666,7 +4409,7 @@ public class BassClientService extends ProfileService { .collect(Collectors.toUnmodifiableList()); } - private boolean isSyncedToBroadcastStream(Long syncState) { + private static boolean isSyncedToBroadcastStream(Long syncState) { return syncState != BassConstants.BCAST_RCVR_STATE_BIS_SYNC_NOT_SYNC_TO_BIS && syncState != BassConstants.BCAST_RCVR_STATE_BIS_SYNC_FAILED_SYNC_TO_BIG; } @@ -4778,7 +4521,7 @@ public class BassClientService extends ProfileService { } } - private void checkForPendingGroupOpRequest(Message msg) { + private static void checkForPendingGroupOpRequest(Message msg) { if (sService == null) { Log.e(TAG, "Service is null"); return; @@ -4809,7 +4552,7 @@ public class BassClientService extends ProfileService { } } - private boolean handleServiceInternalMessage(Message msg) { + private static boolean handleServiceInternalMessage(Message msg) { boolean isMsgHandled = false; if (sService == null) { Log.e(TAG, "Service is null"); @@ -4868,7 +4611,8 @@ public class BassClientService extends ProfileService { } } - private void invokeCallback(IBluetoothLeBroadcastAssistantCallback callback, Message msg) + private static void invokeCallback( + IBluetoothLeBroadcastAssistantCallback callback, Message msg) throws RemoteException { final int reason = msg.arg1; final int sourceId = msg.arg2; @@ -5121,7 +4865,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"); } @@ -5130,7 +4874,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); } } @@ -5200,7 +4944,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); } 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 95c9d0d508..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; @@ -32,7 +35,6 @@ import android.bluetooth.BluetoothGattCallback; import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothLeAudioCodecConfigMetadata; import android.bluetooth.BluetoothLeAudioContentMetadata; import android.bluetooth.BluetoothLeBroadcastAssistant; import android.bluetooth.BluetoothLeBroadcastChannel; @@ -41,22 +43,15 @@ import android.bluetooth.BluetoothLeBroadcastReceiveState; import android.bluetooth.BluetoothLeBroadcastSubgroup; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothStatusCodes; -import android.bluetooth.BluetoothUtils; -import android.bluetooth.BluetoothUtils.TypeValueEntry; import android.bluetooth.le.PeriodicAdvertisingCallback; -import android.bluetooth.le.PeriodicAdvertisingReport; -import android.bluetooth.le.ScanRecord; -import android.bluetooth.le.ScanResult; import android.content.AttributionSource; import android.content.Intent; import android.os.Binder; import android.os.Looper; import android.os.Message; -import android.os.ParcelUuid; import android.os.SystemClock; import android.provider.DeviceConfig; import android.util.Log; -import android.util.Pair; import com.android.bluetooth.BluetoothMethodProxy; import com.android.bluetooth.BluetoothStatsLog; @@ -64,7 +59,6 @@ import com.android.bluetooth.Utils; import com.android.bluetooth.btservice.AdapterService; import com.android.bluetooth.btservice.MetricsLogger; import com.android.bluetooth.btservice.ProfileService; -import com.android.bluetooth.flags.Flags; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.util.State; import com.android.internal.util.StateMachine; @@ -73,7 +67,6 @@ import java.io.ByteArrayOutputStream; import java.io.FileDescriptor; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -87,7 +80,8 @@ import java.util.UUID; import java.util.stream.IntStream; class BassClientStateMachine extends StateMachine { - private static final String TAG = "BassClientStateMachine"; + private static final String TAG = BassClientStateMachine.class.getSimpleName(); + @VisibleForTesting static final byte[] REMOTE_SCAN_STOP = {00}; @VisibleForTesting static final byte[] REMOTE_SCAN_START = {01}; private static final byte OPCODE_ADD_SOURCE = 0x02; @@ -103,18 +97,15 @@ class BassClientStateMachine extends StateMachine { static final int READ_BASS_CHARACTERISTICS = 5; static final int START_SCAN_OFFLOAD = 6; static final int STOP_SCAN_OFFLOAD = 7; - static final int SELECT_BCAST_SOURCE = 8; - static final int ADD_BCAST_SOURCE = 9; - static final int UPDATE_BCAST_SOURCE = 10; - static final int SET_BCAST_CODE = 11; - static final int REMOVE_BCAST_SOURCE = 12; - static final int GATT_TXN_TIMEOUT = 13; - static final int PSYNC_ACTIVE_TIMEOUT = 14; - static final int CONNECT_TIMEOUT = 15; - static final int REACHED_MAX_SOURCE_LIMIT = 16; - static final int SWITCH_BCAST_SOURCE = 17; - static final int CANCEL_PENDING_SOURCE_OPERATION = 18; - static final int INITIATE_PA_SYNC_TRANSFER = 19; + static final int ADD_BCAST_SOURCE = 8; + static final int UPDATE_BCAST_SOURCE = 9; + static final int SET_BCAST_CODE = 10; + static final int REMOVE_BCAST_SOURCE = 11; + static final int GATT_TXN_TIMEOUT = 12; + static final int CONNECT_TIMEOUT = 13; + static final int SWITCH_BCAST_SOURCE = 14; + static final int CANCEL_PENDING_SOURCE_OPERATION = 15; + static final int INITIATE_PA_SYNC_TRANSFER = 16; // NOTE: the value is not "final" - it is modified in the unit tests @VisibleForTesting private int mConnectTimeoutMs; @@ -125,8 +116,6 @@ class BassClientStateMachine extends StateMachine { static final int ATT_WRITE_CMD_HDR_LEN = 3; - private final Map<Integer, PeriodicAdvertisingCallback> mPeriodicAdvCallbacksMap = - new HashMap<>(); /*key is combination of sourceId, Address and advSid for this hashmap*/ private final Map<Integer, BluetoothLeBroadcastReceiveState> mBluetoothLeBroadcastReceiveStates = @@ -136,8 +125,6 @@ class BassClientStateMachine extends StateMachine { private final Connected mConnected = new Connected(); private final Connecting mConnecting = new Connecting(); private final ConnectedProcessing mConnectedProcessing = new ConnectedProcessing(); - private final List<Pair<ScanResult, Integer>> mSourceSyncRequestsQueue = - new ArrayList<Pair<ScanResult, Integer>>(); private final Map<Integer, LeAudioBroadcastSyncStats> mBroadcastSyncStats = new LinkedHashMap<>(); @@ -154,8 +141,6 @@ class BassClientStateMachine extends StateMachine { @VisibleForTesting BassClientService mService; AdapterService mAdapterService; @VisibleForTesting BluetoothGattCharacteristic mBroadcastScanControlPoint; - private final Map<Integer, Boolean> mFirstTimeBisDiscoveryMap; - private int mPASyncRetryCounter = 0; private boolean mBassStateReady = false; @VisibleForTesting int mNumOfBroadcastReceiverStates = 0; int mNumOfReadyBroadcastReceiverStates = 0; @@ -165,10 +150,8 @@ class BassClientStateMachine extends StateMachine { private BluetoothLeBroadcastMetadata mSetBroadcastPINMetadata = null; @VisibleForTesting boolean mSetBroadcastCodePending = false; private final Map<Integer, Boolean> mPendingRemove = new HashMap(); - @VisibleForTesting boolean mAutoTriggered = false; private boolean mDefNoPAS = false; private boolean mForceSB = false; - @VisibleForTesting BluetoothLeBroadcastMetadata mPendingSourceToAdd = null; private int mBroadcastSourceIdLength = 3; @VisibleForTesting byte mNextSourceId = 0; private boolean mAllowReconnect = false; @@ -194,7 +177,6 @@ class BassClientStateMachine extends StateMachine { addState(mConnecting); addState(mConnectedProcessing); setInitialState(mDisconnected); - mFirstTimeBisDiscoveryMap = new HashMap<Integer, Boolean>(); final long token = Binder.clearCallingIdentity(); try { mIsAllowedList = @@ -352,12 +334,9 @@ class BassClientStateMachine extends StateMachine { mPendingOperation = -1; mPendingSourceId = -1; mPendingMetadata = null; - mPendingSourceToAdd = null; mPendingSourceToSwitch = null; mCurrentMetadata.clear(); mPendingRemove.clear(); - mPeriodicAdvCallbacksMap.clear(); - mSourceSyncRequestsQueue.clear(); mBroadcastSyncStats.clear(); } @@ -444,249 +423,6 @@ class BassClientStateMachine extends StateMachine { })); } - void parseBaseData(BluetoothDevice device, int syncHandle, byte[] serviceData) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("parseBaseData" + Arrays.toString(serviceData)); - BaseData base = BaseData.parseBaseData(serviceData); - if (base != null) { - mService.updateBase(syncHandle, base); - base.print(); - if (mAutoTriggered) { - // successful auto periodic synchrnization with source - log("auto triggered assist"); - mAutoTriggered = false; - // perform PAST with this device - BluetoothDevice srcDevice = mService.getDeviceForSyncHandle(syncHandle); - if (srcDevice != null) { - BluetoothLeBroadcastReceiveState recvState = - getBroadcastReceiveStateForSourceDevice(srcDevice); - processPASyncState(recvState); - } else { - Log.w(TAG, "Autoassist: no matching device"); - } - } - } else { - Log.e(TAG, "Seems BASE is not in parsable format"); - if (!mAutoTriggered) { - cancelActiveSync(syncHandle); - } else { - mAutoTriggered = false; - } - } - } - - void parseScanRecord(int syncHandle, ScanRecord record) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("parseScanRecord: " + record); - Map<ParcelUuid, byte[]> bmsAdvDataMap = record.getServiceData(); - if (bmsAdvDataMap != null) { - for (Map.Entry<ParcelUuid, byte[]> entry : bmsAdvDataMap.entrySet()) { - log( - "ParcelUUid = " - + entry.getKey() - + ", Value = " - + Arrays.toString(entry.getValue())); - } - } - byte[] advData = record.getServiceData(BassConstants.BASIC_AUDIO_UUID); - if (advData != null) { - parseBaseData(mDevice, syncHandle, advData); - } else { - Log.e(TAG, "No service data in Scan record"); - if (!mAutoTriggered) { - cancelActiveSync(syncHandle); - } else { - mAutoTriggered = false; - } - } - } - - private String checkAndParseBroadcastName(ScanRecord record) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("checkAndParseBroadcastName"); - byte[] rawBytes = record.getBytes(); - List<TypeValueEntry> entries = BluetoothUtils.parseLengthTypeValueBytes(rawBytes); - if (rawBytes.length > 0 && rawBytes[0] > 0 && entries.isEmpty()) { - Log.e(TAG, "Invalid LTV entries in Scan record"); - return null; - } - - String broadcastName = null; - for (TypeValueEntry entry : entries) { - // Only use the first value of each type - if (broadcastName == null && entry.getType() == BassConstants.BCAST_NAME_AD_TYPE) { - byte[] bytes = entry.getValue(); - int len = bytes.length; - if (len < BassConstants.BCAST_NAME_LEN_MIN - || len > BassConstants.BCAST_NAME_LEN_MAX) { - Log.e(TAG, "Invalid broadcast name length in Scan record" + len); - return null; - } - broadcastName = new String(bytes, StandardCharsets.UTF_8); - } - } - return broadcastName; - } - - private boolean selectSource(ScanResult scanRes, boolean autoTriggered) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("selectSource: ScanResult " + scanRes); - mAutoTriggered = autoTriggered; - mPASyncRetryCounter = 1; - - // updating mainly for Address type and PA Interval here - // extract BroadcastId from ScanResult - ScanRecord scanRecord = scanRes.getScanRecord(); - if (scanRecord != null) { - Map<ParcelUuid, byte[]> listOfUuids = scanRecord.getServiceData(); - int broadcastId = BassConstants.INVALID_BROADCAST_ID; - PublicBroadcastData pbData = null; - if (listOfUuids != null) { - if (listOfUuids.containsKey(BassConstants.BAAS_UUID)) { - byte[] bId = listOfUuids.get(BassConstants.BAAS_UUID); - broadcastId = BassUtils.parseBroadcastId(bId); - } - if (listOfUuids.containsKey(BassConstants.PUBLIC_BROADCAST_UUID)) { - byte[] pbAnnouncement = listOfUuids.get(BassConstants.PUBLIC_BROADCAST_UUID); - pbData = PublicBroadcastData.parsePublicBroadcastData(pbAnnouncement); - } - } - - if (broadcastId == BassConstants.INVALID_BROADCAST_ID) { - Log.w(TAG, "Invalid broadcast ID"); - return false; - } - - // Check if broadcast name present in scan record and parse - // null if no name present - String broadcastName = checkAndParseBroadcastName(scanRecord); - - // Avoid duplicated sync request if the same broadcast BIG is synced - if (isSourceSynced(broadcastId)) { - log("Skip duplicated sync request to broadcast id: " + broadcastId); - return false; - } - - PeriodicAdvertisingCallback paCb = new PACallback(); - // put temp sync handle and update in onSyncEstablished - int tempHandle = BassConstants.INVALID_SYNC_HANDLE; - mPeriodicAdvCallbacksMap.put(tempHandle, paCb); - try { - BluetoothMethodProxy.getInstance() - .periodicAdvertisingManagerRegisterSync( - BassClientPeriodicAdvertisingManager - .getPeriodicAdvertisingManager(), - scanRes, - 0, - BassConstants.PSYNC_TIMEOUT, - paCb, - null); - } catch (IllegalArgumentException ex) { - Log.w(TAG, "registerSync:IllegalArgumentException"); - mPeriodicAdvCallbacksMap.remove(tempHandle); - return false; - } - - mService.updatePeriodicAdvertisementResultMap( - scanRes.getDevice(), - scanRes.getDevice().getAddressType(), - BassConstants.INVALID_SYNC_HANDLE, - BassConstants.INVALID_ADV_SID, - scanRes.getPeriodicAdvertisingInterval(), - broadcastId, - pbData, - broadcastName); - } - return true; - } - - private boolean isSourceSynced(int broadcastId) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - List<Integer> activeSyncedSrc = mService.getActiveSyncedSources(mDevice); - return (activeSyncedSrc != null - && activeSyncedSrc.contains(mService.getSyncHandleForBroadcastId(broadcastId))); - } - - private void cancelActiveSync(Integer syncHandle) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("cancelActiveSync: syncHandle = " + syncHandle); - if (syncHandle == null) { - // clean up the pending sync request if syncHandle is null - mPeriodicAdvCallbacksMap.remove(BassConstants.INVALID_SYNC_HANDLE); - } - List<Integer> activeSyncedSrc = mService.getActiveSyncedSources(mDevice); - - /* Stop sync if there is some running */ - if (activeSyncedSrc != null - && (syncHandle == null || activeSyncedSrc.contains(syncHandle))) { - if (syncHandle != null) { - // only one source needs to be unsynced - unsyncSource(syncHandle); - mService.removeActiveSyncedSource(mDevice, syncHandle); - } else { - // remove all the sources - for (int handle : activeSyncedSrc) { - unsyncSource(handle); - } - mService.removeActiveSyncedSource(mDevice, null); - } - if (mService.getActiveSyncedSources(mDevice) == null) { - // all sources are removed, clean up - removeMessages(PSYNC_ACTIVE_TIMEOUT); - mService.clearNotifiedFlags(); - } - } - } - - private boolean unsyncSource(int syncHandle) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - if (syncHandle != BassConstants.INVALID_SYNC_HANDLE - && mPeriodicAdvCallbacksMap.containsKey(syncHandle)) { - try { - BluetoothMethodProxy.getInstance() - .periodicAdvertisingManagerUnregisterSync( - BassClientPeriodicAdvertisingManager - .getPeriodicAdvertisingManager(), - mPeriodicAdvCallbacksMap.get(syncHandle)); - } catch (IllegalArgumentException ex) { - Log.w(TAG, "unregisterSync:IllegalArgumentException"); - return false; - } - mPeriodicAdvCallbacksMap.remove(syncHandle); - } else { - log("calling unregisterSync, not found syncHandle: " + syncHandle); - } - return true; - } - private void resetBluetoothGatt() { // cleanup mBluetoothGatt if (mBluetoothGatt != null) { @@ -695,108 +431,6 @@ class BassClientStateMachine extends StateMachine { } } - private BluetoothLeBroadcastMetadata getBroadcastMetadataFromBaseData( - BaseData baseData, BluetoothDevice device, int syncHandle, boolean encrypted) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - BluetoothLeBroadcastMetadata.Builder metaData = new BluetoothLeBroadcastMetadata.Builder(); - int index = 0; - for (BaseData.BaseInformation baseLevel2 : baseData.getLevelTwo()) { - BluetoothLeBroadcastSubgroup.Builder subGroup = - new BluetoothLeBroadcastSubgroup.Builder(); - for (int j = 0; j < baseLevel2.numSubGroups; j++) { - BaseData.BaseInformation baseLevel3 = baseData.getLevelThree().get(index++); - BluetoothLeBroadcastChannel.Builder channel = - new BluetoothLeBroadcastChannel.Builder(); - channel.setChannelIndex(baseLevel3.index); - channel.setSelected(false); - try { - channel.setCodecMetadata( - BluetoothLeAudioCodecConfigMetadata.fromRawBytes( - baseLevel3.codecConfigInfo)); - } catch (IllegalArgumentException e) { - Log.w(TAG, "Invalid metadata, adding empty data. Error: " + e); - channel.setCodecMetadata( - BluetoothLeAudioCodecConfigMetadata.fromRawBytes(new byte[0])); - } - subGroup.addChannel(channel.build()); - } - byte[] arrayCodecId = baseLevel2.codecId; - long codeId = - ((long) (arrayCodecId[4] & 0xff)) << 32 - | (arrayCodecId[3] & 0xff) << 24 - | (arrayCodecId[2] & 0xff) << 16 - | (arrayCodecId[1] & 0xff) << 8 - | (arrayCodecId[0] & 0xff); - subGroup.setCodecId(codeId); - try { - subGroup.setCodecSpecificConfig( - BluetoothLeAudioCodecConfigMetadata.fromRawBytes( - baseLevel2.codecConfigInfo)); - } catch (IllegalArgumentException e) { - Log.w(TAG, "Invalid config, adding empty one. Error: " + e); - subGroup.setCodecSpecificConfig( - BluetoothLeAudioCodecConfigMetadata.fromRawBytes(new byte[0])); - } - - try { - subGroup.setContentMetadata( - BluetoothLeAudioContentMetadata.fromRawBytes(baseLevel2.metaData)); - } catch (IllegalArgumentException e) { - Log.w(TAG, "Invalid metadata, adding empty one. Error: " + e); - subGroup.setContentMetadata( - BluetoothLeAudioContentMetadata.fromRawBytes(new byte[0])); - } - - metaData.addSubgroup(subGroup.build()); - } - metaData.setSourceDevice(device, device.getAddressType()); - byte[] arrayPresentationDelay = baseData.getLevelOne().presentationDelay; - int presentationDelay = - (int) - ((arrayPresentationDelay[2] & 0xff) << 16 - | (arrayPresentationDelay[1] & 0xff) << 8 - | (arrayPresentationDelay[0] & 0xff)); - metaData.setPresentationDelayMicros(presentationDelay); - PeriodicAdvertisementResult result = - mService.getPeriodicAdvertisementResult( - device, mService.getBroadcastIdForSyncHandle(syncHandle)); - if (result != null) { - int broadcastId = result.getBroadcastId(); - log("broadcast ID: " + broadcastId); - metaData.setBroadcastId(broadcastId); - metaData.setSourceAdvertisingSid(result.getAdvSid()); - - PublicBroadcastData pbData = result.getPublicBroadcastData(); - if (pbData != null) { - metaData.setPublicBroadcast(true); - metaData.setAudioConfigQuality(pbData.getAudioConfigQuality()); - try { - metaData.setPublicBroadcastMetadata( - BluetoothLeAudioContentMetadata.fromRawBytes(pbData.getMetadata())); - } catch (IllegalArgumentException e) { - Log.w(TAG, "Invalid public metadata, adding empty one. Error " + e); - metaData.setPublicBroadcastMetadata(null); - } - } - - String broadcastName = result.getBroadcastName(); - if (broadcastName != null) { - metaData.setBroadcastName(broadcastName); - } - } - metaData.setEncrypted(encrypted); - // update the rssi value - ScanResult scanRes = mService.getCachedBroadcast(result.getBroadcastId()); - if (scanRes != null) { - metaData.setRssi(scanRes.getRssi()); - } - return metaData.build(); - } - private void broadcastReceiverState(BluetoothLeBroadcastReceiveState state, int sourceId) { log("broadcastReceiverState: " + mDevice); mService.getCallbacks().notifyReceiveStateChanged(mDevice, sourceId, state); @@ -979,13 +613,13 @@ class BassClientStateMachine extends StateMachine { mBroadcastSyncStats.clear(); } - private boolean isSourceAbsent(BluetoothLeBroadcastReceiveState recvState) { + private static boolean isSourceAbsent(BluetoothLeBroadcastReceiveState recvState) { return recvState == null || recvState.getSourceDevice() == null || recvState.getSourceDevice().getAddress().equals("00:00:00:00:00:00"); } - private boolean isSourcePresent(BluetoothLeBroadcastReceiveState recvState) { + private static boolean isSourcePresent(BluetoothLeBroadcastReceiveState recvState) { return !isSourceAbsent(recvState); } @@ -1203,10 +837,6 @@ class BassClientStateMachine extends StateMachine { BluetoothDevice removedDevice = oldRecvState.getSourceDevice(); log("sourceInfo removal " + removedDevice); int prevSourceId = oldRecvState.getSourceId(); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync( - mService.getSyncHandleForBroadcastId(recvState.getBroadcastId())); - } BluetoothLeBroadcastMetadata metaData = getCurrentBroadcastMetadata(prevSourceId); if (metaData != null) { @@ -1449,9 +1079,6 @@ class BassClientStateMachine extends StateMachine { } else if (isSourcePresent(prevRecvState) && isSourceAbsent(recvState)) { BluetoothDevice removedDevice = prevRecvState.getSourceDevice(); log("processBroadcastReceiverState: Source Removal " + removedDevice); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(mService.getSyncHandleForBroadcastId(recvState.getBroadcastId())); - } BluetoothLeBroadcastMetadata metaData = getCurrentBroadcastMetadata(sourceId); if (metaData != null) { logBroadcastSyncStatsWithStatus( @@ -1489,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)) { @@ -1508,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."); } @@ -1645,150 +1271,6 @@ class BassClientStateMachine extends StateMachine { /** Internal periodc Advertising manager callback */ private final class PACallback extends PeriodicAdvertisingCallback { @Override - public void onSyncEstablished( - int syncHandle, - BluetoothDevice device, - int advertisingSid, - int skip, - int timeout, - int status) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log( - "onSyncEstablished syncHandle: " - + syncHandle - + ", device: " - + device - + ", advertisingSid: " - + advertisingSid - + ", skip: " - + skip - + ", timeout: " - + timeout - + ", status: " - + status); - if (status == BluetoothGatt.GATT_SUCCESS) { - // updates syncHandle, advSid - // set other fields as invalid or null - mService.updatePeriodicAdvertisementResultMap( - device, - BassConstants.INVALID_ADV_ADDRESS_TYPE, - syncHandle, - advertisingSid, - BassConstants.INVALID_ADV_INTERVAL, - BassConstants.INVALID_BROADCAST_ID, - null, - null); - removeMessages(PSYNC_ACTIVE_TIMEOUT); - // Refresh sync timeout if another source synced - sendMessageDelayed(PSYNC_ACTIVE_TIMEOUT, BassConstants.PSYNC_ACTIVE_TIMEOUT_MS); - mService.addActiveSyncedSource(mDevice, syncHandle); - - // update valid sync handle in mPeriodicAdvCallbacksMap - if (mPeriodicAdvCallbacksMap.containsKey(BassConstants.INVALID_SYNC_HANDLE)) { - PeriodicAdvertisingCallback paCb = - mPeriodicAdvCallbacksMap.get(BassConstants.INVALID_SYNC_HANDLE); - mPeriodicAdvCallbacksMap.put(syncHandle, paCb); - mPeriodicAdvCallbacksMap.remove(BassConstants.INVALID_SYNC_HANDLE); - } - mFirstTimeBisDiscoveryMap.put(syncHandle, true); - if (mPendingSourceToAdd != null) { - Message message = obtainMessage(ADD_BCAST_SOURCE); - message.obj = mPendingSourceToAdd; - sendMessage(message); - } - } else { - log("failed to sync to PA: " + mPASyncRetryCounter); - mAutoTriggered = false; - // remove failed sync handle - mPeriodicAdvCallbacksMap.remove(BassConstants.INVALID_SYNC_HANDLE); - } - mPendingSourceToAdd = null; - if (!mSourceSyncRequestsQueue.isEmpty()) { - log("Processing the next source to sync"); - Pair<ScanResult, Integer> queuedSourceToSync = mSourceSyncRequestsQueue.remove(0); - Message msg = obtainMessage(SELECT_BCAST_SOURCE); - msg.obj = queuedSourceToSync.first; - msg.arg1 = queuedSourceToSync.second; - sendMessage(msg); - } - } - - @Override - public void onPeriodicAdvertisingReport(PeriodicAdvertisingReport report) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("onPeriodicAdvertisingReport"); - Boolean first = mFirstTimeBisDiscoveryMap.get(report.getSyncHandle()); - // Parse the BIS indices from report's service data - if (first != null && first.booleanValue() == true) { - parseScanRecord(report.getSyncHandle(), report.getData()); - mFirstTimeBisDiscoveryMap.put(report.getSyncHandle(), false); - } - } - - @Override - public void onSyncLost(int syncHandle) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log("OnSyncLost" + syncHandle); - int broadcastId = mService.getBroadcastIdForSyncHandle(syncHandle); - if (broadcastId != BassConstants.INVALID_BROADCAST_ID) { - log("Notify broadcast source lost, broadcast id: " + broadcastId); - mService.getCallbacks().notifySourceLost(broadcastId); - } - cancelActiveSync(syncHandle); - } - - @Override - public void onBigInfoAdvertisingReport(int syncHandle, boolean encrypted) { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine flag"); - } - log( - "onBIGInfoAdvertisingReport: syncHandle=" - + syncHandle - + ", encrypted =" - + encrypted); - BluetoothDevice srcDevice = mService.getDeviceForSyncHandle(syncHandle); - if (srcDevice == null) { - log("No device found."); - return; - } - PeriodicAdvertisementResult result = - mService.getPeriodicAdvertisementResult( - srcDevice, mService.getBroadcastIdForSyncHandle(syncHandle)); - if (result == null) { - log("No PA record found"); - return; - } - if (!result.isNotified()) { - result.setNotified(true); - BaseData baseData = mService.getBase(syncHandle); - if (baseData == null) { - log("No BaseData found"); - return; - } - BluetoothLeBroadcastMetadata metaData = - getBroadcastMetadataFromBaseData( - baseData, srcDevice, syncHandle, encrypted); - log("Notify broadcast source found"); - mService.getCallbacks().notifySourceFound(metaData); - } - } - - @Override public void onSyncTransferred(BluetoothDevice device, int status) { log("onSyncTransferred: device=" + device + ", status =" + status); } @@ -1909,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); @@ -1927,7 +1408,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -1968,16 +1449,13 @@ 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 { Log.w(TAG, "Disconnected: Connection failed to " + mDevice); } break; - case PSYNC_ACTIVE_TIMEOUT: - cancelActiveSync(null); - break; default: log("DISCONNECTED: not handled message:" + message.what); return NOT_HANDLED; @@ -1996,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 @@ -2007,7 +1484,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -2034,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); @@ -2052,9 +1529,6 @@ class BassClientStateMachine extends StateMachine { resetBluetoothGatt(); transitionTo(mDisconnected); break; - case PSYNC_ACTIVE_TIMEOUT: - deferMessage(message); - break; default: log("CONNECTING: not handled message:" + message.what); return NOT_HANDLED; @@ -2291,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); } } @@ -2304,7 +1777,7 @@ class BassClientStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } private void writeBassControlPoint(byte[] value) { @@ -2336,9 +1809,6 @@ class BassClientStateMachine extends StateMachine { mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(null); - } transitionTo(mDisconnected); } else { log("mBluetoothGatt is null"); @@ -2347,15 +1817,12 @@ 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); mService.handleDeviceDisconnection(mDevice, false); resetBluetoothGatt(); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(null); - } transitionTo(mDisconnected); } break; @@ -2387,36 +1854,6 @@ class BassClientStateMachine extends StateMachine { log("no Bluetooth Gatt handle, may need to fetch write"); } break; - case SELECT_BCAST_SOURCE: - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine" - + " flag"); - } - ScanResult scanRes = (ScanResult) message.obj; - boolean auto = ((int) message.arg1) == BassConstants.AUTO; - // check if invalid sync handle exists indicating a pending sync request - if (mPeriodicAdvCallbacksMap.containsKey(BassConstants.INVALID_SYNC_HANDLE)) { - log( - "SELECT_BCAST_SOURCE queued due to waiting for a previous sync" - + " response"); - mSourceSyncRequestsQueue.add( - new Pair<ScanResult, Integer>(scanRes, message.arg1)); - } else { - selectSource(scanRes, auto); - } - break; - case REACHED_MAX_SOURCE_LIMIT: - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - throw new RuntimeException( - "Should never be executed with" - + " leaudioBroadcastExtractPeriodicScannerFromStateMachine" - + " flag"); - } - int handle = message.arg1; - cancelActiveSync(handle); - break; case SWITCH_BCAST_SOURCE: metaData = (BluetoothLeBroadcastMetadata) message.obj; int sourceIdToRemove = message.arg1; @@ -2441,37 +1878,6 @@ class BassClientStateMachine extends StateMachine { break; case ADD_BCAST_SOURCE: metaData = (BluetoothLeBroadcastMetadata) message.obj; - - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - List<Integer> activeSyncedSrc = mService.getActiveSyncedSources(mDevice); - BluetoothDevice sourceDevice = metaData.getSourceDevice(); - if (!mService.isLocalBroadcast(metaData) - && (activeSyncedSrc == null - || !activeSyncedSrc.contains( - mService.getSyncHandleForBroadcastId( - metaData.getBroadcastId())))) { - log("Adding inactive source: " + sourceDevice); - int broadcastId = metaData.getBroadcastId(); - if (broadcastId != BassConstants.INVALID_BROADCAST_ID - && mService.getCachedBroadcast(broadcastId) != null) { - // If the source has been synced before, try to re-sync(auto/true) - // with the source by previously cached scan result - Message msg = obtainMessage(SELECT_BCAST_SOURCE); - msg.obj = mService.getCachedBroadcast(broadcastId); - msg.arg1 = BassConstants.AUTO; - sendMessage(msg); - mPendingSourceToAdd = metaData; - } else { - mService.getCallbacks() - .notifySourceAddFailed( - mDevice, - metaData, - BluetoothStatusCodes.ERROR_UNKNOWN); - } - break; - } - } - byte[] addSourceInfo = convertMetadataToAddSourceByteArray(metaData); if (addSourceInfo == null) { Log.e(TAG, "add source: source Info is NULL"); @@ -2626,9 +2032,6 @@ class BassClientStateMachine extends StateMachine { } } break; - case PSYNC_ACTIVE_TIMEOUT: - cancelActiveSync(null); - break; case CANCEL_PENDING_SOURCE_OPERATION: int broadcastId = message.arg1; cancelPendingSourceOperation(broadcastId); @@ -2646,7 +2049,7 @@ class BassClientStateMachine extends StateMachine { } } - private boolean isSuccess(int status) { + private static boolean isSuccess(int status) { boolean ret = false; switch (status) { case BluetoothStatusCodes.REASON_LOCAL_APP_REQUEST: @@ -2664,22 +2067,10 @@ class BassClientStateMachine extends StateMachine { void sendPendingCallbacks(int pendingOp, int status) { switch (pendingOp) { case START_SCAN_OFFLOAD: - // Do not want to cancel sync because one remote does not receive START_SCAN_OFFLOAD - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - if (!isSuccess(status)) { - if (!mAutoTriggered) { - cancelActiveSync(null); - } else { - mAutoTriggered = false; - } - } - } + log("sendPendingCallbacks: START_SCAN_OFFLOAD"); break; case ADD_BCAST_SOURCE: if (!isSuccess(status)) { - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(null); - } if (mPendingMetadata != null) { mService.getCallbacks() .notifySourceAddFailed(mDevice, mPendingMetadata, status); @@ -2689,16 +2080,11 @@ class BassClientStateMachine extends StateMachine { } break; case UPDATE_BCAST_SOURCE: - if (!mAutoTriggered - || Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - if (!isSuccess(status)) { - mService.getCallbacks() - .notifySourceModifyFailed(mDevice, mPendingSourceId, status); - mPendingMetadata = null; - removeMessages(CANCEL_PENDING_SOURCE_OPERATION); - } - } else { - mAutoTriggered = false; + if (!isSuccess(status)) { + mService.getCallbacks() + .notifySourceModifyFailed(mDevice, mPendingSourceId, status); + mPendingMetadata = null; + removeMessages(CANCEL_PENDING_SOURCE_OPERATION); } break; case REMOVE_BCAST_SOURCE: @@ -2768,9 +2154,6 @@ class BassClientStateMachine extends StateMachine { mBluetoothGatt.disconnect(); mBluetoothGatt.close(); mBluetoothGatt = null; - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(null); - } transitionTo(mDisconnected); } else { log("mBluetoothGatt is null"); @@ -2783,15 +2166,12 @@ 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); mService.handleDeviceDisconnection(mDevice, false); resetBluetoothGatt(); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - cancelActiveSync(null); - } transitionTo(mDisconnected); } break; @@ -2820,13 +2200,10 @@ class BassClientStateMachine extends StateMachine { break; case START_SCAN_OFFLOAD: case STOP_SCAN_OFFLOAD: - case SELECT_BCAST_SOURCE: case ADD_BCAST_SOURCE: case SET_BCAST_CODE: case REMOVE_BCAST_SOURCE: - case REACHED_MAX_SOURCE_LIMIT: case SWITCH_BCAST_SOURCE: - case PSYNC_ACTIVE_TIMEOUT: case INITIATE_PA_SYNC_TRANSFER: log( "defer the message: " @@ -2848,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; } @@ -2876,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; } } @@ -2926,20 +2302,14 @@ class BassClientStateMachine extends StateMachine { return "STOP_SCAN_OFFLOAD"; case ADD_BCAST_SOURCE: return "ADD_BCAST_SOURCE"; - case SELECT_BCAST_SOURCE: - return "SELECT_BCAST_SOURCE"; case UPDATE_BCAST_SOURCE: return "UPDATE_BCAST_SOURCE"; case SET_BCAST_CODE: return "SET_BCAST_CODE"; case REMOVE_BCAST_SOURCE: return "REMOVE_BCAST_SOURCE"; - case REACHED_MAX_SOURCE_LIMIT: - return "REACHED_MAX_SOURCE_LIMIT"; case SWITCH_BCAST_SOURCE: return "SWITCH_BCAST_SOURCE"; - case PSYNC_ACTIVE_TIMEOUT: - return "PSYNC_ACTIVE_TIMEOUT"; case CONNECT_TIMEOUT: return "CONNECT_TIMEOUT"; case CANCEL_PENDING_SOURCE_OPERATION: diff --git a/android/app/src/com/android/bluetooth/bass_client/BassConstants.java b/android/app/src/com/android/bluetooth/bass_client/BassConstants.java index 768f32b7d9..13b0339853 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassConstants.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassConstants.java @@ -69,8 +69,6 @@ public class BassConstants { // 30 secs time out for all gatt writes public static final int GATT_TXN_TIMEOUT_MS = 30000; public static final int SOURCE_OPERATION_TIMEOUT_MS = 3000; - // 3 min time out for keeping PSYNC active - public static final int PSYNC_ACTIVE_TIMEOUT_MS = 3 * 60000; // 2 secs time out achieving psync public static final int PSYNC_TIMEOUT = 200; public static final int PIN_CODE_CMD_LEN = 18; diff --git a/android/app/src/com/android/bluetooth/bass_client/BassObjectsFactory.java b/android/app/src/com/android/bluetooth/bass_client/BassObjectsFactory.java index d65913d722..b44d067c61 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassObjectsFactory.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassObjectsFactory.java @@ -29,6 +29,7 @@ import com.android.internal.annotations.VisibleForTesting; /** Factory class for object initialization to help with unit testing */ public class BassObjectsFactory { private static final String TAG = BassObjectsFactory.class.getSimpleName(); + private static BassObjectsFactory sInstance; private static final Object INSTANCE_LOCK = new Object(); diff --git a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java index 02c38be501..a5dca87a68 100644 --- a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java +++ b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java @@ -33,7 +33,7 @@ import java.util.Map; /** Bass Utility functions */ class BassUtils { - private static final String TAG = "BassUtils"; + private static final String TAG = BassUtils.class.getSimpleName(); static boolean containUuid(List<ScanFilter> filters, ParcelUuid uuid) { for (ScanFilter filter : filters) { diff --git a/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java b/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java index 4601cafa6c..4cd4062906 100644 --- a/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java +++ b/android/app/src/com/android/bluetooth/bass_client/PublicBroadcastData.java @@ -23,7 +23,9 @@ import java.util.Arrays; /** Helper class to parse the Public Broadcast Announcement data */ class PublicBroadcastData { - private static final String TAG = "Bassclient.PublicBroadcastData"; + private static final String TAG = + BassClientService.TAG + "." + PublicBroadcastData.class.getSimpleName(); + private static final int FEATURES_ENCRYPTION_BIT = 0x01 << 0; private static final int FEATURES_STANDARD_QUALITY_BIT = 0x01 << 1; private static final int FEATURES_HIGH_QUALITY_BIT = 0x01 << 2; diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java index eb30fe82dd..ebd4c4a4f9 100644 --- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java +++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java @@ -16,6 +16,8 @@ package com.android.bluetooth.btservice; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import android.annotation.NonNull; import android.annotation.Nullable; import android.bluetooth.BluetoothAdapter; @@ -110,6 +112,7 @@ import java.util.Set; */ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallback { private static final String TAG = ActiveDeviceManager.class.getSimpleName(); + @VisibleForTesting static final int A2DP_HFP_SYNC_CONNECTION_TIMEOUT_MS = 5_000; private final AdapterService mAdapterService; @@ -179,7 +182,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)); @@ -197,7 +200,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)); diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterApp.java b/android/app/src/com/android/bluetooth/btservice/AdapterApp.java index d3849e86b0..eb72f08fba 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterApp.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterApp.java @@ -18,8 +18,10 @@ package com.android.bluetooth.btservice; import android.app.Application; import android.util.Log; +import com.android.bluetooth.Utils; + public class AdapterApp extends Application { - private static final String TAG = "BluetoothAdapterApp"; + private static final String TAG = Utils.TAG_PREFIX_BLUETOOTH + AdapterApp.class.getSimpleName(); @Override public void onCreate() { diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java index b99debdede..f195eec079 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java @@ -19,6 +19,10 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_SCAN; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.annotation.NonNull; import android.app.BroadcastOptions; @@ -597,7 +601,7 @@ class AdapterProperties { if (p != null) { return p.first; } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } @@ -667,24 +671,22 @@ class AdapterProperties { } } - - - private boolean validateProfileConnectionState(int state) { - return (state == BluetoothProfile.STATE_DISCONNECTED - || state == BluetoothProfile.STATE_CONNECTING - || state == BluetoothProfile.STATE_CONNECTED - || state == BluetoothProfile.STATE_DISCONNECTING); + private static boolean validateProfileConnectionState(int state) { + return (state == STATE_DISCONNECTED + || state == STATE_CONNECTING + || state == STATE_CONNECTED + || state == STATE_DISCONNECTING); } private static int convertToAdapterState(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return BluetoothAdapter.STATE_DISCONNECTED; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: return BluetoothAdapter.STATE_DISCONNECTING; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: return BluetoothAdapter.STATE_CONNECTED; - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: return BluetoothAdapter.STATE_CONNECTING; } Log.e(TAG, "convertToAdapterState, unknow state " + state); @@ -693,14 +695,13 @@ class AdapterProperties { private static boolean isNormalStateTransition(int prevState, int nextState) { switch (prevState) { - case BluetoothProfile.STATE_DISCONNECTED: - return nextState == BluetoothProfile.STATE_CONNECTING; - case BluetoothProfile.STATE_CONNECTED: - return nextState == BluetoothProfile.STATE_DISCONNECTING; - case BluetoothProfile.STATE_DISCONNECTING: - case BluetoothProfile.STATE_CONNECTING: - return (nextState == BluetoothProfile.STATE_DISCONNECTED) - || (nextState == BluetoothProfile.STATE_CONNECTED); + case STATE_DISCONNECTED: + return nextState == STATE_CONNECTING; + case STATE_CONNECTED: + return nextState == STATE_DISCONNECTING; + case STATE_DISCONNECTING: + case STATE_CONNECTING: + return (nextState == STATE_DISCONNECTED) || (nextState == STATE_CONNECTED); default: return false; } @@ -708,7 +709,7 @@ class AdapterProperties { private boolean updateCountersAndCheckForConnectionStateChange(int state, int prevState) { switch (prevState) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: if (mProfilesConnecting > 0) { mProfilesConnecting--; } else { @@ -718,7 +719,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: if (mProfilesConnected > 0) { mProfilesConnected--; } else { @@ -728,7 +729,7 @@ class AdapterProperties { } break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: if (mProfilesDisconnecting > 0) { mProfilesDisconnecting--; } else { @@ -740,19 +741,19 @@ class AdapterProperties { } switch (state) { - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: mProfilesConnecting++; return (mProfilesConnected == 0 && mProfilesConnecting == 1); - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: mProfilesConnected++; return (mProfilesConnected == 1); - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: mProfilesDisconnecting++; return (mProfilesConnected == 0 && mProfilesDisconnecting == 1); - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return (mProfilesConnected == 0 && mProfilesConnecting == 0); default: @@ -787,17 +788,15 @@ class AdapterProperties { if (newState == currHashState) { numDev++; - } else if (newState == BluetoothProfile.STATE_CONNECTED - || (newState == BluetoothProfile.STATE_CONNECTING - && currHashState != BluetoothProfile.STATE_CONNECTED)) { + } else if (newState == STATE_CONNECTED + || (newState == STATE_CONNECTING && currHashState != STATE_CONNECTED)) { numDev = 1; } else if (numDev == 1 && oldState == currHashState) { update = true; } else if (numDev > 1 && oldState == currHashState) { numDev--; - if (currHashState == BluetoothProfile.STATE_CONNECTED - || currHashState == BluetoothProfile.STATE_CONNECTING) { + if (currHashState == STATE_CONNECTED || currHashState == STATE_CONNECTING) { newHashState = currHashState; } } else { @@ -1159,7 +1158,7 @@ class AdapterProperties { writer.println(sb.toString()); } - private String dumpDeviceType(int deviceType) { + private static String dumpDeviceType(int deviceType) { switch (deviceType) { case BluetoothDevice.DEVICE_TYPE_UNKNOWN: return " ???? "; @@ -1174,7 +1173,7 @@ class AdapterProperties { } } - private String dumpConnectionState(int state) { + private static String dumpConnectionState(int state) { switch (state) { case BluetoothAdapter.STATE_DISCONNECTED: return "STATE_DISCONNECTED"; diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java index 7e6430aab3..26918e8dd3 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java @@ -28,6 +28,9 @@ 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.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; @@ -209,7 +212,8 @@ import java.util.regex.Pattern; import java.util.stream.Collectors; public class AdapterService extends Service { - private static final String TAG = "BluetoothAdapterService"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + AdapterService.class.getSimpleName(); private static final int MESSAGE_PROFILE_SERVICE_STATE_CHANGED = 1; private static final int MESSAGE_PROFILE_SERVICE_REGISTERED = 2; @@ -1124,7 +1128,7 @@ public class AdapterService extends Service { } } - private void invalidateBluetoothGetStateCache() { + private static void invalidateBluetoothGetStateCache() { if (Flags.getStateFromSystemServer()) { // State is managed by the system server return; @@ -1248,6 +1252,9 @@ public class AdapterService extends Service { BluetoothProperties.snoop_log_filter_profile_map() .orElse(BluetoothProperties.snoop_log_filter_profile_map_values.EMPTY); + if (Utils.isInstrumentationTestMode()) { + return; + } BluetoothProperties.snoop_default_mode( BluetoothProperties.snoop_default_mode_values.DISABLED); for (BluetoothProperties.snoop_default_mode_values value : @@ -1505,7 +1512,7 @@ public class AdapterService extends Service { mMetadataListeners.values().forEach(v -> v.kill()); } - private void invalidateBluetoothCaches() { + private static void invalidateBluetoothCaches() { BluetoothAdapter.invalidateGetProfileConnectionStateCache(); BluetoothAdapter.invalidateIsOffloadedFilteringSupportedCache(); BluetoothDevice.invalidateBluetoothGetBondStateCache(); @@ -1561,7 +1568,7 @@ public class AdapterService extends Service { Log.wtf(TAG, logHdr + " profile is already started"); return; } - Log.d(TAG, logHdr + " starting profile"); + Log.i(TAG, logHdr + " starting profile"); ProfileService profileService = PROFILE_CONSTRUCTORS.get(profileId).apply(this); mStartedProfiles.put(profileId, profileService); addProfile(profileService); @@ -1579,7 +1586,7 @@ public class AdapterService extends Service { Log.wtf(TAG, logHdr + " profile is already stopped"); return; } - Log.d(TAG, logHdr + " stopping profile"); + Log.i(TAG, logHdr + " stopping profile"); profileService.setAvailable(false); onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_OFF); removeProfile(profileService); @@ -1589,7 +1596,7 @@ public class AdapterService extends Service { } } Instant end = Instant.now(); - Log.d(TAG, logHdr + " completed in " + Duration.between(start, end).toMillis() + "ms"); + Log.i(TAG, logHdr + " completed in " + Duration.between(start, end).toMillis() + "ms"); } private void setAllProfileServiceStates(int[] profileIds, int state) { @@ -1725,17 +1732,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) @@ -2135,7 +2141,7 @@ public class AdapterService extends Service { } } - private void pendingSocketTimeoutRunnable( + private static void pendingSocketTimeoutRunnable( RfcommListenerData listenerData, BluetoothSocket socket) { boolean socketFound = listenerData.mPendingSockets.remove(socket); if (socketFound) { @@ -2642,7 +2648,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); @@ -4852,6 +4858,11 @@ public class AdapterService extends Service { mAdapterStateMachine.sendMessage(AdapterState.USER_TURN_OFF); } + void disconnectAllAcls() { + Log.d(TAG, "disconnectAllAcls()"); + mNativeInterface.disconnectAllAcls(); + } + public String getName() { return mAdapterProperties.getName(); } @@ -5784,134 +5795,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 " @@ -5919,9 +5907,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); } @@ -6698,19 +6685,19 @@ public class AdapterService extends Service { list.finishBroadcast(); } - private int getIdleCurrentMa() { + private static int getIdleCurrentMa() { return BluetoothProperties.getHardwareIdleCurrentMa().orElse(0); } - private int getTxCurrentMa() { + private static int getTxCurrentMa() { return BluetoothProperties.getHardwareTxCurrentMa().orElse(0); } - private int getRxCurrentMa() { + private static int getRxCurrentMa() { return BluetoothProperties.getHardwareRxCurrentMa().orElse(0); } - private double getOperatingVolt() { + private static double getOperatingVolt() { return BluetoothProperties.getHardwareOperatingVoltageMv().orElse(0) / 1000.0; } @@ -6718,7 +6705,7 @@ public class AdapterService extends Service { return mRemoteDevices; } - private String dumpScanMode(int scanMode) { + private static String dumpScanMode(int scanMode) { switch (scanMode) { case SCAN_MODE_NONE: return "SCAN_MODE_NONE"; @@ -7382,7 +7369,7 @@ public class AdapterService extends Service { deleteDirectoryContents("/data/misc/bluetooth/"); } - private void deleteDirectoryContents(String dirPath) { + private static void deleteDirectoryContents(String dirPath) { Path directoryPath = Paths.get(dirPath); try { Files.walkFileTree( diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterState.java b/android/app/src/com/android/bluetooth/btservice/AdapterState.java index bcdd092716..b5ff730b5a 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterState.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterState.java @@ -22,6 +22,7 @@ import android.os.Message; import android.os.SystemProperties; import android.util.Log; +import com.android.bluetooth.flags.Flags; import com.android.internal.util.State; import com.android.internal.util.StateMachine; @@ -90,7 +91,7 @@ final class AdapterState extends StateMachine { start(); } - private String messageString(int message) { + private static String messageString(int message) { switch (message) { case BLE_TURN_ON: return "BLE_TURN_ON"; @@ -342,6 +343,13 @@ final class AdapterState extends StateMachine { @Override public void exit() { removeMessages(BREDR_STOP_TIMEOUT); + if (Flags.disconnectAclsByBredrDisabled()) { + if (mAdapterService != null) { + Log.i(TAG, "Disconnecting all ACLs with BREDR Stopped"); + mAdapterService.disconnectAllAcls(); + } + } + super.exit(); } diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterSuspend.java b/android/app/src/com/android/bluetooth/btservice/AdapterSuspend.java index 857121b1f9..d49865e1ce 100644 --- a/android/app/src/com/android/bluetooth/btservice/AdapterSuspend.java +++ b/android/app/src/com/android/bluetooth/btservice/AdapterSuspend.java @@ -31,11 +31,13 @@ import android.util.Log; import androidx.annotation.RequiresApi; +import com.android.bluetooth.Utils; import com.android.internal.annotations.VisibleForTesting; @RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM) public class AdapterSuspend { - private static final String TAG = "BtAdapterSuspend"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + AdapterSuspend.class.getSimpleName(); // Event mask bits corresponding to specific HCI events // as defined in Bluetooth core v5.4, Vol 4, Part E, 7.3.1. diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothAdapterProxy.java b/android/app/src/com/android/bluetooth/btservice/BluetoothAdapterProxy.java index aeb297dcb0..b7a67a7e66 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothAdapterProxy.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothAdapterProxy.java @@ -30,6 +30,7 @@ import com.android.internal.annotations.VisibleForTesting; */ public class BluetoothAdapterProxy { private static final String TAG = BluetoothAdapterProxy.class.getSimpleName(); + private static BluetoothAdapterProxy sInstance; private static final Object INSTANCE_LOCK = new Object(); diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificDispatcher.java b/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificDispatcher.java index fe40294d20..626e4cf61f 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificDispatcher.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificDispatcher.java @@ -32,7 +32,7 @@ import java.util.Set; import java.util.UUID; class BluetoothHciVendorSpecificDispatcher { - private static final String TAG = "BluetoothHciVendorSpecificDispatcher"; + private static final String TAG = BluetoothHciVendorSpecificDispatcher.class.getSimpleName(); private final class Registration implements IBinder.DeathRecipient { final IBluetoothHciVendorSpecificCallback mCallback; diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificNativeInterface.java b/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificNativeInterface.java index dc3517171c..010b1e6ce5 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificNativeInterface.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothHciVendorSpecificNativeInterface.java @@ -20,7 +20,8 @@ import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; public class BluetoothHciVendorSpecificNativeInterface { - private static final String TAG = "BluetoothHciVendorSpecificNativeInterface"; + private static final String TAG = + BluetoothHciVendorSpecificNativeInterface.class.getSimpleName(); @GuardedBy("INSTANCE_LOCK") private static BluetoothHciVendorSpecificNativeInterface sInstance; diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java b/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java index a97ba6a5cb..2f4c03c17c 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothQualityReportNativeInterface.java @@ -16,6 +16,8 @@ package com.android.bluetooth.btservice; +import static java.util.Objects.requireNonNull; + import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; @@ -29,14 +31,18 @@ import com.android.internal.annotations.VisibleForTesting; /** Native interface to BQR */ public class BluetoothQualityReportNativeInterface { - private static final String TAG = "BluetoothQualityReportNativeInterface"; + private static final String TAG = BluetoothQualityReportNativeInterface.class.getSimpleName(); @GuardedBy("INSTANCE_LOCK") private static BluetoothQualityReportNativeInterface sInstance; private static final Object INSTANCE_LOCK = new Object(); - private BluetoothQualityReportNativeInterface() {} + private final AdapterService mAdapterService; + + private BluetoothQualityReportNativeInterface() { + mAdapterService = requireNonNull(AdapterService.getAdapterService()); + } /** Get singleton instance. */ public static BluetoothQualityReportNativeInterface getInstance() { @@ -84,14 +90,9 @@ public class BluetoothQualityReportNativeInterface { Log.e(TAG, "bqrDeliver failed: adapter is null"); return; } - AdapterService adapterService = AdapterService.getAdapterService(); - if (adapterService == null) { - Log.e(TAG, "bqrDeliver failed: adapterService is null"); - return; - } BluetoothDevice device = adapter.getRemoteDevice(remoteAddress); - BluetoothClass remoteClass = new BluetoothClass(adapterService.getRemoteClass(device)); + BluetoothClass remoteClass = new BluetoothClass(mAdapterService.getRemoteClass(device)); BluetoothQualityReport bqr; try { bqr = @@ -100,7 +101,7 @@ public class BluetoothQualityReportNativeInterface { .setLmpVersion(lmpVer) .setLmpSubVersion(lmpSubVer) .setManufacturerId(manufacturerId) - .setRemoteName(adapterService.getRemoteName(device)) + .setRemoteName(mAdapterService.getRemoteName(device)) .setBluetoothClass(remoteClass) .build(); Log.i(TAG, bqr.toString()); @@ -110,7 +111,7 @@ public class BluetoothQualityReportNativeInterface { } try { - int status = adapterService.bluetoothQualityReportReadyCallback(device, bqr); + int status = mAdapterService.bluetoothQualityReportReadyCallback(device, bqr); if (status != BluetoothStatusCodes.SUCCESS) { Log.e(TAG, "bluetoothQualityReportReadyCallback failed, status: " + status); } diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java index d5309f6ad7..8c9be74c98 100644 --- a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java +++ b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java @@ -32,7 +32,7 @@ import com.android.bluetooth.Utils; import com.android.bluetooth.flags.Flags; class BluetoothSocketManagerBinder extends IBluetoothSocketManager.Stub { - private static final String TAG = "BtSocketManagerBinder"; + private static final String TAG = BluetoothSocketManagerBinder.class.getSimpleName(); private static final int INVALID_FD = -1; diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java index f3132b9c32..1411961bee 100644 --- a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java +++ b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java @@ -65,7 +65,8 @@ import java.util.Set; * state. TODO(BT) This class can be removed and this logic moved to the stack. */ final class BondStateMachine extends StateMachine { - private static final String TAG = "BluetoothBondStateMachine"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + BondStateMachine.class.getSimpleName(); static final int CREATE_BOND = 1; static final int CANCEL_BOND = 2; @@ -764,7 +765,7 @@ final class BondStateMachine extends StateMachine { removeMessages(what); } - private void clearProfilePriority(BluetoothDevice device) { + private static void clearProfilePriority(BluetoothDevice device) { HidHostService hidService = HidHostService.getHidHostService(); A2dpService a2dpService = A2dpService.getA2dpService(); HeadsetService headsetService = HeadsetService.getHeadsetService(); @@ -824,19 +825,19 @@ final class BondStateMachine extends StateMachine { } else return "UNKNOWN(" + state + ")"; } - private void infoLog(String msg) { + private static void infoLog(String msg) { Log.i(TAG, msg); } - private void errorLog(String msg) { + private static void errorLog(String msg) { Log.e(TAG, msg); } - private void warnLog(String msg) { + private static void warnLog(String msg) { Log.w(TAG, msg); } - private int getUnbondReasonFromHALCode(int reason) { + private static int getUnbondReasonFromHALCode(int reason) { if (reason == AbstractionLayer.BT_STATUS_SUCCESS) { return BluetoothDevice.BOND_SUCCESS; } else if (reason == AbstractionLayer.BT_STATUS_RMT_DEV_DOWN) { diff --git a/android/app/src/com/android/bluetooth/btservice/CompanionManager.java b/android/app/src/com/android/bluetooth/btservice/CompanionManager.java index 175e9c5a25..949efd5e1e 100644 --- a/android/app/src/com/android/bluetooth/btservice/CompanionManager.java +++ b/android/app/src/com/android/bluetooth/btservice/CompanionManager.java @@ -28,6 +28,7 @@ import android.util.Log; import androidx.annotation.VisibleForTesting; import com.android.bluetooth.R; +import com.android.bluetooth.Utils; import java.util.HashSet; import java.util.Set; @@ -42,7 +43,8 @@ import java.util.Set; * individual GATT connection parameters. */ public class CompanionManager { - private static final String TAG = "BluetoothCompanionManager"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + CompanionManager.class.getSimpleName(); private BluetoothDevice mCompanionDevice; private int mCompanionType; diff --git a/android/app/src/com/android/bluetooth/btservice/Config.java b/android/app/src/com/android/bluetooth/btservice/Config.java index f372983d7e..dbed62a154 100644 --- a/android/app/src/com/android/bluetooth/btservice/Config.java +++ b/android/app/src/com/android/bluetooth/btservice/Config.java @@ -53,7 +53,8 @@ import com.android.internal.annotations.VisibleForTesting; import java.util.Arrays; public class Config { - private static final String TAG = "AdapterServiceConfig"; + private static final String TAG = + AdapterService.class.getSimpleName() + Config.class.getSimpleName(); private static final String LE_AUDIO_DYNAMIC_SWITCH_PROPERTY = "ro.bluetooth.leaudio_switcher.supported"; diff --git a/android/app/src/com/android/bluetooth/btservice/DataMigration.java b/android/app/src/com/android/bluetooth/btservice/DataMigration.java index f0cdf7214e..ec46a85a38 100644 --- a/android/app/src/com/android/bluetooth/btservice/DataMigration.java +++ b/android/app/src/com/android/bluetooth/btservice/DataMigration.java @@ -32,9 +32,9 @@ import com.android.internal.annotations.VisibleForTesting; import java.util.List; final class DataMigration { - private DataMigration() {} + private static final String TAG = DataMigration.class.getSimpleName(); - private static final String TAG = "DataMigration"; + private DataMigration() {} @VisibleForTesting static final String AUTHORITY = "bluetooth_legacy.provider"; @@ -46,13 +46,13 @@ final class DataMigration { // AvrcpVolumeManager.VOLUME_MAP private static final String VOLUME_MAP_PREFERENCE_FILE = "bluetooth_volume_map"; - // com.android.blueotooth.opp.Constants.BLUETOOTHOPP_CHANNEL_PREFERENCE + // com.android.bluetooth.opp.Constants.BLUETOOTHOPP_CHANNEL_PREFERENCE private static final String BLUETOOTHOPP_CHANNEL_PREFERENCE = "btopp_channels"; - // com.android.blueotooth.opp.Constants.BLUETOOTHOPP_NAME_PREFERENCE + // com.android.bluetooth.opp.Constants.BLUETOOTHOPP_NAME_PREFERENCE private static final String BLUETOOTHOPP_NAME_PREFERENCE = "btopp_names"; - // com.android.blueotooth.opp.OPP_PREFERENCE_FILE + // com.android.bluetooth.opp.OPP_PREFERENCE_FILE private static final String OPP_PREFERENCE_FILE = "OPPMGR"; @VisibleForTesting diff --git a/android/app/src/com/android/bluetooth/btservice/InteropUtil.java b/android/app/src/com/android/bluetooth/btservice/InteropUtil.java index da6eb5b76e..8fe114826f 100644 --- a/android/app/src/com/android/bluetooth/btservice/InteropUtil.java +++ b/android/app/src/com/android/bluetooth/btservice/InteropUtil.java @@ -25,7 +25,7 @@ import android.util.Log; * interop.cc to do matching or entry adding/removing. */ public class InteropUtil { - private static final String TAG = "InteropUtil"; + private static final String TAG = InteropUtil.class.getSimpleName(); /** * Add interop feature from device/include/interop.h to below InteropFeature if this feature diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java index 59b483ba5f..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; @@ -95,7 +97,9 @@ import java.util.List; /** Class of Bluetooth Metrics */ public class MetricsLogger { - private static final String TAG = "BluetoothMetricsLogger"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + MetricsLogger.class.getSimpleName(); + private static final String BLOOMFILTER_PATH = "/data/misc/bluetooth"; private static final String BLOOMFILTER_FILE = "/devices_for_metrics_v3"; private static final String MEDICAL_DEVICE_BLOOMFILTER_FILE = "/medical_devices_for_metrics_v1"; @@ -342,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); @@ -470,7 +474,7 @@ public class MetricsLogger { mAlarmManager.cancel(mOnAlarmListener); } - private void writeFieldIfNotNull( + private static void writeFieldIfNotNull( ProtoOutputStream proto, long fieldType, long fieldCount, @@ -592,7 +596,7 @@ public class MetricsLogger { } } - private int getOui(BluetoothDevice device) { + private static int getOui(BluetoothDevice device) { return Integer.parseInt(device.getAddress().replace(":", "").substring(0, 6), 16); } @@ -805,7 +809,7 @@ public class MetricsLogger { return digest.digest(name.getBytes(StandardCharsets.UTF_8)); } - private int getProfileEnumFromProfileId(int profile) { + private static int getProfileEnumFromProfileId(int profile) { return switch (profile) { case BluetoothProfile.A2DP -> BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP; diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java index 452f4ba6a9..5fbd207c5e 100644 --- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java +++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java @@ -77,7 +77,8 @@ import java.util.List; // will try to connect other profiles on the same device. This is to avoid collision if devices // somehow end up trying to connect at same time or general connection issues. public class PhonePolicy implements AdapterService.BluetoothStateCallback { - private static final String TAG = "BluetoothPhonePolicy"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + PhonePolicy.class.getSimpleName(); private static final String AUTO_CONNECT_PROFILES_PROPERTY = "bluetooth.auto_connect_profiles.enabled"; @@ -1008,8 +1009,7 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback { if (!connectedDevices.contains(device) && (hapClientService.getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) - && (hapClientService.getConnectionState(device) - == BluetoothProfile.STATE_DISCONNECTED)) { + && (hapClientService.getConnectionState(device) == STATE_DISCONNECTED)) { Log.d(TAG, log + "Retrying HAP connection"); hapClientService.connect(device); } diff --git a/android/app/src/com/android/bluetooth/btservice/ProfileService.java b/android/app/src/com/android/bluetooth/btservice/ProfileService.java index 5fdce6626f..8a0fc82555 100644 --- a/android/app/src/com/android/bluetooth/btservice/ProfileService.java +++ b/android/app/src/com/android/bluetooth/btservice/ProfileService.java @@ -25,6 +25,7 @@ import android.os.IBinder; import android.util.Log; import com.android.bluetooth.BluetoothMetricsProto; +import com.android.bluetooth.Utils; /** Base class for a background service that runs a Bluetooth profile */ public abstract class ProfileService extends ContextWrapper { @@ -114,7 +115,12 @@ public abstract class ProfileService extends ContextWrapper { * @param enable True to enable the component, False to disable it */ protected void setComponentAvailable(ComponentName component, boolean enable) { - Log.d(mName, "setComponentAvailable(component=" + component + ", enable=" + enable + ")"); + // Test should not set components available for the device + if (Utils.isInstrumentationTestMode()) { + Log.w(mName, "Skip call to setComponentAvailable(" + component + ", " + enable + ")"); + return; + } + Log.d(mName, "setComponentAvailable(" + component + ", " + enable + ")"); if (component == null) { return; } diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java index 049690da95..77ddffd420 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; @@ -40,7 +42,6 @@ import android.bluetooth.BluetoothProtoEnums; import android.bluetooth.BluetoothSinkAudioPolicy; import android.bluetooth.BluetoothUtils; import android.bluetooth.IBluetoothConnectionCallback; -import android.content.Context; import android.content.Intent; import android.net.MacAddress; import android.os.Handler; @@ -70,7 +71,8 @@ import java.util.function.Predicate; /** Remote device manager. This class is currently mostly used for HF and AG remote devices. */ public class RemoteDevices { - private static final String TAG = "BluetoothRemoteDevices"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + RemoteDevices.class.getSimpleName(); // Maximum number of device properties to remember private static final int MAX_DEVICE_QUEUE_SIZE = 200; @@ -161,7 +163,7 @@ public class RemoteDevices { }; RemoteDevices(AdapterService service, Looper looper) { - mAdapter = ((Context) service).getSystemService(BluetoothManager.class).getAdapter(); + mAdapter = service.getSystemService(BluetoothManager.class).getAdapter(); mAdapterService = service; mSdpTracker = new ArrayList<>(); mDevices = new HashMap<>(); @@ -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); } @@ -1689,11 +1709,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 +1783,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 +1924,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 +1939,7 @@ public class RemoteDevices { Log.e(TAG, "onHeadsetClientConnectionStateChanged() remote device is null"); return; } - if (toState == BluetoothProfile.STATE_DISCONNECTED && !hasBatteryService(device)) { + if (toState == STATE_DISCONNECTED && !hasBatteryService(device)) { resetBatteryLevel(device, /* isBas= */ false); } } diff --git a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java index bbc8dfc521..4d6c706e06 100644 --- a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java +++ b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java @@ -17,6 +17,7 @@ package com.android.bluetooth.btservice; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; @@ -135,13 +136,13 @@ public class SilenceDeviceManager { int prevState = msg.arg1; int nextState = msg.arg2; - if (nextState == BluetoothProfile.STATE_CONNECTED) { + if (nextState == STATE_CONNECTED) { // enter connected state addConnectedDevice(device, BluetoothProfile.A2DP); if (!mSilenceDevices.containsKey(device)) { mSilenceDevices.put(device, false); } - } else if (prevState == BluetoothProfile.STATE_CONNECTED) { + } else if (prevState == STATE_CONNECTED) { // exiting from connected state removeConnectedDevice(device, BluetoothProfile.A2DP); if (!isBluetoothAudioConnected(device)) { @@ -156,13 +157,13 @@ public class SilenceDeviceManager { int prev = msg.arg1; int next = msg.arg2; - if (next == BluetoothProfile.STATE_CONNECTED) { + if (next == STATE_CONNECTED) { // enter connected state addConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET); if (!mSilenceDevices.containsKey(bluetoothDevice)) { mSilenceDevices.put(bluetoothDevice, false); } - } else if (prev == BluetoothProfile.STATE_CONNECTED) { + } else if (prev == STATE_CONNECTED) { // exiting from connected state removeConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET); if (!isBluetoothAudioConnected(bluetoothDevice)) { diff --git a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java index 6c7d69a723..9812509ea0 100644 --- a/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java +++ b/android/app/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreService.java @@ -246,7 +246,7 @@ public class BluetoothKeystoreService { } } - private boolean isFactoryReset() { + private static boolean isFactoryReset() { return SystemProperties.getBoolean("persist.bluetooth.factoryreset", false); } @@ -310,7 +310,7 @@ public class BluetoothKeystoreService { cleanupMemory(); } - private void cleanupFile() throws IOException { + private static void cleanupFile() throws IOException { Files.deleteIfExists(Paths.get(CONFIG_CHECKSUM_ENCRYPTION_PATH)); Files.deleteIfExists(Paths.get(CONFIG_FILE_ENCRYPTION_PATH)); } @@ -676,7 +676,7 @@ public class BluetoothKeystoreService { return output; } - private KeyStore getKeyStore() { + private static KeyStore getKeyStore() { KeyStore keyStore = null; int counter = 0; diff --git a/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java index b790e92c73..76ba89e0a4 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/AudioPolicyEntity.java @@ -50,7 +50,7 @@ class AudioPolicyEntity { return builder.toString(); } - private String metadataToString(int metadata) { + private static String metadataToString(int metadata) { return String.valueOf(metadata); } } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java index 9743bba805..d9fdf936e5 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java @@ -31,7 +31,7 @@ import java.util.List; /** Class for regrouping the migration that occur when going mainline */ public final class BluetoothDatabaseMigration { - private static final String TAG = "BluetoothDatabaseMigration"; + private static final String TAG = BluetoothDatabaseMigration.class.getSimpleName(); public static boolean run(Context ctx, Cursor cursor) { boolean result = true; diff --git a/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java index c100a45495..4b224c24d0 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/CustomizedMetadataEntity.java @@ -117,7 +117,7 @@ class CustomizedMetadataEntity { return builder.toString(); } - private String metadataToString(byte[] metadata) { + private static String metadataToString(byte[] metadata) { if (metadata == null) { return null; } diff --git a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java index 644a1e1196..7874b066c2 100644 --- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java +++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java @@ -65,7 +65,8 @@ import java.util.stream.Collectors; * The active device manager is responsible to handle a Room database for Bluetooth persistent data. */ public class DatabaseManager { - private static final String TAG = "BluetoothDatabase"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + DatabaseManager.class.getSimpleName(); private final AdapterService mAdapterService; private HandlerThread mHandlerThread = null; diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java index 1247cb7330..5480a61463 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorNativeInterface.java @@ -30,7 +30,8 @@ import java.util.UUID; /** CSIP Set Coordinator role native interface */ public class CsipSetCoordinatorNativeInterface { - private static final String TAG = "CsipSetCoordinatorNativeInterface"; + private static final String TAG = CsipSetCoordinatorNativeInterface.class.getSimpleName(); + private final BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); CsipSetCoordinatorNativeInterface() { @@ -57,14 +58,14 @@ public class CsipSetCoordinatorNativeInterface { return mAdapter.getRemoteDevice(address); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } return Utils.getBytesFromAddress(device.getAddress()); } - private void sendMessageToService(CsipSetCoordinatorStackEvent event) { + private static void sendMessageToService(CsipSetCoordinatorStackEvent event) { CsipSetCoordinatorService service = CsipSetCoordinatorService.getCsipSetCoordinatorService(); if (service != null) { diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java index 1e5b936f69..35c4a6721e 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java @@ -19,6 +19,8 @@ package com.android.bluetooth.csip; 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 java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -69,7 +71,7 @@ import java.util.stream.Collectors; /** Provides Bluetooth CSIP Set Coordinator profile, as a service. */ public class CsipSetCoordinatorService extends ProfileService { - private static final String TAG = "CsipSetCoordinatorService"; + private static final String TAG = CsipSetCoordinatorService.class.getSimpleName(); // Timeout for state machine thread join, to prevent potential ANR. private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1000; @@ -330,7 +332,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 +403,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(); } @@ -689,7 +691,7 @@ public class CsipSetCoordinatorService extends ProfileService { } } - private void executeCallback( + private static void executeCallback( Executor exec, IBluetoothCsipSetCoordinatorCallback callback, BluetoothDevice device, @@ -914,7 +916,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 +965,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 +1055,7 @@ public class CsipSetCoordinatorService extends ProfileService { CsipSetCoordinatorService service = getService(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java index 3a7d62745c..6a10b28c8b 100644 --- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java +++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java @@ -18,6 +18,10 @@ 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 android.bluetooth.BluetoothCsipSetCoordinator; import android.bluetooth.BluetoothDevice; @@ -39,7 +43,7 @@ import java.util.Scanner; /** CSIP Set Coordinator role device state machine */ public class CsipSetCoordinatorStateMachine extends StateMachine { - private static final String TAG = "CsipSetCoordinatorStateMachine"; + private static final String TAG = CsipSetCoordinatorStateMachine.class.getSimpleName(); static final int CONNECT = 1; static final int DISCONNECT = 2; @@ -95,6 +99,11 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { return CsisSm; } + @VisibleForTesting + boolean doesSuperHaveDeferredMessages(int what) { + return super.hasDeferredMessages(what); + } + /** Quit state machine execution */ public void doQuit() { log("doQuit for device " + mDevice); @@ -120,7 +129,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { removeDeferredMessages(DISCONNECT); if (mLastConnectionState != -1) { - csipConnectionState(BluetoothProfile.STATE_DISCONNECTED, mLastConnectionState); + csipConnectionState(STATE_DISCONNECTED, mLastConnectionState); } } @@ -131,7 +140,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -243,7 +252,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - csipConnectionState(BluetoothProfile.STATE_CONNECTING, mLastConnectionState); + csipConnectionState(STATE_CONNECTING, mLastConnectionState); } @Override @@ -253,7 +262,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -341,7 +350,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs); - csipConnectionState(BluetoothProfile.STATE_DISCONNECTING, mLastConnectionState); + csipConnectionState(STATE_DISCONNECTING, mLastConnectionState); } @Override @@ -351,7 +360,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING; + mLastConnectionState = STATE_DISCONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -458,7 +467,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + "): " + messageWhatToString(getCurrentMessage().what)); removeDeferredMessages(CONNECT); - csipConnectionState(BluetoothProfile.STATE_CONNECTED, mLastConnectionState); + csipConnectionState(STATE_CONNECTED, mLastConnectionState); } @Override @@ -468,7 +477,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } @Override @@ -540,16 +549,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; } } @@ -593,13 +602,13 @@ public class CsipSetCoordinatorStateMachine extends StateMachine { private static String profileStateToString(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return "DISCONNECTED"; - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: return "CONNECTING"; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: return "CONNECTED"; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: return "DISCONNECTING"; default: break; diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java b/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java index 51f5bb9785..c276e6e017 100644 --- a/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java +++ b/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java @@ -26,8 +26,7 @@ import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; class AdvertiseHelper { - - private static final String TAG = "AdvertiseHelper"; + private static final String TAG = AdvertiseHelper.class.getSimpleName(); private static final int DEVICE_NAME_MAX = 26; diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java index c64774dee3..0f28f6742c 100644 --- a/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java +++ b/android/app/src/com/android/bluetooth/gatt/AdvertiseManager.java @@ -43,7 +43,8 @@ import java.util.concurrent.TimeoutException; /** Manages Bluetooth LE advertising operations. */ public class AdvertiseManager { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "AdvertiseManager"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + AdvertiseManager.class.getSimpleName(); private static final long RUN_SYNC_WAIT_TIME_MS = 2000L; @@ -670,7 +671,7 @@ public class AdvertiseManager { } } - private void sendToCallback(int advertiserId, CallbackWrapper wrapper) { + private static void sendToCallback(int advertiserId, CallbackWrapper wrapper) { try { wrapper.call(); } catch (RemoteException e) { diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java b/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java index c1169f77f3..7917915a2b 100644 --- a/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java +++ b/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java @@ -33,7 +33,8 @@ import java.util.HashMap; /** Helper class that keeps track of advertiser stats. */ class AdvertiserMap { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "AdvertiserMap"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + AdvertiserMap.class.getSimpleName(); /** Internal map to keep track of logging information by advertise id */ @GuardedBy("this") diff --git a/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java b/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java index 1746194f17..4656976850 100644 --- a/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java +++ b/android/app/src/com/android/bluetooth/gatt/AppAdvertiseStats.java @@ -224,7 +224,7 @@ class AppAdvertiseStats { MetricsLogger.getInstance().cacheCount(BluetoothProtoEnums.LE_ADV_ERROR_ON_START_COUNT, 1); } - private int convertStatusCode(int status) { + private static int convertStatusCode(int status) { switch (status) { case AdvertisingSetCallback.ADVERTISE_SUCCESS: return BluetoothStatsLog.LE_ADV_ERROR_REPORTED__STATUS_CODE__ADV_STATUS_SUCCESS; @@ -444,7 +444,7 @@ class AppAdvertiseStats { } } - private int convertAdvInterval(int interval) { + private static int convertAdvInterval(int interval) { switch (interval) { case AdvertisingSetParameters.INTERVAL_HIGH: return BluetoothStatsLog.LE_ADV_STATE_CHANGED__ADV_INTERVAL__INTERVAL_HIGH; @@ -457,7 +457,7 @@ class AppAdvertiseStats { } } - private int convertTxPowerLevel(int level) { + private static int convertTxPowerLevel(int level) { switch (level) { case AdvertisingSetParameters.TX_POWER_ULTRA_LOW: return BluetoothStatsLog.LE_ADV_STATE_CHANGED__ADV_TX_POWER__TX_POWER_ULTRA_LOW; diff --git a/android/app/src/com/android/bluetooth/gatt/ContextMap.java b/android/app/src/com/android/bluetooth/gatt/ContextMap.java index 8ba3e3b671..b725f31b6f 100644 --- a/android/app/src/com/android/bluetooth/gatt/ContextMap.java +++ b/android/app/src/com/android/bluetooth/gatt/ContextMap.java @@ -50,7 +50,9 @@ import java.util.function.Predicate; * @param <C> the callback type for this map */ public class ContextMap<C> { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "ContextMap"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + ContextMap.class.getSimpleName(); + private static final DateTimeFormatter sDateFormat = DateTimeFormatter.ofPattern("MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()); private static final int MAX_LAST_RECORDS = 5; diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java index abadff3ad7..04c6f7fff8 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java @@ -337,7 +337,7 @@ public class DistanceMeasurementManager { return BluetoothStatusCodes.SUCCESS; } - private void invokeStartFail( + private static void invokeStartFail( IDistanceMeasurementCallback callback, BluetoothDevice device, int reason) { try { callback.onStartFail(device, reason); @@ -346,7 +346,7 @@ public class DistanceMeasurementManager { } } - private void invokeOnStopped( + private static void invokeOnStopped( IDistanceMeasurementCallback callback, BluetoothDevice device, int reason) { try { callback.onStopped(device, reason); @@ -356,7 +356,7 @@ public class DistanceMeasurementManager { } /** Convert frequency into interval in ms */ - private int getIntervalValue(int frequency, int method) { + private static int getIntervalValue(int frequency, int method) { switch (method) { case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_AUTO: case DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI: diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java index ad8a7f9bd4..5992a7b9ce 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java @@ -127,7 +127,7 @@ public class DistanceMeasurementNativeInterface { method); } - private int convertErrorCode(int errorCode) { + private static int convertErrorCode(int errorCode) { switch (errorCode) { case REASON_FEATURE_NOT_SUPPORTED_LOCAL: return BluetoothStatusCodes.FEATURE_NOT_SUPPORTED; diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementTracker.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementTracker.java index 161bcb3431..adebbd0d33 100644 --- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementTracker.java +++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementTracker.java @@ -27,7 +27,7 @@ import java.util.UUID; /** Manages information of apps that registered distance measurement */ class DistanceMeasurementTracker { - private static final String TAG = "DistanceMeasurementTracker"; + private static final String TAG = DistanceMeasurementTracker.class.getSimpleName(); final DistanceMeasurementManager mManager; final BluetoothDevice mDevice; diff --git a/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java b/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java index 04f28151d1..5df28f5336 100644 --- a/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java +++ b/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java @@ -27,7 +27,9 @@ import java.util.UUID; /** Helper class containing useful tools for GATT service debugging. */ /*package*/ class GattDebugUtils { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "DebugUtils"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + GattDebugUtils.class.getSimpleName(); + private static final boolean DEBUG_ADMIN = GattServiceConfig.DEBUG_ADMIN; @VisibleForTesting diff --git a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java index 257e42b398..529ac579cf 100644 --- a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java +++ b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java @@ -24,6 +24,7 @@ import com.android.bluetooth.btservice.AdapterService; /** Factory class for object initialization to help with unit testing */ public class GattObjectsFactory { private static final String TAG = GattObjectsFactory.class.getSimpleName(); + private static GattObjectsFactory sInstance; private static final Object INSTANCE_LOCK = new Object(); diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java index e4d6c225d6..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; @@ -87,7 +89,8 @@ import java.util.stream.Stream; /** Provides Bluetooth Gatt profile, as a service in the Bluetooth application. */ public class GattService extends ProfileService { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "GattService"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + GattService.class.getSimpleName(); private static final UUID HID_SERVICE_UUID = UUID.fromString("00001812-0000-1000-8000-00805F9B34FB"); @@ -1471,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); } } @@ -1484,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); } } @@ -2981,11 +2984,11 @@ public class GattService extends ProfileService { * Private functions *************************************************************************/ - private boolean isHidSrvcUuid(final UUID uuid) { + private static boolean isHidSrvcUuid(final UUID uuid) { return HID_SERVICE_UUID.equals(uuid); } - private boolean isHidCharUuid(final UUID uuid) { + private static boolean isHidCharUuid(final UUID uuid) { for (UUID hidUuid : HID_UUIDS) { if (hidUuid.equals(uuid)) { return true; @@ -2994,15 +2997,15 @@ public class GattService extends ProfileService { return false; } - private boolean isAndroidTvRemoteSrvcUuid(final UUID uuid) { + private static boolean isAndroidTvRemoteSrvcUuid(final UUID uuid) { return ANDROID_TV_REMOTE_SERVICE_UUID.equals(uuid); } - private boolean isFidoSrvcUuid(final UUID uuid) { + private static boolean isFidoSrvcUuid(final UUID uuid) { return FIDO_SERVICE_UUID.equals(uuid); } - private boolean isLeAudioSrvcUuid(final UUID uuid) { + private static boolean isLeAudioSrvcUuid(final UUID uuid) { for (UUID leAudioUuid : LE_AUDIO_SERVICE_UUIDS) { if (leAudioUuid.equals(uuid)) { return true; @@ -3011,11 +3014,11 @@ public class GattService extends ProfileService { return false; } - private boolean isAndroidHeadtrackerSrvcUuid(final UUID uuid) { + private static boolean isAndroidHeadtrackerSrvcUuid(final UUID uuid) { return HidHostService.ANDROID_HEADTRACKER_UUID.getUuid().equals(uuid); } - private boolean isRestrictedSrvcUuid(final UUID uuid) { + private static boolean isRestrictedSrvcUuid(final UUID uuid) { return isFidoSrvcUuid(uuid) || isAndroidTvRemoteSrvcUuid(uuid) || isLeAudioSrvcUuid(uuid) diff --git a/android/app/src/com/android/bluetooth/gatt/HandleMap.java b/android/app/src/com/android/bluetooth/gatt/HandleMap.java index 1e0839d0f7..8e0ce8023e 100644 --- a/android/app/src/com/android/bluetooth/gatt/HandleMap.java +++ b/android/app/src/com/android/bluetooth/gatt/HandleMap.java @@ -24,7 +24,8 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; class HandleMap { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "HandleMap"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + HandleMap.class.getSimpleName(); public static final int TYPE_UNDEFINED = 0; public static final int TYPE_SERVICE = 1; diff --git a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java index 05b6963739..8bb7cc0db5 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java @@ -18,6 +18,7 @@ package com.android.bluetooth.hap; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -44,6 +45,7 @@ import java.util.List; class HapClientBinder extends IBluetoothHapClient.Stub implements ProfileService.IProfileServiceBinder { private static final String TAG = HapClientBinder.class.getSimpleName(); + private HapClientService mService; HapClientBinder(HapClientService svc) { @@ -101,7 +103,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); diff --git a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java index 6160e4efa9..42d234c346 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientNativeInterface.java @@ -43,7 +43,7 @@ public class HapClientNativeInterface { return disconnectHapClientNative(getByteAddress(device)); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java index e4c020f61b..ba18faf23d 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientService.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java @@ -21,6 +21,7 @@ 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 java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -225,7 +226,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 +265,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 +309,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(); } @@ -392,7 +393,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"); @@ -620,7 +621,7 @@ public class HapClientService extends ProfileService { return 0x00; } - private int stackEventPresetInfoReasonToProfileStatus(int statusCode) { + private static int stackEventPresetInfoReasonToProfileStatus(int statusCode) { return switch (statusCode) { case HapClientStackEvent.PRESET_INFO_REASON_ALL_PRESET_INFO -> BluetoothStatusCodes.REASON_LOCAL_STACK_REQUEST; @@ -648,7 +649,7 @@ public class HapClientService extends ProfileService { stackEventPresetInfoReasonToProfileStatus(infoReason))); } - private int stackEventStatusToProfileStatus(int statusCode) { + private static int stackEventStatusToProfileStatus(int statusCode) { return switch (statusCode) { case HapClientStackEvent.STATUS_SET_NAME_NOT_ALLOWED -> BluetoothStatusCodes.ERROR_REMOTE_OPERATION_REJECTED; diff --git a/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java b/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java index a0e978ef1d..02e03f88c9 100644 --- a/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java +++ b/android/app/src/com/android/bluetooth/hap/HapClientStackEvent.java @@ -101,7 +101,7 @@ public class HapClientStackEvent { return result.toString(); } - private String eventTypeValueListToString(int type, List value) { + private static String eventTypeValueListToString(int type, List value) { switch (type) { case EVENT_TYPE_ON_PRESET_INFO: return "{presets count: " + (value == null ? 0 : value.size()) + "}"; @@ -110,7 +110,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt1ToString(int type, int value) { + private static String eventTypeValueInt1ToString(int type, int value) { switch (type) { case EVENT_TYPE_CONNECTION_STATE_CHANGED: return "{state: " + getConnectionStateName(value) + "}"; @@ -132,7 +132,7 @@ public class HapClientStackEvent { } } - private String infoReasonToString(int value) { + private static String infoReasonToString(int value) { switch (value) { case PRESET_INFO_REASON_ALL_PRESET_INFO: return "PRESET_INFO_REASON_ALL_PRESET_INFO"; @@ -149,7 +149,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt2ToString(int type, int value) { + private static String eventTypeValueInt2ToString(int type, int value) { switch (type) { case EVENT_TYPE_ON_PRESET_NAME_SET_ERROR: return "{presetIndex: " + value + "}"; @@ -166,7 +166,7 @@ public class HapClientStackEvent { } } - private String eventTypeValueInt3ToString(int type, int value) { + private static String eventTypeValueInt3ToString(int type, int value) { switch (type) { case EVENT_TYPE_ON_PRESET_INFO: case EVENT_TYPE_ON_PRESET_INFO_ERROR: @@ -177,7 +177,7 @@ public class HapClientStackEvent { } } - private String statusCodeValueToString(int value) { + private static String statusCodeValueToString(int value) { switch (value) { case STATUS_NO_ERROR: return "STATUS_NO_ERROR"; @@ -200,7 +200,7 @@ public class HapClientStackEvent { } } - private String featuresToString(int value) { + private static String featuresToString(int value) { StringBuilder features_sb = new StringBuilder(); if (BigInteger.valueOf(value).testBit(FEATURE_BIT_NUM_TYPE_MONAURAL)) { features_sb.append("TYPE_MONAURAL"); diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java index a0639cfe7b..ae01feab9f 100644 --- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidNativeInterface.java @@ -31,7 +31,8 @@ import com.android.internal.annotations.VisibleForTesting; /** HearingAid Native Interface to/from JNI. */ public class HearingAidNativeInterface { - private static final String TAG = "HearingAidNativeInterface"; + private static final String TAG = HearingAidNativeInterface.class.getSimpleName(); + private BluetoothAdapter mAdapter; @GuardedBy("INSTANCE_LOCK") diff --git a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java index 03ffba8c78..8e2d0bd09f 100644 --- a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java +++ b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java @@ -18,10 +18,11 @@ package com.android.bluetooth.hfp; import static android.Manifest.permission.BLUETOOTH_CONNECT; +import static java.util.Objects.requireNonNull; + import android.app.Activity; import android.bluetooth.BluetoothDevice; import android.content.ContentResolver; -import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; @@ -45,7 +46,8 @@ import java.util.HashMap; /** Helper for managing phonebook presentation over AT commands */ public class AtPhonebook { - private static final String TAG = "BluetoothAtPhonebook"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + AtPhonebook.class.getSimpleName(); /** * The projection to use when querying the call log database in response to AT+CPBR for the MC, @@ -80,9 +82,10 @@ public class AtPhonebook { public int nameColumn; } - private Context mContext; - private ContentResolver mContentResolver; - private HeadsetNativeInterface mNativeInterface; + private final AdapterService mAdapterService; + private final ContentResolver mContentResolver; + private final HeadsetNativeInterface mNativeInterface; + @VisibleForTesting String mCurrentPhonebook; @VisibleForTesting String mCharacterSet = "UTF-8"; @@ -100,13 +103,15 @@ public class AtPhonebook { static final int TYPE_SET = 1; static final int TYPE_TEST = 2; - public AtPhonebook(Context context, HeadsetNativeInterface nativeInterface) { - mContext = context; + public AtPhonebook(AdapterService adapterService, HeadsetNativeInterface nativeInterface) { + mAdapterService = requireNonNull(adapterService); + mContentResolver = requireNonNull(mAdapterService.getContentResolver()); + mNativeInterface = requireNonNull(nativeInterface); + mPairingPackage = SystemProperties.get( - Utils.PAIRING_UI_PROPERTY, context.getString(R.string.pairing_ui_package)); - mContentResolver = context.getContentResolver(); - mNativeInterface = nativeInterface; + Utils.PAIRING_UI_PROPERTY, + mAdapterService.getString(R.string.pairing_ui_package)); mPhonebooks.put("DC", new PhonebookResult()); // dialled calls mPhonebooks.put("RC", new PhonebookResult()); // received calls mPhonebooks.put("MC", new PhonebookResult()); // missed calls @@ -458,7 +463,7 @@ public class AtPhonebook { Bundle queryArgs = new Bundle(); queryArgs.putString(ContentResolver.QUERY_ARG_SQL_SELECTION, where); queryArgs.putInt(ContentResolver.QUERY_ARG_LIMIT, MAX_PHONEBOOK_SIZE); - final Uri phoneContentUri = DevicePolicyUtils.getEnterprisePhoneUri(mContext); + final Uri phoneContentUri = DevicePolicyUtils.getEnterprisePhoneUri(mAdapterService); pbr.cursor = BluetoothMethodProxy.getInstance() .contentResolverQuery( @@ -501,7 +506,7 @@ public class AtPhonebook { return roundUpToPowerOfTwo(maxSize); } - private int roundUpToPowerOfTwo(int x) { + private static int roundUpToPowerOfTwo(int x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; @@ -620,7 +625,7 @@ public class AtPhonebook { number = ""; // TODO: there are 3 types of numbers should have resource // strings for: unknown, private, and payphone - name = mContext.getString(R.string.unknownNumber); + name = mAdapterService.getString(R.string.unknownNumber); } // TODO(): Handle IRA commands. It's basically @@ -628,7 +633,7 @@ public class AtPhonebook { if (!name.isEmpty() && mCharacterSet.equals("GSM")) { byte[] nameByte = GsmAlphabet.stringToGsm8BitPacked(name); if (nameByte == null) { - name = mContext.getString(R.string.unknownNumber); + name = mAdapterService.getString(R.string.unknownNumber); } else { name = new String(nameByte); } @@ -658,7 +663,7 @@ public class AtPhonebook { intent.putExtra(BluetoothDevice.EXTRA_DEVICE, remoteDevice); // Leave EXTRA_PACKAGE_NAME and EXTRA_CLASS_NAME field empty. // BluetoothHandsfree's broadcast receiver is anonymous, cannot be targeted. - mContext.sendOrderedBroadcast( + mAdapterService.sendOrderedBroadcast( intent, BLUETOOTH_CONNECT, Utils.getTempBroadcastOptions().toBundle(), @@ -679,8 +684,7 @@ public class AtPhonebook { */ @VisibleForTesting int checkAccessPermission(BluetoothDevice remoteDevice) { - int permission = - AdapterService.getAdapterService().getPhonebookAccessPermission(remoteDevice); + int permission = mAdapterService.getPhonebookAccessPermission(remoteDevice); if (permission == BluetoothDevice.ACCESS_UNKNOWN) { Log.d(TAG, "checkAccessPermission: ACCESS_UNKNOWN, requesting permissions"); diff --git a/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java b/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java index 99cb4e3af4..96a573ffd2 100644 --- a/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java +++ b/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java @@ -48,12 +48,6 @@ public class BluetoothHeadsetProxy { } @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public void clccResponse( - int index, int direction, int status, int mode, boolean mpty, String number, int type) { - mBluetoothHeadset.clccResponse(index, direction, status, mode, mpty, number, type); - } - - @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); diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java index 0c5dcad50e..9dbcd6d4e8 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java @@ -34,7 +34,7 @@ import com.android.internal.annotations.VisibleForTesting; * file. */ public class HeadsetNativeInterface { - private static final String TAG = "HeadsetNativeInterface"; + private static final String TAG = HeadsetNativeInterface.class.getSimpleName(); private final BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter(); @@ -71,12 +71,12 @@ public class HeadsetNativeInterface { } } - private void sendMessageToService(HeadsetStackEvent event) { + private static void sendMessageToService(HeadsetStackEvent event) { HeadsetService service = HeadsetService.getHeadsetService(); if (service != null) { service.messageFromNative(event); } else { - // Service must call cleanup() when quiting and native stack shouldn't send any event + // Service must call cleanup() when quitting and native stack shouldn't send any event // after cleanup() -> cleanupNative() is called. Log.w(TAG, "Stack sent event while service is not available: " + event); } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetObjectsFactory.java b/android/app/src/com/android/bluetooth/hfp/HeadsetObjectsFactory.java index 2f2a80088f..3e2948c382 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetObjectsFactory.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetObjectsFactory.java @@ -25,6 +25,7 @@ import com.android.bluetooth.btservice.AdapterService; /** Factory class for object initialization to help with unit testing */ public class HeadsetObjectsFactory { private static final String TAG = HeadsetObjectsFactory.class.getSimpleName(); + private static HeadsetObjectsFactory sInstance; private static final Object INSTANCE_LOCK = new Object(); diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java b/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java index 75d0ebaf4b..0350085539 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java @@ -44,7 +44,7 @@ import java.util.concurrent.Executor; * Call them from the HeadsetPhoneStateMachine message handler only. */ public class HeadsetPhoneState { - private static final String TAG = "HeadsetPhoneState"; + private static final String TAG = HeadsetPhoneState.class.getSimpleName(); private final HeadsetService mHeadsetService; private final TelephonyManager mTelephonyManager; diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java index 60f39ec7e5..f0dd2816be 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java @@ -19,6 +19,9 @@ 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.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; @@ -109,7 +112,7 @@ import java.util.Optional; * Handsfree device, device running headset client, e.g. Wireless headphones or car kits */ public class HeadsetService extends ProfileService { - private static final String TAG = "HeadsetService"; + private static final String TAG = HeadsetService.class.getSimpleName(); /** HFP AG owned/managed components */ private static final String HFP_AG_IN_CALL_SERVICE = @@ -120,9 +123,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 +506,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 +591,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); @@ -783,25 +784,6 @@ public class HeadsetService extends ProfileService { } @Override - public void clccResponse( - int index, - int direction, - int status, - int mode, - boolean mpty, - String number, - int type, - AttributionSource source) { - HeadsetService service = getService(source); - if (service == null) { - return; - } - - service.enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, null); - service.clccResponse(index, direction, status, mode, mpty, number, type); - } - - @Override public boolean sendVendorSpecificResultCode( BluetoothDevice device, String command, String arg, AttributionSource source) { HeadsetService service = getService(source); @@ -900,8 +882,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 " @@ -948,8 +929,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 " @@ -967,7 +947,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()); } } @@ -1013,7 +993,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(); } @@ -1148,8 +1128,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; } @@ -1222,8 +1201,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; } @@ -1376,7 +1354,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; } @@ -1447,7 +1425,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 " @@ -1582,7 +1560,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; } @@ -2072,8 +2050,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=" @@ -2086,7 +2063,7 @@ public class HeadsetService extends ProfileService { } } - void clccResponse( + public void clccResponse( int index, int direction, int status, int mode, boolean mpty, String number, int type) { mPendingClccResponses.add( stateMachine -> @@ -2113,7 +2090,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,7 +2136,7 @@ public class HeadsetService extends ProfileService { && !isHeadsetClientConnected(); } - private boolean isHeadsetClientConnected() { + private static boolean isHeadsetClientConnected() { HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); if (headsetClientService == null) { return false; @@ -2178,13 +2155,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); diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java index 30d252f70c..d8391f68c0 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java @@ -17,16 +17,18 @@ package com.android.bluetooth.hfp; import static android.Manifest.permission.BLUETOOTH_CONNECT; -import static android.Manifest.permission.MODIFY_PHONE_STATE; 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; import static java.util.Objects.requireNonNull; -import android.annotation.RequiresPermission; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAssignedNumbers; import android.bluetooth.BluetoothDevice; @@ -55,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; @@ -546,7 +549,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnected extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @Override @@ -574,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 @@ -582,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); @@ -590,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; @@ -654,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( @@ -666,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: @@ -703,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)); } @@ -717,7 +737,7 @@ class HeadsetStateMachine extends StateMachine { class Connecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } @Override @@ -750,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; } @@ -899,7 +923,7 @@ class HeadsetStateMachine extends StateMachine { class Disconnecting extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; } @Override @@ -990,7 +1014,7 @@ class HeadsetStateMachine extends StateMachine { private abstract class ConnectedBase extends HeadsetStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } /** @@ -1286,6 +1310,9 @@ class HeadsetStateMachine extends StateMachine { broadcastStateTransitions(); logSuccessIfNeeded(); + logHfpSessionMetric( + mDevice, + BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECTED); } @Override @@ -1309,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); @@ -1422,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)); } @@ -2174,7 +2198,6 @@ class HeadsetStateMachine extends StateMachine { } @VisibleForTesting - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) void processAtClcc(BluetoothDevice device) { if (mHeadsetService.isVirtualCallStarted()) { // In virtual call, send our phone number instead of remote phone number @@ -2187,7 +2210,7 @@ class HeadsetStateMachine extends StateMachine { mNativeInterface.clccResponse(device, 0, 0, 0, 0, false, "", 0); } else { // In Telecom call, ask Telecom to send send remote phone number - if (!mSystemInterface.listCurrentCalls()) { + if (!mSystemInterface.listCurrentCalls(mHeadsetService)) { Log.e(TAG, "processAtClcc: failed to list current calls for " + device); mNativeInterface.clccResponse(device, 0, 0, 0, 0, false, "", 0); } else { @@ -2655,6 +2678,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; @@ -2840,4 +2868,14 @@ class HeadsetStateMachine extends StateMachine { return "UNKNOWN(" + what + ")"; } } + + private static void logHfpSessionMetric(BluetoothDevice device, int state) { + MetricsLogger.getInstance() + .logBluetoothEvent( + device, + BluetoothStatsLog + .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__HFP_SESSION, + state, + 0); + } } diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java index 7ebf5545c7..78e350fc37 100644 --- a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java +++ b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java @@ -68,7 +68,7 @@ class HeadsetSystemInterface { mTelecomManager = mHeadsetService.getSystemService(TelecomManager.class); } - private BluetoothInCallService getBluetoothInCallServiceInstance() { + private static BluetoothInCallService getBluetoothInCallServiceInstance() { return BluetoothInCallService.getInstance(); } @@ -274,18 +274,17 @@ class HeadsetSystemInterface { } /** - * Ask the Telecomm service to list current list of calls through CLCC response {@link + * Ask the Telecom service to list current list of calls through CLCC response {@link * BluetoothHeadset#clccResponse(int, int, int, int, boolean, String, int)} */ @VisibleForTesting - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public boolean listCurrentCalls() { + public boolean listCurrentCalls(HeadsetService headsetService) { BluetoothInCallService bluetoothInCallService = getBluetoothInCallServiceInstance(); if (bluetoothInCallService == null) { Log.e(TAG, "listCurrentCalls() failed: mBluetoothInCallService is null"); return false; } - return bluetoothInCallService.listCurrentCalls(); + return bluetoothInCallService.listCurrentCalls(headsetService); } /** diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java index 83c0d90f7a..98f0d15d01 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java @@ -18,6 +18,9 @@ package com.android.bluetooth.hfpclient; 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.content.pm.PackageManager.FEATURE_WATCH; import static java.util.Objects.requireNonNull; @@ -366,7 +369,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); @@ -672,8 +675,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 +691,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 +729,7 @@ public class HeadsetClientService extends ProfileService { return sm.getConnectionState(device); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -780,7 +782,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 +796,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 +936,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 +959,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 +973,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 +990,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 +1007,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 +1025,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 +1043,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 +1079,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 +1100,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 +1114,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 +1131,7 @@ public class HeadsetClientService extends ProfileService { } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return false; } @@ -1155,7 +1150,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 +1163,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 +1176,7 @@ public class HeadsetClientService extends ProfileService { return null; } int connectionState = sm.getConnectionState(device); - if (connectionState != BluetoothProfile.STATE_CONNECTED) { + if (connectionState != STATE_CONNECTED) { return null; } return sm.getCurrentAgFeatures(); @@ -1200,7 +1195,7 @@ public class HeadsetClientService extends ProfileService { sm.sendMessage(StackEvent.STACK_EVENT, stackEvent); } - private boolean isConnectionEvent(StackEvent stackEvent) { + private static boolean isConnectionEvent(StackEvent stackEvent) { if (stackEvent.type == StackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED) { if ((stackEvent.valueInt == HeadsetClientHalConstants.CONNECTION_STATE_CONNECTING) || (stackEvent.valueInt diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java index cade6848d7..9cf8237e09 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientServiceInterface.java @@ -29,7 +29,7 @@ import java.util.Set; * <p>Deals with service lifecycle and returns consistent error values */ public class HeadsetClientServiceInterface { - private static final String TAG = "HeadsetClientServiceInterface"; + private static final String TAG = HeadsetClientServiceInterface.class.getSimpleName(); /* Action policy for other calls when accepting call */ public static final int CALL_ACCEPT_NONE = 0; @@ -38,7 +38,7 @@ public class HeadsetClientServiceInterface { public HeadsetClientServiceInterface() {} - private boolean isServiceAvailable(HeadsetClientService service) { + private static boolean isServiceAvailable(HeadsetClientService service) { if (service == null) { Log.w(TAG, "HeadsetClientService is not available"); return false; diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java index 123cf5eb7a..b8b689a200 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java @@ -33,6 +33,10 @@ package com.android.bluetooth.hfpclient; 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 android.content.pm.PackageManager.FEATURE_WATCH; import static java.util.Objects.requireNonNull; @@ -881,7 +885,7 @@ public class HeadsetClientStateMachine extends StateMachine { return features; } - private boolean isSupported(int bitfield, int mask) { + private static boolean isSupported(int bitfield, int mask) { return (bitfield & mask) == mask; } @@ -1053,21 +1057,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 +1093,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 +1145,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 +1173,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 +1344,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 +1380,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 +1949,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 +2170,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 +2284,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); @@ -2517,7 +2493,7 @@ public class HeadsetClientStateMachine extends StateMachine { return mAudioRouteAllowed; } - private String createMaskString(BluetoothSinkAudioPolicy policies) { + private static String createMaskString(BluetoothSinkAudioPolicy policies) { StringBuilder mask = new StringBuilder(); mask.append(BluetoothSinkAudioPolicy.HFP_SET_SINK_AUDIO_POLICY_ID); mask.append(",").append(policies.getCallEstablishPolicy()); @@ -2582,7 +2558,7 @@ public class HeadsetClientStateMachine extends StateMachine { } /** handles the value of {@link BluetoothSinkAudioPolicy} from system property */ - private int getAudioPolicySystemProp(String propKey) { + private static int getAudioPolicySystemProp(String propKey) { int mProp = SystemProperties.getInt(propKey, BluetoothSinkAudioPolicy.POLICY_UNCONFIGURED); if (mProp < BluetoothSinkAudioPolicy.POLICY_UNCONFIGURED || mProp > BluetoothSinkAudioPolicy.POLICY_NOT_ALLOWED) { diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConference.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConference.java index 7d49d2254f..1d42fc6240 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConference.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConference.java @@ -22,7 +22,7 @@ import android.telecom.PhoneAccountHandle; import android.util.Log; public class HfpClientConference extends Conference { - private static final String TAG = "HfpClientConference"; + private static final String TAG = HfpClientConference.class.getSimpleName(); private final BluetoothDevice mDevice; private final HeadsetClientServiceInterface mServiceInterface; diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java index 4b2dae00b0..792953a634 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java @@ -15,6 +15,9 @@ */ package com.android.bluetooth.hfpclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; @@ -59,7 +62,7 @@ public class HfpClientConnectionService extends ConnectionService { private static final Object INSTANCE_LOCK = new Object(); private static HfpClientConnectionService sHfpClientConnectionService; - private void setInstance(HfpClientConnectionService instance) { + private static void setInstance(HfpClientConnectionService instance) { synchronized (INSTANCE_LOCK) { sHfpClientConnectionService = instance; } @@ -120,14 +123,14 @@ public class HfpClientConnectionService extends ConnectionService { private void onConnectionStateChangedInternal( BluetoothDevice device, int newState, int oldState) { - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { Log.d(TAG, "Established connection with " + device); HfpClientDeviceBlock block = createBlockForDevice(device); if (block == null) { Log.w(TAG, "Block already exists for device= " + device + ", ignoring."); } - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { + } else if (newState == STATE_DISCONNECTED) { Log.d(TAG, "Disconnecting from " + device); // Disconnect any inflight calls from the connection service. diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java index aa259bebb3..f33acb586d 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java +++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java @@ -320,7 +320,7 @@ public class HfpClientDeviceBlock { } } - private Bundle getScoStateFromDevice(BluetoothDevice device) { + private static Bundle getScoStateFromDevice(BluetoothDevice device) { Bundle bundle = new Bundle(); HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); diff --git a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java index fbe6e2f299..603beae96b 100644 --- a/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java +++ b/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java @@ -35,7 +35,6 @@ import java.util.Map; import java.util.Objects; class VendorCommandResponseProcessor { - private static final String TAG = VendorCommandResponseProcessor.class.getSimpleName(); private final HeadsetClientService mService; @@ -114,7 +113,7 @@ class VendorCommandResponseProcessor { return true; } - private String getVendorIdFromAtCommand(String atString) { + private static String getVendorIdFromAtCommand(String atString) { // Get event code int indexOfEqual = atString.indexOf('='); int indexOfColon = atString.indexOf(':'); diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java b/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java index e4ae3da3b9..81da626bc8 100644 --- a/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java +++ b/android/app/src/com/android/bluetooth/hid/HidDeviceNativeInterface.java @@ -34,7 +34,8 @@ import com.android.internal.annotations.VisibleForTesting; /** HID Device Native Interface to/from JNI. */ public class HidDeviceNativeInterface { - private static final String TAG = "HidDeviceNativeInterface"; + private static final String TAG = HidDeviceNativeInterface.class.getSimpleName(); + private final AdapterService mAdapterService; HidDeviceNativeInterface(AdapterService adapterService) { diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java index 9068d666a8..6342798001 100644 --- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java +++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java @@ -18,6 +18,10 @@ package com.android.bluetooth.hid; 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; import static java.util.Objects.requireNonNullElseGet; @@ -493,8 +497,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 @@ -884,7 +887,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 +902,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 73d8557f23..d2c82279e9 100644 --- a/android/app/src/com/android/bluetooth/hid/HidHostService.java +++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java @@ -18,6 +18,9 @@ package com.android.bluetooth.hid; 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.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -68,8 +71,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 +125,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 +156,8 @@ public class HidHostService extends ProfileService { if (mInputDevices != null) { for (BluetoothDevice device : mInputDevices.keySet()) { // Set both HID and HOGP connection states to disconnected - updateConnectionState( - device, BluetoothDevice.TRANSPORT_LE, BluetoothProfile.STATE_DISCONNECTED); - updateConnectionState( - device, - BluetoothDevice.TRANSPORT_BREDR, - BluetoothProfile.STATE_DISCONNECTED); + updateConnectionState(device, BluetoothDevice.TRANSPORT_LE, STATE_DISCONNECTED); + updateConnectionState(device, BluetoothDevice.TRANSPORT_BREDR, STATE_DISCONNECTED); } mInputDevices.clear(); } @@ -210,7 +205,7 @@ public class HidHostService extends ProfileService { * @param device remote device * @return address type */ - private int getAddressType(BluetoothDevice device) { + private static int getAddressType(BluetoothDevice device) { return device.getAddressType(); } @@ -265,7 +260,7 @@ public class HidHostService extends ProfileService { return inputDevice.getState(transport); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } public static synchronized HidHostService getHidHostService() { @@ -416,9 +411,10 @@ public class HidHostService extends ProfileService { + (" device=" + device) + (" transport: prev=" + prevTransport + " -> new=" + transport)); - // Save the preferred transport InputDevice inputDevice = getOrCreateInputDevice(device); - inputDevice.mSelectedTransport = transport; + if (!Flags.ignoreUnselectedHidTransportStates()) { + inputDevice.mSelectedTransport = transport; + } /* If connections are allowed, ensure that the previous transport is disconnected and the new transport is connected */ @@ -431,11 +427,20 @@ public class HidHostService extends ProfileService { + (" transport: prev=" + prevTransport + " -> new=" + transport)); // Disconnect the other transport and disallow reconnections nativeDisconnect(device, prevTransport, false); - + 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, STATE_DISCONNECTED); + } // Request to connect the preferred transport nativeConnect(device, transport); } } + + if (Flags.ignoreUnselectedHidTransportStates()) { + // Save the preferred transport + inputDevice.mSelectedTransport = transport; + } } private void handleMessageSetIdleTime(Message msg) { @@ -471,7 +476,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; @@ -612,25 +617,28 @@ public class HidHostService extends ProfileService { + (" transport=" + transport) + (" newState=" + state) + (" prevState=" + prevState)); + if (Flags.ignoreUnselectedHidTransportStates()) { + return; + } } Log.d( TAG, "handleMessageConnectStateChanged:" + (" device=" + device) + + (" transport=" + transport) + (" newState=" + state) + (" 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); } @@ -760,15 +768,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 @@ -917,7 +924,7 @@ 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; } @@ -971,7 +978,7 @@ public class HidHostService extends ProfileService { if (inputDevice != null) { return inputDevice.getState(); } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @VisibleForTesting @@ -1078,7 +1085,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); @@ -1090,7 +1097,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); @@ -1102,7 +1109,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); @@ -1116,7 +1123,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); @@ -1134,7 +1141,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); @@ -1151,7 +1158,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; } @@ -1166,7 +1173,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); @@ -1177,7 +1184,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); @@ -1287,7 +1294,7 @@ public class HidHostService extends ProfileService { return; } - if (newState == BluetoothProfile.STATE_CONNECTED) { + if (newState == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HID_HOST); } diff --git a/android/app/src/com/android/bluetooth/le_audio/ContentControlIdKeeper.java b/android/app/src/com/android/bluetooth/le_audio/ContentControlIdKeeper.java index 920d6fde33..3025d1df0e 100644 --- a/android/app/src/com/android/bluetooth/le_audio/ContentControlIdKeeper.java +++ b/android/app/src/com/android/bluetooth/le_audio/ContentControlIdKeeper.java @@ -34,7 +34,7 @@ import java.util.TreeSet; /** This class keeps Content Control Ids for LE Audio profiles. */ public class ContentControlIdKeeper { - private static final String TAG = "ContentControlIdKeeper"; + private static final String TAG = ContentControlIdKeeper.class.getSimpleName(); public static final int CCID_INVALID = 0; public static final int CCID_MIN = 0x01; diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java index 65b2d0a07d..b34f2a989d 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioBroadcasterNativeInterface.java @@ -33,7 +33,8 @@ import com.android.internal.annotations.VisibleForTesting; /** LeAudio Native Interface to/from JNI. */ public class LeAudioBroadcasterNativeInterface { - private static final String TAG = "LeAudioBroadcasterNativeInterface"; + private static final String TAG = LeAudioBroadcasterNativeInterface.class.getSimpleName(); + private BluetoothAdapter mAdapter; @GuardedBy("INSTANCE_LOCK") @@ -66,7 +67,7 @@ public class LeAudioBroadcasterNativeInterface { } } - private void sendMessageToService(LeAudioStackEvent event) { + private static void sendMessageToService(LeAudioStackEvent event) { LeAudioService service = LeAudioService.getLeAudioService(); if (service != null) { service.messageFromNative(event); diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java index 334475d443..dcdc56c67e 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioCodecConfig.java @@ -25,7 +25,7 @@ import android.util.Log; * LeAudio Codec Configuration setup. */ class LeAudioCodecConfig { - private static final String TAG = "LeAudioCodecConfig"; + private static final String TAG = LeAudioCodecConfig.class.getSimpleName(); private Context mContext; private BluetoothLeAudioCodecConfig[] mCodecConfigOffloading = diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java index a501c6d8a7..e2d1490c9f 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioNativeInterface.java @@ -69,14 +69,14 @@ public class LeAudioNativeInterface { } } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } return Utils.getBytesFromAddress(device.getAddress()); } - private void sendMessageToService(LeAudioStackEvent event) { + private static void sendMessageToService(LeAudioStackEvent event) { LeAudioService service = LeAudioService.getLeAudioService(); if (service != null) { service.messageFromNative(event); @@ -92,7 +92,7 @@ public class LeAudioNativeInterface { // Callbacks from the native stack back into the Java framework. // All callbacks are routed via the Service which will disambiguate which // state machine the message should be routed to. - private void onInitialized() { + private static void onInitialized() { LeAudioStackEvent event = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_NATIVE_INITIALIZED); diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java index ceaffde228..955b3e2df7 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java @@ -25,6 +25,7 @@ import com.android.internal.annotations.VisibleForTesting; /** Factory class for object initialization to help with unit testing */ public class LeAudioObjectsFactory { private static final String TAG = LeAudioObjectsFactory.class.getSimpleName(); + private static LeAudioObjectsFactory sInstance; private static final Object INSTANCE_LOCK = new Object(); 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 addd9c9cf5..e197d892fc 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java @@ -19,15 +19,14 @@ 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.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.leaudioAllowedContextMask; 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.leaudioUseAudioModeListener; import static com.android.bluetooth.flags.Flags.leaudioUseAudioRecordingListener; import static com.android.modules.utils.build.SdkLevel.isAtLeastU; @@ -81,6 +80,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; @@ -119,7 +119,7 @@ import java.util.stream.Collectors; /** Provides Bluetooth LeAudio profile, as a service in the Bluetooth application. */ public class LeAudioService extends ProfileService { - private static final String TAG = "LeAudioService"; + private static final String TAG = LeAudioService.class.getSimpleName(); // Timeout for state machine thread join, to prevent potential ANR. private static final int SM_THREAD_JOIN_TIMEOUT_MS = 1000; @@ -213,6 +213,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; @@ -288,16 +292,14 @@ public class LeAudioService extends ProfileService { mLeAudioCodecConfig = new LeAudioCodecConfig(this); mNativeInterface.init(mLeAudioCodecConfig.getCodecConfigOffloading()); - if (leaudioUseAudioModeListener()) { - mAudioManager.addOnModeChangedListener(getMainExecutor(), mAudioModeChangeListener); - } + mAudioManager.addOnModeChangedListener(getMainExecutor(), mAudioModeChangeListener); if (leaudioUseAudioRecordingListener()) { mAudioManager.registerAudioRecordingCallback(mAudioRecordingCallback, null); } } - private static class LeAudioGroupDescriptor { + private class LeAudioGroupDescriptor { LeAudioGroupDescriptor(int groupId, boolean isInbandRingtonEnabled) { mGroupId = groupId; mIsConnected = false; @@ -336,6 +338,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; } @@ -352,17 +363,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; } @@ -533,7 +544,7 @@ public class LeAudioService extends ProfileService { mSessionStatus); } - private int convertToStatsAudioQuality(int audioQuality) { + private static int convertToStatsAudioQuality(int audioQuality) { switch (audioQuality) { case BluetoothLeBroadcastSubgroupSettings.QUALITY_STANDARD: return BluetoothStatsLog @@ -657,9 +668,7 @@ public class LeAudioService extends ProfileService { } mQueuedInCallValue = Optional.empty(); - if (leaudioUseAudioModeListener()) { - mAudioManager.removeOnModeChangedListener(mAudioModeChangeListener); - } + mAudioManager.removeOnModeChangedListener(mAudioModeChangeListener); if (leaudioUseAudioRecordingListener()) { mAudioManager.unregisterAudioRecordingCallback(mAudioRecordingCallback); @@ -987,7 +996,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( @@ -1049,12 +1058,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 { @@ -1420,17 +1429,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"); @@ -1737,8 +1744,7 @@ public class LeAudioService extends ProfileService { } if (groupDescriptor.mCurrentLeadDevice != null - && getConnectionState(groupDescriptor.mCurrentLeadDevice) - == BluetoothProfile.STATE_CONNECTED) { + && getConnectionState(groupDescriptor.mCurrentLeadDevice) == STATE_CONNECTED) { return groupDescriptor.mCurrentLeadDevice; } @@ -1748,7 +1754,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(); @@ -1795,6 +1801,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) { @@ -1814,14 +1826,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."); @@ -1864,9 +1868,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); @@ -1889,13 +1893,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."); @@ -1942,7 +1939,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( @@ -1951,6 +1948,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) { @@ -1979,12 +1979,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() { @@ -2152,12 +2153,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)) { @@ -2167,9 +2169,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 @@ -2186,9 +2188,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) @@ -2202,7 +2204,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; } @@ -2210,13 +2211,16 @@ public class LeAudioService extends ProfileService { } if (device.equals(mActiveAudioInDevice) || device.equals(mActiveAudioOutDevice)) { - Log.i(TAG, "Audio manager disactivate LeAudio device " + mExposedActiveDevice); + mEventLogger.loge( + TAG, + "[From AudioManager]: Audio manager autonomusly disactivated LeAudio device " + + mExposedActiveDevice); mExposedActiveDevice = null; setActiveDevice(null); return; } - Log.i( + mEventLogger.logd( TAG, ("LeAudio active device switch: " + mExposedActiveDevice @@ -2294,9 +2298,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); @@ -2382,12 +2386,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 = @@ -2402,6 +2409,12 @@ public class LeAudioService extends ProfileService { } if (isNewActiveInDevice) { + mEventLogger.logd( + TAG, + "[To AudioManager]: handleBluetoothActiveDeviceChanged previousActiveInDevice: " + + previousActiveInDevice + + (", mActiveAudioInDevice: " + mActiveAudioInDevice) + + " isLeOutput: false"); mAudioManager.handleBluetoothActiveDeviceChanged( mActiveAudioInDevice, previousActiveInDevice, @@ -2556,7 +2569,7 @@ public class LeAudioService extends ProfileService { + groupId + ", exposedDevice: " + mExposedActiveDevice); - sentActiveDeviceChangeIntent(mExposedActiveDevice); + sendActiveDeviceChangeIntent(mExposedActiveDevice); } return true; } @@ -2572,16 +2585,14 @@ public class LeAudioService extends ProfileService { return false; } - if (Flags.leaudioGettingActiveStateSupport()) { - mGroupReadLock.lock(); - try { - LeAudioGroupDescriptor descriptor = mGroupDescriptorsView.get(groupId); - if (descriptor != null) { - descriptor.setActiveState(ACTIVE_STATE_GETTING_ACTIVE); - } - } finally { - mGroupReadLock.unlock(); + mGroupReadLock.lock(); + try { + LeAudioGroupDescriptor descriptor = mGroupDescriptorsView.get(groupId); + if (descriptor != null) { + descriptor.setActiveState(ACTIVE_STATE_GETTING_ACTIVE); } + } finally { + mGroupReadLock.unlock(); } mNativeInterface.groupSetActive(groupId); @@ -2616,20 +2627,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(" @@ -3243,13 +3252,6 @@ public class LeAudioService extends ProfileService { return; } - if (!leaudioUseAudioModeListener()) { - if (mQueuedInCallValue.isPresent()) { - mNativeInterface.setInCall(mQueuedInCallValue.get()); - mQueuedInCallValue = Optional.empty(); - } - } - BluetoothDevice unicastDevice = getLeadDeviceForTheGroup(mUnicastGroupIdDeactivatedForBroadcastTransition); if (unicastDevice == null) { @@ -3701,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: @@ -3715,51 +3725,43 @@ public class LeAudioService extends ProfileService { } case LeAudioStackEvent.GROUP_STATUS_INACTIVE: { - if (Flags.leaudioGettingActiveStateSupport()) { - LeAudioGroupDescriptor descriptor = getGroupDescriptor(groupId); - if (descriptor == null) { - Log.e( - TAG, - "deviceDisconnected: no descriptors for group: " + groupId); - return; - } + LeAudioGroupDescriptor descriptor = getGroupDescriptor(groupId); + if (descriptor == null) { + Log.e( + TAG, + "deviceDisconnected: no descriptors for group: " + groupId); + return; + } - if (descriptor.isActive()) { - handleGroupTransitToInactive(groupId); - } + if (descriptor.isActive()) { + handleGroupTransitToInactive(groupId); + } - descriptor.setActiveState(ACTIVE_STATE_INACTIVE); + descriptor.setActiveState(ACTIVE_STATE_INACTIVE); - /* In case if group is inactivated due to switch to other */ - Integer gettingActiveGroupId = getFirstGroupIdInGettingActiveState(); - if (gettingActiveGroupId != LE_AUDIO_GROUP_ID_INVALID) { - if (leaudioAllowedContextMask()) { - /* Context were modified, apply mask to activating group */ - if (descriptor.areAllowedContextsModified()) { - setGroupAllowedContextMask( - gettingActiveGroupId, - descriptor.getAllowedSinkContexts(), - descriptor.getAllowedSourceContexts()); - setGroupAllowedContextMask( - groupId, - BluetoothLeAudio.CONTEXTS_ALL, - BluetoothLeAudio.CONTEXTS_ALL); - } - } - break; + /* In case if group is inactivated due to switch to other */ + Integer gettingActiveGroupId = getFirstGroupIdInGettingActiveState(); + if (gettingActiveGroupId != LE_AUDIO_GROUP_ID_INVALID) { + /* Context were modified, apply mask to activating group */ + if (descriptor.areAllowedContextsModified()) { + setGroupAllowedContextMask( + gettingActiveGroupId, + descriptor.getAllowedSinkContexts(), + descriptor.getAllowedSourceContexts()); + setGroupAllowedContextMask( + groupId, + BluetoothLeAudio.CONTEXTS_ALL, + BluetoothLeAudio.CONTEXTS_ALL); } + break; + } - if (leaudioAllowedContextMask()) { - /* Clear allowed context mask if there is no switch of group */ - if (descriptor.areAllowedContextsModified()) { - setGroupAllowedContextMask( - groupId, - BluetoothLeAudio.CONTEXTS_ALL, - BluetoothLeAudio.CONTEXTS_ALL); - } - } - } else { - handleGroupTransitToInactive(groupId); + /* Clear allowed context mask if there is no switch of group */ + if (descriptor.areAllowedContextsModified()) { + setGroupAllowedContextMask( + groupId, + BluetoothLeAudio.CONTEXTS_ALL, + BluetoothLeAudio.CONTEXTS_ALL); } if (isBroadcastAllowedToBeActivateInCurrentAudioMode()) { @@ -3768,9 +3770,6 @@ public class LeAudioService extends ProfileService { if (!Flags.leaudioBroadcastPrimaryGroupSelection()) { updateFallbackUnicastGroupIdForBroadcast(groupId); } - if (!leaudioUseAudioModeListener()) { - mQueuedInCallValue = Optional.empty(); - } startBroadcast(mBroadcastIdDeactivatedForUnicastTransition.get()); mBroadcastIdDeactivatedForUnicastTransition = Optional.empty(); } @@ -3957,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); } } @@ -4150,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; @@ -4418,29 +4415,7 @@ public class LeAudioService extends ProfileService { return; } - if (!leaudioUseAudioModeListener()) { - /* For setting inCall mode */ - if (inCall && !areBroadcastsAllStopped()) { - mQueuedInCallValue = Optional.of(true); - - /* Request activation of unicast group */ - handleUnicastStreamStatusChange( - LeAudioStackEvent.DIRECTION_SINK, - LeAudioStackEvent.STATUS_LOCAL_STREAM_REQUESTED); - return; - } - } - mNativeInterface.setInCall(inCall); - - if (!leaudioUseAudioModeListener()) { - /* For clearing inCall mode */ - if (!inCall && mBroadcastIdDeactivatedForUnicastTransition.isPresent()) { - handleUnicastStreamStatusChange( - LeAudioStackEvent.DIRECTION_SINK, - LeAudioStackEvent.STATUS_LOCAL_STREAM_SUSPENDED); - } - } } /** @@ -4624,7 +4599,7 @@ public class LeAudioService extends ProfileService { try { LeAudioDeviceDescriptor descriptor = getDeviceDescriptor(device); if (descriptor == null) { - Log.e(TAG, "getGroupId: No valid descriptor for device: " + device); + Log.v(TAG, "getGroupId: No valid descriptor for device: " + device); return LE_AUDIO_GROUP_ID_INVALID; } @@ -4784,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(); @@ -4801,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); } } @@ -4940,7 +4897,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; @@ -5336,7 +5295,8 @@ public class LeAudioService extends ProfileService { } } - private boolean isAudioModeChangedFromCommunicationToNormal(int previousMode, int currentMode) { + private static boolean isAudioModeChangedFromCommunicationToNormal( + int previousMode, int currentMode) { switch (previousMode) { case AudioManager.MODE_RINGTONE: case AudioManager.MODE_IN_CALL: @@ -5812,7 +5772,7 @@ public class LeAudioService extends ProfileService { LeAudioService service = getServiceAndEnforceConnect(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -6295,6 +6255,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 8d1fec5c72..d3d80735ce 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,12 @@ 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 android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.os.Looper; import android.os.Message; import android.util.Log; @@ -61,7 +65,7 @@ import java.io.StringWriter; import java.util.Scanner; final class LeAudioStateMachine extends StateMachine { - private static final String TAG = "LeAudioStateMachine"; + private static final String TAG = LeAudioStateMachine.class.getSimpleName(); static final int CONNECT = 1; static final int DISCONNECT = 2; @@ -74,7 +78,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 +141,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 +158,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED; + mLastConnectionState = STATE_DISCONNECTED; } @Override @@ -252,8 +256,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 +267,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTING; + mLastConnectionState = STATE_CONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -354,8 +358,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 +369,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING; + mLastConnectionState = STATE_DISCONNECTING; removeMessages(CONNECT_TIMEOUT); } @@ -463,9 +467,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 +479,7 @@ final class LeAudioStateMachine extends StateMachine { + mDevice + "): " + messageWhatToString(getCurrentMessage().what)); - mLastConnectionState = BluetoothProfile.STATE_CONNECTED; + mLastConnectionState = STATE_CONNECTED; } @Override @@ -544,7 +548,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) @@ -577,13 +581,13 @@ final class LeAudioStateMachine extends StateMachine { private static String profileStateToString(int state) { switch (state) { - case BluetoothProfile.STATE_DISCONNECTED: + case STATE_DISCONNECTED: return "DISCONNECTED"; - case BluetoothProfile.STATE_CONNECTING: + case STATE_CONNECTING: return "CONNECTING"; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: return "CONNECTED"; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: return "DISCONNECTING"; default: break; diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java index 14033e40ae..9f932470fb 100644 --- a/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java +++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioTmapGattServer.java @@ -36,7 +36,7 @@ import java.util.UUID; /** A GATT server for Telephony and Media Audio Profile (TMAP) */ @VisibleForTesting public class LeAudioTmapGattServer { - private static final String TAG = "LeAudioTmapGattServer"; + private static final String TAG = LeAudioTmapGattServer.class.getSimpleName(); /* Telephony and Media Audio Profile Role Characteristic UUID */ @VisibleForTesting diff --git a/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java b/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java index 9f4c910432..6d38a07d93 100644 --- a/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java +++ b/android/app/src/com/android/bluetooth/le_scan/AdvtFilterOnFoundOnLostInfo.java @@ -16,119 +16,29 @@ package com.android.bluetooth.le_scan; -import android.annotation.Nullable; import android.bluetooth.BluetoothDevice; -class AdvtFilterOnFoundOnLostInfo { - private int mClientIf; - - private int mAdvPktLen; - @Nullable private byte[] mAdvPkt; - - private int mScanRspLen; - - @Nullable private byte[] mScanRsp; - - private int mFiltIndex; - private int mAdvState; - private int mAdvInfoPresent; - private String mAddress; - - private int mAddrType; - private int mTxPower; - private int mRssiValue; - private int mTimeStamp; - - AdvtFilterOnFoundOnLostInfo( - int clientIf, - int advPktLen, - byte[] advPkt, - int scanRspLen, - byte[] scanRsp, - int filtIndex, - int advState, - int advInfoPresent, - String address, - int addrType, - int txPower, - int rssiValue, - int timeStamp) { - - mClientIf = clientIf; - mAdvPktLen = advPktLen; - mAdvPkt = advPkt; - mScanRspLen = scanRspLen; - mScanRsp = scanRsp; - mFiltIndex = filtIndex; - mAdvState = advState; - mAdvInfoPresent = advInfoPresent; - mAddress = address; - mAddrType = addrType; - mTxPower = txPower; - mRssiValue = rssiValue; - mTimeStamp = timeStamp; - } - - public int getClientIf() { - return mClientIf; - } - - public int getFiltIndex() { - return mFiltIndex; - } - - public int getAdvState() { - return mAdvState; - } - - public int getTxPower() { - return mTxPower; - } - - public int getTimeStamp() { - return mTimeStamp; - } - - public int getRSSIValue() { - return mRssiValue; - } - - public int getAdvInfoPresent() { - return mAdvInfoPresent; - } - - public String getAddress() { - return mAddress; - } - - @BluetoothDevice.AddressType - public int getAddressType() { - return mAddrType; - } - - public byte[] getAdvPacketData() { - return mAdvPkt; - } - - public int getAdvPacketLen() { - return mAdvPktLen; - } - - public byte[] getScanRspData() { - return mScanRsp; - } - - public int getScanRspLen() { - return mScanRspLen; - } +import com.google.protobuf.ByteString; + +record AdvtFilterOnFoundOnLostInfo( + int clientIf, + int advPacketLen, + ByteString advPacket, + int scanResponseLen, + ByteString scanResponse, + int filtIndex, + int advState, + int advInfoPresent, + String address, + @BluetoothDevice.AddressType int addressType, + int txPower, + int rssiValue, + int timeStamp) { public byte[] getResult() { - int resultLength = mAdvPkt.length + ((mScanRsp != null) ? mScanRsp.length : 0); - byte[] result = new byte[resultLength]; - System.arraycopy(mAdvPkt, 0, result, 0, mAdvPkt.length); - if (mScanRsp != null) { - System.arraycopy(mScanRsp, 0, result, mAdvPkt.length, mScanRsp.length); + if (scanResponse == null) { + return advPacket.toByteArray(); } - return result; + return advPacket.concat(scanResponse).toByteArray(); } } diff --git a/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java b/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java index 4d3bcc8a74..420a808e6d 100644 --- a/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java +++ b/android/app/src/com/android/bluetooth/le_scan/AppScanStats.java @@ -17,6 +17,7 @@ package com.android.bluetooth.le_scan; import static java.util.Objects.requireNonNull; +import static java.util.Objects.requireNonNullElseGet; import android.annotation.Nullable; import android.bluetooth.BluetoothProtoEnums; @@ -43,15 +44,13 @@ import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; /** ScanStats class helps keep track of information about scans on a per application basis. */ class AppScanStats { private static final String TAG = AppScanStats.class.getSimpleName(); - private static final ThreadLocal<DateFormat> DATE_FORMAT = - ThreadLocal.withInitial(() -> new SimpleDateFormat("MM-dd HH:mm:ss")); - // Weight is the duty cycle of the scan mode static final int OPPORTUNISTIC_WEIGHT = 0; static final int SCREEN_OFF_LOW_POWER_WEIGHT = 5; @@ -62,22 +61,8 @@ class AppScanStats { static final int LARGE_SCAN_TIME_GAP_MS = 24000; - // ScannerMap here is needed to grab Apps - ScannerMap mScannerMap; - - // ScanController is needed to add scan event protos to be dumped later - final ScanController mScanController; - - // Battery stats is used to keep track of scans and result stats - BatteryStatsManager mBatteryStatsManager; - - private final AdapterService mAdapterService; - private final TimeProvider mTimeProvider; - - private static Object sLock = new Object(); - - @GuardedBy("sLock") - static long sRadioStartTime = 0; + private static final ThreadLocal<DateFormat> DATE_FORMAT = + ThreadLocal.withInitial(() -> new SimpleDateFormat("MM-dd HH:mm:ss")); static WorkSourceUtil sRadioScanWorkSourceUtil; static int sRadioScanType; @@ -87,27 +72,32 @@ class AppScanStats { static boolean sIsRadioStarted = false; static boolean sIsScreenOn = false; + @GuardedBy("sLock") + static long sRadioStartTime = 0; + + private static Object sLock = new Object(); + private static class LastScan { public long duration; public long suspendDuration; public long suspendStartTime; public boolean isSuspended; - public long timestamp; - public long reportDelayMillis; + public final long timestamp; + public final long reportDelayMillis; public boolean isOpportunisticScan; public boolean isTimeout; public boolean isDowngraded; public boolean isBackgroundScan; - public boolean isFilterScan; - public boolean isCallbackScan; + public final boolean isFilterScan; + public final boolean isCallbackScan; public boolean isBatchScan; public boolean isAutoBatchScan; public int results; - public int scannerId; - public int scanMode; - public int scanCallbackType; - public StringBuilder filterString; - @Nullable public String attributionTag; + public final int scannerId; + public final int scanMode; + public final int scanCallbackType; + public final StringBuilder filterString; + @Nullable public final String attributionTag; LastScan( long timestamp, @@ -141,12 +131,23 @@ class AppScanStats { } } - String mAppName; - private WorkSource mWorkSource; // Used for BatteryStatsManager + private final List<LastScan> mLastScans = new ArrayList<>(); + private final Map<Integer, LastScan> mOngoingScans = new HashMap<>(); + + final String mAppName; + final ScannerMap mScannerMap; // Used to grab Apps + final BatteryStatsManager mBatteryStatsManager; // Used to keep track of scans and result stats + final ScanController mScanController; // Used to add scan event protos to be dumped later + + private final WorkSource mWorkSource; // Used for BatteryStatsManager private final WorkSourceUtil mWorkSourceUtil; // Used for BluetoothStatsLog + private final AdapterService mAdapterService; + private final TimeProvider mTimeProvider; + + public boolean isAppDead = false; + public boolean isRegistered = false; private int mScansStarted = 0; private int mScansStopped = 0; - public boolean isRegistered = false; private long mScanStartTime = 0; private long mTotalActiveTime = 0; private long mTotalSuspendTime = 0; @@ -161,12 +162,9 @@ class AppScanStats { private int mBalancedScan = 0; private int mLowLatencyScan = 0; private int mAmbientDiscoveryScan = 0; - private List<LastScan> mLastScans = new ArrayList<LastScan>(); - private HashMap<Integer, LastScan> mOngoingScans = new HashMap<Integer, LastScan>(); private long startTime = 0; private long stopTime = 0; private int results = 0; - public boolean isAppDead = false; AppScanStats( String name, @@ -175,19 +173,31 @@ class AppScanStats { AdapterService adapterService, ScanController scanController, TimeProvider timeProvider) { - mAdapterService = requireNonNull(adapterService); - mTimeProvider = requireNonNull(timeProvider); mAppName = name; + mWorkSource = + requireNonNullElseGet( + // Bill the caller if the work source isn't passed through + source, () -> new WorkSource(Binder.getCallingUid(), mAppName)); + mWorkSourceUtil = new WorkSourceUtil(mWorkSource); mScannerMap = map; - mScanController = scanController; + mAdapterService = requireNonNull(adapterService); mBatteryStatsManager = adapterService.getSystemService(BatteryStatsManager.class); + mScanController = scanController; + mTimeProvider = requireNonNull(timeProvider); + } - if (source == null) { - // Bill the caller if the work source isn't passed through - source = new WorkSource(Binder.getCallingUid(), mAppName); - } - mWorkSource = source; - mWorkSourceUtil = new WorkSourceUtil(source); + private synchronized LastScan getScanFromScannerId(int scannerId) { + return mOngoingScans.get(scannerId); + } + + private BluetoothMetricsProto.ScanEvent.Builder createBaseScanEvent( + BluetoothMetricsProto.ScanEvent.ScanEventType type) { + return BluetoothMetricsProto.ScanEvent.newBuilder() + .setScanEventType(type) + .setScanTechnologyType( + BluetoothMetricsProto.ScanEvent.ScanTechnologyType.SCAN_TECH_TYPE_LE) + .setEventTimeMillis(System.currentTimeMillis()) + .setInitiator(truncateAppName(mAppName)); } synchronized void addResult(int scannerId) { @@ -214,10 +224,6 @@ class AppScanStats { return !mOngoingScans.isEmpty(); } - synchronized LastScan getScanFromScannerId(int scannerId) { - return mOngoingScans.get(scannerId); - } - synchronized boolean isScanTimeout(int scannerId) { LastScan scan = getScanFromScannerId(scannerId); if (scan == null) { @@ -301,14 +307,7 @@ class AppScanStats { } BluetoothMetricsProto.ScanEvent scanEvent = - BluetoothMetricsProto.ScanEvent.newBuilder() - .setScanEventType( - BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_START) - .setScanTechnologyType( - BluetoothMetricsProto.ScanEvent.ScanTechnologyType - .SCAN_TECH_TYPE_LE) - .setEventTimeMillis(System.currentTimeMillis()) - .setInitiator(truncateAppName(mAppName)) + createBaseScanEvent(BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_START) .build(); mScanController.addScanEvent(scanEvent); @@ -352,14 +351,7 @@ class AppScanStats { mLastScans.add(scan); BluetoothMetricsProto.ScanEvent scanEvent = - BluetoothMetricsProto.ScanEvent.newBuilder() - .setScanEventType( - BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_STOP) - .setScanTechnologyType( - BluetoothMetricsProto.ScanEvent.ScanTechnologyType - .SCAN_TECH_TYPE_LE) - .setEventTimeMillis(System.currentTimeMillis()) - .setInitiator(truncateAppName(mAppName)) + createBaseScanEvent(BluetoothMetricsProto.ScanEvent.ScanEventType.SCAN_EVENT_STOP) .setNumberResults(scan.results) .build(); mScanController.addScanEvent(scanEvent); @@ -470,7 +462,7 @@ class AppScanStats { } } - private int convertScanCallbackType(int type) { + private static int convertScanCallbackType(int type) { switch (type) { case ScanSettings.CALLBACK_TYPE_ALL_MATCHES: return BluetoothStatsLog @@ -851,7 +843,7 @@ class AppScanStats { // or less package names names are untouched. // Examples: one.two.three.four => one.two.three // one.two.three => one.two - private String truncateAppName(String name) { + private static String truncateAppName(String name) { String initiator = name; String[] nameSplit = initiator.split("\\."); if (nameSplit.length > 3) { @@ -974,39 +966,37 @@ class AppScanStats { int lowLatencyScan = mLowLatencyScan; long ambientDiscoveryScan = mAmbientDiscoveryScan; - if (!mOngoingScans.isEmpty()) { - for (Integer key : mOngoingScans.keySet()) { - LastScan scan = mOngoingScans.get(key); - scanDuration = currTime - scan.timestamp; - - if (scan.isSuspended) { - suspendDuration = currTime - scan.suspendStartTime; - totalSuspendTime += suspendDuration; - } + for (LastScan scan : mOngoingScans.values()) { + scanDuration = currTime - scan.timestamp; - totalScanTime += scanDuration; + if (scan.isSuspended) { + suspendDuration = currTime - scan.suspendStartTime; totalSuspendTime += suspendDuration; - activeDuration = scanDuration - scan.suspendDuration - suspendDuration; - totalActiveTime += activeDuration; - switch (scan.scanMode) { - case ScanSettings.SCAN_MODE_OPPORTUNISTIC: - oppScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_LOW_POWER: - lowPowerScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_BALANCED: - balancedScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_LOW_LATENCY: - lowLatencyScanTime += activeDuration; - break; - case ScanSettings.SCAN_MODE_AMBIENT_DISCOVERY: - ambientDiscoveryScan += activeDuration; - break; - } + } + + totalScanTime += scanDuration; + totalSuspendTime += suspendDuration; + activeDuration = scanDuration - scan.suspendDuration - suspendDuration; + totalActiveTime += activeDuration; + switch (scan.scanMode) { + case ScanSettings.SCAN_MODE_OPPORTUNISTIC: + oppScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_LOW_POWER: + lowPowerScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_BALANCED: + balancedScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_LOW_LATENCY: + lowLatencyScanTime += activeDuration; + break; + case ScanSettings.SCAN_MODE_AMBIENT_DISCOVERY: + ambientDiscoveryScan += activeDuration; + break; } } + long Score = (oppScanTime * OPPORTUNISTIC_WEIGHT + lowPowerScanTime * LOW_POWER_WEIGHT @@ -1117,8 +1107,7 @@ class AppScanStats { if (!mOngoingScans.isEmpty()) { sb.append("\n Ongoing scans :"); - for (Integer key : mOngoingScans.keySet()) { - LastScan scan = mOngoingScans.get(key); + for (LastScan scan : mOngoingScans.values()) { Date timestamp = new Date(currentTime - currTime + scan.timestamp); sb.append("\n ").append(DATE_FORMAT.get().format(timestamp)).append(" - "); sb.append((currTime - scan.timestamp)).append("ms "); diff --git a/android/app/src/com/com/android/bluetooth/le_scan/BatchScanThrottler.java b/android/app/src/com/android/bluetooth/le_scan/BatchScanThrottler.java index 4fd324dcf9..3cc06fffe4 100644 --- a/android/app/src/com/com/android/bluetooth/le_scan/BatchScanThrottler.java +++ b/android/app/src/com/android/bluetooth/le_scan/BatchScanThrottler.java @@ -91,9 +91,9 @@ class BatchScanThrottler { : UNFILTERED_DELAY_FLOOR_MS; long intervalMillis = Long.MAX_VALUE; for (ScanClient client : batchClients) { - if (client.settings.getReportDelayMillis() > 0) { - long clientIntervalMillis = client.settings.getReportDelayMillis(); - if ((client.filters == null || client.filters.isEmpty()) + if (client.mSettings.getReportDelayMillis() > 0) { + long clientIntervalMillis = client.mSettings.getReportDelayMillis(); + if ((client.mFilters == null || client.mFilters.isEmpty()) && clientIntervalMillis < unfilteredFloor) { clientIntervalMillis = unfilteredFloor; } diff --git a/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java b/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java index feb30fd9c9..57729351c6 100644 --- a/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java +++ b/android/app/src/com/android/bluetooth/le_scan/MsftAdvMonitor.java @@ -135,7 +135,7 @@ class MsftAdvMonitor { return mAddress; } - private boolean dataMaskIsEmpty(byte[] mask) { + private static boolean dataMaskIsEmpty(byte[] mask) { if (mask == null || mask.length == 0) return true; if (mask.length == 1 && mask[0] == 0) return true; return false; diff --git a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java index c2408f1294..c06bdd465a 100644 --- a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java +++ b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java @@ -40,7 +40,8 @@ import java.util.concurrent.ConcurrentHashMap; /** Manages Bluetooth LE Periodic scans */ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE) public class PeriodicScanManager { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "SyncManager"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + PeriodicScanManager.class.getSimpleName(); private final BluetoothAdapter mAdapter; private final PeriodicScanNativeInterface mNativeInterface; diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanBinder.java b/android/app/src/com/android/bluetooth/le_scan/ScanBinder.java new file mode 100644 index 0000000000..905a8b20af --- /dev/null +++ b/android/app/src/com/android/bluetooth/le_scan/ScanBinder.java @@ -0,0 +1,186 @@ +/* + * Copyright (C) 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. + */ + +package com.android.bluetooth.le_scan; + +import android.app.PendingIntent; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.IBluetoothScan; +import android.bluetooth.le.IPeriodicAdvertisingCallback; +import android.bluetooth.le.IScannerCallback; +import android.bluetooth.le.ScanFilter; +import android.bluetooth.le.ScanResult; +import android.bluetooth.le.ScanSettings; +import android.content.AttributionSource; +import android.os.WorkSource; +import android.util.Log; + +import java.util.List; + +class ScanBinder extends IBluetoothScan.Stub { + private static final String TAG = ScanBinder.class.getSimpleName(); + + private ScanController mScanController; + + ScanBinder(ScanController scanController) { + mScanController = scanController; + } + + @Override + public void registerScanner( + IScannerCallback callback, WorkSource workSource, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.registerScanner(callback, workSource, attributionSource); + } + + @Override + public void unregisterScanner(int scannerId, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.unregisterScanner(scannerId, attributionSource); + } + + @Override + public void startScan( + int scannerId, + ScanSettings settings, + List<ScanFilter> filters, + AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.startScan(scannerId, settings, filters, attributionSource); + } + + @Override + public void startScanForIntent( + PendingIntent intent, + ScanSettings settings, + List<ScanFilter> filters, + AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.registerPiAndStartScan(intent, settings, filters, attributionSource); + } + + @Override + public void stopScan(int scannerId, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.stopScan(scannerId, attributionSource); + } + + @Override + public void stopScanForIntent(PendingIntent intent, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.stopScan(intent, attributionSource); + } + + @Override + public void flushPendingBatchResults(int scannerId, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.flushPendingBatchResults(scannerId, attributionSource); + } + + @Override + public void registerSync( + ScanResult scanResult, + int skip, + int timeout, + IPeriodicAdvertisingCallback callback, + AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.registerSync(scanResult, skip, timeout, callback, attributionSource); + } + + @Override + public void unregisterSync( + IPeriodicAdvertisingCallback callback, AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.unregisterSync(callback, attributionSource); + } + + @Override + public void transferSync( + BluetoothDevice bda, + int serviceData, + int syncHandle, + AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.transferSync(bda, serviceData, syncHandle, attributionSource); + } + + @Override + public void transferSetInfo( + BluetoothDevice bda, + int serviceData, + int advHandle, + IPeriodicAdvertisingCallback callback, + AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return; + } + scanController.transferSetInfo(bda, serviceData, advHandle, callback, attributionSource); + } + + @Override + public int numHwTrackFiltersAvailable(AttributionSource attributionSource) { + ScanController scanController = getScanController(); + if (scanController == null) { + return 0; + } + return scanController.numHwTrackFiltersAvailable(attributionSource); + } + + void clearScanController() { + mScanController = null; + } + + private ScanController getScanController() { + ScanController controller = mScanController; + if (controller != null && controller.isAvailable()) { + return controller; + } + Log.e(TAG, "getScanController() - ScanController requested, but not available!"); + return null; + } +} 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 1c73883482..f0ea7894ea 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanController.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanController.java @@ -32,7 +32,6 @@ import android.app.PendingIntent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothUtils; -import android.bluetooth.IBluetoothScan; import android.bluetooth.le.BluetoothLeScanner; import android.bluetooth.le.IPeriodicAdvertisingCallback; import android.bluetooth.le.IScannerCallback; @@ -72,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; @@ -153,7 +154,7 @@ public class ScanController { public final HandlerThread mScanThread; - private final BluetoothScanBinder mBinder; + private final ScanBinder mBinder; /** Internal list of scan events to use with the proto */ private final ArrayDeque<BluetoothMetricsProto.ScanEvent> mScanEvents = @@ -193,7 +194,7 @@ public class ScanController { return false; }; mMainLooper = adapterService.getMainLooper(); - mBinder = new BluetoothScanBinder(this); + mBinder = new ScanBinder(this); mIsAvailable = true; mScanThread = new HandlerThread("BluetoothScanManager"); mScanThread.start(); @@ -221,6 +222,10 @@ public class ScanController { mPeriodicScanManager.cleanup(); } + boolean isAvailable() { + return mIsAvailable; + } + ScannerMap getScannerMap() { return mScannerMap; } @@ -313,7 +318,7 @@ public class ScanController { return true; } - private ScanResult getSanitizedExposureNotification(ScanResult result) { + private static ScanResult getSanitizedExposureNotification(ScanResult result) { ScanRecord record = result.getScanRecord(); // Remove the flags part of the payload, if present if (record.getBytes().length > EXPOSURE_NOTIFICATION_FLAGS_LENGTH @@ -421,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()) { @@ -457,23 +462,23 @@ public class ScanController { scanRecord, SystemClock.elapsedRealtimeNanos()); - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { if (mLocationDenylistPredicate.test(result)) { - Log.i(TAG, "Skipping client 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; @@ -496,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 { @@ -523,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); } @@ -585,35 +590,35 @@ public class ScanController { /** Determines if the given scan client has the appropriate permissions to receive callbacks. */ private boolean hasScanResultPermission(final ScanClient client) { - if (leaudioBassScanWithInternalScanController() && client.isInternalClient) { + if (leaudioBassScanWithInternalScanController() && client.mIsInternalClient) { // Bypass permission check for internal clients return true; } - if (client.hasNetworkSettingsPermission - || client.hasNetworkSetupWizardPermission - || client.hasScanWithoutLocationPermission) { + if (client.mHasNetworkSettingsPermission + || client.mHasNetworkSetupWizardPermission + || client.mHasScanWithoutLocationPermission) { return true; } - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { return true; } - return client.hasLocationPermission - && !Utils.blockedByLocationOff(mAdapterService, client.userHandle); + return client.mHasLocationPermission + && !Utils.blockedByLocationOff(mAdapterService, client.mUserHandle); } // Check if a scan record matches a specific filters. - private boolean matchesFilters(ScanClient client, ScanResult scanResult) { + private static boolean matchesFilters(ScanClient client, ScanResult scanResult) { return matchesFilters(client, scanResult, null); } // Check if a scan record matches a specific filters or original address - private boolean matchesFilters( + private static boolean matchesFilters( ScanClient client, ScanResult scanResult, String originalAddress) { - if (client.filters == null || client.filters.isEmpty()) { + if (client.mFilters == null || client.mFilters.isEmpty()) { // TODO: Do we really wanna return true here? return true; } - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { // Need to check the filter matches, and the original address without changing the API if (filter.matches(scanResult)) { return true; @@ -627,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. */ @@ -707,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; } } @@ -759,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); @@ -768,7 +773,7 @@ public class ScanController { } } - if (client.hasDisavowedLocation) { + if (client.mHasDisavowedLocation) { permittedResults.removeIf(mLocationDenylistPredicate); } if (permittedResults.isEmpty()) { @@ -808,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 { @@ -829,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; } @@ -840,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); } @@ -848,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; } @@ -940,7 +945,7 @@ public class ScanController { } // Reverse byte array. - private void reverse(byte[] address) { + private static void reverse(byte[] address) { int len = address.length; for (int i = 0; i < len / 2; ++i) { byte b = address[i]; @@ -963,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, @@ -975,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, @@ -996,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; @@ -1012,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)) { @@ -1049,7 +1052,7 @@ public class ScanController { "Not reporting onlost/onfound : " + advertiserState + " scannerId = " - + client.scannerId + + client.mScannerId + " callbackType " + settings.getCallbackType()); } @@ -1131,7 +1134,6 @@ public class ScanController { *************************************************************************/ @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void registerScanner( IScannerCallback callback, WorkSource workSource, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( @@ -1167,7 +1169,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private void unregisterScanner(int scannerId, AttributionSource attributionSource) { + void unregisterScanner(int scannerId, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( mAdapterService, attributionSource, "ScanHelper unregisterScanner")) { return; @@ -1210,7 +1212,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private void startScan( + void startScan( int scannerId, ScanSettings settings, List<ScanFilter> filters, @@ -1227,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); } @@ -1263,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); } @@ -1283,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; @@ -1304,7 +1306,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private void registerPiAndStartScan( + void registerPiAndStartScan( PendingIntent pendingIntent, ScanSettings settings, List<ScanFilter> filters, @@ -1390,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, @@ -1418,7 +1421,6 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void flushPendingBatchResults(int scannerId, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( mAdapterService, attributionSource, "ScanHelper flushPendingBatchResults")) { @@ -1433,7 +1435,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private void stopScan(int scannerId, AttributionSource attributionSource) { + void stopScan(int scannerId, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( mAdapterService, attributionSource, "ScanHelper stopScan")) { return; @@ -1456,7 +1458,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private void stopScan(PendingIntent intent, AttributionSource attributionSource) { + void stopScan(PendingIntent intent, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( mAdapterService, attributionSource, "ScanHelper stopScan")) { return; @@ -1483,7 +1485,6 @@ public class ScanController { * PERIODIC SCANNING *************************************************************************/ @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void registerSync( ScanResult scanResult, int skip, @@ -1498,7 +1499,6 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void unregisterSync( IPeriodicAdvertisingCallback callback, AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( @@ -1509,7 +1509,6 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void transferSync( BluetoothDevice bda, int serviceData, @@ -1523,7 +1522,6 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - @VisibleForTesting void transferSetInfo( BluetoothDevice bda, int serviceData, @@ -1538,7 +1536,7 @@ public class ScanController { } @RequiresPermission(BLUETOOTH_SCAN) - private int numHwTrackFiltersAvailable(AttributionSource attributionSource) { + int numHwTrackFiltersAvailable(AttributionSource attributionSource) { if (!Utils.checkScanPermissionForDataDelivery( mAdapterService, attributionSource, "ScanHelper numHwTrackFiltersAvailable")) { return 0; @@ -1578,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; } } @@ -1736,168 +1734,4 @@ public class ScanController { builder.addAllScanEvent(mScanEvents); } } - - static class BluetoothScanBinder extends IBluetoothScan.Stub { - private ScanController mScanController; - - BluetoothScanBinder(ScanController scanController) { - mScanController = scanController; - } - - @Override - public void registerScanner( - IScannerCallback callback, - WorkSource workSource, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .registerScanner(callback, workSource, attributionSource); - } - - @Override - public void unregisterScanner(int scannerId, AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .unregisterScanner(scannerId, attributionSource); - } - - @Override - public void startScan( - int scannerId, - ScanSettings settings, - List<ScanFilter> filters, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .startScan(scannerId, settings, filters, attributionSource); - } - - @Override - public void startScanForIntent( - PendingIntent intent, - ScanSettings settings, - List<ScanFilter> filters, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .registerPiAndStartScan(intent, settings, filters, attributionSource); - } - - @Override - public void stopScan(int scannerId, AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController.stopScan(scannerId, attributionSource); - } - - @Override - public void stopScanForIntent(PendingIntent intent, AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController.stopScan(intent, attributionSource); - } - - @Override - public void flushPendingBatchResults(int scannerId, AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .flushPendingBatchResults(scannerId, attributionSource); - } - - @Override - public void registerSync( - ScanResult scanResult, - int skip, - int timeout, - IPeriodicAdvertisingCallback callback, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .registerSync(scanResult, skip, timeout, callback, attributionSource); - } - - @Override - public void unregisterSync( - IPeriodicAdvertisingCallback callback, AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController.unregisterSync(callback, attributionSource); - } - - @Override - public void transferSync( - BluetoothDevice bda, - int serviceData, - int syncHandle, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .transferSync(bda, serviceData, syncHandle, attributionSource); - } - - @Override - public void transferSetInfo( - BluetoothDevice bda, - int serviceData, - int advHandle, - IPeriodicAdvertisingCallback callback, - AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return; - } - mScanController - .transferSetInfo(bda, serviceData, advHandle, callback, attributionSource); - } - - @Override - public int numHwTrackFiltersAvailable(AttributionSource attributionSource) { - ScanController mScanController = getScanController(); - if (mScanController == null) { - return 0; - } - return mScanController - .numHwTrackFiltersAvailable(attributionSource); - } - - private void clearScanController() { - mScanController = null; - } - - private ScanController getScanController() { - ScanController controller = mScanController; - if (controller != null && controller.mIsAvailable) { - return controller; - } - Log.e(TAG, "getScanController() - ScanController requested, but not available!"); - return null; - } - } } diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java b/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java index b2b0b7eec0..b5614ea927 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java @@ -293,7 +293,8 @@ import java.util.UUID; } } - private byte[] concatenate(ParcelUuid serviceDataUuid, byte[] serviceData, boolean isMask) { + private static byte[] concatenate( + ParcelUuid serviceDataUuid, byte[] serviceData, boolean isMask) { byte[] uuid = BluetoothUuid.uuidToBytes(serviceDataUuid); int dataLen = uuid.length + serviceData.length; diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java index b8079fbbe0..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; @@ -72,7 +76,8 @@ import java.util.concurrent.atomic.AtomicReference; /** Class that handles Bluetooth LE scan related operations. */ public class ScanManager { - private static final String TAG = GattServiceConfig.TAG_PREFIX + "ScanManager"; + private static final String TAG = + GattServiceConfig.TAG_PREFIX + ScanManager.class.getSimpleName(); /** Scan params corresponding to regular scan setting */ @VisibleForTesting static final int SCAN_MODE_LOW_POWER_WINDOW_MS = 140; @@ -267,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); } } @@ -396,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; } @@ -410,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; } @@ -450,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) { @@ -462,18 +467,18 @@ public class ScanManager { return !mScanNative.isOpportunisticScanClient(client) && !isFiltered; } - private boolean requiresLocationOn(ScanClient client) { + private static boolean requiresLocationOn(ScanClient client) { boolean isFiltered = isFilteredScan(client); - return !client.hasDisavowedLocation && !isFiltered; + return !client.mHasDisavowedLocation && !isFiltered; } - private boolean isFilteredScan(ScanClient client) { - if ((client.filters == null) || client.filters.isEmpty()) { + private static boolean isFilteredScan(ScanClient client) { + if ((client.mFilters == null) || client.mFilters.isEmpty()) { return false; } boolean atLeastOneValidFilter = false; - for (ScanFilter filter : client.filters) { + for (ScanFilter filter : client.mFilters) { // A valid filter need at least one field not empty if (!filter.isAllFieldsEmpty()) { atLeastOneValidFilter = true; @@ -506,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); } } @@ -518,23 +523,23 @@ public class ScanManager { Log.d(TAG, "There is no batch scan client to flush " + client); return; } - mScanNative.flushBatchResults(client.scannerId); + mScanNative.flushBatchResults(client.mScannerId); } - private boolean isBatchClient(ScanClient client) { - if (client == null || client.settings == null) { + private static boolean isBatchClient(ScanClient client) { + if (client == null || client.mSettings == null) { return false; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; return settings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES && settings.getReportDelayMillis() != 0; } private boolean isScanSupported(ScanClient client) { - if (client == null || client.settings == null) { + if (client == null || client.mSettings == null) { return true; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; if (isFilteringSupported()) { return true; } @@ -601,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); @@ -652,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); } } @@ -661,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); } } @@ -687,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; @@ -712,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); @@ -723,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) { @@ -731,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; } @@ -743,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) { @@ -765,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)) { @@ -781,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()); @@ -790,8 +795,8 @@ public class ScanManager { return false; } - private boolean upgradeScanModeByOneLevel(ScanClient client) { - switch (client.scanModeApp) { + private static boolean upgradeScanModeByOneLevel(ScanClient client) { + switch (client.mScanModeApp) { case ScanSettings.SCAN_MODE_LOW_POWER: return client.updateScanMode(ScanSettings.SCAN_MODE_BALANCED); case ScanSettings.SCAN_MODE_BALANCED: @@ -805,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(); @@ -825,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 @@ -833,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 " @@ -862,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) { @@ -892,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); @@ -1086,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 = @@ -1141,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); @@ -1166,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; @@ -1180,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) { @@ -1195,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( @@ -1220,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"); } @@ -1246,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"); } @@ -1268,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++; } } @@ -1287,46 +1292,46 @@ public class ScanManager { } } - private boolean isExemptFromScanTimeout(ScanClient client) { + private static boolean isExemptFromScanTimeout(ScanClient client) { return isOpportunisticScanClient(client) || isFirstMatchScanClient(client); } - private boolean isExemptFromAutoBatchScanUpdate(ScanClient client) { + private static boolean isExemptFromAutoBatchScanUpdate(ScanClient client) { return isOpportunisticScanClient(client) || !isAllMatchesAutoBatchScanClient(client); } - private boolean isAutoBatchScanClientEnabled(ScanClient client) { - return client.stats != null && client.stats.isAutoBatchScan(client.scannerId); + private static boolean isAutoBatchScanClientEnabled(ScanClient client) { + return client.mStats != null && client.mStats.isAutoBatchScan(client.mScannerId); } - private boolean isAllMatchesAutoBatchScanClient(ScanClient client) { - return client.settings.getCallbackType() + private static boolean isAllMatchesAutoBatchScanClient(ScanClient client) { + return client.mSettings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH; } - private boolean isOpportunisticScanClient(ScanClient client) { - return client.settings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; + private static boolean isOpportunisticScanClient(ScanClient client) { + return client.mSettings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC; } - private boolean isTimeoutScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanTimeout(client.scannerId); + private static boolean isTimeoutScanClient(ScanClient client) { + return (client.mStats != null) && client.mStats.isScanTimeout(client.mScannerId); } - private boolean isDowngradedScanClient(ScanClient client) { - return (client.stats != null) && client.stats.isScanDowngraded(client.scannerId); + private static boolean isDowngradedScanClient(ScanClient client) { + return (client.mStats != null) && client.mStats.isScanDowngraded(client.mScannerId); } - private boolean isForceDowngradedScanClient(ScanClient client) { + private static boolean isForceDowngradedScanClient(ScanClient client) { return isTimeoutScanClient(client) || isDowngradedScanClient(client); } - private boolean isFirstMatchScanClient(ScanClient client) { - return (client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) + private static boolean isFirstMatchScanClient(ScanClient client) { + return (client.mSettings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH) != 0; } private void resetBatchScan(ScanClient client) { - int scannerId = client.scannerId; + int scannerId = client.mScannerId; BatchScanParams batchScanParams = getBatchScanParams(); // Stop batch if batch scan params changed and previous params is not null. if (mBatchScanParams != null && (!mBatchScanParams.equals(batchScanParams))) { @@ -1345,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 = @@ -1367,7 +1372,7 @@ public class ScanManager { setBatchAlarm(); } - private int getFullScanStoragePercent(int resultType) { + private static int getFullScanStoragePercent(int resultType) { switch (resultType) { case SCAN_RESULT_TYPE_FULL: return 100; @@ -1387,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; @@ -1471,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, @@ -1480,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); } @@ -1497,7 +1502,7 @@ public class ScanManager { } if (!mIsMsftSupported) { - removeScanFilters(client.scannerId); + removeScanFilters(client.mScannerId); } else { removeFiltersMsft(client); } @@ -1505,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()); } } @@ -1548,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; } } @@ -1569,7 +1574,7 @@ public class ScanManager { ScanClient getSuspendedScanClient(int scannerId) { for (ScanClient client : mSuspendedScanClients) { - if (client.scannerId == scannerId) { + if (client.mScannerId == scannerId) { return client; } } @@ -1578,7 +1583,7 @@ public class ScanManager { void stopBatchScan(ScanClient client) { mBatchClients.remove(client); - removeScanFilters(client.scannerId); + removeScanFilters(client.mScannerId); if (!isOpportunisticScanClient(client)) { resetBatchScan(client); } @@ -1614,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; @@ -1626,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; @@ -1655,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(); @@ -1668,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 { @@ -1705,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; } } @@ -1744,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; } } @@ -1752,7 +1757,7 @@ public class ScanManager { } /** Return batch scan result type value defined in bt stack. */ - private int getResultType(BatchScanParams params) { + private static int getResultType(BatchScanParams params) { if (params.mFullScanScannerId != -1 && params.mTruncatedScanScannerId != -1) { return SCAN_RESULT_TYPE_BOTH; } @@ -1770,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; @@ -1810,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; @@ -1842,11 +1847,11 @@ public class ScanManager { } // Get delivery mode based on scan settings. - private int getDeliveryMode(ScanClient client) { + private static int getDeliveryMode(ScanClient client) { if (client == null) { return DELIVERY_MODE_IMMEDIATE; } - ScanSettings settings = client.settings; + ScanSettings settings = client.mSettings; if (settings == null) { return DELIVERY_MODE_IMMEDIATE; } @@ -1950,7 +1955,7 @@ public class ScanManager { return phy; } - private int getOnFoundOnLostTimeoutMillis(ScanSettings settings, boolean onFound) { + private static int getOnFoundOnLostTimeoutMillis(ScanSettings settings, boolean onFound) { int factor; int timeout = ONLOST_ONFOUND_BASE_TIMEOUT_MS; @@ -1965,7 +1970,7 @@ public class ScanManager { return (timeout * factor); } - private int getOnFoundOnLostSightings(ScanSettings settings) { + private static int getOnFoundOnLostSightings(ScanSettings settings) { if (settings == null) { return ONFOUND_SIGHTINGS_AGGRESSIVE; } @@ -2050,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) { @@ -2103,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)) { @@ -2129,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); @@ -2221,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 { @@ -2230,7 +2235,7 @@ public class ScanManager { "Invalid state transition, " + prevState + " -> " + state); } break; - case BluetoothProfile.STATE_CONNECTED: + case STATE_CONNECTED: if (mProfilesConnected > 0) { mProfilesConnected--; } else { @@ -2239,7 +2244,7 @@ public class ScanManager { "Invalid state transition, " + prevState + " -> " + state); } break; - case BluetoothProfile.STATE_DISCONNECTING: + case STATE_DISCONNECTING: if (mProfilesDisconnecting > 0) { mProfilesDisconnecting--; } else { @@ -2250,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: } @@ -2286,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 @@ -2299,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))) { @@ -2310,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/le_scan/ScanObjectsFactory.java b/android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java index 3d5521786c..7f0b1ef7b3 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java @@ -28,6 +28,7 @@ import com.android.bluetooth.btservice.BluetoothAdapterProxy; /** Factory class for object initialization to help with unit testing */ public class ScanObjectsFactory { private static final String TAG = ScanObjectsFactory.class.getSimpleName(); + private static ScanObjectsFactory sInstance; private static final Object INSTANCE_LOCK = new Object(); diff --git a/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java b/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java index 196886beb2..57a9cc53c1 100644 --- a/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java +++ b/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java @@ -43,7 +43,7 @@ import java.util.stream.Collectors; /** List of our registered scanners. */ public class ScannerMap { - private static final String TAG = "ScannerMap"; + private static final String TAG = ScannerMap.class.getSimpleName(); /** Internal map to keep track of logging information by app name */ private final HashMap<Integer, AppScanStats> mAppScanStatsMap = new HashMap<>(); diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAccountItem.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAccountItem.java index d1a77bb469..e8640454bf 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapAccountItem.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAccountItem.java @@ -23,7 +23,7 @@ import android.util.Log; * both Email Apps (group Parent item) and Accounts (Group child Item). */ public class BluetoothMapAccountItem implements Comparable<BluetoothMapAccountItem> { - private static final String TAG = "BluetoothMapAccountItem"; + private static final String TAG = BluetoothMapAccountItem.class.getSimpleName(); protected boolean mIsChecked; private final String mName; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAccountLoader.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAccountLoader.java index f985c0dfbd..0149e4368f 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapAccountLoader.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAccountLoader.java @@ -43,7 +43,7 @@ import java.util.Objects; // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class BluetoothMapAccountLoader { - private static final String TAG = "BluetoothMapAccountLoader"; + private static final String TAG = BluetoothMapAccountLoader.class.getSimpleName(); private Context mContext = null; private PackageManager mPackageManager = null; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java index 8169cb9305..10f8c788eb 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java @@ -40,8 +40,7 @@ import java.util.Objects; /** Class to construct content observers for email applications on the system. */ // Next tag value for ContentProfileErrorReportUtils.report(): 6 public class BluetoothMapAppObserver { - - private static final String TAG = "BluetoothMapAppObserver"; + private static final String TAG = BluetoothMapAppObserver.class.getSimpleName(); /* */ private Map<BluetoothMapAccountItem, List<BluetoothMapAccountItem>> mFullList; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java index f840e89c63..0e06971960 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java @@ -33,8 +33,7 @@ import java.util.Date; /** This class encapsulates the appParams needed for MAP. */ // Next tag value for ContentProfileErrorReportUtils.report(): 41 public class BluetoothMapAppParams { - - private static final String TAG = "BluetoothMapAppParams"; + private static final String TAG = BluetoothMapAppParams.class.getSimpleName(); private static final int MAX_LIST_COUNT = 0x01; private static final int START_OFFSET = 0x02; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java index 2cb5b3f014..d3d87e660a 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java @@ -69,8 +69,7 @@ import java.util.stream.Collectors; // Next tag value for ContentProfileErrorReportUtils.report(): 15 public class BluetoothMapContent { - - private static final String TAG = "BluetoothMapContent"; + private static final String TAG = BluetoothMapContent.class.getSimpleName(); // Parameter Mask for selection of parameters to return in listings private static final int MASK_SUBJECT = 0x00000001; @@ -359,7 +358,7 @@ public class BluetoothMapContent { mMessageColReception = c.getColumnIndex(BluetoothMapContract.MessageColumns.RECEPTION_STATE); mMessageColDelivery = - c.getColumnIndex(BluetoothMapContract.MessageColumns.DEVILERY_STATE); + c.getColumnIndex(BluetoothMapContract.MessageColumns.DELIVERY_STATE); mMessageColThreadId = c.getColumnIndex(BluetoothMapContract.MessageColumns.THREAD_ID); } @@ -468,7 +467,7 @@ public class BluetoothMapContent { } } - private void setProtected( + private static void setProtected( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -486,7 +485,7 @@ public class BluetoothMapContent { } } - private void setThreadId( + private static void setThreadId( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -508,7 +507,7 @@ public class BluetoothMapContent { } } - private void setThreadName( + private static void setThreadName( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -523,7 +522,7 @@ public class BluetoothMapContent { } } - private void setSent( + private static void setSent( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -548,7 +547,7 @@ public class BluetoothMapContent { } } - private void setRead( + private static void setRead( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -567,7 +566,7 @@ public class BluetoothMapContent { e.setRead((read == 1), ((ap.getParameterMask() & MASK_READ) != 0)); } - private void setPriority( + private static void setPriority( BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi, @@ -692,7 +691,8 @@ public class BluetoothMapContent { } } - private void setReceptionStatus(BluetoothMapMessageListingElement e, BluetoothMapAppParams ap) { + private static void setReceptionStatus( + BluetoothMapMessageListingElement e, BluetoothMapAppParams ap) { if ((ap.getParameterMask() & MASK_RECEPTION_STATUS) != 0) { String status = "complete"; Log.v(TAG, "setReceptionStatus: " + status); @@ -757,7 +757,7 @@ public class BluetoothMapContent { } } - private TYPE getType(FilterInfo fi) { + private static TYPE getType(FilterInfo fi) { TYPE type = null; Log.d(TAG, "getType: for filterMsgType" + fi.mMsgType); if (fi.mMsgType == FilterInfo.TYPE_SMS) { @@ -1287,7 +1287,7 @@ public class BluetoothMapContent { } } - private void setHandle(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi) { + private static void setHandle(BluetoothMapMessageListingElement e, Cursor c, FilterInfo fi) { long handle = -1; if (fi.mMsgType == FilterInfo.TYPE_SMS) { handle = c.getLong(fi.mSmsColId); @@ -1641,10 +1641,8 @@ public class BluetoothMapContent { return matchOriginator(c, fi, ap) && matchRecipient(c, fi, ap); } - /* - * Where filter functions - */ - private String setWhereFilterFolderTypeSms(String folder) { + /* Where filter functions */ + private static String setWhereFilterFolderTypeSms(String folder) { String where = ""; if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) { where = Sms.TYPE + " = 1 AND " + Sms.THREAD_ID + " <> -1"; @@ -1677,7 +1675,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeMms(String folder) { + private static String setWhereFilterFolderTypeMms(String folder) { String where = ""; if (BluetoothMapContract.FOLDER_NAME_INBOX.equalsIgnoreCase(folder)) { where = Mms.MESSAGE_BOX + " = 1 AND " + Mms.THREAD_ID + " <> -1"; @@ -1701,7 +1699,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeEmail(long folderId) { + private static String setWhereFilterFolderTypeEmail(long folderId) { String where = ""; if (folderId >= 0) { where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId; @@ -1717,7 +1715,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderTypeIm(long folderId) { + private static String setWhereFilterFolderTypeIm(long folderId) { String where = ""; if (folderId > BluetoothMapContract.FOLDER_ID_OTHER) { where = BluetoothMapContract.MessageColumns.FOLDER_ID + " = " + folderId; @@ -1733,7 +1731,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterFolderType( + private static String setWhereFilterFolderType( BluetoothMapFolderElement folderElement, FilterInfo fi) { String where = "1=1"; if (!folderElement.shouldIgnore()) { @@ -1751,7 +1749,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterReadStatus(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterReadStatus(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; if (ap.getFilterReadStatus() != -1) { if (fi.mMsgType == FilterInfo.TYPE_SMS) { @@ -1782,7 +1780,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterPeriod(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterPeriod(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; if ((ap.getFilterPeriodBegin() != -1)) { @@ -1816,7 +1814,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterOriginatorEmail(BluetoothMapAppParams ap) { + private static String setWhereFilterOriginatorEmail(BluetoothMapAppParams ap) { String where = ""; String orig = ap.getFilterOriginator(); @@ -1833,7 +1831,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterOriginatorIM(BluetoothMapAppParams ap) { + private static String setWhereFilterOriginatorIM(BluetoothMapAppParams ap) { String where = ""; String orig = ap.getFilterOriginator(); @@ -1850,7 +1848,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterPriority(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterPriority(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; int pri = ap.getFilterPriority(); /*only MMS have priority info */ @@ -1876,7 +1874,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) { + private static String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) { String where = ""; String recip = ap.getFilterRecipient(); @@ -1901,7 +1899,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterMessageHandle(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterMessageHandle(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; long id = -1; String msgHandle = ap.getFilterMsgHandleString(); @@ -1921,7 +1919,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilterThreadId(BluetoothMapAppParams ap, FilterInfo fi) { + private static String setWhereFilterThreadId(BluetoothMapAppParams ap, FilterInfo fi) { String where = ""; long id = -1; String msgHandle = ap.getFilterConvoIdString(); @@ -1942,7 +1940,7 @@ public class BluetoothMapContent { return where; } - private String setWhereFilter( + private static String setWhereFilter( BluetoothMapFolderElement folderElement, FilterInfo fi, BluetoothMapAppParams ap) { StringBuilder where = new StringBuilder(setWhereFilterFolderType(folderElement, fi)); @@ -2084,7 +2082,7 @@ public class BluetoothMapContent { * * @return boolean true if email is selected, false if not */ - private boolean emailSelected(BluetoothMapAppParams ap) { + private static boolean emailSelected(BluetoothMapAppParams ap) { int msgType = ap.getFilterMessageType(); Log.d(TAG, "emailSelected msgType: " + msgType); @@ -2106,7 +2104,7 @@ public class BluetoothMapContent { * * @return boolean true if im is selected, false if not */ - private boolean imSelected(BluetoothMapAppParams ap) { + private static boolean imSelected(BluetoothMapAppParams ap) { int msgType = ap.getFilterMessageType(); Log.d(TAG, "imSelected msgType: " + msgType); @@ -3382,7 +3380,7 @@ public class BluetoothMapContent { * @param contentUri the URI to append parameters to * @return the new URI with the appended parameters (if any) */ - private Uri appendConvoListQueryParameters(BluetoothMapAppParams ap, Uri contentUri) { + private static Uri appendConvoListQueryParameters(BluetoothMapAppParams ap, Uri contentUri) { Uri.Builder newUri = contentUri.buildUpon(); String str = ap.getFilterRecipient(); if (str != null) { @@ -3532,7 +3530,7 @@ public class BluetoothMapContent { * * @return the folder name. */ - private String getFolderName(int type, int threadId) { + private static String getFolderName(int type, int threadId) { if (threadId == -1) { return BluetoothMapContract.FOLDER_NAME_DELETED; @@ -3564,7 +3562,7 @@ public class BluetoothMapContent { long id = BluetoothMapUtils.getCpHandle(handle); if (appParams.getFractionRequest() == BluetoothMapAppParams.FRACTION_REQUEST_NEXT) { throw new IllegalArgumentException( - "FRACTION_REQUEST_NEXT does not make sence as" + "FRACTION_REQUEST_NEXT does not make sense as" + " we always return the full message."); } switch (type) { diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java index 31e6e90b79..15945c8fc1 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContentObserver.java @@ -90,7 +90,7 @@ import java.util.concurrent.TimeUnit; // Next tag value for ContentProfileErrorReportUtils.report(): 41 public class BluetoothMapContentObserver { - private static final String TAG = "BluetoothMapContentObserver"; + private static final String TAG = BluetoothMapContentObserver.class.getSimpleName(); // A message older than this will be ignored when notifying a new message. @VisibleForTesting @@ -100,7 +100,7 @@ public class BluetoothMapContentObserver { @VisibleForTesting static final String EVENT_TYPE_DELETE = "MessageDeleted"; @VisibleForTesting static final String EVENT_TYPE_REMOVED = "MessageRemoved"; @VisibleForTesting static final String EVENT_TYPE_SHIFT = "MessageShift"; - @VisibleForTesting static final String EVENT_TYPE_DELEVERY_SUCCESS = "DeliverySuccess"; + @VisibleForTesting static final String EVENT_TYPE_DELIVERY_SUCCESS = "DeliverySuccess"; @VisibleForTesting static final String EVENT_TYPE_SENDING_SUCCESS = "SendingSuccess"; @VisibleForTesting static final String EVENT_TYPE_SENDING_FAILURE = "SendingFailure"; @VisibleForTesting static final String EVENT_TYPE_DELIVERY_FAILURE = "DeliveryFailure"; @@ -346,9 +346,9 @@ public class BluetoothMapContentObserver { // Warning according to page 46/123 of MAP 1.3 spec Log.w( TAG, - "setObserverRemoteFeatureMask: Extended Event Reports 1.2 is not set eventhough" - + " PARTICIPANT_PRESENCE_CHANGE_BIT or PARTICIPANT_CHAT_STATE_CHANGE_BIT" - + " were set, mMapSupportedFeatures=" + "setObserverRemoteFeatureMask: Extended Event Reports 1.2 is not set even" + + " though PARTICIPANT_PRESENCE_CHANGE_BIT or" + + " PARTICIPANT_CHAT_STATE_CHANGE_BIT were set, mMapSupportedFeatures=" + mMapSupportedFeatures); ContentProfileErrorReportUtils.report( BluetoothProfile.MAP, @@ -518,7 +518,7 @@ public class BluetoothMapContentObserver { + Thread.currentThread().getId() + " Uri: " + uri.toString() - + " selfchange: " + + " selfChange: " + selfChange); if (uri.toString().contains(BluetoothMapContract.TABLE_CONVOCONTACT)) { @@ -604,7 +604,7 @@ public class BluetoothMapContentObserver { public int mContactColPriority = -1; public int mContactColLastOnline = -1; - public void setConvoColunms(Cursor c) { + public void setConvoColumns(Cursor c) { // mConvoColConvoId = c.getColumnIndex( // BluetoothMapContract.ConversationColumns.THREAD_ID); // mConvoColLastActivity = c.getColumnIndex( @@ -1262,7 +1262,7 @@ public class BluetoothMapContentObserver { Log.d(TAG, "Skip sending event of type: " + evt.eventType); return; } - } else if (Objects.equals(evt.eventType, EVENT_TYPE_DELEVERY_SUCCESS)) { + } else if (Objects.equals(evt.eventType, EVENT_TYPE_DELIVERY_SUCCESS)) { if (!sendEventDeliverySuccess(eventFilter)) { Log.d(TAG, "Skip sending event of type: " + evt.eventType); return; @@ -1451,7 +1451,7 @@ public class BluetoothMapContentObserver { try { if (c != null && c.moveToFirst()) { ConvoContactInfo cInfo = new ConvoContactInfo(); - cInfo.setConvoColunms(c); + cInfo.setConvoColumns(c); do { long convoId = c.getLong(cInfo.mContactColConvoId); if (convoId == 0) { @@ -1773,7 +1773,7 @@ public class BluetoothMapContentObserver { } long id = c.getLong(idIndex); int type = c.getInt(c.getColumnIndex(Mms.MESSAGE_BOX)); - int mtype = c.getInt(c.getColumnIndex(Mms.MESSAGE_TYPE)); + int mType = c.getInt(c.getColumnIndex(Mms.MESSAGE_TYPE)); int threadId = c.getInt(c.getColumnIndex(Mms.THREAD_ID)); // TODO: Go through code to see if we have an issue with mismatch in types // for threadId. Seems to be a long in DB?? @@ -1790,7 +1790,7 @@ public class BluetoothMapContentObserver { if (getMmsFolderName(type) .equalsIgnoreCase( BluetoothMapContract.FOLDER_NAME_INBOX) - && mtype != MESSAGE_TYPE_RETRIEVE_CONF) { + && mType != MESSAGE_TYPE_RETRIEVE_CONF) { continue; } msg = new Msg(id, type, threadId, read); @@ -2265,7 +2265,7 @@ public class BluetoothMapContentObserver { TAG, "Problems contacting the ContentProvider in mas Instance " + mMasId - + " restaring ObexServerSession"); + + " restarting ObexServerSession"); } } // TODO: check to see if there could be problem with IM and SMS in one instance @@ -2295,7 +2295,7 @@ public class BluetoothMapContentObserver { null, null, null); - cInfo.setConvoColunms(c); + cInfo.setConvoColumns(c); } else { Log.v( TAG, @@ -2536,7 +2536,7 @@ public class BluetoothMapContentObserver { TAG, "Problems contacting the ContentProvider in mas Instance " + mMasId - + " restaring ObexServerSession"); + + " restarting ObexServerSession"); } } // TODO: conversation contact updates if IM and SMS(MMS in one instance @@ -3480,7 +3480,7 @@ public class BluetoothMapContentObserver { if (uri == null) { // unable to insert MMS - Log.e(TAG, "Unabled to insert MMS " + values + "Uri: " + uri); + Log.e(TAG, "Unable to insert MMS " + values + "Uri: " + uri); ContentProfileErrorReportUtils.report( BluetoothProfile.MAP, BluetoothProtoEnums.BLUETOOTH_MAP_CONTENT_OBSERVER, diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java index 4782f09d39..1061ea6714 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java @@ -31,6 +31,7 @@ import java.util.Objects; // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class BluetoothMapConvoContactElement implements Comparable<BluetoothMapConvoContactElement> { + private static final String TAG = BluetoothMapConvoContactElement.class.getSimpleName(); public static final long CONTACT_ID_TYPE_SMS_MMS = 1; public static final long CONTACT_ID_TYPE_EMAIL = 2; @@ -46,7 +47,6 @@ public class BluetoothMapConvoContactElement private static final String XML_ATT_DISPLAY_NAME = "display_name"; private static final String XML_ATT_UCI = "x_bt_uci"; protected static final String XML_TAG_CONVOCONTACT = "convocontact"; - private static final String TAG = "BluetoothMapConvoContactElement"; private String mUci = null; private String mName = null; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListing.java b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListing.java index 03d233213f..e0a8073c32 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListing.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListing.java @@ -39,8 +39,9 @@ import java.util.Objects; // Next tag value for ContentProfileErrorReportUtils.report(): 3 public class BluetoothMapConvoListing { + private static final String TAG = BluetoothMapConvoListing.class.getSimpleName(); + private boolean mHasUnread = false; - private static final String TAG = "BluetoothMapConvoListing"; private static final String XML_TAG = "MAP-convo-listing"; private List<BluetoothMapConvoListingElement> mList; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListingElement.java b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListingElement.java index 9d29a77fc7..9a7fc80d39 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListingElement.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoListingElement.java @@ -39,6 +39,7 @@ import java.util.Objects; // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class BluetoothMapConvoListingElement implements Comparable<BluetoothMapConvoListingElement> { + private static final String TAG = BluetoothMapConvoListingElement.class.getSimpleName(); public static final String XML_TAG_CONVERSATION = "conversation"; private static final String XML_ATT_LAST_ACTIVITY = "last_activity"; @@ -47,7 +48,6 @@ public class BluetoothMapConvoListingElement private static final String XML_ATT_READ = "readstatus"; private static final String XML_ATT_VERSION_COUNTER = "version_counter"; private static final String XML_ATT_SUMMARY = "summary"; - private static final String TAG = "BluetoothMapConvoListingElement"; private SignedLongLong mId = null; private String mName = ""; // title of the conversation #REQUIRED, but allowed empty diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapFolderElement.java b/android/app/src/com/android/bluetooth/map/BluetoothMapFolderElement.java index e026ccd690..6430485642 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapFolderElement.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapFolderElement.java @@ -39,6 +39,8 @@ import java.util.Locale; /** Class to contain a single folder element representation. */ // Next tag value for ContentProfileErrorReportUtils.report(): 3 public class BluetoothMapFolderElement implements Comparable<BluetoothMapFolderElement> { + private static final String TAG = BluetoothMapFolderElement.class.getSimpleName(); + private String mName; private BluetoothMapFolderElement mParent = null; private long mFolderId = -1; @@ -50,8 +52,6 @@ public class BluetoothMapFolderElement implements Comparable<BluetoothMapFolderE private HashMap<String, BluetoothMapFolderElement> mSubFolders; - private static final String TAG = "BluetoothMapFolderElement"; - public BluetoothMapFolderElement(String name, BluetoothMapFolderElement parent) { this.mName = name; this.mParent = parent; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java index 35c18655f6..578cb4b4c5 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java @@ -44,7 +44,7 @@ import java.util.concurrent.atomic.AtomicLong; // Next tag value for ContentProfileErrorReportUtils.report(): 4 public class BluetoothMapMasInstance implements IObexConnectionHandler { - private static final String TAG = "BluetoothMapMasInstance"; + private static final String TAG = BluetoothMapMasInstance.class.getSimpleName(); private static int sInstanceCounter = 0; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java b/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java index daeb252363..9aa913de6f 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java @@ -35,8 +35,9 @@ import java.util.List; // Next tag value for ContentProfileErrorReportUtils.report(): 3 public class BluetoothMapMessageListing { + private static final String TAG = BluetoothMapMessageListing.class.getSimpleName(); + private boolean mHasUnread = false; - private static final String TAG = "BluetoothMapMessageListing"; private List<BluetoothMapMessageListingElement> mList; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java b/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java index 7e6dc2743e..87dd614f18 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java @@ -25,8 +25,7 @@ import java.util.Date; public class BluetoothMapMessageListingElement implements Comparable<BluetoothMapMessageListingElement> { - - private static final String TAG = "BluetoothMapMessageListingElement"; + private static final String TAG = BluetoothMapMessageListingElement.class.getSimpleName(); private long mCpHandle = 0; /* The content provider handle - without type information */ private String mSubject = null; diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java index 4c503bd0e1..77430eb319 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java @@ -52,8 +52,7 @@ import java.util.Calendar; // Next tag value for ContentProfileErrorReportUtils.report(): 74 public class BluetoothMapObexServer extends ServerRequestHandler { - - private static final String TAG = "BluetoothMapObexServer"; + private static final String TAG = BluetoothMapObexServer.class.getSimpleName(); private static final int UUID_LENGTH = 16; @@ -222,7 +221,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { } /** Add base (Inbox/Outbox/Sent/Deleted) */ - private void addBaseFolders(BluetoothMapFolderElement root) { + private static void addBaseFolders(BluetoothMapFolderElement root) { root.addFolder(BluetoothMapContract.FOLDER_NAME_INBOX); // root/telecom/msg/inbox root.addFolder(BluetoothMapContract.FOLDER_NAME_OUTBOX); root.addFolder(BluetoothMapContract.FOLDER_NAME_SENT); @@ -230,7 +229,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { } /** Add SMS / MMS Base folders */ - private void addSmsMmsFolders(BluetoothMapFolderElement root) { + private static void addSmsMmsFolders(BluetoothMapFolderElement root) { root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_INBOX); // root/telecom/msg/inbox root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_OUTBOX); root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_SENT); @@ -238,7 +237,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler { root.addSmsMmsFolder(BluetoothMapContract.FOLDER_NAME_DRAFT); } - private void addImFolders(BluetoothMapFolderElement root) throws RemoteException { + private static void addImFolders(BluetoothMapFolderElement root) throws RemoteException { // Select all parent folders root.addImFolder( BluetoothMapContract.FOLDER_NAME_INBOX, diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java index 09f6961c12..b82c3e7333 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java @@ -17,6 +17,8 @@ package com.android.bluetooth.map; 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 java.util.Objects.requireNonNull; @@ -70,7 +72,7 @@ import java.util.List; // Next tag value for ContentProfileErrorReportUtils.report(): 25 public class BluetoothMapService extends ProfileService { - private static final String TAG = "BluetoothMapService"; + private static final String TAG = BluetoothMapService.class.getSimpleName(); /** * To enable MAP DEBUG/VERBOSE logging - run below cmd in adb shell, and restart @@ -648,9 +650,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; } } } @@ -1276,7 +1278,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 +1358,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); diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java index 7909aea4ce..b22065ac28 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java @@ -43,8 +43,8 @@ import java.util.Random; // Next tag value for ContentProfileErrorReportUtils.report(): 10 public class BluetoothMapSmsPdu { + private static final String TAG = BluetoothMapSmsPdu.class.getSimpleName(); - private static final String TAG = "BluetoothMapSmsPdu"; private static final int INVALID_VALUE = -1; public static final int SMS_TYPE_GSM = 1; public static final int SMS_TYPE_CDMA = 2; @@ -381,7 +381,7 @@ public class BluetoothMapSmsPdu { } @SuppressWarnings("JavaUtilDate") // TODO: b/365629730 -- prefer Instant or LocalDate - private void gsmWriteDate(ByteArrayOutputStream header, long time) { + private static void gsmWriteDate(ByteArrayOutputStream header, long time) { SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss"); Date date = new Date(time); String timeStr = format.format(date); // Format to YYMMDDTHHMMSS UTC time diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java b/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java index 6f5687dc36..7fdc6601fb 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java @@ -49,8 +49,8 @@ import java.util.regex.Pattern; /** Various utility methods and generic defines that can be used throughout MAPS */ // Next tag value for ContentProfileErrorReportUtils.report(): 11 public class BluetoothMapUtils { + private static final String TAG = BluetoothMapUtils.class.getSimpleName(); - private static final String TAG = "BluetoothMapUtils"; /* We use the upper 4 bits for the type mask. * TODO: When more types are needed, consider just using a number * in stead of a bit to indicate the message type. Then 4 diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java index 7b7d879d0a..c79f3eaca9 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java @@ -36,8 +36,7 @@ import java.util.regex.Pattern; // Next tag value for ContentProfileErrorReportUtils.report(): 10 public abstract class BluetoothMapbMessage { - - protected static final String TAG = BluetoothMapbMessage.class.getSimpleName(); + static final String TAG = BluetoothMapbMessage.class.getSimpleName(); private static final Pattern UNESCAPE_COLON = Pattern.compile("[^\\\\]:"); protected static final Pattern COLON = Pattern.compile(":"); diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java index 6e5204576a..a93f85dd3b 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java @@ -742,7 +742,7 @@ public class BluetoothMapbMessageMime extends BluetoothMapbMessage { newPart.mData = decodeBody(body, mMyEncoding, mCharset); } - private byte[] decodeBody(String body, String encoding, String charset) { + private static byte[] decodeBody(String body, String encoding, String charset) { if (encoding != null && Ascii.toUpperCase(encoding).contains("BASE64")) { return Base64.decode(body, Base64.DEFAULT); } else if (encoding != null && Ascii.toUpperCase(encoding).contains("QUOTED-PRINTABLE")) { diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java b/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java index c5de8eb6ba..8f37895bfc 100644 --- a/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java +++ b/android/app/src/com/android/bluetooth/map/BluetoothMnsObexClient.java @@ -47,8 +47,7 @@ import java.io.OutputStream; */ // Next tag value for ContentProfileErrorReportUtils.report(): 16 public class BluetoothMnsObexClient { - - private static final String TAG = "BluetoothMnsObexClient"; + private static final String TAG = BluetoothMnsObexClient.class.getSimpleName(); private ObexTransport mTransport; public Handler mHandler = null; @@ -523,7 +522,7 @@ public class BluetoothMnsObexClient { BluetoothProtoEnums.BLUETOOTH_MNS_OBEX_CLIENT, BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION, 12); - handleSendException(e.toString()); + Log.e(TAG, "Error when sending event", e); error = true; } catch (IndexOutOfBoundsException e) { ContentProfileErrorReportUtils.report( @@ -531,7 +530,7 @@ public class BluetoothMnsObexClient { BluetoothProtoEnums.BLUETOOTH_MNS_OBEX_CLIENT, BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION, 13); - handleSendException(e.toString()); + Log.e(TAG, "Error when sending event", e); error = true; } finally { try { @@ -572,10 +571,6 @@ public class BluetoothMnsObexClient { return responseCode; } - private void handleSendException(String exception) { - Log.e(TAG, "Error when sending event: " + exception); - } - private void notifyUpdateWakeLock() { if (mCallback != null) { Message msg = Message.obtain(mCallback); diff --git a/android/app/src/com/android/bluetooth/map/MmsFileProvider.java b/android/app/src/com/android/bluetooth/map/MmsFileProvider.java index 75c821e046..22810e182c 100644 --- a/android/app/src/com/android/bluetooth/map/MmsFileProvider.java +++ b/android/app/src/com/android/bluetooth/map/MmsFileProvider.java @@ -26,6 +26,7 @@ import android.provider.Telephony.Mms; import android.util.Log; import com.android.bluetooth.BluetoothStatsLog; +import com.android.bluetooth.Utils; import com.android.bluetooth.content_profiles.ContentProfileErrorReportUtils; import com.google.android.mms.MmsException; @@ -43,7 +44,9 @@ import java.io.IOException; */ // Next tag value for ContentProfileErrorReportUtils.report(): 5 public class MmsFileProvider extends ContentProvider { - static final String TAG = "BluetoothMmsFileProvider"; + private static final String TAG = + Utils.TAG_PREFIX_BLUETOOTH + MmsFileProvider.class.getSimpleName(); + private PipeWriter mPipeWriter = new PipeWriter(); /*package*/ diff --git a/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java b/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java index c800ec3aac..62bd674145 100644 --- a/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java +++ b/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java @@ -42,8 +42,7 @@ import java.util.regex.Pattern; */ // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class SmsMmsContacts { - - private static final String TAG = "SmsMmsContacts"; + private static final String TAG = SmsMmsContacts.class.getSimpleName(); private HashMap<Long, String> mPhoneNumbers = null; diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java index 109bc1411a..eee34a4aa3 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientContent.java @@ -524,7 +524,7 @@ class MapClientContent { return Telephony.Threads.getOrCreateThreadId(mContext, messageContacts); } - private void getRecipientsFromMessage(Bmessage message, Set<String> messageContacts) { + private static void getRecipientsFromMessage(Bmessage message, Set<String> messageContacts) { List<VCardEntry> recipients = message.getRecipients(); for (VCardEntry recipient : recipients) { List<VCardEntry.PhoneData> phoneData = recipient.getPhoneList(); @@ -535,7 +535,7 @@ class MapClientContent { } } - private String getOriginatorNumber(Bmessage message) { + private static String getOriginatorNumber(Bmessage message) { VCardEntry originator = message.getOriginator(); if (originator == null) { return null; @@ -549,7 +549,7 @@ class MapClientContent { return PhoneNumberUtils.extractNetworkPortion(phoneData.get(0).getNumber()); } - private String getFirstRecipientNumber(Bmessage message) { + private static String getFirstRecipientNumber(Bmessage message) { List<VCardEntry> recipients = message.getRecipients(); if (recipients == null || recipients.isEmpty()) { return null; @@ -794,7 +794,7 @@ class MapClientContent { return messages; } - private Type getMessageTypeFromUri(Uri uri) { + private static Type getMessageTypeFromUri(Uri uri) { if (Sms.CONTENT_URI.equals(uri) || Sms.Inbox.CONTENT_URI.equals(uri) || Sms.Sent.CONTENT_URI.equals(uri)) { diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java index 506c2a3bb7..d7fd0169c2 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java +++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java @@ -18,6 +18,9 @@ package com.android.bluetooth.mapclient; 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 java.util.Objects.requireNonNull; import static java.util.Objects.requireNonNullElseGet; @@ -168,8 +171,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 +208,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 +245,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(); } /** @@ -359,7 +358,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 +517,7 @@ public class MapClientService extends ProfileService { MapClientService service = getServiceAndEnforcePrivileged(source); if (service == null) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } return service.getConnectionState(device); @@ -591,7 +590,7 @@ public class MapClientService extends ProfileService { return; } - if (stateMachine.getState() == BluetoothProfile.STATE_CONNECTED) { + if (stateMachine.getState() == STATE_CONNECTED) { stateMachine.disconnect(); } } diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java index 2c3420af84..f5f53a7378 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java +++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java @@ -41,6 +41,10 @@ package com.android.bluetooth.mapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; import static android.Manifest.permission.RECEIVE_SMS; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -165,8 +169,8 @@ class MceStateMachine extends StateMachine { private final AdapterService mAdapterService; // Connectivity States - private int mPreviousState = BluetoothProfile.STATE_DISCONNECTED; - private int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED; + private int mPreviousState = STATE_DISCONNECTED; + private int mMostRecentState = STATE_DISCONNECTED; private MasClient mMasClient; private MapClientContent mDatabase; @@ -266,8 +270,7 @@ class MceStateMachine extends StateMachine { } private void initStateMachine() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; - + mPreviousState = STATE_DISCONNECTED; addState(mDisconnected); addState(mConnecting); @@ -307,7 +310,7 @@ class MceStateMachine extends StateMachine { + prevState + ", new=" + state); - if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) { + if (prevState != state && state == STATE_CONNECTED) { MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.MAP_CLIENT); } setState(state); @@ -360,7 +363,7 @@ class MceStateMachine extends StateMachine { if (contacts == null || contacts.length <= 0) { return false; } - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { Bmessage bmsg = new Bmessage(); // Set type and status. bmsg.setType(getDefaultMessageType()); @@ -413,7 +416,7 @@ class MceStateMachine extends StateMachine { synchronized boolean getMessage(String handle) { Log.d(TAG, "getMessage" + handle); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { sendMessage(MSG_INBOUND_MESSAGE, handle); return true; } @@ -422,7 +425,7 @@ class MceStateMachine extends StateMachine { synchronized boolean getUnreadMessages() { Log.d(TAG, "getMessage"); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { sendMessage(MSG_GET_MESSAGE_LISTING, FOLDER_INBOX); return true; } @@ -430,7 +433,7 @@ class MceStateMachine extends StateMachine { } synchronized int getSupportedFeatures() { - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED && mMasClient != null) { + if (mMostRecentState == STATE_CONNECTED && mMasClient != null) { Log.d(TAG, "returning getSupportedFeatures from SDP record"); return mMasClient.getSdpMasRecord().getSupportedFeatures(); } @@ -440,7 +443,7 @@ class MceStateMachine extends StateMachine { synchronized boolean setMessageStatus(String handle, int status) { Log.d(TAG, "setMessageStatus(" + handle + ", " + status + ")"); - if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) { + if (mMostRecentState == STATE_CONNECTED) { RequestSetMessageStatus.StatusIndicator statusIndicator; byte value; switch (status) { @@ -478,11 +481,11 @@ class MceStateMachine extends StateMachine { return false; } - private String getContactURIFromPhone(String number) { + private static String getContactURIFromPhone(String number) { return PhoneAccount.SCHEME_TEL + ":" + number; } - private String getContactURIFromEmail(String email) { + private static String getContactURIFromEmail(String email) { return SCHEME_MAILTO + "://" + email; } @@ -536,14 +539,14 @@ class MceStateMachine extends StateMachine { Utils.getLoggableAddress(mDevice) + " [Disconnected]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTED); - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; + onConnectionStateChanged(mPreviousState, STATE_DISCONNECTED); + mPreviousState = STATE_DISCONNECTED; quit(); } @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTED; + mPreviousState = STATE_DISCONNECTED; } } @@ -555,7 +558,7 @@ class MceStateMachine extends StateMachine { Utils.getLoggableAddress(mDevice) + " [Connecting]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTING); + onConnectionStateChanged(mPreviousState, STATE_CONNECTING); // When commanded to connect begin SDP to find the MAS server. mDevice.sdpSearch(BluetoothUuid.MAS); @@ -646,7 +649,7 @@ class MceStateMachine extends StateMachine { @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_CONNECTING; + mPreviousState = STATE_CONNECTING; removeMessages(MSG_CONNECTING_TIMEOUT); } } @@ -671,7 +674,7 @@ class MceStateMachine extends StateMachine { if (mDatabase == null) { mDatabase = new MapClientContent(mService, callbacks, mDevice); } - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTED); + onConnectionStateChanged(mPreviousState, STATE_CONNECTED); if (Utils.isPtsTestMode()) return; mMasClient.makeRequest(new RequestSetPath(FOLDER_TELECOM)); @@ -862,7 +865,7 @@ class MceStateMachine extends StateMachine { public void exit() { mDatabase.cleanUp(); mDatabase = null; - mPreviousState = BluetoothProfile.STATE_CONNECTED; + mPreviousState = STATE_CONNECTED; } /** @@ -1195,7 +1198,7 @@ class MceStateMachine extends StateMachine { * Retrieves the URIs of all the participants of a group conversation, besides the sender of * the message. */ - private String[] getRecipientsUri(List<VCardEntry> recipients) { + private static String[] getRecipientsUri(List<VCardEntry> recipients) { Set<String> uris = new HashSet<>(); for (VCardEntry recipient : recipients) { @@ -1272,7 +1275,7 @@ class MceStateMachine extends StateMachine { + " [Disconnecting]: Entered, message=" + getMessageName(getCurrentMessage().what)); - onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTING); + onConnectionStateChanged(mPreviousState, STATE_DISCONNECTING); if (mMasClient != null) { mMasClient.makeRequest(new RequestSetNotificationRegistration(false)); @@ -1316,7 +1319,7 @@ class MceStateMachine extends StateMachine { @Override public void exit() { - mPreviousState = BluetoothProfile.STATE_DISCONNECTING; + mPreviousState = STATE_DISCONNECTING; removeMessages(MSG_DISCONNECTING_TIMEOUT); } } @@ -1326,7 +1329,7 @@ class MceStateMachine extends StateMachine { sendMessage(MSG_NOTIFICATION, ev); } - private String getMessageName(int what) { + private static String getMessageName(int what) { switch (what) { case MSG_MAS_CONNECTED: return "MSG_MAS_CONNECTED"; diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsService.java b/android/app/src/com/android/bluetooth/mapclient/MnsService.java index 99cee09481..b3194e70e7 100644 --- a/android/app/src/com/android/bluetooth/mapclient/MnsService.java +++ b/android/app/src/com/android/bluetooth/mapclient/MnsService.java @@ -16,8 +16,9 @@ package com.android.bluetooth.mapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSocket; import android.util.Log; @@ -123,7 +124,7 @@ public class MnsService { + " (name: " + Utils.getName(device)); return false; - } else if (stateMachine.getState() != BluetoothProfile.STATE_CONNECTED) { + } else if (stateMachine.getState() != STATE_CONNECTED) { Log.e( TAG, "Error: statemachine for device: " diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java index a5d0c2e996..7550b90850 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/BmessageBuilder.java @@ -148,7 +148,7 @@ class BmessageBuilder { mBmsg.append(VCARD_END).append(CRLF); } - private String buildVcardN(VCardEntry vcard) { + private static String buildVcardN(VCardEntry vcard) { NameData nd = vcard.getNameData(); StringBuilder sb = new StringBuilder(); diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java b/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java index f11c5c845e..8dbd8d349d 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/EventReport.java @@ -39,7 +39,8 @@ import java.util.Map; * <p>This object will be received in {@link Client#EVENT_EVENT_REPORT} callback message. */ public class EventReport { - private static final String TAG = "EventReport"; + private static final String TAG = EventReport.class.getSimpleName(); + private final Type mType; private final String mDateTime; private final String mHandle; @@ -127,7 +128,7 @@ public class EventReport { return ev; } - private Type parseType(String type) throws IllegalArgumentException { + private static Type parseType(String type) throws IllegalArgumentException { for (Type t : Type.values()) { if (t.toString().equals(type)) { return t; @@ -137,7 +138,7 @@ public class EventReport { throw new IllegalArgumentException("Invalid value for type: " + type); } - private Bmessage.Type parseMsgType(String msgType) throws IllegalArgumentException { + private static Bmessage.Type parseMsgType(String msgType) throws IllegalArgumentException { for (Bmessage.Type t : Bmessage.Type.values()) { if (t.name().equals(msgType)) { return t; diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/FolderListing.java b/android/app/src/com/android/bluetooth/mapclient/obex/FolderListing.java index 74a3ed2152..37617d1bb7 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/FolderListing.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/FolderListing.java @@ -28,8 +28,7 @@ import java.util.ArrayList; import java.util.List; class FolderListing { - - private static final String TAG = "FolderListing"; + private static final String TAG = FolderListing.class.getSimpleName(); private final List<String> mFolders = new ArrayList<>(); diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/Message.java b/android/app/src/com/android/bluetooth/mapclient/obex/Message.java index 0cfaf74660..8a2e9d3370 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/Message.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/Message.java @@ -130,11 +130,11 @@ public class Message { mProtected = yesnoToBoolean(attrs.get("protected")); } - private boolean yesnoToBoolean(String yesno) { + private static boolean yesnoToBoolean(String yesno) { return "yes".equals(yesno); } - private Type strToType(String s) { + private static Type strToType(String s) { if ("EMAIL".equals(s)) { return Type.EMAIL; } else if ("SMS_GSM".equals(s)) { @@ -148,7 +148,7 @@ public class Message { return Type.UNKNOWN; } - private ReceptionStatus strToReceptionStatus(String s) { + private static ReceptionStatus strToReceptionStatus(String s) { if ("complete".equals(s)) { return ReceptionStatus.COMPLETE; } else if ("fractioned".equals(s)) { diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/MessagesListing.java b/android/app/src/com/android/bluetooth/mapclient/obex/MessagesListing.java index 799384a57b..1b5e214838 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/MessagesListing.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/MessagesListing.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.Map; class MessagesListing { - private static final String TAG = "MessagesListing"; + private static final String TAG = MessagesListing.class.getSimpleName(); private final List<Message> mMessages = new ArrayList<>(); diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java index 33e576bdac..5d425d0864 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java @@ -36,8 +36,7 @@ import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; class RequestGetMessage extends Request { - - private static final String TAG = "RequestGetMessage"; + private static final String TAG = RequestGetMessage.class.getSimpleName(); private static final String TYPE = "x-bt/message"; diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java index 71b178cce8..afca4d5de8 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessagesListingForOwnNumber.java @@ -243,7 +243,7 @@ class RequestGetMessagesListingForOwnNumber extends Request { + (" maxCount=" + maxCount)); } - private byte messageTypeBasedOnFolder(String folderName) { + private static byte messageTypeBasedOnFolder(String folderName) { byte messageType = (byte) (MessagesFilter.MESSAGE_TYPE_SMS_GSM diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java index 97f6f035c7..73c7193b21 100644 --- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java +++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java @@ -25,12 +25,13 @@ import com.android.obex.HeaderSet; import java.io.IOException; final class RequestSetMessageStatus extends Request { + private static final String TAG = RequestSetMessageStatus.class.getSimpleName(); + public enum StatusIndicator { READ, DELETED } - private static final String TAG = "RequestSetMessageStatus"; private static final String TYPE = "x-bt/messageStatus"; private final StatusIndicator mStatusInd; private final byte mValue; diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java index f92bbcd532..a011fe26c4 100644 --- a/android/app/src/com/android/bluetooth/mcp/McpService.java +++ b/android/app/src/com/android/bluetooth/mcp/McpService.java @@ -39,7 +39,7 @@ import java.util.Map; /** Provides Media Control Profile, as a service in the Bluetooth application. */ public class McpService extends ProfileService { - private static final String TAG = "BluetoothMcpService"; + private static final String TAG = Utils.TAG_PREFIX_BLUETOOTH + McpService.class.getSimpleName(); private static McpService sMcpService; diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java index ef234b19a7..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; @@ -73,7 +75,7 @@ import java.util.UUID; * <p>Implemented according to Media Control Service v1.0 specification. */ public class MediaControlGattService implements MediaControlGattServiceInterface { - private static final String TAG = "MediaControlGattService"; + private static final String TAG = MediaControlGattService.class.getSimpleName(); /* MCS assigned UUIDs */ public static final UUID UUID_PLAYER_NAME = @@ -438,12 +440,12 @@ public class MediaControlGattService implements MediaControlGattServiceInterface } }); - private long millisecondsToMcsInterval(long interval) { + private static long millisecondsToMcsInterval(long interval) { /* MCS presents time in 0.01s intervals */ return interval / 10; } - private long mcsIntervalToMilliseconds(long interval) { + private static long mcsIntervalToMilliseconds(long interval) { /* MCS presents time in 0.01s intervals */ return interval * 10L; } @@ -935,7 +937,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange"); - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { ClearUnauthorizedGattOperations(device); } } @@ -1259,7 +1261,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface public boolean isDeviceConnected(BluetoothDevice device) { return mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT_SERVER) - == BluetoothProfile.STATE_CONNECTED; + == STATE_CONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppBatch.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppBatch.java index b5e70e17b3..9411e4d01c 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppBatch.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppBatch.java @@ -59,7 +59,7 @@ import java.util.ArrayList; */ public class BluetoothOppBatch { - private static final String TAG = "BtOppBatch"; + private static final String TAG = BluetoothOppBatch.class.getSimpleName(); public int mId; public int mStatus; @@ -100,12 +100,11 @@ public class BluetoothOppBatch { * @param info, BluetoothOppShareInfo */ public BluetoothOppBatch(Context context, BluetoothOppShareInfo info) { - BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); mContext = context; mShares = new ArrayList(); mTimestamp = info.mTimestamp; mDirection = info.mDirection; - mDestination = adapter.getRemoteDevice(info.mDestination); + mDestination = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(info.mDestination); mStatus = Constants.BATCH_STATUS_PENDING; mShares.add(info); diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivity.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivity.java index c1c1251f23..10ad0d4154 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivity.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivity.java @@ -54,7 +54,7 @@ import com.android.internal.annotations.VisibleForTesting; /** This class is designed to show BT enabling progress. */ public class BluetoothOppBtEnablingActivity extends AlertActivity { - private static final String TAG = "BluetoothOppEnablingActivity"; + private static final String TAG = BluetoothOppBtEnablingActivity.class.getSimpleName(); private static final int BT_ENABLING_TIMEOUT = 0; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiver.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiver.java index ffaad12849..d7865dd580 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiver.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppHandoverReceiver.java @@ -30,7 +30,7 @@ import com.android.bluetooth.flags.Flags; import java.util.ArrayList; public class BluetoothOppHandoverReceiver extends BroadcastReceiver { - public static final String TAG = "BluetoothOppHandoverReceiver"; + private static final String TAG = BluetoothOppHandoverReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppIncomingFileConfirmActivity.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppIncomingFileConfirmActivity.java index 61b8bbdd51..e3f48eaa56 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppIncomingFileConfirmActivity.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppIncomingFileConfirmActivity.java @@ -63,7 +63,7 @@ import com.android.internal.annotations.VisibleForTesting; /** This class is designed to ask user to confirm if accept incoming file; */ // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class BluetoothOppIncomingFileConfirmActivity extends AlertActivity { - private static final String TAG = "BluetoothIncomingFileConfirmActivity"; + private static final String TAG = BluetoothOppIncomingFileConfirmActivity.class.getSimpleName(); @VisibleForTesting static final int DISMISS_TIMEOUT_DIALOG = 0; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java index 7956690f17..8f3b35de51 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java @@ -71,7 +71,7 @@ import java.util.regex.Pattern; */ // Next tag value for ContentProfileErrorReportUtils.report(): 11 public class BluetoothOppLauncherActivity extends Activity { - private static final String TAG = "BluetoothOppLauncherActivity"; + private static final String TAG = BluetoothOppLauncherActivity.class.getSimpleName(); // Regex that matches characters that have special meaning in HTML. '<', '>', '&' and // multiple continuous spaces. diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java index bc276ec6e9..fda2697750 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java @@ -68,7 +68,7 @@ import java.util.List; */ // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class BluetoothOppManager { - private static final String TAG = "BluetoothOppManager"; + private static final String TAG = BluetoothOppManager.class.getSimpleName(); @VisibleForTesting static BluetoothOppManager sInstance; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java index 61fcb794bd..8e5a95ffd7 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java @@ -62,7 +62,7 @@ import java.util.HashMap; * ongoing transfer, incoming transfer need confirm and complete (successful or failed) transfer. */ class BluetoothOppNotification { - private static final String TAG = "BluetoothOppNotification"; + private static final String TAG = BluetoothOppNotification.class.getSimpleName(); static final String STATUS = "(" + BluetoothShare.STATUS + " == '192'" + ")"; @@ -615,7 +615,8 @@ class BluetoothOppNotification { } } - if (inboundNum > 0 && outboundNum > 0) { + // When removing flag oppRemoveEmptyGroupNotification, remove the summary ID too. + if (!Flags.oppRemoveEmptyGroupNotification() && inboundNum > 0 && outboundNum > 0) { Notification.Builder b = new Notification.Builder(mContext, OPP_NOTIFICATION_CHANNEL) .setGroup(NOTIFICATION_GROUP_KEY_TRANSFER_COMPLETE) @@ -631,11 +632,6 @@ class BluetoothOppNotification { .setLocalOnly(true); mNotificationMgr.notify(NOTIFICATION_ID_COMPLETE_SUMMARY, b.build()); - } else if (Flags.oppRemoveEmptyGroupNotification() && inboundNum == 0 && outboundNum == 0) { - if (mNotificationMgr != null) { - mNotificationMgr.cancel(NOTIFICATION_ID_COMPLETE_SUMMARY); - Log.v(TAG, "empty group summary notification was removed."); - } } } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java index e2880b14e9..1b2e0a15fd 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java @@ -69,8 +69,7 @@ import java.io.OutputStream; /** This class runs as an OBEX client */ // Next tag value for ContentProfileErrorReportUtils.report(): 17 public class BluetoothOppObexClientSession implements BluetoothOppObexSession { - - private static final String TAG = "BtOppObexClient"; + private static final String TAG = BluetoothOppObexClientSession.class.getSimpleName(); private final ObexTransport mTransport; private final Context mContext; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java index 2b703993f9..17a7bdae36 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java @@ -73,7 +73,7 @@ import java.util.Arrays; // Next tag value for ContentProfileErrorReportUtils.report(): 15 public class BluetoothOppObexServerSession extends ServerRequestHandler implements BluetoothOppObexSession { - private static final String TAG = "BtOppObexServer"; + private static final String TAG = BluetoothOppObexServerSession.class.getSimpleName(); private final Context mContext; private final ObexTransport mTransport; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java index a4ee86a1ee..13dc28f2a2 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java @@ -50,7 +50,7 @@ import java.util.HashMap; * replaced by bluetooth_devices in SettingsProvider */ public class BluetoothOppPreference { - private static final String TAG = "BluetoothOppPreference"; + private static final String TAG = BluetoothOppPreference.class.getSimpleName(); private static BluetoothOppPreference sInstance; @@ -86,7 +86,7 @@ public class BluetoothOppPreference { mChannels = (HashMap<String, Integer>) mChannelPreference.getAll(); } - private String getChannelKey(BluetoothDevice remoteDevice, int uuid) { + private static String getChannelKey(BluetoothDevice remoteDevice, int uuid) { return getBrEdrAddress(remoteDevice) + "_" + Integer.toHexString(uuid); } @@ -177,7 +177,7 @@ public class BluetoothOppPreference { } @SuppressLint("AndroidFrameworkRequiresPermission") - private String getBrEdrAddress(BluetoothDevice device) { + private static String getBrEdrAddress(BluetoothDevice device) { if (Flags.identityAddressNullIfNotKnown()) { return Utils.getBrEdrAddress(device); } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppProvider.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppProvider.java index 4def90b438..467654c96e 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppProvider.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppProvider.java @@ -56,7 +56,7 @@ import java.util.List; /** This provider allows application to interact with Bluetooth OPP manager */ // Next tag value for ContentProfileErrorReportUtils.report(): 5 public final class BluetoothOppProvider extends ContentProvider { - private static final String TAG = "BluetoothOppProvider"; + private static final String TAG = BluetoothOppProvider.class.getSimpleName(); /** Database filename */ private static final String DB_NAME = "btopp.db"; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java index 220ec2e870..eb9b7f91c4 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiver.java @@ -60,7 +60,7 @@ import com.android.bluetooth.flags.Flags; */ // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class BluetoothOppReceiver extends BroadcastReceiver { - private static final String TAG = "BluetoothOppReceiver"; + private static final String TAG = BluetoothOppReceiver.class.getSimpleName(); @Override public void onReceive(Context context, Intent intent) { @@ -285,7 +285,7 @@ public class BluetoothOppReceiver extends BroadcastReceiver { } } - private void cancelNotification(Context context, int id) { + private static void cancelNotification(Context context, int id) { NotificationManager notMgr = context.getSystemService(NotificationManager.class); if (notMgr == null) { return; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppSendFileInfo.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppSendFileInfo.java index 2d727f9fdf..374e87b6db 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppSendFileInfo.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppSendFileInfo.java @@ -64,7 +64,7 @@ import java.util.Objects; */ // Next tag value for ContentProfileErrorReportUtils.report(): 16 public class BluetoothOppSendFileInfo { - private static final String TAG = "BluetoothOppSendFileInfo"; + private static final String TAG = BluetoothOppSendFileInfo.class.getSimpleName(); /** Reusable SendFileInfo for error status. */ static final BluetoothOppSendFileInfo SEND_FILE_INFO_ERROR = diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java index 2492f45af0..75af82b1ea 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java @@ -84,6 +84,7 @@ import java.util.Locale; */ // Next tag value for ContentProfileErrorReportUtils.report(): 22 public class BluetoothOppService extends ProfileService implements IObexConnectionHandler { + private static final String TAG = BluetoothOppService.class.getSimpleName(); /** Owned providers and activities */ private static final String OPP_PROVIDER = BluetoothOppProvider.class.getCanonicalName(); @@ -128,8 +129,6 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti } } - private static final String TAG = "BtOppService"; - /** Observer to get notified when the content observer's data changes */ private BluetoothShareContentObserver mObserver; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java index 9006faa3f1..7ce5ef6bb2 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java @@ -73,7 +73,7 @@ import java.io.IOException; // Next tag value for ContentProfileErrorReportUtils.report(): 24 @SuppressLint("AndroidFrameworkRequiresPermission") public class BluetoothOppTransfer implements BluetoothOppBatch.BluetoothOppBatchListener { - private static final String TAG = "BtOppTransfer"; + private static final String TAG = BluetoothOppTransfer.class.getSimpleName(); @VisibleForTesting static final int TRANSPORT_ERROR = 10; @@ -1019,7 +1019,7 @@ public class BluetoothOppTransfer implements BluetoothOppBatch.BluetoothOppBatch } } - private String getBrEdrAddress(BluetoothDevice device) { + private static String getBrEdrAddress(BluetoothDevice device) { if (Flags.identityAddressNullIfNotKnown()) { return Utils.getBrEdrAddress(device); } diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferActivity.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferActivity.java index 77a2191528..6e9c0c5c19 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferActivity.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferActivity.java @@ -68,7 +68,7 @@ import com.google.common.annotations.VisibleForTesting; // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class BluetoothOppTransferActivity extends AlertActivity implements DialogInterface.OnClickListener { - private static final String TAG = "BluetoothOppTransferActivity"; + private static final String TAG = BluetoothOppTransferActivity.class.getSimpleName(); private Uri mUri; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java index a79ab071c3..0332b1394e 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransferHistory.java @@ -71,7 +71,7 @@ import com.android.bluetooth.flags.Flags; // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class BluetoothOppTransferHistory extends Activity implements View.OnCreateContextMenuListener, OnItemClickListener { - private static final String TAG = "BluetoothOppTransferHistory"; + private static final String TAG = BluetoothOppTransferHistory.class.getSimpleName(); private ListView mListView; diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java index 819e35cedd..bb8df3da0e 100644 --- a/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java +++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java @@ -75,7 +75,7 @@ import java.util.concurrent.ConcurrentHashMap; /** This class has some utilities for Opp application; */ // Next tag value for ContentProfileErrorReportUtils.report(): 10 public class BluetoothOppUtility { - private static final String TAG = "BluetoothOppUtility"; + private static final String TAG = BluetoothOppUtility.class.getSimpleName(); /** Whether the device has the "nosdcard" characteristic, or null if not-yet-known. */ private static Boolean sNoSdCard = null; diff --git a/android/app/src/com/android/bluetooth/opp/Constants.java b/android/app/src/com/android/bluetooth/opp/Constants.java index 5560809328..490c7e14c8 100644 --- a/android/app/src/com/android/bluetooth/opp/Constants.java +++ b/android/app/src/com/android/bluetooth/opp/Constants.java @@ -55,7 +55,9 @@ import java.util.regex.Pattern; // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class Constants { /** Tag used for debugging/logging */ - public static final String TAG = "BluetoothOpp"; + public static final String TAG_PREFIX_BLUETOOTH_OPP = "BluetoothOpp"; + + static final String TAG = TAG_PREFIX_BLUETOOTH_OPP + Constants.class.getSimpleName(); /** the permission required for others to send us handover broadcasts */ static final String PERMISSION_ALLOWLIST_BLUETOOTH_DEVICE = diff --git a/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java b/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java index 23c65367f6..5143392d03 100644 --- a/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java +++ b/android/app/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactory.java @@ -41,8 +41,9 @@ import com.android.internal.annotations.GuardedBy; * calls it when a reverse tethered connection needs to be activated or deactivated. */ public class BluetoothTetheringNetworkFactory extends NetworkFactory { + private static final String TAG = BluetoothTetheringNetworkFactory.class.getSimpleName(); + private static final String NETWORK_TYPE = "Bluetooth Tethering"; - private static final String TAG = "BluetoothTetheringNetworkFactory"; private static final int NETWORK_SCORE = 69; private final NetworkCapabilities mNetworkCapabilities; @@ -266,7 +267,7 @@ public class BluetoothTetheringNetworkFactory extends NetworkFactory { terminate(); } - private NetworkCapabilities initNetworkCapabilities() { + private static NetworkCapabilities initNetworkCapabilities() { final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_BLUETOOTH) diff --git a/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java b/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java index 2cce9d1ced..76e91d8477 100644 --- a/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java +++ b/android/app/src/com/android/bluetooth/pan/PanNativeInterface.java @@ -16,10 +16,14 @@ package com.android.bluetooth.pan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static java.util.Objects.requireNonNull; import android.bluetooth.BluetoothPan; -import android.bluetooth.BluetoothProfile; import android.util.Log; import com.android.internal.annotations.VisibleForTesting; @@ -71,16 +75,16 @@ public class PanNativeInterface { static int convertHalState(int halState) { switch (halState) { case CONN_STATE_CONNECTED: - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; case CONN_STATE_CONNECTING: - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; case CONN_STATE_DISCONNECTED: - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; case CONN_STATE_DISCONNECTING: - return BluetoothProfile.STATE_DISCONNECTING; + return STATE_DISCONNECTING; default: Log.e(TAG, "Invalid pan connection state: " + halState); - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } } diff --git a/android/app/src/com/android/bluetooth/pan/PanService.java b/android/app/src/com/android/bluetooth/pan/PanService.java index 3717f797ee..194803f1ff 100644 --- a/android/app/src/com/android/bluetooth/pan/PanService.java +++ b/android/app/src/com/android/bluetooth/pan/PanService.java @@ -19,6 +19,10 @@ 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.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 +182,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 +191,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 +216,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 +238,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 +412,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; } @@ -526,7 +527,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 +608,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 +623,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 +634,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 +658,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 +683,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 +696,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/BluetoothPbapActivity.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java index 0d49e8f09d..7223516e88 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapActivity.java @@ -52,7 +52,7 @@ import com.android.internal.annotations.VisibleForTesting; // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class BluetoothPbapActivity extends AlertActivity implements Preference.OnPreferenceChangeListener, TextWatcher { - private static final String TAG = "BluetoothPbapActivity"; + private static final String TAG = BluetoothPbapActivity.class.getSimpleName(); private static final int BLUETOOTH_OBEX_AUTHKEY_MAX_LENGTH = 16; diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticator.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticator.java index 3bd5296986..55419908eb 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticator.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapAuthenticator.java @@ -31,7 +31,7 @@ import com.android.obex.PasswordAuthentication; */ // Next tag value for ContentProfileErrorReportUtils.report(): 1 public class BluetoothPbapAuthenticator implements Authenticator { - private static final String TAG = "PbapAuthenticator"; + private static final String TAG = BluetoothPbapAuthenticator.class.getSimpleName(); @VisibleForTesting boolean mChallenged; @VisibleForTesting boolean mAuthCancelled; diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java index 5565fbd87d..99b0b13bea 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java @@ -43,7 +43,7 @@ import java.util.Calendar; /** VCard composer especially for Call Log used in Bluetooth. */ // Next tag value for ContentProfileErrorReportUtils.report(): 3 public class BluetoothPbapCallLogComposer implements AutoCloseable { - private static final String TAG = "PbapCallLogComposer"; + private static final String TAG = BluetoothPbapCallLogComposer.class.getSimpleName(); @VisibleForTesting static final String FAILURE_REASON_FAILED_TO_GET_DATABASE_INFO = diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java index 07a2e49744..c755e1b67c 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java @@ -53,8 +53,7 @@ import java.util.List; // Next tag value for ContentProfileErrorReportUtils.report(): 34 public class BluetoothPbapObexServer extends ServerRequestHandler { - - private static final String TAG = "BluetoothPbapObexServer"; + private static final String TAG = BluetoothPbapObexServer.class.getSimpleName(); private static final int UUID_LENGTH = 16; @@ -621,7 +620,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } } - private boolean isNameMatchTarget(String name, String target) { + private static boolean isNameMatchTarget(String name, String target) { if (name == null) { return false; } @@ -643,7 +642,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } /** check whether path is legal */ - private boolean isLegalPath(final String str) { + private static boolean isLegalPath(final String str) { if (str.length() == 0) { return true; } @@ -1071,7 +1070,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler { } /** Function to send vcard data to client */ - private int pushBytes(Operation op, final String vcardString) { + private static int pushBytes(Operation op, final String vcardString) { if (vcardString == null) { Log.w(TAG, "vcardString is null!"); return ResponseCodes.OBEX_HTTP_OK; diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java index ccfea7cbcc..cb9684c7ea 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java @@ -20,6 +20,7 @@ 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.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -68,6 +69,8 @@ import com.android.bluetooth.sdp.SdpManagerNativeInterface; import com.android.bluetooth.util.DevicePolicyUtils; import com.android.internal.annotations.VisibleForTesting; +import com.google.common.util.concurrent.Uninterruptibles; + import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -624,7 +627,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(); } @@ -735,6 +738,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect setBluetoothPbapService(null); mSessionStatusHandler.sendEmptyMessage(SHUTDOWN); mHandlerThread.quitSafely(); + Uninterruptibles.joinUninterruptibly(mHandlerThread); mContactsLoaded = false; unregisterReceiver(mPbapReceiver); mAdapterService.getContentResolver().unregisterContentObserver(mContactChangeObserver); diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManager.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManager.java index 8f894848dd..5705e9c09f 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManager.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManager.java @@ -50,7 +50,7 @@ import java.util.List; /** VCard composer especially for Call Log used in Bluetooth. */ // Next tag value for ContentProfileErrorReportUtils.report(): 6 public class BluetoothPbapSimVcardManager implements AutoCloseable { - private static final String TAG = "PbapSIMvCardComposer"; + private static final String TAG = BluetoothPbapSimVcardManager.class.getSimpleName(); @VisibleForTesting public static final String FAILURE_REASON_FAILED_TO_GET_DATABASE_INFO = diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java index 1574686d45..f19d008912 100644 --- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java +++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java @@ -53,7 +53,7 @@ import java.util.concurrent.atomic.AtomicLong; // Next tag value for ContentProfileErrorReportUtils.report(): 4 class BluetoothPbapUtils { - private static final String TAG = "BluetoothPbapUtils"; + private static final String TAG = BluetoothPbapUtils.class.getSimpleName(); // Filter constants from Bluetooth PBAP specification private static final int FILTER_PHOTO = 3; diff --git a/android/app/src/com/android/bluetooth/pbap/HandlerForStringBuffer.java b/android/app/src/com/android/bluetooth/pbap/HandlerForStringBuffer.java index 59cbdd7e37..0d9a45b285 100644 --- a/android/app/src/com/android/bluetooth/pbap/HandlerForStringBuffer.java +++ b/android/app/src/com/android/bluetooth/pbap/HandlerForStringBuffer.java @@ -30,7 +30,7 @@ import java.io.OutputStream; /** Handler to emit vCards to PCE. */ // Next tag value for ContentProfileErrorReportUtils.report(): 2 public class HandlerForStringBuffer { - private static final String TAG = "HandlerForStringBuffer"; + private static final String TAG = HandlerForStringBuffer.class.getSimpleName(); private final Operation mOperation; private final String mOwnerVCard; diff --git a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java index 5263837bf4..4277c3e791 100644 --- a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java +++ b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java @@ -17,6 +17,9 @@ package com.android.bluetooth.pbap; 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 android.annotation.NonNull; import android.app.Notification; @@ -60,7 +63,8 @@ import java.io.IOException; // Next tag value for ContentProfileErrorReportUtils.report(): 3 @VisibleForTesting(visibility = Visibility.PACKAGE) public class PbapStateMachine extends StateMachine { - private static final String TAG = "PbapStateMachine"; + private static final String TAG = PbapStateMachine.class.getSimpleName(); + private static final String PBAP_OBEX_NOTIFICATION_CHANNEL = "pbap_obex_notification_channel"; static final int AUTHORIZED = 1; @@ -180,7 +184,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(); } @@ -231,7 +235,7 @@ public class PbapStateMachine extends StateMachine { class WaitingForAuth extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } @Override @@ -291,7 +295,7 @@ public class PbapStateMachine extends StateMachine { class Finished extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } @Override @@ -327,7 +331,7 @@ public class PbapStateMachine extends StateMachine { class Connected extends PbapStateBase { @Override int getConnectionStateInt() { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } @Override @@ -482,7 +486,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..680fda6114 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java @@ -18,6 +18,7 @@ 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_DISCONNECTED; import android.annotation.RequiresPermission; import android.bluetooth.BluetoothDevice; @@ -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); } diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java index a7c5a36011..9d064c7598 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientContactsStorage.java @@ -315,7 +315,7 @@ class PbapClientContactsStorage { } @SuppressWarnings("NonApiType") // For convenience, as applyBatch above takes an ArrayList above - private ArrayList<ContentProviderOperation> constructInsertOperationsForContact( + private static ArrayList<ContentProviderOperation> constructInsertOperationsForContact( VCardEntry contact, ArrayList<ContentProviderOperation> operations, ContentResolver contactsProvider) { @@ -481,7 +481,7 @@ class PbapClientContactsStorage { // TODO: b/365629730 -- JavaUtilDate: prefer Instant or LocalDate // NonApiType: For convenience, as the applyBatch API actually takes an ArrayList above @SuppressWarnings({"JavaUtilDate", "NonApiType"}) - private ArrayList<ContentProviderOperation> constructInsertOperationsForCallLog( + private static ArrayList<ContentProviderOperation> constructInsertOperationsForCallLog( Account account, int type, VCardEntry call, diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java index abaff2061f..e4fcad47cc 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java +++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java @@ -16,6 +16,9 @@ package com.android.bluetooth.pbapclient; +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 +28,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 +92,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 +298,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 +364,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 +442,7 @@ public class PbapClientService extends ProfileService { return; } - if (getConnectionState(device) == BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState(device) == STATE_CONNECTED) { disconnect(device); } } @@ -533,7 +537,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 +588,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 +648,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); } 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/PbapClientConnectionHandler.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientConnectionHandler.java index 452955ff73..7d6dbd2b1b 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientConnectionHandler.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientConnectionHandler.java @@ -48,7 +48,7 @@ import java.util.Map; * controlling state machine. */ class PbapClientConnectionHandler extends Handler { - private static final String TAG = "PbapClientConnHandler"; + private static final String TAG = PbapClientConnectionHandler.class.getSimpleName(); // Tradeoff: larger BATCH_SIZE leads to faster download rates, while smaller // BATCH_SIZE is less prone to IO Exceptions if there is a download in diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java index 896962ee10..e8b461b797 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java @@ -18,6 +18,10 @@ package com.android.bluetooth.pbapclient; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -85,7 +89,7 @@ class PbapClientObexClient { private final BluetoothDevice mDevice; private final int mLocalSupportedFeatures; - private int mState = BluetoothProfile.STATE_DISCONNECTED; + private int mState = STATE_DISCONNECTED; private AtomicInteger mPsm = new AtomicInteger(L2CAP_INVALID_PSM); private AtomicInteger mChannelId = new AtomicInteger(RFCOMM_INVALID_CHANNEL_ID); @@ -234,7 +238,7 @@ class PbapClientObexClient { * @return True if connected, False otherwise */ public boolean isConnected() { - return getConnectionState() == BluetoothProfile.STATE_CONNECTED; + return getConnectionState() == STATE_CONNECTED; } /** @@ -355,7 +359,7 @@ class PbapClientObexClient { if (mThread != null) { mThread.quit(); } - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); } /** Handles this PBAP Client OBEX Client's requests */ @@ -370,7 +374,7 @@ class PbapClientObexClient { debug("Handling Message, type=" + messageToString(msg.what)); switch (msg.what) { case MSG_CONNECT: - if (getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) { + if (getConnectionState() != STATE_DISCONNECTED) { warn("Cannot connect, device not disconnected"); return; } @@ -402,13 +406,13 @@ class PbapClientObexClient { return; } - setConnectionState(BluetoothProfile.STATE_CONNECTING); + setConnectionState(STATE_CONNECTING); mSocket = connectSocket(transport, psmOrChannel); if (mSocket == null) { mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); return; } @@ -418,22 +422,22 @@ class PbapClientObexClient { mSocket = null; mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); return; } - setConnectionState(BluetoothProfile.STATE_CONNECTED); + setConnectionState(STATE_CONNECTED); break; case MSG_DISCONNECT: removeCallbacksAndMessages(null); - if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) { + if (getConnectionState() != STATE_CONNECTED) { warn("Cannot disconnect, device not connected"); return; } - setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + setConnectionState(STATE_DISCONNECTING); // To disconnect, first bring down the OBEX session, then bring down the // underlying transport/socket. If there are any errors while bringing down the @@ -449,7 +453,7 @@ class PbapClientObexClient { mPsm.set(L2CAP_INVALID_PSM); mChannelId.set(RFCOMM_INVALID_CHANNEL_ID); - setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + setConnectionState(STATE_DISCONNECTED); break; case MSG_REQUEST: diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientRequest.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientRequest.java index fd9d0f60a6..d69fc25a62 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientRequest.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientRequest.java @@ -27,7 +27,7 @@ import java.io.IOException; import java.io.InputStream; abstract class PbapClientRequest { - static final String TAG = PbapClientRequest.class.getSimpleName(); + private static final String TAG = PbapClientRequest.class.getSimpleName(); // Request Types public static final int TYPE_PULL_PHONEBOOK_METADATA = 0; diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java index b3e6cb21fc..81582c462b 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapPhonebook.java @@ -145,7 +145,7 @@ public class PbapPhonebook { * any other {@link VCardException} or succeeds (i.e., no {@link VCardException}). * @throws IOException if there's an issue reading the {@link InputStream}. */ - private boolean parsedWithVcardVersionException(VCardParser parser, InputStream in) + private static boolean parsedWithVcardVersionException(VCardParser parser, InputStream in) throws IOException { try { parser.parse(in); @@ -170,7 +170,7 @@ public class PbapPhonebook { /** * Get the offset associated with this PbapPhonebook object * - * <p>The offset respresents the start index of the remote contacts pull + * <p>The offset represents the start index of the remote contacts pull * * @return an int representing the offset index where this pull started from */ diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PhonebookPullRequest.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PhonebookPullRequest.java index a651d55f86..ef36b3a23a 100644 --- a/android/app/src/com/android/bluetooth/pbapclient/obex/PhonebookPullRequest.java +++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PhonebookPullRequest.java @@ -30,7 +30,7 @@ import com.android.vcard.VCardEntry; import java.util.ArrayList; public class PhonebookPullRequest extends PullRequest { - private static final String TAG = "PhonebookPullRequest"; + private static final String TAG = PhonebookPullRequest.class.getSimpleName(); @VisibleForTesting static final int MAX_OPS = 250; diff --git a/android/app/src/com/android/bluetooth/sap/SapMessage.java b/android/app/src/com/android/bluetooth/sap/SapMessage.java index 0ee9eb178a..f1d7dee878 100644 --- a/android/app/src/com/android/bluetooth/sap/SapMessage.java +++ b/android/app/src/com/android/bluetooth/sap/SapMessage.java @@ -34,8 +34,8 @@ import java.util.concurrent.atomic.AtomicInteger; * <p>For incoming messages */ public class SapMessage { + private static final String TAG = SapMessage.class.getSimpleName(); - public static final String TAG = "SapMessage"; public static final boolean TEST = false; /* Message IDs - SAP specification */ diff --git a/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java b/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java index 6a7290165d..af9cedf745 100644 --- a/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java +++ b/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java @@ -31,7 +31,7 @@ import java.util.concurrent.atomic.AtomicLong; /** SapRiilReceiver is the AIDL implementation of ISapRilReceiver */ public class SapRilReceiver implements ISapRilReceiver { - private static final String TAG = "SapRilReceiver"; + private static final String TAG = SapRilReceiver.class.getSimpleName(); // todo: add support for slot2 and slot3 private static final String HAL_INSTANCE_NAME = ISap.DESCRIPTOR + "/slot1"; diff --git a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java index 9d153bfa87..b97d860bc6 100644 --- a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java +++ b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java @@ -31,7 +31,7 @@ import java.util.concurrent.atomic.AtomicLong; /** SapRiilReceiverHidl is the HIDL implementation of ISapRilReceiver */ @SuppressWarnings("NonApiType") // We cannot change hidl anymore public class SapRilReceiverHidl implements ISapRilReceiver { - private static final String TAG = "SapRilReceiverHidl"; + private static final String TAG = SapRilReceiverHidl.class.getSimpleName(); // todo: add support for slot2 and slot3 private static final String SERVICE_NAME_RIL_BT = "slot1"; @@ -48,7 +48,7 @@ public class SapRilReceiverHidl implements ISapRilReceiver { public static final int RIL_MAX_COMMAND_BYTES = (8 * 1024); public byte[] buffer = new byte[RIL_MAX_COMMAND_BYTES]; - private ArrayList<Byte> primitiveArrayToContainerArrayList(byte[] arr) { + private static ArrayList<Byte> primitiveArrayToContainerArrayList(byte[] arr) { ArrayList<Byte> arrayList = new ArrayList<>(arr.length); for (byte b : arr) { arrayList.add(b); diff --git a/android/app/src/com/android/bluetooth/sap/SapServer.java b/android/app/src/com/android/bluetooth/sap/SapServer.java index e9ce21a245..a7486b9396 100644 --- a/android/app/src/com/android/bluetooth/sap/SapServer.java +++ b/android/app/src/com/android/bluetooth/sap/SapServer.java @@ -44,7 +44,8 @@ import java.util.concurrent.CountDownLatch; * and a BroadcastReceiver. */ public class SapServer extends Thread implements Handler.Callback { - private static final String TAG = "SapServer"; + private static final String TAG = SapServer.class.getSimpleName(); + private static final String TAG_HANDLER = "SapServerHandler"; @VisibleForTesting diff --git a/android/app/src/com/android/bluetooth/sap/SapService.java b/android/app/src/com/android/bluetooth/sap/SapService.java index f09e4b2db3..9dfd6ee4d0 100644 --- a/android/app/src/com/android/bluetooth/sap/SapService.java +++ b/android/app/src/com/android/bluetooth/sap/SapService.java @@ -18,6 +18,8 @@ package com.android.bluetooth.sap; 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 java.util.Objects.requireNonNull; @@ -62,7 +64,7 @@ import java.util.Collections; import java.util.List; public class SapService extends ProfileService implements AdapterService.BluetoothStateCallback { - private static final String TAG = "SapService"; + private static final String TAG = SapService.class.getSimpleName(); private static final String SDP_SAP_SERVICE_NAME = "SIM Access"; private static final int SDP_SAP_VERSION = 0x0102; @@ -534,7 +536,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 +619,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; } } } @@ -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); diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java index 6cf2642366..d9e9dfb8f0 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java @@ -18,6 +18,7 @@ package com.android.bluetooth.tbs; import static android.bluetooth.BluetoothDevice.METADATA_GTBS_CCCD; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -28,7 +29,6 @@ import android.bluetooth.BluetoothGattCharacteristic; import android.bluetooth.BluetoothGattDescriptor; import android.bluetooth.BluetoothGattServerCallback; import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothProfile; import android.net.Uri; import android.os.Handler; import android.os.Looper; @@ -1491,7 +1491,7 @@ public class TbsGatt { BluetoothDevice device, int status, int newState) { super.onConnectionStateChange(device, status, newState); Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange"); - if (newState == BluetoothProfile.STATE_DISCONNECTED) { + if (newState == STATE_DISCONNECTED) { clearUnauthorizedGattOperationss(device); } } diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java index b49eee0a03..b88f6e7d9c 100644 --- a/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java +++ b/android/app/src/com/android/bluetooth/tbs/TbsGeneric.java @@ -1021,7 +1021,7 @@ public class TbsGeneric { } }; - private String callControlRequestOpcodeStr(int opcode) { + private static String callControlRequestOpcodeStr(int opcode) { switch (opcode) { case TbsGatt.CALL_CONTROL_POINT_OPCODE_ACCEPT: return "ACCEPT"; diff --git a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java index 349159acfd..99b0efc2a3 100644 --- a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java +++ b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java @@ -58,6 +58,7 @@ 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; import java.util.ArrayDeque; @@ -84,8 +85,8 @@ import java.util.concurrent.Executors; * the service triggering InCallActivity (via CallList) to finish soon after. */ public class BluetoothInCallService extends InCallService { + private static final String TAG = BluetoothInCallService.class.getSimpleName(); - private static final String TAG = "BluetoothInCallService"; // match up with bthf_call_state_t of bt_hf.h private static final int CALL_STATE_ACTIVE = 0; private static final int CALL_STATE_HELD = 1; @@ -537,8 +538,7 @@ public class BluetoothInCallService extends InCallService { } } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - public boolean listCurrentCalls() { + public boolean listCurrentCalls(HeadsetService headsetService) { synchronized (LOCK) { // only log if it is after we recently updated the headset state or else it can // clog the android log since this can be queried every second. @@ -549,7 +549,7 @@ public class BluetoothInCallService extends InCallService { Log.i(TAG, "listcurrentCalls"); } - sendListOfCalls(logQuery); + sendListOfCalls(headsetService, logQuery); return true; } } @@ -827,8 +827,7 @@ public class BluetoothInCallService extends InCallService { || call.getChildrenIds().isEmpty()); } - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - private void sendListOfCalls(boolean shouldLog) { + private void sendListOfCalls(HeadsetService headsetService, boolean shouldLog) { Collection<BluetoothCall> calls = mCallInfo.getBluetoothCalls(); // either do conference call CLCC index inference or normal conference call @@ -924,7 +923,7 @@ public class BluetoothInCallService extends InCallService { (int) response[2], (boolean) response[4], (int) response[6])); - mBluetoothHeadset.clccResponse( + headsetService.clccResponse( (int) response[0], (int) response[1], (int) response[2], @@ -933,7 +932,7 @@ public class BluetoothInCallService extends InCallService { (String) response[5], (int) response[6]); } - sendClccEndMarker(); + headsetService.clccResponse(0 /* index */, 0, 0, 0, false, null, 0); // End marker return; } @@ -949,23 +948,15 @@ public class BluetoothInCallService extends InCallService { + ", call.getChildrenIds() size " + call.getChildrenIds().size()); if (!call.isConference() || isConferenceWithNoChildren) { - sendClccForCall(call, shouldLog); + sendClccForCall(headsetService, call, shouldLog); } } - sendClccEndMarker(); - } - - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - private void sendClccEndMarker() { - // End marker is recognized with an index value of 0. All other parameters are ignored. - if (mBluetoothHeadset != null) { - mBluetoothHeadset.clccResponse(0 /* index */, 0, 0, 0, false, null, 0); - } + headsetService.clccResponse(0 /* index */, 0, 0, 0, false, null, 0); // End marker } /** Sends a single clcc (C* List Current Calls) event for the specified call. */ - @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE}) - private void sendClccForCall(BluetoothCall call, boolean shouldLog) { + private void sendClccForCall( + HeadsetService headsetService, BluetoothCall call, boolean shouldLog) { boolean isForeground = call.equals(mCallInfo.getForegroundCall()); int state = getBtCallState(call, isForeground); boolean isPartOfConference = false; @@ -1058,23 +1049,8 @@ public class BluetoothInCallService extends InCallService { + addressType); } - if (mBluetoothHeadset == null) { - Log.w( - TAG, - "mBluetoothHeasdset is null when sending clcc for BluetoothCall " - + index - + ", " - + direction - + ", " - + state - + ", " - + isPartOfConference - + ", " - + addressType); - } else { - mBluetoothHeadset.clccResponse( - index, direction, state, 0, isPartOfConference, address, addressType); - } + headsetService.clccResponse( + index, direction, state, 0, isPartOfConference, address, addressType); } int getNextAvailableClccIndex(int index) { @@ -1419,7 +1395,7 @@ public class BluetoothInCallService extends InCallService { return bluetoothCallState; } - private int getBtCallState(BluetoothCall call, boolean isForeground) { + private static int getBtCallState(BluetoothCall call, boolean isForeground) { switch (call.getState()) { case Call.STATE_NEW: case Call.STATE_DISCONNECTED: @@ -1635,7 +1611,7 @@ public class BluetoothInCallService extends InCallService { } } - private Integer getTbsCallState(BluetoothCall call) { + private static Integer getTbsCallState(BluetoothCall call) { switch (call.getState()) { case Call.STATE_ACTIVE: return BluetoothLeCall.STATE_ACTIVE; diff --git a/android/app/src/com/android/bluetooth/util/GsmAlphabet.java b/android/app/src/com/android/bluetooth/util/GsmAlphabet.java index 17611954a4..fcd3c78d8e 100644 --- a/android/app/src/com/android/bluetooth/util/GsmAlphabet.java +++ b/android/app/src/com/android/bluetooth/util/GsmAlphabet.java @@ -24,7 +24,7 @@ import android.util.SparseIntArray; * TS 23.038 6.2.1 and UTF-16 */ public class GsmAlphabet { - private static final String TAG = "GSM"; + private static final String TAG = GsmAlphabet.class.getSimpleName(); /** * This escapes extended characters, and when present indicates that the following character diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java index 90add03ed7..68e368fd2a 100644 --- a/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java +++ b/android/app/src/com/android/bluetooth/vc/VolumeControlNativeInterface.java @@ -43,7 +43,7 @@ public class VolumeControlNativeInterface { cleanupNative(); } - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java index 8b65e0d332..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() @@ -1925,7 +1917,7 @@ public class VolumeControlService extends ProfileService { service.unmuteGroup(groupId); } - private void postAndWait(Handler handler, Runnable runnable) { + private static void postAndWait(Handler handler, Runnable runnable) { FutureTask<Void> task = new FutureTask(Executors.callable(runnable)); handler.post(task); @@ -1980,7 +1972,7 @@ public class VolumeControlService extends ProfileService { postAndWait(service.mHandler, () -> service.notifyNewRegisteredCallback(callback)); } - private void validateBluetoothDevice(BluetoothDevice device) { + private static void validateBluetoothDevice(BluetoothDevice device) { requireNonNull(device); String address = device.getAddress(); if (!BluetoothAdapter.checkBluetoothAddress(address)) { diff --git a/android/app/tests/instrumentation/Android.bp b/android/app/tests/instrumentation/Android.bp new file mode 100644 index 0000000000..50016fac81 --- /dev/null +++ b/android/app/tests/instrumentation/Android.bp @@ -0,0 +1,85 @@ +package { + default_applicable_licenses: ["Android-Apache-2.0"], +} + +java_defaults { + name: "BluetoothInstrumentationTestsDefaults", + defaults: [ + "bluetooth_errorprone_rules", + ], + + sdk_version: "module_current", + min_sdk_version: "Tiramisu", + target_sdk_version: "current", + libs: [ + "android.test.base.stubs", + "android.test.mock.stubs", + "android.test.runner.stubs", + "framework-annotations-lib", + "framework-configinfrastructure.stubs.module_lib", + "framework-connectivity.stubs.module_lib", + "framework-location.stubs.module_lib", + "framework-mediaprovider.stubs.module_lib", + "framework-tethering.stubs.module_lib", + "javax.obex.stubs", + "libprotobuf-java-micro", + ], + + static_libs: [ + "PlatformProperties", + "TestParameterInjector", + "android.media.audio-aconfig-exported-java", + "androidx.media_media", + "androidx.room_room-migration", + "androidx.room_room-runtime", + "androidx.room_room-testing", + "androidx.test.espresso.intents", + "androidx.test.ext.truth", + "androidx.test.rules", + "androidx.test.uiautomator_uiautomator", + "bluetooth_flags_java_lib", + "com.android.sysprop.bluetooth", + "flag-junit", + "framework-bluetooth-pre-jarjar", + "gson", + "mmslib", + "mockito-target", + "modules-utils-handlerexecutor", + "platform-parametric-runner-lib", + "platform-test-annotations", + "truth", + ], + + jarjar_rules: ":bluetooth-jarjar-rules", + + // Include all test java files. + srcs: [ + "**/*.java", + ":bluetooth_test_looper", + ], + jacoco: { + include_filter: ["android.bluetooth.*"], + exclude_filter: [], + }, + + test_suites: [ + "automotive-general-tests", + "general-tests", + "mts-bluetooth", + "mts-bt", + ], + + instrumentation_for: "Bluetooth", +} + +android_test { + name: "BluetoothInstrumentationTests", + defaults: ["BluetoothInstrumentationTestsDefaults"], +} + +android_test { + name: "GoogleBluetoothInstrumentationTests", + defaults: ["BluetoothInstrumentationTestsDefaults"], + test_config: "GoogleAndroidTest.xml", + instrumentation_target_package: "com.google.android.bluetooth", +} diff --git a/android/app/tests/instrumentation/AndroidManifest.xml b/android/app/tests/instrumentation/AndroidManifest.xml new file mode 100644 index 0000000000..5e03504fb5 --- /dev/null +++ b/android/app/tests/instrumentation/AndroidManifest.xml @@ -0,0 +1,84 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- package name must be unique so suffix with "tests" so package loader doesn't ignore us --> +<manifest xmlns:android="http://schemas.android.com/apk/res/android" + xmlns:tools="http://schemas.android.com/tools" + package="com.android.bluetooth.tests"> + + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <uses-permission android:name="android.permission.ACCESS_BLUETOOTH_SHARE" /> + <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.BLUETOOTH" /> + <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> + <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> + <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.READ_CONTACTS" /> + <uses-permission android:name="android.permission.WRITE_CONTACTS" /> + <uses-permission android:name="android.permission.READ_CALL_LOG" /> + <uses-permission android:name="android.permission.READ_PHONE_STATE" /> + <uses-permission android:name="android.permission.WRITE_SETTINGS" /> + <uses-permission android:name="android.permission.NFC_HANDOVER_STATUS" /> + <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> + <uses-permission android:name="android.permission.NET_ADMIN" /> + <uses-permission android:name="android.permission.CALL_PRIVILEGED" /> + <uses-permission android:name="com.android.permission.HANDOVER_STATUS" /> + <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> + <uses-permission android:name="android.permission.NET_TUNNELING" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> + <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> + <uses-permission android:name="android.permission.BLUETOOTH_STACK" /> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"/> + <uses-permission android:name="android.permission.MANAGE_USERS"/> + <uses-permission android:name="android.permission.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH"/> + <uses-permission android:name="com.google.android.gallery3d.permission.GALLERY_PROVIDER"/> + <uses-permission android:name="com.android.gallery3d.permission.GALLERY_PROVIDER"/> + + <uses-permission android:name="android.permission.RECEIVE_SMS" /> + <uses-permission android:name="android.permission.READ_PHONE_STATE" /> + <uses-permission android:name="android.permission.SEND_SMS" /> + <uses-permission android:name="android.permission.READ_SMS" /> + <uses-permission android:name="android.permission.WRITE_SMS" /> + <uses-permission android:name="android.permission.READ_CONTACTS" /> + <uses-permission android:name="com.android.permission.ALLOWLIST_BLUETOOTH_DEVICE" /> + <uses-permission android:name="com.android.email.permission.ACCESS_PROVIDER"/> + + <!-- For testing Email content access --> + <uses-permission android:name="com.android.email.permission.BT_ACCESS_PROVIDER"/> + <uses-permission android:name="com.android.email.permission.READ_ATTACHMENT"/> + <!-- For PBAP Owner Vcard Info --> + <uses-permission android:name="android.permission.READ_PROFILE"/> + + <!-- We add an application tag here just so that we can indicate that + this package needs to link against the android.test library, + which is needed when building test cases. --> + + <application android:allowBackup="true" + android:autoRevokePermissions="disallowed"> + <uses-library android:name="android.test.runner" /> + <uses-library android:name="org.apache.http.legacy" android:required="false" /> + + <!-- Workaround for *ActivityTest failures (b/260295342) --> + <activity + android:name="androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity" + tools:node="merge"> + <intent-filter tools:node="removeAll" /> + </activity> + <activity + android:name="androidx.test.core.app.InstrumentationActivityInvoker$EmptyActivity" + tools:node="merge"> + <intent-filter tools:node="removeAll" /> + </activity> + + </application> + <!-- + This declares that this application uses the instrumentation test runner targeting + the package of com.android.bluetooth. To run the tests use the command: + "adb shell am instrument -w com.android.bluetooth.tests/android.test.InstrumentationTestRunner" + --> + <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner" + android:targetPackage="com.android.bluetooth" + android:label="Tests for com.android.bluetooth"/> +</manifest> + diff --git a/android/app/tests/instrumentation/AndroidTest.xml b/android/app/tests/instrumentation/AndroidTest.xml new file mode 100644 index 0000000000..7734f9a3e0 --- /dev/null +++ b/android/app/tests/instrumentation/AndroidTest.xml @@ -0,0 +1,60 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- 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. +--> +<configuration description="Runs Bluetooth Test Cases."> + <option name="test-suite-tag" value="apct" /> + <option name="test-suite-tag" value="apct-instrumentation" /> + <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller"> + <option name="cleanup-apks" value="true" /> + <option name="test-file-name" value="BluetoothInstrumentationTests.apk" /> + </target_preparer> + <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"> + <option name="force-root" value="true" /> + </target_preparer> + <target_preparer class="com.android.tradefed.targetprep.RunCommandTargetPreparer"> + <option name="throw-if-cmd-fail" value="true" /> + <option name="run-command" value="input keyevent KEYCODE_WAKEUP" /> + <option name="run-command" value="wm dismiss-keyguard" /> + <option name="run-command" value="settings put global ble_scan_always_enabled 0" /> + <option name="run-command" value="cmd bluetooth_manager disable" /> + <option name="run-command" value="cmd bluetooth_manager wait-for-state:STATE_OFF" /> + <option name="run-command" value="settings put global satellite_mode_radios bluetooth" /> + <option name="run-command" value="settings put global satellite_mode_enabled 1" /> + <option name="teardown-command" value="settings delete global satellite_mode_radios" /> + <option name="teardown-command" value="settings put global satellite_mode_enabled 0" /> + <option name="teardown-command" value="cmd bluetooth_manager enable" /> + <option name="teardown-command" value="cmd bluetooth_manager wait-for-state:STATE_ON" /> + <option name="teardown-command" value="settings put global ble_scan_always_enabled 1" /> + </target_preparer> + <target_preparer class="com.android.tradefed.targetprep.FolderSaver"> + <option name="device-path" value="/data/vendor/ssrdump" /> + </target_preparer> + <option name="test-tag" value="BluetoothInstrumentationTests" /> + <test class="com.android.tradefed.testtype.AndroidJUnitTest" > + <option name="package" value="com.android.bluetooth.tests" /> + <!-- include and exclude filters go into /data/local/tmp/ajur/ by default + However it's prohibited for access by system uid packages. + 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"/> + </test> + + <!-- Only run if the Bluetooth Mainline module is installed. --> + <object type="module_controller" + class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController"> + <option name="enable" value="true" /> + <option name="mainline-module-package-name" value="com.android.bt" /> + </object> +</configuration> diff --git a/android/app/tests/unit/GoogleAndroidTest.xml b/android/app/tests/instrumentation/GoogleAndroidTest.xml index bcda5eacce..b9c133fa84 100644 --- a/android/app/tests/unit/GoogleAndroidTest.xml +++ b/android/app/tests/instrumentation/GoogleAndroidTest.xml @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> -<!-- Copyright 2017 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. diff --git a/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java b/android/app/tests/instrumentation/com/android/bluetooth/FileSystemWriteTest.java index 4f2b921d7c..52288f1072 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/FileSystemWriteTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/FileSystemWriteTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2017 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. @@ -32,22 +32,22 @@ import java.io.IOException; public class FileSystemWriteTest { @Test public void testBluetoothDirWrite() throws IOException { - File file = new File("/data/misc/bluetooth/test.file"); + File file = new File("/data/misc/bluetooth/test.file"); assertThat(file.createNewFile()).isTrue(); - file.delete(); + file.delete(); } @Test public void testBluedroidDirWrite() throws IOException { - File file = new File("/data/misc/bluedroid/test.file"); + File file = new File("/data/misc/bluedroid/test.file"); assertThat(file.createNewFile()).isTrue(); - file.delete(); + file.delete(); } @Test public void testBluetoothLogsDirWrite() throws IOException { - File file = new File("/data/misc/bluetooth/logs/test.file"); + File file = new File("/data/misc/bluetooth/logs/test.file"); assertThat(file.createNewFile()).isTrue(); - file.delete(); + file.delete(); } } diff --git a/android/app/tests/instrumentation/com/android/bluetooth/TestUtils.java b/android/app/tests/instrumentation/com/android/bluetooth/TestUtils.java new file mode 100644 index 0000000000..c9357fc0be --- /dev/null +++ b/android/app/tests/instrumentation/com/android/bluetooth/TestUtils.java @@ -0,0 +1,202 @@ +/* + * 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. + */ +package com.android.bluetooth; + +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import android.annotation.IntRange; +import android.bluetooth.BluetoothDevice; +import android.bluetooth.BluetoothManager; +import android.content.Context; +import android.os.Message; +import android.util.Log; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.uiautomator.UiDevice; + +import org.junit.rules.MethodRule; +import org.junit.rules.TestRule; +import org.junit.runner.Description; +import org.junit.runners.model.FrameworkMethod; +import org.junit.runners.model.Statement; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnit; + +import java.util.stream.IntStream; + +/** A set of methods useful in Bluetooth instrumentation tests */ +public class TestUtils { + private static String sSystemScreenOffTimeout = "10000"; + + private static final String TAG = "BluetoothTestUtils"; + + /** Helper function to mock getSystemService calls */ + public static <T> void mockGetSystemService( + Context ctx, String serviceName, Class<T> serviceClass, T mockService) { + // doReturn(mockService).when(ctx).getSystemService(eq(serviceClass)); // need extended mock + doReturn(mockService).when(ctx).getSystemService(eq(serviceName)); + doReturn(serviceName).when(ctx).getSystemServiceName(eq(serviceClass)); + } + + /** Helper function to mock getSystemService calls */ + public static <T> T mockGetSystemService( + Context ctx, String serviceName, Class<T> serviceClass) { + T mockedService = mock(serviceClass); + mockGetSystemService(ctx, serviceName, serviceClass, mockedService); + return mockedService; + } + + /** + * Create a test device. + * + * @param id the test device ID. It must be an integer in the interval [0, 0xFF]. + * @return {@link BluetoothDevice} test device for the device ID + */ + public static BluetoothDevice getTestDevice(@IntRange(from = 0x00, to = 0xFF) int id) { + assertThat(id).isAtMost(0xFF); + BluetoothDevice testDevice = + InstrumentationRegistry.getInstrumentation() + .getTargetContext() + .getSystemService(BluetoothManager.class) + .getAdapter() + .getRemoteDevice(String.format("00:01:02:03:04:%02X", id)); + assertThat(testDevice).isNotNull(); + return testDevice; + } + + /** + * Dispatch all the message on the Loopper and check that the `what` is expected + * + * @param looper looper to execute the message from + * @param what list of Messages.what that are expected to be run by the handler + */ + public static void syncHandler(TestLooper looper, int... what) { + IntStream.of(what) + .forEach( + w -> { + Message msg = looper.nextMessage(); + assertWithMessage("Expecting [" + w + "] instead of null Msg") + .that(msg) + .isNotNull(); + assertWithMessage("Not the expected Message:\n" + msg) + .that(msg.what) + .isEqualTo(w); + Log.d(TAG, "Processing message: " + msg); + msg.getTarget().dispatchMessage(msg); + }); + } + + public static void setUpUiTest() throws Exception { + final UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); + // Disable animation + device.executeShellCommand("settings put global window_animation_scale 0.0"); + device.executeShellCommand("settings put global transition_animation_scale 0.0"); + device.executeShellCommand("settings put global animator_duration_scale 0.0"); + + // change device screen_off_timeout to 5 minutes + sSystemScreenOffTimeout = + device.executeShellCommand("settings get system screen_off_timeout"); + device.executeShellCommand("settings put system screen_off_timeout 300000"); + + // Turn on screen and unlock + device.wakeUp(); + device.executeShellCommand("wm dismiss-keyguard"); + + // Back to home screen, in case some dialog/activity is in front + UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()).pressHome(); + } + + public static void tearDownUiTest() throws Exception { + final UiDevice device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation()); + device.executeShellCommand("wm dismiss-keyguard"); + + // Re-enable animation + device.executeShellCommand("settings put global window_animation_scale 1.0"); + device.executeShellCommand("settings put global transition_animation_scale 1.0"); + device.executeShellCommand("settings put global animator_duration_scale 1.0"); + + // restore screen_off_timeout + device.executeShellCommand( + "settings put system screen_off_timeout " + sSystemScreenOffTimeout); + } + + public static class RetryTestRule implements TestRule { + private int retryCount = 5; + + public RetryTestRule() { + this(5); + } + + public RetryTestRule(int retryCount) { + this.retryCount = retryCount; + } + + public Statement apply(Statement base, Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + Throwable caughtThrowable = null; + + // implement retry logic here + for (int i = 0; i < retryCount; i++) { + try { + base.evaluate(); + return; + } catch (Throwable t) { + caughtThrowable = t; + Log.e( + TAG, + description.getDisplayName() + ": run " + (i + 1) + " failed", + t); + } + } + Log.e( + TAG, + description.getDisplayName() + + ": giving up after " + + retryCount + + " failures"); + throw caughtThrowable; + } + }; + } + } + + /** Wrapper around MockitoJUnit.rule() to clear the inline mock at the end of the test. */ + public static class MockitoRule implements MethodRule { + private final org.mockito.junit.MockitoRule mMockitoRule = MockitoJUnit.rule(); + + public Statement apply(Statement base, FrameworkMethod method, Object target) { + Statement nestedStatement = mMockitoRule.apply(base, method, target); + + return new Statement() { + @Override + public void evaluate() throws Throwable { + nestedStatement.evaluate(); + + // Prevent OutOfMemory errors due to mock maker leaks. + // See https://github.com/mockito/mockito/issues/1614, b/259280359, b/396177821 + Mockito.framework().clearInlineMocks(); + } + }; + } + } +} diff --git a/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java new file mode 100644 index 0000000000..439186e4fa --- /dev/null +++ b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java @@ -0,0 +1,528 @@ +/* + * 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. + */ + +package com.android.bluetooth.btservice; + +import static android.bluetooth.BluetoothAdapter.STATE_BLE_ON; +import static android.bluetooth.BluetoothAdapter.STATE_BLE_TURNING_OFF; +import static android.bluetooth.BluetoothAdapter.STATE_BLE_TURNING_ON; +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 com.google.common.truth.Truth.assertThat; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +import android.app.ActivityManager; +import android.app.AlarmManager; +import android.app.AppOpsManager; +import android.app.admin.DevicePolicyManager; +import android.bluetooth.BluetoothManager; +import android.bluetooth.BluetoothProfile; +import android.bluetooth.IBluetoothCallback; +import android.companion.CompanionDeviceManager; +import android.content.Context; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageManager; +import android.content.pm.PermissionInfo; +import android.content.res.Resources; +import android.hardware.display.DisplayManager; +import android.media.AudioManager; +import android.os.BatteryStatsManager; +import android.os.Binder; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.PowerManager; +import android.os.RemoteException; +import android.os.UserHandle; +import android.os.UserManager; +import android.permission.PermissionManager; +import android.platform.test.annotations.RequiresFlagsEnabled; +import android.platform.test.flag.junit.FlagsParameterization; +import android.platform.test.flag.junit.SetFlagsRule; +import android.provider.Settings; +import android.sysprop.BluetoothProperties; +import android.test.mock.MockContentProvider; +import android.test.mock.MockContentResolver; +import android.util.Log; + +import androidx.test.filters.MediumTest; +import androidx.test.platform.app.InstrumentationRegistry; + +import com.android.bluetooth.TestLooper; +import com.android.bluetooth.TestUtils; +import com.android.bluetooth.Utils; +import com.android.bluetooth.btservice.bluetoothkeystore.BluetoothKeystoreNativeInterface; +import com.android.bluetooth.flags.Flags; +import com.android.bluetooth.gatt.AdvertiseManagerNativeInterface; +import com.android.bluetooth.gatt.DistanceMeasurementNativeInterface; +import com.android.bluetooth.gatt.GattNativeInterface; +import com.android.bluetooth.le_audio.LeAudioService; +import com.android.bluetooth.le_scan.PeriodicScanNativeInterface; +import com.android.bluetooth.le_scan.ScanNativeInterface; +import com.android.bluetooth.sdp.SdpManagerNativeInterface; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import platform.test.runner.parameterized.ParameterizedAndroidJunit4; +import platform.test.runner.parameterized.Parameters; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +@MediumTest +@RunWith(ParameterizedAndroidJunit4.class) +public class AdapterServiceTest { + private static final String TAG = AdapterServiceTest.class.getSimpleName(); + + private static final int MESSAGE_PROFILE_SERVICE_STATE_CHANGED = 1; + private static final int MESSAGE_PROFILE_SERVICE_REGISTERED = 2; + private static final int MESSAGE_PROFILE_SERVICE_UNREGISTERED = 3; + + private MockAdapterService mAdapterService; + + static class MockAdapterService extends AdapterService { + + int mSetProfileServiceStateCounter = 0; + + MockAdapterService(Looper looper, Context ctx) { + super(looper, ctx); + } + + @Override + void setProfileServiceState(int profileId, int state) { + mSetProfileServiceStateCounter++; + } + } + + @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); + + private @Mock Context mMockContext; + private @Mock ApplicationInfo mMockApplicationInfo; + private @Mock LeAudioService mMockLeAudioService; + private @Mock Resources mMockResources; + private @Mock ProfileService mMockGattService; + private @Mock ProfileService mMockService; + private @Mock ProfileService mMockService2; + private @Mock IBluetoothCallback mIBluetoothCallback; + private @Mock Binder mBinder; + private @Mock MetricsLogger mMockMetricsLogger; + private @Mock AdapterNativeInterface mNativeInterface; + private @Mock BluetoothKeystoreNativeInterface mKeystoreNativeInterface; + private @Mock BluetoothQualityReportNativeInterface mQualityNativeInterface; + private @Mock BluetoothHciVendorSpecificNativeInterface mHciVendorSpecificNativeInterface; + private @Mock SdpManagerNativeInterface mSdpNativeInterface; + private @Mock AdvertiseManagerNativeInterface mAdvertiseNativeInterface; + private @Mock DistanceMeasurementNativeInterface mDistanceNativeInterface; + private @Mock GattNativeInterface mGattNativeInterface; + private @Mock PeriodicScanNativeInterface mPeriodicNativeInterface; + private @Mock ScanNativeInterface mScanNativeInterface; + private @Mock JniCallbacks mJniCallbacks; + + @Rule public final SetFlagsRule mSetFlagsRule; + + // SystemService that are not mocked + private BluetoothManager mBluetoothManager; + private CompanionDeviceManager mCompanionDeviceManager; + private DisplayManager mDisplayManager; + private PowerManager mPowerManager; + private PermissionManager mPermissionManager; + + private static final int CONTEXT_SWITCH_MS = 100; + + private PackageManager mMockPackageManager; + private MockContentResolver mMockContentResolver; + private int mForegroundUserId; + private TestLooper mLooper; + + static void configureEnabledProfiles() { + Log.e(TAG, "configureEnabledProfiles"); + + for (int profileId = 0; profileId <= BluetoothProfile.MAX_PROFILE_ID; profileId++) { + boolean enabled = + profileId == BluetoothProfile.PAN + || profileId == BluetoothProfile.PBAP + || profileId == BluetoothProfile.GATT; + + Config.setProfileEnabled(profileId, enabled); + } + } + + <T> void mockGetSystemService(String serviceName, Class<T> serviceClass, T mockService) { + TestUtils.mockGetSystemService(mMockContext, serviceName, serviceClass, mockService); + } + + <T> T mockGetSystemService(String serviceName, Class<T> serviceClass) { + return TestUtils.mockGetSystemService(mMockContext, serviceName, serviceClass); + } + + @Parameters(name = "{0}") + public static List<FlagsParameterization> getParams() { + return FlagsParameterization.allCombinationsOf(); + } + + public AdapterServiceTest(FlagsParameterization flags) { + mSetFlagsRule = new SetFlagsRule(flags); + } + + @Before + public void setUp() throws PackageManager.NameNotFoundException { + Log.e(TAG, "setUp()"); + + mLooper = new TestLooper(); + Handler handler = new Handler(mLooper.getLooper()); + + doReturn(mJniCallbacks).when(mNativeInterface).getCallbacks(); + + doReturn(true).when(mMockLeAudioService).isAvailable(); + LeAudioService.setLeAudioService(mMockLeAudioService); + doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED) + .when(mMockLeAudioService) + .getConnectionPolicy(any()); + + AdapterNativeInterface.setInstance(mNativeInterface); + BluetoothKeystoreNativeInterface.setInstance(mKeystoreNativeInterface); + BluetoothQualityReportNativeInterface.setInstance(mQualityNativeInterface); + BluetoothHciVendorSpecificNativeInterface.setInstance(mHciVendorSpecificNativeInterface); + SdpManagerNativeInterface.setInstance(mSdpNativeInterface); + AdvertiseManagerNativeInterface.setInstance(mAdvertiseNativeInterface); + DistanceMeasurementNativeInterface.setInstance(mDistanceNativeInterface); + GattNativeInterface.setInstance(mGattNativeInterface); + PeriodicScanNativeInterface.setInstance(mPeriodicNativeInterface); + ScanNativeInterface.setInstance(mScanNativeInterface); + + // Post the creation of AdapterService since it rely on Looper.myLooper() + handler.post( + () -> mAdapterService = new MockAdapterService(mLooper.getLooper(), mMockContext)); + assertThat(mLooper.dispatchAll()).isEqualTo(1); + assertThat(mAdapterService).isNotNull(); + + mMockPackageManager = mock(PackageManager.class); + when(mMockPackageManager.getPermissionInfo(any(), anyInt())) + .thenReturn(new PermissionInfo()); + + Context targetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + + mMockContentResolver = new MockContentResolver(targetContext); + mMockContentResolver.addProvider( + Settings.AUTHORITY, + new MockContentProvider() { + @Override + public Bundle call(String method, String request, Bundle args) { + return Bundle.EMPTY; + } + }); + + mBluetoothManager = targetContext.getSystemService(BluetoothManager.class); + mCompanionDeviceManager = targetContext.getSystemService(CompanionDeviceManager.class); + mDisplayManager = targetContext.getSystemService(DisplayManager.class); + mPermissionManager = targetContext.getSystemService(PermissionManager.class); + mPowerManager = targetContext.getSystemService(PowerManager.class); + + when(mMockContext.getCacheDir()).thenReturn(targetContext.getCacheDir()); + when(mMockContext.getUser()).thenReturn(targetContext.getUser()); + when(mMockContext.getPackageName()).thenReturn(targetContext.getPackageName()); + when(mMockContext.getApplicationInfo()).thenReturn(mMockApplicationInfo); + when(mMockContext.getContentResolver()).thenReturn(mMockContentResolver); + when(mMockContext.getApplicationContext()).thenReturn(mMockContext); + when(mMockContext.createContextAsUser(UserHandle.SYSTEM, /* flags= */ 0)) + .thenReturn(mMockContext); + when(mMockContext.getResources()).thenReturn(mMockResources); + when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager); + + mockGetSystemService(Context.ALARM_SERVICE, AlarmManager.class); + mockGetSystemService(Context.APP_OPS_SERVICE, AppOpsManager.class); + mockGetSystemService(Context.AUDIO_SERVICE, AudioManager.class); + mockGetSystemService(Context.ACTIVITY_SERVICE, ActivityManager.class); + + DevicePolicyManager dpm = + mockGetSystemService(Context.DEVICE_POLICY_SERVICE, DevicePolicyManager.class); + doReturn(false).when(dpm).isCommonCriteriaModeEnabled(any()); + mockGetSystemService(Context.USER_SERVICE, UserManager.class); + + // BatteryStatsManager is final and cannot be mocked with regular mockito, so just return + // real implementation + mockGetSystemService( + Context.BATTERY_STATS_SERVICE, + BatteryStatsManager.class, + targetContext.getSystemService(BatteryStatsManager.class)); + mockGetSystemService(Context.BLUETOOTH_SERVICE, BluetoothManager.class, mBluetoothManager); + mockGetSystemService( + Context.COMPANION_DEVICE_SERVICE, + CompanionDeviceManager.class, + mCompanionDeviceManager); + mockGetSystemService(Context.DISPLAY_SERVICE, DisplayManager.class, mDisplayManager); + mockGetSystemService( + Context.PERMISSION_SERVICE, PermissionManager.class, mPermissionManager); + mockGetSystemService(Context.POWER_SERVICE, PowerManager.class, mPowerManager); + + when(mMockContext.getSharedPreferences(anyString(), anyInt())) + .thenReturn( + targetContext.getSharedPreferences( + "AdapterServiceTestPrefs", Context.MODE_PRIVATE)); + + doAnswer( + invocation -> { + Object[] args = invocation.getArguments(); + return targetContext.getDatabasePath((String) args[0]); + }) + .when(mMockContext) + .getDatabasePath(anyString()); + + // Sets the foreground user id to match that of the tests (restored in tearDown) + mForegroundUserId = Utils.getForegroundUserId(); + int callingUid = Binder.getCallingUid(); + UserHandle callingUser = UserHandle.getUserHandleForUid(callingUid); + Utils.setForegroundUserId(callingUser.getIdentifier()); + + when(mIBluetoothCallback.asBinder()).thenReturn(mBinder); + + when(mMockGattService.getName()).thenReturn("GattService"); + when(mMockService.getName()).thenReturn("Service1"); + when(mMockService2.getName()).thenReturn("Service2"); + + configureEnabledProfiles(); + Config.init(mMockContext); + + MetricsLogger.setInstanceForTesting(mMockMetricsLogger); + + mAdapterService.onCreate(); + + mLooper.dispatchAll(); + + mAdapterService.registerRemoteCallback(mIBluetoothCallback); + } + + @After + public void tearDown() { + Log.e(TAG, "tearDown()"); + + // Restores the foregroundUserId to the ID prior to the test setup + Utils.setForegroundUserId(mForegroundUserId); + + LeAudioService.setLeAudioService(null); + mAdapterService.cleanup(); + mAdapterService.unregisterRemoteCallback(mIBluetoothCallback); + AdapterNativeInterface.setInstance(null); + BluetoothKeystoreNativeInterface.setInstance(null); + BluetoothQualityReportNativeInterface.setInstance(null); + BluetoothHciVendorSpecificNativeInterface.setInstance(null); + SdpManagerNativeInterface.setInstance(null); + AdvertiseManagerNativeInterface.setInstance(null); + DistanceMeasurementNativeInterface.setInstance(null); + GattNativeInterface.setInstance(null); + PeriodicScanNativeInterface.setInstance(null); + ScanNativeInterface.setInstance(null); + MetricsLogger.setInstanceForTesting(null); + } + + private void syncHandler(int... what) { + TestUtils.syncHandler(mLooper, what); + } + + private void verifyStateChange(int prevState, int currState) { + try { + verify(mIBluetoothCallback).onBluetoothStateChange(prevState, currState); + } catch (RemoteException e) { + // the mocked onBluetoothStateChange doesn't throw RemoteException + } + } + + private void verifyStateChange(int prevState, int currState, int timeoutMs) { + try { + verify(mIBluetoothCallback, timeout(timeoutMs)) + .onBluetoothStateChange(prevState, currState); + } catch (RemoteException e) { + // the mocked onBluetoothStateChange doesn't throw RemoteException + } + } + + private List<ProfileService> listOfMockServices() { + return Flags.scanManagerRefactor() + ? List.of(mMockGattService, mMockService, mMockService2) + : List.of(mMockService, mMockService2); + } + + private void offToBleOn() { + mAdapterService.offToBleOn(false); + syncHandler(0); // `init` need to be run first + syncHandler(AdapterState.BLE_TURN_ON); + verifyStateChange(STATE_OFF, STATE_BLE_TURNING_ON); + + if (!Flags.scanManagerRefactor()) { + syncHandler(MESSAGE_PROFILE_SERVICE_REGISTERED); + syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); + } + + verify(mNativeInterface).enable(); + mAdapterService.stateChangeCallback(AbstractionLayer.BT_STATE_ON); + syncHandler(AdapterState.BLE_STARTED); + verifyStateChange(STATE_BLE_TURNING_ON, STATE_BLE_ON); + assertThat(mAdapterService.getState()).isEqualTo(STATE_BLE_ON); + } + + private void onToBleOn() { + mAdapterService.onToBleOn(); + syncHandler(AdapterState.USER_TURN_OFF); + verifyStateChange(STATE_ON, STATE_TURNING_OFF); + + // Stop (if Flags.scanManagerRefactor GATT), PBAP, and PAN services + assertThat(mAdapterService.mSetProfileServiceStateCounter) + .isEqualTo(listOfMockServices().size() * 2); + + for (ProfileService service : listOfMockServices()) { + mAdapterService.onProfileServiceStateChanged(service, STATE_OFF); + syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); + } + + syncHandler(AdapterState.BREDR_STOPPED); + verifyStateChange(STATE_TURNING_OFF, STATE_BLE_ON); + + assertThat(mAdapterService.getState()).isEqualTo(STATE_BLE_ON); + } + + private void doEnable() { + Log.e(TAG, "doEnable() start"); + + IBluetoothCallback callback = mock(IBluetoothCallback.class); + Binder binder = mock(Binder.class); + doReturn(binder).when(callback).asBinder(); + mAdapterService.registerRemoteCallback(callback); + + assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); + + offToBleOn(); + + mAdapterService.bleOnToOn(); + syncHandler(AdapterState.USER_TURN_ON); + verifyStateChange(STATE_BLE_ON, STATE_TURNING_ON); + + // Start Mock (if Flags.scanManagerRefactor GATT), PBAP, and PAN services + assertThat(mAdapterService.mSetProfileServiceStateCounter) + .isEqualTo(listOfMockServices().size()); + + for (ProfileService service : listOfMockServices()) { + mAdapterService.addProfile(service); + syncHandler(MESSAGE_PROFILE_SERVICE_REGISTERED); + } + // Keep in 2 separate loop to first add the services and then eventually trigger the + // ON transition during the callback + for (ProfileService service : listOfMockServices()) { + mAdapterService.onProfileServiceStateChanged(service, STATE_ON); + syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); + } + syncHandler(AdapterState.BREDR_STARTED); + verifyStateChange(STATE_TURNING_ON, STATE_ON); + + assertThat(mAdapterService.getState()).isEqualTo(STATE_ON); + mAdapterService.unregisterRemoteCallback(callback); + Log.e(TAG, "doEnable() complete success"); + } + + /** Test: Toggle snoop logging setting Check whether the AdapterService restarts fully */ + @Test + public void testSnoopLoggingChange() { + BluetoothProperties.snoop_log_mode_values snoopSetting = + BluetoothProperties.snoop_log_mode() + .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY); + BluetoothProperties.snoop_log_mode(BluetoothProperties.snoop_log_mode_values.DISABLED); + doEnable(); + + assertThat( + BluetoothProperties.snoop_log_mode() + .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY)) + .isNotEqualTo(BluetoothProperties.snoop_log_mode_values.FULL); + + BluetoothProperties.snoop_log_mode(BluetoothProperties.snoop_log_mode_values.FULL); + + onToBleOn(); + + // Do not call bleOnToOff(). The Adapter should turn itself off. + syncHandler(AdapterState.BLE_TURN_OFF); + verifyStateChange(STATE_BLE_ON, STATE_BLE_TURNING_OFF, CONTEXT_SWITCH_MS); + + if (!Flags.scanManagerRefactor()) { + syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); // stop GATT + syncHandler(MESSAGE_PROFILE_SERVICE_UNREGISTERED); + } + + verify(mNativeInterface).disable(); + + mAdapterService.stateChangeCallback(AbstractionLayer.BT_STATE_OFF); + syncHandler(AdapterState.BLE_STOPPED); + // When reaching the OFF state, the cleanup is called that will destroy the state machine of + // the adapterService. Destroying state machine send a -1 event on the handler + syncHandler(-1); + + verifyStateChange(STATE_BLE_TURNING_OFF, STATE_OFF); + assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); + + // Restore earlier setting + BluetoothProperties.snoop_log_mode(snoopSetting); + assertThat(mLooper.nextMessage()).isNull(); + } + + @Test + @RequiresFlagsEnabled(Flags.FLAG_GATT_CLEAR_CACHE_ON_FACTORY_RESET) + public void testClearStorage() throws Exception { + // clearStorage should remove all files under /data/misc/bluetooth/ && /data/misc/bluedroid/ + final Path testCachePath = Paths.get("/data/misc/bluetooth/gatt_cache_a475b9a23d72"); + final Path testHashPath = + Paths.get("/data/misc/bluetooth/gatt_hash_400D017CB2563A6FB62A2DC4C2AEFD6F"); + final Path randomFileUnderBluedroidPath = + Paths.get("/data/misc/bluedroid/random_test_file.txt"); + final Path randomFileUnderBluetoothPath = + Paths.get("/data/misc/bluetooth/random_test_file.txt"); + + try { + Files.createFile(testCachePath); + Files.createFile(testHashPath); + Files.createFile(randomFileUnderBluedroidPath); + Files.createFile(randomFileUnderBluetoothPath); + + assertThat(Files.exists(testCachePath)).isTrue(); + assertThat(Files.exists(testHashPath)).isTrue(); + assertThat(Files.exists(randomFileUnderBluedroidPath)).isTrue(); + assertThat(Files.exists(randomFileUnderBluetoothPath)).isTrue(); + + mAdapterService.clearStorage(); + + assertThat(Files.exists(testCachePath)).isFalse(); + assertThat(Files.exists(testHashPath)).isFalse(); + assertThat(Files.exists(randomFileUnderBluedroidPath)).isFalse(); + assertThat(Files.exists(randomFileUnderBluetoothPath)).isFalse(); + } finally { + Files.deleteIfExists(testCachePath); + Files.deleteIfExists(testHashPath); + Files.deleteIfExists(randomFileUnderBluedroidPath); + Files.deleteIfExists(randomFileUnderBluetoothPath); + } + assertThat(mLooper.nextMessage()).isNull(); + } +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java index 158a29caa9..23b8b132f3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnableActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 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. @@ -27,8 +27,10 @@ import static androidx.test.espresso.matcher.ViewMatchers.withText; import static org.mockito.Mockito.mock; +import android.content.ComponentName; import android.content.Context; import android.content.Intent; +import android.content.pm.PackageManager; import android.sysprop.BluetoothProperties; import androidx.test.core.app.ActivityScenario; @@ -60,6 +62,14 @@ public class BluetoothOppBtEnableActivityTest { Assume.assumeTrue(BluetoothProperties.isProfileOppEnabled().orElse(false)); mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting( + new ComponentName( + mTargetContext.getPackageName(), + "com.android.bluetooth.opp.BluetoothOppBtEnableActivity"), + PackageManager.COMPONENT_ENABLED_STATE_ENABLED, + PackageManager.DONT_KILL_APP); mIntent = new Intent(); mIntent.setClass(mTargetContext, BluetoothOppBtEnableActivity.class); Intents.init(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java index dafa80f14f..d31d579e47 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppBtEnablingActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022 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. @@ -159,8 +159,8 @@ public class BluetoothOppBtEnablingActivityTest { assertThat(finishCalled.get()).isTrue(); } - private void assertActivityState(ActivityScenario activityScenario, Lifecycle.State state) - throws Exception { + private static void assertActivityState( + ActivityScenario activityScenario, Lifecycle.State state) throws Exception { // TODO: Change this into an event driven systems Thread.sleep(3_000); assertThat(activityScenario.getState()).isEqualTo(state); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java index 6e2b2625b0..3396591ef1 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppLauncherActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 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. @@ -208,8 +208,8 @@ public class BluetoothOppLauncherActivityTest { assertActivityState(scenario, Lifecycle.State.DESTROYED); } - private void assertActivityState(ActivityScenario activityScenario, Lifecycle.State state) - throws Exception { + private static void assertActivityState( + ActivityScenario activityScenario, Lifecycle.State state) throws Exception { Thread.sleep(2_000); assertThat(activityScenario.getState()).isEqualTo(state); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceCleanupTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppServiceCleanupTest.java index b53450cc8f..a1cb6e8fa9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceCleanupTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppServiceCleanupTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2024 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. diff --git a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppTestUtils.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppTestUtils.java new file mode 100644 index 0000000000..deb1268be5 --- /dev/null +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppTestUtils.java @@ -0,0 +1,159 @@ +/* + * 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. + */ + +package com.android.bluetooth.opp; + +import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; +import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; +import static android.content.pm.PackageManager.DONT_KILL_APP; + +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; + +import android.content.ComponentName; +import android.content.Context; +import android.database.Cursor; + +import org.mockito.internal.util.MockUtil; + +import java.util.List; +import java.util.Objects; + +public class BluetoothOppTestUtils { + + /** + * A class containing the data to be return by a cursor. Intended to be use with setUpMockCursor + * + * @attr columnName is name of column to be used as a parameter in cursor.getColumnIndexOrThrow + * @attr mIndex should be returned from cursor.getColumnIndexOrThrow + * @attr mValue should be returned from cursor.getInt() or cursor.getString() or + * cursor.getLong() + */ + public static class CursorMockData { + public final String mColumnName; + public final int mColumnIndex; + public final Object mValue; + + public CursorMockData(String columnName, int index, Object value) { + mColumnName = columnName; + mColumnIndex = index; + mValue = value; + } + } + + /** + * Set up a mock single-row Cursor that work for common use cases in the OPP package. It mocks + * the database column index and value of the cell in that column of the current row + * + * <pre> + * cursorMockDataList.add( + * new CursorMockData(BluetoothShare.DIRECTION, 2, BluetoothShare.DIRECTION_INBOUND + * ); + * ... + * setUpMockCursor(cursor, cursorMockDataList); + * // This will return 2 + * int index = cursor.getColumnIndexOrThrow(BluetoothShare.DIRECTION); + * int direction = cursor.getInt(index); // This will return BluetoothShare.DIRECTION_INBOUND + * </pre> + * + * @param cursor a mock/spy cursor to be setup + * @param cursorMockDataList a list representing what cursor will return + */ + public static void setUpMockCursor(Cursor cursor, List<CursorMockData> cursorMockDataList) { + assert (MockUtil.isMock(cursor)); + + doAnswer( + invocation -> { + String name = invocation.getArgument(0); + return cursorMockDataList.stream() + .filter( + mockCursorData -> + Objects.equals( + mockCursorData.mColumnName, name)) + .findFirst() + .orElse(new CursorMockData("", -1, null)) + .mColumnIndex; + }) + .when(cursor) + .getColumnIndexOrThrow(anyString()); + + doAnswer( + invocation -> { + int index = invocation.getArgument(0); + return cursorMockDataList.stream() + .filter(mockCursorData -> mockCursorData.mColumnIndex == index) + .findFirst() + .orElse(new CursorMockData("", -1, -1)) + .mValue; + }) + .when(cursor) + .getInt(anyInt()); + + doAnswer( + invocation -> { + int index = invocation.getArgument(0); + return cursorMockDataList.stream() + .filter(mockCursorData -> mockCursorData.mColumnIndex == index) + .findFirst() + .orElse(new CursorMockData("", -1, -1)) + .mValue; + }) + .when(cursor) + .getLong(anyInt()); + + doAnswer( + invocation -> { + int index = invocation.getArgument(0); + return cursorMockDataList.stream() + .filter(mockCursorData -> mockCursorData.mColumnIndex == index) + .findFirst() + .orElse(new CursorMockData("", -1, null)) + .mValue; + }) + .when(cursor) + .getString(anyInt()); + + doReturn(true).when(cursor).moveToFirst(); + doReturn(true).when(cursor).moveToLast(); + doReturn(true).when(cursor).moveToNext(); + doReturn(true).when(cursor).moveToPrevious(); + doReturn(true).when(cursor).moveToPosition(anyInt()); + } + + /** + * Enable/Disable an activity for testing + * + * @param activityClass the activity class to enable/disable + * @param enable true to enable, false to disable + * @param mTargetContext target context + */ + public static void enableActivity(Class activityClass, boolean enable, Context mTargetContext) { + int enabledState = + enable ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DEFAULT; + + mTargetContext + .getPackageManager() + .setApplicationEnabledSetting( + mTargetContext.getPackageName(), enabledState, DONT_KILL_APP); + + ComponentName activityName = new ComponentName(mTargetContext, activityClass); + mTargetContext + .getPackageManager() + .setComponentEnabledSetting(activityName, enabledState, DONT_KILL_APP); + } +} diff --git a/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppUtilityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppUtilityTest.java new file mode 100644 index 0000000000..92423c17ea --- /dev/null +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/BluetoothOppUtilityTest.java @@ -0,0 +1,68 @@ +/* + * 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. + */ + +package com.android.bluetooth.opp; + +import static com.android.bluetooth.TestUtils.MockitoRule; + +import static com.google.common.truth.Truth.assertThat; + +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; + +import androidx.test.platform.app.InstrumentationRegistry; + +import com.android.bluetooth.BluetoothMethodProxy; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.Spy; + +public class BluetoothOppUtilityTest { + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); + + @Mock Cursor mCursor; + + @Spy BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance(); + + private static final Uri CORRECT_FORMAT_BUT_INVALID_FILE_URI = + Uri.parse("content://com.android.bluetooth.opp/btopp/0123455343467"); + + private final Context mTargetContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + + @Before + public void setUp() { + BluetoothMethodProxy.setInstanceForTesting(mCallProxy); + } + + @After + public void tearDown() { + BluetoothMethodProxy.setInstanceForTesting(null); + } + + @Test + public void fileExists_returnFalse() { + assertThat( + BluetoothOppUtility.fileExists( + mTargetContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI)) + .isFalse(); + } +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java index 8a5a10e271..473b55c3e0 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/opp/IncomingFileConfirmActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 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. diff --git a/android/app/tests/instrumentation/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java b/android/app/tests/instrumentation/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java new file mode 100644 index 0000000000..30b6528520 --- /dev/null +++ b/android/app/tests/instrumentation/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java @@ -0,0 +1,97 @@ +/* + * Copyright 2022 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. + */ + +package com.android.bluetooth.pan; + +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; + +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import android.bluetooth.BluetoothDevice; +import android.content.Context; +import android.net.ConnectivityManager; +import android.os.Looper; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; + +import java.util.ArrayList; +import java.util.List; + +/** Test cases for {@link BluetoothTetheringNetworkFactory}. */ +@SmallTest +@RunWith(AndroidJUnit4.class) +public class BluetoothTetheringNetworkFactoryTest { + + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); + + @Mock private PanService mPanService; + @Mock Context mContext; + + @Test + public void networkStartReverseTether() { + mockGetSystemService(mContext, Context.CONNECTIVITY_SERVICE, ConnectivityManager.class); + + if (Looper.myLooper() == null) { + Looper.prepare(); + } + + BluetoothTetheringNetworkFactory bluetoothTetheringNetworkFactory = + new BluetoothTetheringNetworkFactory(mContext, Looper.myLooper(), mPanService); + + String iface = "iface"; + bluetoothTetheringNetworkFactory.startReverseTether(iface); + + assertThat(bluetoothTetheringNetworkFactory.getProvider()).isNotNull(); + } + + @Test + public void networkStartReverseTetherStop() { + mockGetSystemService(mContext, Context.CONNECTIVITY_SERVICE, ConnectivityManager.class); + if (Looper.myLooper() == null) { + Looper.prepare(); + } + + BluetoothTetheringNetworkFactory bluetoothTetheringNetworkFactory = + new BluetoothTetheringNetworkFactory(mContext, Looper.myLooper(), mPanService); + + String iface = "iface"; + bluetoothTetheringNetworkFactory.startReverseTether(iface); + + assertThat(bluetoothTetheringNetworkFactory.getProvider()).isNotNull(); + + List<BluetoothDevice> bluetoothDevices = new ArrayList<>(); + BluetoothDevice bluetoothDevice = getTestDevice(11); + bluetoothDevices.add(bluetoothDevice); + + when(mPanService.getConnectedDevices()).thenReturn(bluetoothDevices); + + bluetoothTetheringNetworkFactory.stopReverseTether(); + + verify(mPanService).getConnectedDevices(); + verify(mPanService).disconnect(bluetoothDevice); + } +} diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java b/android/app/tests/instrumentation/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java index 1e837f3d9a..09316dbc78 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/pbap/BluetoothPbapActivityTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 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. diff --git a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java index 593a09ebbb..a9eea3da60 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java @@ -52,6 +52,7 @@ 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.Before; @@ -70,7 +71,7 @@ import java.util.UUID; @MediumTest @RunWith(AndroidJUnit4.class) public class BluetoothInCallServiceTest { - private static final String TAG = "BluetoothInCallServiceTest"; + private static final String TAG = BluetoothInCallServiceTest.class.getSimpleName(); private static final int TEST_DTMF_TONE = 0; private static final String TEST_ACCOUNT_ADDRESS = "//foo.com/"; @@ -99,6 +100,7 @@ public class BluetoothInCallServiceTest { @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); @Mock private BluetoothHeadsetProxy mMockBluetoothHeadset; + @Mock private HeadsetService mHeadsetService; @Mock private BluetoothLeCallControlProxy mLeCallControl; @Mock private BluetoothInCallService.CallInfo mMockCallInfo; @@ -211,19 +213,11 @@ public class BluetoothInCallServiceTest { doReturn(List.of(activeCall)).when(mMockCallInfo).getBluetoothCalls(); mBluetoothInCallService.onCallAdded(activeCall); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset) - .clccResponse( - eq(1), - eq(0), - eq(0), - eq(0), - eq(false), - eq("555000"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService) + .clccResponse(1, 0, 0, 0, false, "555000", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } /** @@ -272,19 +266,11 @@ public class BluetoothInCallServiceTest { doReturn(silentRingingCall).when(mMockCallInfo).getRingingOrSimulatedRingingCall(); mBluetoothInCallService.onCallAdded(silentRingingCall); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset, never()) - .clccResponse( - eq(1), - eq(0), - eq(0), - eq(0), - eq(false), - eq("555000"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, never()) + .clccResponse(1, 0, 0, 0, false, "555000", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -388,28 +374,15 @@ public class BluetoothInCallServiceTest { doReturn(parentId).when(heldCall).getParentId(); doReturn(true).when(parentCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( - eq(1), - eq(0), - eq(CALL_STATE_ACTIVE), - eq(0), - eq(false), - eq("5550001"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset) + 1, 0, CALL_STATE_ACTIVE, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService) .clccResponse( - eq(2), - eq(1), - eq(CALL_STATE_HELD), - eq(0), - eq(false), - eq("5550002"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + 2, 1, CALL_STATE_HELD, 0, false, "5550002", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -445,28 +418,15 @@ public class BluetoothInCallServiceTest { doReturn(parentId).when(confCall2).getParentId(); doReturn(true).when(parentCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( - eq(1), - eq(0), - eq(CALL_STATE_ACTIVE), - eq(0), - eq(true), - eq("5550000"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset) + 1, 0, CALL_STATE_ACTIVE, 0, true, "5550000", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService) .clccResponse( - eq(2), - eq(1), - eq(CALL_STATE_ACTIVE), - eq(0), - eq(true), - eq("5550001"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + 2, 1, CALL_STATE_ACTIVE, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -485,9 +445,8 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_RINGING).when(waitingCall).getState(); doReturn(Uri.parse("tel:555-0000")).when(waitingCall).getHandle(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, @@ -496,8 +455,8 @@ public class BluetoothInCallServiceTest { false, "5550000", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset, times(2)) + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, times(2)) .clccResponse( anyInt(), anyInt(), @@ -516,10 +475,9 @@ public class BluetoothInCallServiceTest { doReturn(Call.STATE_NEW).when(newCall).getState(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService) .clccResponse( anyInt(), anyInt(), @@ -546,9 +504,8 @@ public class BluetoothInCallServiceTest { .when(activeCall) .getGatewayInfo(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, @@ -560,10 +517,10 @@ public class BluetoothInCallServiceTest { // call handle changed doReturn(Uri.parse("tel:213-555-0000")).when(activeCall).getHandle(); - clearInvocations(mMockBluetoothHeadset); + clearInvocations(mHeadsetService); Log.w(TAG, "call handle" + Uri.parse("tel:213-555-0000")); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, @@ -587,9 +544,8 @@ public class BluetoothInCallServiceTest { .when(ringingCall) .getGatewayInfo(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, @@ -598,8 +554,8 @@ public class BluetoothInCallServiceTest { false, "5550000", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset, times(2)) + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, times(2)) .clccResponse( anyInt(), anyInt(), @@ -626,8 +582,8 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, @@ -650,14 +606,14 @@ public class BluetoothInCallServiceTest { .when(newHoldingCall) .getGatewayInfo(); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 1, CALL_STATE_ACTIVE, 0, false, "5550000", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_HELD, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset, times(2)).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, times(2)).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -673,8 +629,8 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, @@ -683,8 +639,8 @@ public class BluetoothInCallServiceTest { false, "5550000", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset, times(2)) + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, times(2)) .clccResponse( anyInt(), anyInt(), @@ -720,8 +676,8 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, @@ -730,11 +686,11 @@ public class BluetoothInCallServiceTest { false, "5550000", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_HELD, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset, times(3)) + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService, times(3)) .clccResponse( anyInt(), anyInt(), @@ -759,18 +715,10 @@ public class BluetoothInCallServiceTest { mBluetoothInCallService.onCallAdded(parentCall); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset) - .clccResponse( - eq(1), - eq(1), - eq(CALL_STATE_ACTIVE), - eq(0), - eq(true), - eq("5550000"), - eq(129)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + verify(mHeadsetService).clccResponse(1, 1, CALL_STATE_ACTIVE, 0, true, "5550000", 129); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -804,27 +752,15 @@ public class BluetoothInCallServiceTest { doReturn(true).when(parentCall).isIncoming(); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( - eq(1), - eq(0), - eq(CALL_STATE_HELD), - eq(0), - eq(true), - eq("5550001"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset) + 1, 0, CALL_STATE_HELD, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService) .clccResponse( - eq(2), - eq(0), - eq(CALL_STATE_HELD), - eq(0), - eq(true), - eq("5550002"), - eq(PhoneNumberUtils.TOA_Unknown)); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); + 2, 0, CALL_STATE_HELD, 0, true, "5550002", PhoneNumberUtils.TOA_Unknown); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -842,9 +778,8 @@ public class BluetoothInCallServiceTest { mBluetoothInCallService.onCallAdded(conferenceCall); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) - .clccResponse(eq(1), eq(1), eq(0), eq(0), eq(true), eq("5551234"), eq(129)); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService).clccResponse(1, 1, 0, 0, true, "5551234", 129); } @Test @@ -879,11 +814,11 @@ public class BluetoothInCallServiceTest { // needs to have at least one CLCC response before merge to enable call inference clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_HELD, 0, false, "5550002", PhoneNumberUtils.TOA_Unknown); calls.clear(); @@ -911,11 +846,11 @@ public class BluetoothInCallServiceTest { mBluetoothInCallService.onCallAdded(conferenceCall); clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_ACTIVE, 0, true, "5550002", PhoneNumberUtils.TOA_Unknown); @@ -929,12 +864,12 @@ public class BluetoothInCallServiceTest { doReturn(true).when(holdingCall).isConference(); doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_ACTIVE, 0, true, "5550002", PhoneNumberUtils.TOA_Unknown); @@ -948,36 +883,18 @@ public class BluetoothInCallServiceTest { calls.remove(holdingCall); assertThat(calls).hasSize(1); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset) - .clccResponse( - anyInt(), - anyInt(), - anyInt(), - anyInt(), - anyBoolean(), - nullable(String.class), - anyInt()); + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); // when parent is removed doReturn(cause).when(conferenceCall).getDisconnectCause(); calls.remove(conferenceCall); mBluetoothInCallService.onCallRemoved(conferenceCall, true); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset).clccResponse(0, 0, 0, 0, false, null, 0); - verify(mMockBluetoothHeadset) - .clccResponse( - anyInt(), - anyInt(), - anyInt(), - anyInt(), - anyBoolean(), - nullable(String.class), - anyInt()); + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService).clccResponse(0, 0, 0, 0, false, null, 0); } @Test @@ -1081,12 +998,12 @@ public class BluetoothInCallServiceTest { .getGatewayInfo(); // needs to have at least one CLCC response before merge to enable call inference - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, false, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_HELD, 0, false, "5550002", PhoneNumberUtils.TOA_Unknown); calls.clear(); @@ -1114,12 +1031,12 @@ public class BluetoothInCallServiceTest { assertThat(calls).hasSize(1); mBluetoothInCallService.onCallAdded(conferenceCall); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_ACTIVE, 0, true, "5550002", PhoneNumberUtils.TOA_Unknown); @@ -1133,12 +1050,12 @@ public class BluetoothInCallServiceTest { doReturn(true).when(activeCall_2).isConference(); doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); - verify(mMockBluetoothHeadset) + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); + verify(mHeadsetService) .clccResponse( 1, 0, CALL_STATE_ACTIVE, 0, true, "5550001", PhoneNumberUtils.TOA_Unknown); - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_ACTIVE, 0, true, "5550002", PhoneNumberUtils.TOA_Unknown); @@ -1156,11 +1073,11 @@ public class BluetoothInCallServiceTest { mBluetoothInCallService.onCallRemoved(activeCall_2, true); doReturn(false).when(activeCall_2).isConference(); - clearInvocations(mMockBluetoothHeadset); - mBluetoothInCallService.listCurrentCalls(); + clearInvocations(mHeadsetService); + mBluetoothInCallService.listCurrentCalls(mHeadsetService); // Index 2 is retained - verify(mMockBluetoothHeadset) + verify(mHeadsetService) .clccResponse( 2, 1, CALL_STATE_ACTIVE, 0, false, "5550002", PhoneNumberUtils.TOA_Unknown); } @@ -2011,7 +1928,7 @@ public class BluetoothInCallServiceTest { verify(firstCall).conference(any(BluetoothCall.class)); } - private void addCallCapability(BluetoothCall call, int capability) { + private static void addCallCapability(BluetoothCall call, int capability) { doReturn(true).when(call).can(eq(capability)); } @@ -2062,11 +1979,11 @@ public class BluetoothInCallServiceTest { makeQuickConnectionServiceComponentName(), id, Binder.getCallingUserHandle()); } - private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { + private static PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { return new PhoneAccount.Builder(makeQuickAccountHandle(id), "label" + idx); } - private PhoneAccount makeQuickAccount(String id, int idx) { + private static PhoneAccount makeQuickAccount(String id, int idx) { return makeQuickAccountBuilder(id, idx) .setAddress(Uri.parse(TEST_ACCOUNT_ADDRESS + idx)) .setSubscriptionAddress(Uri.parse("tel:555-000" + idx)) @@ -2075,7 +1992,7 @@ public class BluetoothInCallServiceTest { .build(); } - private BluetoothCall getMockCall(UUID uuid) { + private static BluetoothCall getMockCall(UUID uuid) { BluetoothCall call = mock(com.android.bluetooth.telephony.BluetoothCall.class); Integer integerUuid = uuid.hashCode(); doReturn(integerUuid).when(call).getId(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java index a87d95f349..79ebced7de 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/telephony/CallInfoTest.java +++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2022 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. @@ -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; @@ -39,13 +40,12 @@ import androidx.test.core.app.ApplicationProvider; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; -import com.android.bluetooth.TestUtils; - import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -61,7 +61,7 @@ public class CallInfoTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); - private TelecomManager mMockTelecomManager; + @Mock private TelecomManager mTelecomManager; private BluetoothInCallService mBluetoothInCallService; private BluetoothInCallService.CallInfo mMockCallInfo; @@ -69,9 +69,8 @@ public class CallInfoTest { @Before public void setUp() throws Exception { Context spiedContext = spy(new ContextWrapper(ApplicationProvider.getApplicationContext())); - mMockTelecomManager = - TestUtils.mockGetSystemService( - spiedContext, Context.TELECOM_SERVICE, TelecomManager.class); + mockGetSystemService( + spiedContext, Context.TELECOM_SERVICE, TelecomManager.class, mTelecomManager); mBluetoothInCallService = new BluetoothInCallService(spiedContext, null, null, null); mBluetoothInCallService.onCreate(); @@ -278,11 +277,11 @@ public class CallInfoTest { List<PhoneAccountHandle> handles = new ArrayList<>(); PhoneAccountHandle testHandle = makeQuickAccountHandle(testId); handles.add(testHandle); - when(mMockTelecomManager.getPhoneAccountsSupportingScheme(PhoneAccount.SCHEME_TEL)) + when(mTelecomManager.getPhoneAccountsSupportingScheme(PhoneAccount.SCHEME_TEL)) .thenReturn(handles); PhoneAccount fakePhoneAccount = makeQuickAccount(testId, TEST_ACCOUNT_INDEX); - when(mMockTelecomManager.getPhoneAccount(testHandle)).thenReturn(fakePhoneAccount); + when(mTelecomManager.getPhoneAccount(testHandle)).thenReturn(fakePhoneAccount); assertThat(mMockCallInfo.getBestPhoneAccount()).isEqualTo(fakePhoneAccount); } @@ -298,11 +297,11 @@ public class CallInfoTest { makeQuickConnectionServiceComponentName(), id, Process.myUserHandle()); } - private PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { + private static PhoneAccount.Builder makeQuickAccountBuilder(String id, int idx) { return new PhoneAccount.Builder(makeQuickAccountHandle(id), "label" + idx); } - private PhoneAccount makeQuickAccount(String id, int idx) { + private static PhoneAccount makeQuickAccount(String id, int idx) { return makeQuickAccountBuilder(id, idx) .setAddress(Uri.parse(TEST_ACCOUNT_ADDRESS + idx)) .setSubscriptionAddress(Uri.parse("tel:555-000" + idx)) @@ -311,7 +310,7 @@ public class CallInfoTest { .build(); } - private BluetoothCall getMockCall() { + private static BluetoothCall getMockCall() { return mock(BluetoothCall.class); } } diff --git a/android/app/tests/unit/Android.bp b/android/app/tests/unit/Android.bp index e8e50eeb2b..e0ed60ac22 100644 --- a/android/app/tests/unit/Android.bp +++ b/android/app/tests/unit/Android.bp @@ -2,8 +2,8 @@ package { default_applicable_licenses: ["Android-Apache-2.0"], } -java_defaults { - name: "BluetoothInstrumentationTestsDefaults", +android_test { + name: "BluetoothJavaUnitTests", defaults: [ "bluetooth_errorprone_rules", ], @@ -26,6 +26,7 @@ java_defaults { ], static_libs: [ + "BluetoothLib", "PlatformProperties", "TestParameterInjector", "android.media.audio-aconfig-exported-java", @@ -43,13 +44,19 @@ java_defaults { "framework-bluetooth-pre-jarjar", "gson", "mmslib", - "mockito-target", + "mockito-target-extended", "modules-utils-handlerexecutor", "platform-parametric-runner-lib", "platform-test-annotations", "truth", ], + // these are needed for Extended Mockito + jni_libs: [ + "libdexmakerjvmtiagent", + "libstaticjvmtiagent", + ], + jarjar_rules: ":bluetooth-jarjar-rules", asset_dirs: ["src/com/android/bluetooth/btservice/storage/schemas"], @@ -66,18 +73,11 @@ java_defaults { "mts-bluetooth", "mts-bt", ], - - instrumentation_for: "Bluetooth", } -android_test { - name: "BluetoothInstrumentationTests", - defaults: ["BluetoothInstrumentationTestsDefaults"], -} - -android_test { - name: "GoogleBluetoothInstrumentationTests", - defaults: ["BluetoothInstrumentationTestsDefaults"], - test_config: "GoogleAndroidTest.xml", - instrumentation_target_package: "com.google.android.bluetooth", +// TODO delete this filegroup to replace by a shadow looper +filegroup { + name: "bluetooth_test_looper", + srcs: ["src/com/android/bluetooth/TestLooper.java"], + visibility: ["//packages/modules/Bluetooth/android/app/tests:__subpackages__"], } diff --git a/android/app/tests/unit/AndroidManifest.xml b/android/app/tests/unit/AndroidManifest.xml index 5e03504fb5..a2861fb7cf 100644 --- a/android/app/tests/unit/AndroidManifest.xml +++ b/android/app/tests/unit/AndroidManifest.xml @@ -4,45 +4,48 @@ xmlns:tools="http://schemas.android.com/tools" package="com.android.bluetooth.tests"> - <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.ACCESS_BLUETOOTH_SHARE" /> - <uses-permission android:name="android.permission.INTERNET" /> + <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> + <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> - <uses-permission android:name="android.permission.WAKE_LOCK" /> - <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> - <uses-permission android:name="android.permission.READ_CONTACTS" /> - <uses-permission android:name="android.permission.WRITE_CONTACTS" /> - <uses-permission android:name="android.permission.READ_CALL_LOG" /> - <uses-permission android:name="android.permission.READ_PHONE_STATE" /> - <uses-permission android:name="android.permission.WRITE_SETTINGS" /> - <uses-permission android:name="android.permission.NFC_HANDOVER_STATUS" /> - <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> - <uses-permission android:name="android.permission.NET_ADMIN" /> + <uses-permission android:name="android.permission.BLUETOOTH_STACK" /> <uses-permission android:name="android.permission.CALL_PRIVILEGED" /> - <uses-permission android:name="com.android.permission.HANDOVER_STATUS" /> - <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> - <uses-permission android:name="android.permission.NET_TUNNELING" /> - <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /> - <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> - <uses-permission android:name="android.permission.BLUETOOTH_STACK" /> <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"/> - <uses-permission android:name="android.permission.MANAGE_USERS"/> + <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" /> + <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.LISTEN_ALWAYS_REPORTED_SIGNAL_STRENGTH"/> - <uses-permission android:name="com.google.android.gallery3d.permission.GALLERY_PROVIDER"/> - <uses-permission android:name="com.android.gallery3d.permission.GALLERY_PROVIDER"/> - - <uses-permission android:name="android.permission.RECEIVE_SMS" /> + <uses-permission android:name="android.permission.MANAGE_USERS"/> + <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/> + <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> + <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" /> + <uses-permission android:name="android.permission.NET_ADMIN" /> + <uses-permission android:name="android.permission.NET_TUNNELING" /> + <uses-permission android:name="android.permission.NETWORK_SETTINGS"/> + <uses-permission android:name="android.permission.NETWORK_FACTORY"/> + <uses-permission android:name="android.permission.NFC_HANDOVER_STATUS" /> + <uses-permission android:name="android.permission.READ_CALL_LOG" /> + <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> - <uses-permission android:name="android.permission.SEND_SMS" /> <uses-permission android:name="android.permission.READ_SMS" /> + <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> + <uses-permission android:name="android.permission.RECEIVE_SMS" /> + <uses-permission android:name="android.permission.SEND_SMS" /> + <uses-permission android:name="android.permission.START_FOREGROUND_SERVICES_FROM_BACKGROUND"/> + <uses-permission android:name="android.permission.WAKE_LOCK" /> + <uses-permission android:name="android.permission.WRITE_CONTACTS" /> + <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> + <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" /> + <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.WRITE_SMS" /> - <uses-permission android:name="android.permission.READ_CONTACTS" /> - <uses-permission android:name="com.android.permission.ALLOWLIST_BLUETOOTH_DEVICE" /> <uses-permission android:name="com.android.email.permission.ACCESS_PROVIDER"/> + <uses-permission android:name="com.android.gallery3d.permission.GALLERY_PROVIDER"/> + <uses-permission android:name="com.android.permission.ALLOWLIST_BLUETOOTH_DEVICE" /> + <uses-permission android:name="com.android.permission.HANDOVER_STATUS" /> + <uses-permission android:name="com.google.android.gallery3d.permission.GALLERY_PROVIDER"/> <!-- For testing Email content access --> <uses-permission android:name="com.android.email.permission.BT_ACCESS_PROVIDER"/> @@ -55,7 +58,8 @@ which is needed when building test cases. --> <application android:allowBackup="true" - android:autoRevokePermissions="disallowed"> + android:autoRevokePermissions="disallowed" + android:debuggable="true"> <uses-library android:name="android.test.runner" /> <uses-library android:name="org.apache.http.legacy" android:required="false" /> @@ -78,7 +82,7 @@ "adb shell am instrument -w com.android.bluetooth.tests/android.test.InstrumentationTestRunner" --> <instrumentation android:name="androidx.test.runner.AndroidJUnitRunner" - android:targetPackage="com.android.bluetooth" + android:targetPackage="com.android.bluetooth.tests" android:label="Tests for com.android.bluetooth"/> </manifest> diff --git a/android/app/tests/unit/AndroidTest.xml b/android/app/tests/unit/AndroidTest.xml index 5ac9bd5608..7196d996d0 100644 --- a/android/app/tests/unit/AndroidTest.xml +++ b/android/app/tests/unit/AndroidTest.xml @@ -15,10 +15,11 @@ --> <configuration description="Runs Bluetooth Test Cases."> <option name="test-suite-tag" value="apct" /> - <option name="test-suite-tag" value="apct-instrumentation" /> <target_preparer class="com.android.tradefed.targetprep.suite.SuiteApkInstaller"> <option name="cleanup-apks" value="true" /> - <option name="test-file-name" value="BluetoothInstrumentationTests.apk" /> + <option name="test-file-name" value="BluetoothJavaUnitTests.apk" /> + <option name="install-arg" value="-r" /> + <option name="install-arg" value="-g" /> </target_preparer> <target_preparer class="com.android.tradefed.targetprep.RootTargetPreparer"> <option name="force-root" value="true" /> @@ -27,21 +28,33 @@ <option name="throw-if-cmd-fail" value="true" /> <option name="run-command" value="input keyevent KEYCODE_WAKEUP" /> <option name="run-command" value="wm dismiss-keyguard" /> - <option name="run-command" value="settings put global ble_scan_always_enabled 0" /> - <option name="run-command" value="cmd bluetooth_manager disable" /> - <option name="run-command" value="cmd bluetooth_manager wait-for-state:STATE_OFF" /> - <option name="run-command" value="settings put global satellite_mode_radios bluetooth" /> - <option name="run-command" value="settings put global satellite_mode_enabled 1" /> - <option name="teardown-command" value="settings delete global satellite_mode_radios" /> - <option name="teardown-command" value="settings put global satellite_mode_enabled 0" /> - <option name="teardown-command" value="cmd bluetooth_manager enable" /> - <option name="teardown-command" value="cmd bluetooth_manager wait-for-state:STATE_ON" /> - <option name="teardown-command" value="settings put global ble_scan_always_enabled 1" /> + + <!-- Disable caches to prevent failure when calling invalidate cache in test. Replace by IpcDataCache.setTestMode when available as module API --> + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_device_get_bond_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_device_get_bond_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_map_get_connection_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_map_get_connection_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_sap_get_connection_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_sap_get_connection_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_connection_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_connection_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_profile_connection_state 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_adapter_get_profile_connection_state 0" /> + + <option name="run-command" value="setprop cache_key.bluetooth.bluetooth_adapter_is_offloaded_filtering_supported 1" /> + <option name="teardown-command" value="setprop cache_key.bluetooth.bluetooth_adapter_is_offloaded_filtering_supported 0" /> </target_preparer> <target_preparer class="com.android.tradefed.targetprep.FolderSaver"> <option name="device-path" value="/data/vendor/ssrdump" /> </target_preparer> - <option name="test-tag" value="BluetoothInstrumentationTests" /> + <option name="test-tag" value="BluetoothJavaUnitTests" /> <test class="com.android.tradefed.testtype.AndroidJUnitTest" > <option name="package" value="com.android.bluetooth.tests" /> <!-- include and exclude filters go into /data/local/tmp/ajur/ by default @@ -56,5 +69,6 @@ class="com.android.tradefed.testtype.suite.module.MainlineTestModuleController"> <option name="enable" value="true" /> <option name="mainline-module-package-name" value="com.android.bt" /> + <option name="mainline-module-package-name" value="com.google.android.bt" /> </object> </configuration> diff --git a/android/app/tests/unit/src/com/android/bluetooth/TestLooper.java b/android/app/tests/unit/src/com/android/bluetooth/TestLooper.java index ae64352e37..e7294ec77f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/TestLooper.java +++ b/android/app/tests/unit/src/com/android/bluetooth/TestLooper.java @@ -46,6 +46,8 @@ import java.util.concurrent.Executor; * allows advancing time. */ public class TestLooper { + private static final String TAG = TestLooper.class.getSimpleName(); + protected final Looper mLooper; private static final Constructor<Looper> LOOPER_CONSTRUCTOR; @@ -54,7 +56,6 @@ public class TestLooper { private static final Field MESSAGE_NEXT_FIELD; private static final Field MESSAGE_WHEN_FIELD; private static final Method MESSAGE_MARK_IN_USE_METHOD; - private static final String TAG = "TestLooper"; private final Clock mClock; diff --git a/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java b/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java index 106bc0008a..94e86b3778 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java +++ b/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java @@ -47,6 +47,7 @@ import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; +import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import java.time.Duration; @@ -55,9 +56,9 @@ import java.util.stream.IntStream; /** A set of methods useful in Bluetooth instrumentation tests */ public class TestUtils { - private static String sSystemScreenOffTimeout = "10000"; + private static final String TAG = Utils.TAG_PREFIX_BLUETOOTH + TestUtils.class.getSimpleName(); - private static final String TAG = "BluetoothTestUtils"; + private static String sSystemScreenOffTimeout = "10000"; /** * Set the return value of {@link AdapterService#getAdapterService()} to a test specified value @@ -96,6 +97,7 @@ public class TestUtils { /** Helper function to mock getSystemService calls */ public static <T> void mockGetSystemService( Context ctx, String serviceName, Class<T> serviceClass, T mockService) { + doReturn(mockService).when(ctx).getSystemService(eq(serviceClass)); doReturn(mockService).when(ctx).getSystemService(eq(serviceName)); doReturn(serviceName).when(ctx).getSystemServiceName(eq(serviceClass)); } @@ -327,7 +329,7 @@ public class TestUtils { } } - /** Wrapper around MockitoJUnit.rule() to be extended in follow-up. */ + /** Wrapper around MockitoJUnit.rule() to clear the inline mock at the end of the test. */ public static class MockitoRule implements MethodRule { private final org.mockito.junit.MockitoRule mMockitoRule = MockitoJUnit.rule(); @@ -338,6 +340,10 @@ public class TestUtils { @Override public void evaluate() throws Throwable { nestedStatement.evaluate(); + + // Prevent OutOfMemory errors due to mock maker leaks. + // See https://github.com/mockito/mockito/issues/1614, b/259280359, b/396177821 + Mockito.framework().clearInlineMocks(); } }; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java index a6bf4950ca..d0c253523a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpCodecConfigTest.java @@ -767,7 +767,8 @@ public class A2dpCodecConfigTest { } } - private BluetoothCodecConfig getDefaultCodecConfigByType(int codecType, int codecPriority) { + private static BluetoothCodecConfig getDefaultCodecConfigByType( + int codecType, int codecPriority) { for (BluetoothCodecConfig codecConfig : sDefaultCodecConfigs) { if (codecConfig.getCodecType() != codecType) { continue; @@ -794,7 +795,7 @@ public class A2dpCodecConfigTest { return null; } - private BluetoothCodecConfig getCodecCapabilitiesByType(int codecType) { + private static BluetoothCodecConfig getCodecCapabilitiesByType(int codecType) { for (BluetoothCodecConfig codecCapabilities : sCodecCapabilities) { if (codecCapabilities.getCodecType() != codecType) { continue; diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java index 0f41af59dd..2c097171f9 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,7 @@ package com.android.bluetooth.a2dp; import static android.bluetooth.BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java index d6e88738f2..5fd8426565 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 @@ -552,8 +552,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); @@ -1287,7 +1286,7 @@ public class A2dpServiceTest { .setA2dpOptionalCodecsEnabled(mDevice, BluetoothA2dp.OPTIONAL_CODECS_PREF_ENABLED); } - private BluetoothCodecConfig buildBluetoothCodecConfig( + private static BluetoothCodecConfig buildBluetoothCodecConfig( int sourceCodecType, int codecPriority, int sampleRate, diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java index 3c653bf444..bbc53e21cc 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,6 +16,8 @@ package com.android.bluetooth.a2dpsink; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java index 25723ab0c9..5470187c0a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java @@ -15,12 +15,16 @@ */ package com.android.bluetooth.a2dpsink; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.getTestDevice; import static com.google.common.truth.Truth.assertThat; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import androidx.test.runner.AndroidJUnit4; @@ -33,22 +37,22 @@ public class StackEventTest { @Test public void testCreateConnectionStateChangedDisconnectedEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_DISCONNECTED); + testConnectionStateChangedBase(STATE_DISCONNECTED); } @Test public void testCreateConnectionStateChangedConnectingEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_CONNECTING); + testConnectionStateChangedBase(STATE_CONNECTING); } @Test public void testCreateConnectionStateChangedConnectedEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_CONNECTED); + testConnectionStateChangedBase(STATE_CONNECTED); } @Test public void testCreateConnectionStateChangedDisconnectingEvent() { - testConnectionStateChangedBase(BluetoothProfile.STATE_DISCONNECTING); + testConnectionStateChangedBase(STATE_DISCONNECTING); } private void testConnectionStateChangedBase(int state) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java index 94c59c7424..dfa391c909 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/BrowserPlayerWrapperTest.java @@ -143,7 +143,7 @@ public class BrowserPlayerWrapperTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaDescription getMediaDescription( + private static MediaDescription getMediaDescription( String id, String title, String artist, @@ -169,7 +169,7 @@ public class BrowserPlayerWrapperTest { return builder.build(); } - private MediaItem getMediaItem(MediaDescription description, int flags) { + private static MediaItem getMediaItem(MediaDescription description, int flags) { return new MediaItem(description, flags); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java index cfb35313b8..d74b4ecd5b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/ImageTest.java @@ -124,7 +124,7 @@ public class ImageTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaMetadata getMediaMetadataWithoutArt() { + private static MediaMetadata getMediaMetadataWithoutArt() { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -134,7 +134,7 @@ public class ImageTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { + private static MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -145,7 +145,7 @@ public class ImageTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithUri(String field, String uri) { + private static MediaMetadata getMediaMetadataWithUri(String field, String uri) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_TITLE, "BT Test Song") @@ -156,7 +156,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithoutArt() { + private static MediaDescription getMediaDescriptionWithoutArt() { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -164,7 +164,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithBitmap(Bitmap image) { + private static MediaDescription getMediaDescriptionWithBitmap(Bitmap image) { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -173,7 +173,7 @@ public class ImageTest { return builder.build(); } - private MediaDescription getMediaDescriptionWithUri(Uri uri) { + private static MediaDescription getMediaDescriptionWithUri(Uri uri) { MediaDescription.Builder builder = new MediaDescription.Builder() .setTitle("BT Test Song") @@ -182,13 +182,13 @@ public class ImageTest { return builder.build(); } - private Bundle getBundleWithBitmap(String field, Bitmap image) { + private static Bundle getBundleWithBitmap(String field, Bitmap image) { Bundle bundle = new Bundle(); bundle.putParcelable(field, image); return bundle; } - private Bundle getBundleWithUri(String field, String uri) { + private static Bundle getBundleWithUri(String field, String uri) { Bundle bundle = new Bundle(); bundle.putString(field, uri); return bundle; diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java index 3f689acd70..7a084783fb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.audio_util; +import static android.Manifest.permission.MEDIA_CONTENT_CONTROL; +import static android.Manifest.permission.MODIFY_PHONE_STATE; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -60,15 +63,14 @@ public class MediaPlayerListTest { private @Mock MediaController mMockController; private @Mock MediaPlayerWrapper mMockPlayerWrapper; - private final String mFlagDexmarker = System.getProperty("dexmaker.share_classloader", "false"); private MediaPlayerWrapper.Callback mActivePlayerCallback; private MediaSessionManager mMediaSessionManager; @Before public void setUp() throws Exception { - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", "true"); - } + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .adoptShellPermissionIdentity(MEDIA_CONTENT_CONTROL, MODIFY_PHONE_STATE); if (Looper.myLooper() == null) { Looper.prepare(); @@ -124,12 +126,12 @@ public class MediaPlayerListTest { MediaControllerFactory.inject(null); MediaPlayerWrapperFactory.inject(null); mMediaPlayerList.cleanup(); - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", mFlagDexmarker); - } + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .dropShellPermissionIdentity(); } - private MediaData prepareMediaData(int playbackState) { + private static MediaData prepareMediaData(int playbackState) { PlaybackState.Builder builder = new PlaybackState.Builder(); builder.setState(playbackState, 0, 1); ArrayList<Metadata> list = new ArrayList<Metadata>(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java index d7f7cb56cc..0ad8530e75 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java @@ -130,7 +130,7 @@ public class MetadataTest { return BitmapFactory.decodeStream(imageInputStream); } - private MediaMetadata getMediaMetadata() { + private static MediaMetadata getMediaMetadata() { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -149,7 +149,7 @@ public class MetadataTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { + private static MediaMetadata getMediaMetadataWithBitmap(String field, Bitmap image) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -168,7 +168,7 @@ public class MetadataTest { return builder.build(); } - private MediaMetadata getMediaMetadataWithUri(String field, Uri uri) { + private static MediaMetadata getMediaMetadataWithUri(String field, Uri uri) { MediaMetadata.Builder builder = new MediaMetadata.Builder() .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID) @@ -187,7 +187,7 @@ public class MetadataTest { return builder.build(); } - private MediaDescription getMediaDescription(Bitmap bitmap, Uri uri, Bundle extras) { + private static MediaDescription getMediaDescription(Bitmap bitmap, Uri uri, Bundle extras) { MediaDescription.Builder builder = new MediaDescription.Builder() .setMediaId(SONG_MEDIA_ID) @@ -206,15 +206,15 @@ public class MetadataTest { return builder.build(); } - private MediaItem getMediaItem(MediaDescription description) { + private static MediaItem getMediaItem(MediaDescription description) { return new MediaItem(description, 0 /* not browsable/playable */); } - private QueueItem getQueueItem(MediaDescription description) { + private static QueueItem getQueueItem(MediaDescription description) { return new QueueItem(description, 1 /* queue ID */); } - private Bundle getBundle() { + private static Bundle getBundle() { Bundle bundle = new Bundle(); bundle.putString(MediaMetadata.METADATA_KEY_MEDIA_ID, SONG_MEDIA_ID); bundle.putString(MediaMetadata.METADATA_KEY_TITLE, SONG_TITLE); @@ -227,19 +227,19 @@ public class MetadataTest { return bundle; } - private Bundle getBundleWithBitmap(String field, Bitmap image) { + private static Bundle getBundleWithBitmap(String field, Bitmap image) { Bundle bundle = getBundle(); bundle.putParcelable(field, image); return bundle; } - private Bundle getBundleWithUri(String field, Uri uri) { + private static Bundle getBundleWithUri(String field, Uri uri) { Bundle bundle = getBundle(); bundle.putString(field, uri.toString()); return bundle; } - private void assertMetadata( + private static void assertMetadata( String mediaId, String title, String artist, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java index da529d669b..93c2fe0678 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java @@ -161,7 +161,8 @@ public class AvrcpBipObexServerTest { * <p>Our server will use: - getReceivedHeader - sendHeaders - getMaxPacketSize - * openOutputStream */ - private Operation makeOperation(HeaderSet requestHeaders, OutputStream os) throws Exception { + private static Operation makeOperation(HeaderSet requestHeaders, OutputStream os) + throws Exception { Operation op = mock(Operation.class); when(op.getReceivedHeader()).thenReturn(requestHeaders); when(op.getMaxPacketSize()).thenReturn(256); @@ -169,7 +170,7 @@ public class AvrcpBipObexServerTest { return op; } - private byte[] makeDescriptor(int encoding, int width, int height) { + private static byte[] makeDescriptor(int encoding, int width, int height) { return new BipImageDescriptor.Builder() .setEncoding(encoding) .setFixedDimensions(width, height) diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java index d4bf4a17af..172692a4e9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpTargetServiceTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.avrcp; +import static android.Manifest.permission.MEDIA_CONTENT_CONTROL; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.mockGetSystemService; @@ -82,6 +84,9 @@ public class AvrcpTargetServiceTest { @Before public void setUp() throws Exception { + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .adoptShellPermissionIdentity(MEDIA_CONTENT_CONTROL); mLooper = new TestLooper(); mLooper.startAutoDispatch(); @@ -109,6 +114,9 @@ public class AvrcpTargetServiceTest { @After public void tearDown() throws Exception { mLooper.stopAutoDispatchAndIgnoreExceptions(); + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .dropShellPermissionIdentity(); } @Test @@ -143,7 +151,7 @@ public class AvrcpTargetServiceTest { assertThat(AvrcpTargetService.isQueueUpdated(firstQueue, secondQueue)).isTrue(); } - private Metadata createEmptyMetadata() { + private static Metadata createEmptyMetadata() { Metadata.Builder builder = new Metadata.Builder(); return builder.useDefaults().build(); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java index f9585fe54e..bcf90f4066 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcp/CoverArtTest.java @@ -81,19 +81,19 @@ public class CoverArtTest { return BitmapFactory.decodeStream(imageInputStream); } - private Bitmap toBitmap(byte[] imageBytes) { + private static Bitmap toBitmap(byte[] imageBytes) { ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes); return BitmapFactory.decodeStream(inputStream); } - private BipImageDescriptor getDescriptor(int encoding, int width, int height) { + private static BipImageDescriptor getDescriptor(int encoding, int width, int height) { return new BipImageDescriptor.Builder() .setEncoding(encoding) .setFixedDimensions(width, height) .build(); } - private boolean containsThumbnailFormat(BipImageProperties properties) { + private static boolean containsThumbnailFormat(BipImageProperties properties) { if (properties == null) return false; for (BipImageFormat format : properties.getNativeFormats()) { @@ -117,7 +117,7 @@ public class CoverArtTest { return false; } - private boolean isThumbnailFormat(Bitmap image) { + private static boolean isThumbnailFormat(Bitmap image) { if (image == null) return false; return (200 == image.getHeight() && 200 == image.getWidth()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java index d4213b5b9f..f98bda00db 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,11 @@ 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 com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -24,7 +29,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,23 +99,23 @@ public class AvrcpBipClientTest { @Test public void setConnectionState() { - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING); + mClient.setConnectionState(STATE_CONNECTING); - assertThat(mClient.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mClient.getState()).isEqualTo(STATE_CONNECTING); } @Test public void getConnectionState() { - mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTED); + mClient.setConnectionState(STATE_DISCONNECTED); assertThat(mClient.getStateName()).isEqualTo("Disconnected"); - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING); + mClient.setConnectionState(STATE_CONNECTING); assertThat(mClient.getStateName()).isEqualTo("Connecting"); - mClient.setConnectionState(BluetoothProfile.STATE_CONNECTED); + mClient.setConnectionState(STATE_CONNECTED); assertThat(mClient.getStateName()).isEqualTo("Connected"); - mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTING); + mClient.setConnectionState(STATE_DISCONNECTING); assertThat(mClient.getStateName()).isEqualTo("Disconnecting"); int invalidState = 4; 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 633cb43668..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()); @@ -115,7 +117,7 @@ public class AvrcpControllerStateMachineTest { doReturn(mBrowseTree).when(mAvrcpControllerService).getBrowseTree(); mockGetSystemService( - mAvrcpControllerService, Context.AUDIO_SERVICE, AudioManager.class, mAudioManager); + mAdapterService, Context.AUDIO_SERVICE, AudioManager.class, mAudioManager); doReturn(mCoverArtManager).when(mAvrcpControllerService).getCoverArtManager(); if (Looper.myLooper() == null) { Looper.prepare(); @@ -157,13 +159,13 @@ public class AvrcpControllerStateMachineTest { /** Destroy a state machine you created to test */ private void destroyStateMachine(AvrcpControllerStateMachine sm) { - if (sm == null || sm.getState() == BluetoothProfile.STATE_DISCONNECTED) return; + if (sm == null || sm.getState() == STATE_DISCONNECTED) return; sm.disconnect(); TestUtils.waitForLooperToBeIdle(sm.getHandler().getLooper()); // is disconnected - assertThat(sm.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(sm.getState()).isEqualTo(STATE_DISCONNECTED); // told mAvrcpControllerService to remove it verify(mAvrcpControllerService).removeStateMachine(eq(sm)); @@ -203,9 +205,9 @@ public class AvrcpControllerStateMachineTest { .sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class)); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Connected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_CONNECTED); - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } private AvrcpItem makeTrack( @@ -239,7 +241,7 @@ public class AvrcpControllerStateMachineTest { return builder.build(); } - private AvrcpPlayer makePlayer( + private static AvrcpPlayer makePlayer( BluetoothDevice device, int playerId, String playerName, @@ -356,10 +358,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } @@ -385,10 +387,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } @@ -414,10 +416,10 @@ public class AvrcpControllerStateMachineTest { assertThat(mIntentArgument.getValue().getAction()) .isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED); assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mAvrcpStateMachine.getCurrentState()) .isInstanceOf(AvrcpControllerStateMachine.Disconnected.class); - assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED); verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java index 580de97ba5..c1b0f52616 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayerTest.java @@ -178,7 +178,7 @@ public class AvrcpPlayerTest { assertThat(avrcpPlayer.notifyImageDownload(uuid, uri)).isTrue(); } - private void setSupportedFeature(byte[] supportedFeatures, int feature) { + private static void setSupportedFeature(byte[] supportedFeatures, int feature) { int byteNumber = feature / 8; byte bitMask = (byte) (1 << (feature % 8)); supportedFeatures[byteNumber] = (byte) (supportedFeatures[byteNumber] | bitMask); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java index 3500d0e0c7..02a63b298b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java @@ -33,7 +33,8 @@ import java.util.TimeZone; @RunWith(AndroidJUnit4.class) public class BipAttachmentFormatTest { - private Date makeDate(int month, int day, int year, int hours, int min, int sec, TimeZone tz) { + private static Date makeDate( + int month, int day, int year, int hours, int min, int sec, TimeZone tz) { Calendar.Builder builder = new Calendar.Builder(); /* Note that Calendar months are zero-based in Java framework */ @@ -43,12 +44,12 @@ public class BipAttachmentFormatTest { return builder.build().getTime(); } - private Date makeDate(int month, int day, int year, int hours, int min, int sec) { + private static Date makeDate(int month, int day, int year, int hours, int min, int sec) { return makeDate(month, day, year, hours, min, sec, null); } @SuppressLint("UndefinedEquals") - private void testParse( + private static void testParse( String contentType, String charset, String name, @@ -83,7 +84,7 @@ public class BipAttachmentFormatTest { } @SuppressLint("UndefinedEquals") - private void testCreate( + private static void testCreate( String contentType, String charset, String name, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java index 9b3032c657..bf3b29a00d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java @@ -34,7 +34,8 @@ import java.util.TimeZone; @RunWith(AndroidJUnit4.class) public class BipDatetimeTest { - private Date makeDate(int month, int day, int year, int hours, int min, int sec, TimeZone tz) { + private static Date makeDate( + int month, int day, int year, int hours, int min, int sec, TimeZone tz) { Calendar.Builder builder = new Calendar.Builder(); /* Note that Calendar months are zero-based in Java framework */ @@ -44,11 +45,12 @@ public class BipDatetimeTest { return builder.build().getTime(); } - private Date makeDate(int month, int day, int year, int hours, int min, int sec) { + private static Date makeDate(int month, int day, int year, int hours, int min, int sec) { return makeDate(month, day, year, hours, min, sec, null); } - private String makeTzAdjustedString(int month, int day, int year, int hours, int min, int sec) { + private static String makeTzAdjustedString( + int month, int day, int year, int hours, int min, int sec) { Calendar cal = Calendar.getInstance(); cal.setTime(makeDate(month, day, year, hours, min, sec)); cal.setTimeZone(TimeZone.getDefault()); @@ -64,7 +66,8 @@ public class BipDatetimeTest { } @SuppressLint("UndefinedEquals") - private void testParse(String date, Date expectedDate, boolean isUtc, String expectedStr) { + private static void testParse( + String date, Date expectedDate, boolean isUtc, String expectedStr) { BipDateTime bipDateTime = new BipDateTime(date); assertThat(bipDateTime.getTime()).isEqualTo(expectedDate); assertThat(bipDateTime.isUtc()).isEqualTo(isUtc); @@ -72,7 +75,7 @@ public class BipDatetimeTest { } @SuppressLint("UndefinedEquals") - private void testCreate(Date date, String dateStr) { + private static void testCreate(Date date, String dateStr) { BipDateTime bipDate = new BipDateTime(date); assertThat(bipDate.getTime()).isEqualTo(date); assertThat(bipDate.isUtc()).isTrue(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java index 99f4a5281a..712c304c33 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipEncodingTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class BipEncodingTest { - private void testParse( + private static void testParse( String input, int encodingType, String encodingStr, @@ -40,7 +40,7 @@ public class BipEncodingTest { assertThat(encoding.isAndroidSupported()).isEqualTo(isAndroidSupported); } - private void testParseMany( + private static void testParseMany( String[] inputs, int encodingType, String encodingStr, diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java index 6e767249e9..8f11f9218f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImagePropertiesTest.java @@ -108,7 +108,7 @@ public class BipImagePropertiesTest { private static final String IMAGE_PROPERTIES_END = "</image-properties>"; - private InputStream toUtf8Stream(String s) { + private static InputStream toUtf8Stream(String s) { return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java index 88f093966a..8d2146218a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipPixelTest.java @@ -27,7 +27,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class BipPixelTest { - private void testParse( + private static void testParse( String input, int pixelType, int minWidth, @@ -44,7 +44,7 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testFixed(int width, int height, String pixelStr) { + private static void testFixed(int width, int height, String pixelStr) { BipPixel pixel = BipPixel.createFixed(width, height); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_FIXED); assertThat(pixel.getMinWidth()).isEqualTo(width); @@ -54,7 +54,7 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testResizableModified( + private static void testResizableModified( int minWidth, int minHeight, int maxWidth, int maxHeight, String pixelStr) { BipPixel pixel = BipPixel.createResizableModified(minWidth, minHeight, maxWidth, maxHeight); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_RESIZE_MODIFIED_ASPECT_RATIO); @@ -65,7 +65,8 @@ public class BipPixelTest { assertThat(pixel.toString()).isEqualTo(pixelStr); } - private void testResizableFixed(int minWidth, int maxWidth, int maxHeight, String pixelStr) { + private static void testResizableFixed( + int minWidth, int maxWidth, int maxHeight, String pixelStr) { int minHeight = (minWidth * maxHeight) / maxWidth; // spec defined BipPixel pixel = BipPixel.createResizableFixed(minWidth, maxWidth, maxHeight); assertThat(pixel.getType()).isEqualTo(BipPixel.TYPE_RESIZE_FIXED_ASPECT_RATIO); diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java index d3d9e6ca34..e4791e3956 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 @@ -304,6 +304,13 @@ public class BassClientServiceTest { doReturn(true).when(stateMachine).isBassStateReady(); mStateMachines.put( (BluetoothDevice) invocation.getArgument(0), stateMachine); + doAnswer( + inv -> { + return Message.obtain( + (Handler) null, (int) inv.getArgument(0)); + }) + .when(stateMachine) + .obtainMessage(anyInt()); return stateMachine; }) .when(mObjectsFactory) @@ -325,7 +332,6 @@ public class BassClientServiceTest { @After public void tearDown() throws Exception { - android.util.Log.e("WILLIAM", "tearDown"); mBassClientService.unregisterCallback(mCallback); mBassClientService.cleanup(); @@ -548,7 +554,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testStopSearchingForSources() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -589,7 +594,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testStop() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -626,7 +630,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testStopSearchingForSources_startAndSyncAgain() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -660,7 +663,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testStop_startAndSyncAgain() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -698,7 +700,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testStopSearchingForSources_addSourceCauseSyncEvenWithoutScanning() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -756,7 +757,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testNotRemovingCachedBroadcastOnLostWithoutScanning_noResyncFlag() throws RemoteException { @@ -818,10 +818,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testNotRemovingCachedBroadcastOnLostWithoutScanning() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -882,7 +879,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testNotRemovingCachedBroadcastOnFailEstablishWithoutScanning() throws RemoteException { final BluetoothDevice device1 = @@ -1016,7 +1012,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testMultipleAddSourceToUnsyncedBroadcaster() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -1074,7 +1069,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testMultipleAddSourceToUnsyncedInactiveBroadcaster() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -1145,7 +1139,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testStopSearchingForSources_timeoutForActiveSync() { prepareConnectedDeviceGroup(); @@ -1192,7 +1185,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testStopSearchingForSources_clearTimeoutForActiveSync() { prepareConnectedDeviceGroup(); @@ -1241,7 +1233,7 @@ public class BassClientServiceTest { .isEqualTo(TEST_BROADCAST_ID); } - private byte[] getScanRecord(int broadcastId) { + private static byte[] getScanRecord(int broadcastId) { return new byte[] { 0x02, 0x01, @@ -1326,7 +1318,7 @@ public class BassClientServiceTest { generateScanResult(scanResult); } - private byte[] getPAScanRecord() { + private static byte[] getPAScanRecord() { return new byte[] { (byte) 0x02, (byte) 0x01, @@ -1450,7 +1442,7 @@ public class BassClientServiceTest { } } - private BluetoothLeBroadcastReceiveState injectRemoteSourceState( + private static BluetoothLeBroadcastReceiveState injectRemoteSourceState( BassClientStateMachine sm, BluetoothLeBroadcastMetadata meta, int sourceId, @@ -2407,85 +2399,56 @@ public class BassClientServiceTest { @Test public void testActiveSyncedSource_AddRemoveGet() { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - final int handle1 = 1; - final int handle2 = 2; - final int handle3 = 3; - - // Check if empty - assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); - - // Check adding first handle - mBassClientService.addActiveSyncedSource(handle1); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); - assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle1); - - // Check if cannot add duplicate element - mBassClientService.addActiveSyncedSource(handle1); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); - assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle1); - - // Check adding second element - mBassClientService.addActiveSyncedSource(handle2); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); - assertThat(mBassClientService.getActiveSyncedSources()) - .containsExactly(handle1, handle2) - .inOrder(); - - // Check removing non existing element - mBassClientService.removeActiveSyncedSource(handle3); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); - assertThat(mBassClientService.getActiveSyncedSources()) - .containsExactly(handle1, handle2) - .inOrder(); - // Check removing second element - mBassClientService.removeActiveSyncedSource(handle1); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); - assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle2); - - // Check removing first element - mBassClientService.removeActiveSyncedSource(handle2); - assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); - - // Add 2 elements - mBassClientService.addActiveSyncedSource(handle1); - mBassClientService.addActiveSyncedSource(handle2); - assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); - - // Check removing all at once - mBassClientService.removeActiveSyncedSource(null); - assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); - } else { - final int testSyncHandle = 1; - prepareConnectedDeviceGroup(); - assertThat(mStateMachines).hasSize(2); - - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNull(); - - // Verify add active synced source - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle); - // Verify duplicated source won't be added - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice).size()) - .isEqualTo(1); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1).size()) - .isEqualTo(1); - - // Verify remove active synced source - mBassClientService.removeActiveSyncedSource(mCurrentDevice, testSyncHandle); - mBassClientService.removeActiveSyncedSource(mCurrentDevice1, testSyncHandle); - expect.that(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNull(); - expect.that(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNull(); - } + final int handle1 = 1; + final int handle2 = 2; + final int handle3 = 3; + + // Check if empty + assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); + + // Check adding first handle + mBassClientService.addActiveSyncedSource(handle1); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); + assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle1); + + // Check if cannot add duplicate element + mBassClientService.addActiveSyncedSource(handle1); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); + assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle1); + + // Check adding second element + mBassClientService.addActiveSyncedSource(handle2); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); + assertThat(mBassClientService.getActiveSyncedSources()) + .containsExactly(handle1, handle2) + .inOrder(); + + // Check removing non existing element + mBassClientService.removeActiveSyncedSource(handle3); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); + assertThat(mBassClientService.getActiveSyncedSources()) + .containsExactly(handle1, handle2) + .inOrder(); + // Check removing second element + mBassClientService.removeActiveSyncedSource(handle1); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(1); + assertThat(mBassClientService.getActiveSyncedSources()).containsExactly(handle2); + + // Check removing first element + mBassClientService.removeActiveSyncedSource(handle2); + assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); + + // Add 2 elements + mBassClientService.addActiveSyncedSource(handle1); + mBassClientService.addActiveSyncedSource(handle2); + assertThat(mBassClientService.getActiveSyncedSources()).hasSize(2); + + // Check removing all at once + mBassClientService.removeActiveSyncedSource(null); + assertThat(mBassClientService.getActiveSyncedSources()).isEmpty(); } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testScanResult_withSameBroadcastId() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -2515,7 +2478,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_withSameBroadcastId() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -2538,7 +2500,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_wrongBassUUID() { byte[] scanRecord = new byte[] { @@ -2616,7 +2577,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSyncEstablished_statusFailed() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -2640,7 +2600,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_wrongPublicBroadcastUUID() { byte[] scanRecord = new byte[] { @@ -2718,7 +2677,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_wrongPublicBroadcastData() { byte[] scanRecord = new byte[] { @@ -2796,7 +2754,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_queueAndRemoveAfterMaxLimit() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -2992,10 +2949,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testSelectSource_removeAfterMaxLimit_notSyncedToAnySink() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -3087,10 +3041,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void testSelectSource_removeAfterMaxLimit_firstIfAllSyncedToSinks() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -3221,7 +3172,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testAddSourceToUnsyncedSource_causesSyncBeforeAddingSource() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -3368,11 +3318,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_ALLOWED_CONTEXT_MASK, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT - }) public void testAddSourceForExternalBroadcast_triggerSetContextMask() { final int testGroupId = 1; prepareConnectedDeviceGroup(); @@ -3439,7 +3384,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testSelectSource_orderOfSyncRegisteringByPriorityAndRssi() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -3686,10 +3630,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_SORT_SCANS_TO_SYNC_BY_FAILS, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_SORT_SCANS_TO_SYNC_BY_FAILS) public void testSelectSource_orderOfSyncRegisteringByRssiAndFailsCounter() { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -3880,64 +3821,6 @@ public class BassClientServiceTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void testSelectSource_invalidActiveSource() { - final int testSyncHandle = 0; - final int testSyncHandle1 = 1; - final int testSyncHandle2 = 2; - final int testSyncHandle3 = 3; - byte[] scanRecord = getScanRecord(12345); - ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - - prepareConnectedDeviceGroup(); - assertThat(mStateMachines).hasSize(2); - - // Verify add active synced source - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).hasSize(1); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).hasSize(1); - - // Verify selectSource with max synced device should not proceed - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle1); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle1); - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle2); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle2); - mBassClientService.addActiveSyncedSource(mCurrentDevice, testSyncHandle3); - mBassClientService.addActiveSyncedSource(mCurrentDevice1, testSyncHandle3); - - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNotNull(); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice)).hasSize(4); - assertThat(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).hasSize(4); - - BluetoothDevice testDevice4 = - mBluetoothAdapter.getRemoteLeDevice( - "00:01:02:03:04:05", BluetoothDevice.ADDRESS_TYPE_RANDOM); - ScanResult scanResult1 = new ScanResult(testDevice4, 0, 0, 0, 0, 0, 0, 0, record, 0); - mBassClientService.selectSource(mCurrentDevice, scanResult1, false); - mBassClientService.selectSource(mCurrentDevice1, scanResult1, false); - for (BassClientStateMachine sm : mStateMachines.values()) { - ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); - verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); - - Optional<Message> msg = - messageCaptor.getAllValues().stream() - .filter(m -> m.what == BassClientStateMachine.REACHED_MAX_SOURCE_LIMIT) - .findFirst(); - assertThat(msg.isPresent()).isEqualTo(true); - } - - // Verify remove all active synced source - mBassClientService.removeActiveSyncedSource(mCurrentDevice, null); - mBassClientService.removeActiveSyncedSource(mCurrentDevice1, null); - expect.that(mBassClientService.getActiveSyncedSources(mCurrentDevice)).isNull(); - expect.that(mBassClientService.getActiveSyncedSources(mCurrentDevice1)).isNull(); - } - - @Test public void testPeriodicAdvertisementResultMap_updateGetAndModifyNotifiedFlag() { final String testBroadcastName = "Test"; final int testSyncHandle = 1; @@ -3990,7 +3873,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void testPeriodicAdvertisementResultMap_syncEstablishedOnTheSameSyncHandle() { final String testBroadcastName1 = "Test1"; final String testBroadcastName2 = "Test2"; @@ -4077,65 +3959,24 @@ public class BassClientServiceTest { @Test public void testSyncHandleToBroadcastIdMap_getSyncHandleAndGetBroadcastId() { - if (Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - final int testSyncHandle = 1; - final int testSyncHandleInvalid = 2; - final int testBroadcastId = 42; - final int testBroadcastIdInvalid = 43; - - prepareConnectedDeviceGroup(); - startSearchingForSources(); - onScanResult(mSourceDevice, testBroadcastId); - onSyncEstablished(mSourceDevice, testSyncHandle); - - assertThat(mBassClientService.getSyncHandleForBroadcastId(testBroadcastIdInvalid)) - .isEqualTo(BassConstants.INVALID_SYNC_HANDLE); - assertThat(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandleInvalid)) - .isEqualTo(BassConstants.INVALID_BROADCAST_ID); - assertThat(mBassClientService.getSyncHandleForBroadcastId(testBroadcastId)) - .isEqualTo(testSyncHandle); - assertThat(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandle)) - .isEqualTo(testBroadcastId); - } else { - final String testBroadcastName = "Test"; - final int testSyncHandle = 1; - final int testSyncHandleInvalid = 2; - final int testBroadcastId = 42; - final int testBroadcastIdInvalid = 43; - final int testAdvertiserSid = 1234; - final int testAdvInterval = 100; - - // mock the update in selectSource - mBassClientService.updatePeriodicAdvertisementResultMap( - mSourceDevice, - mSourceDevice.getAddressType(), - BassConstants.PENDING_SYNC_HANDLE, - BassConstants.INVALID_ADV_SID, - testAdvInterval, - testBroadcastId, - null, - testBroadcastName); - - // mock the update in onSyncEstablished - mBassClientService.updatePeriodicAdvertisementResultMap( - mSourceDevice, - BassConstants.INVALID_ADV_ADDRESS_TYPE, - testSyncHandle, - testAdvertiserSid, - BassConstants.INVALID_ADV_INTERVAL, - BassConstants.INVALID_BROADCAST_ID, - null, - null); + final int testSyncHandle = 1; + final int testSyncHandleInvalid = 2; + final int testBroadcastId = 42; + final int testBroadcastIdInvalid = 43; - expect.that(mBassClientService.getSyncHandleForBroadcastId(testBroadcastIdInvalid)) - .isEqualTo(BassConstants.INVALID_SYNC_HANDLE); - expect.that(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandleInvalid)) - .isEqualTo(BassConstants.INVALID_BROADCAST_ID); - expect.that(mBassClientService.getSyncHandleForBroadcastId(testBroadcastId)) - .isEqualTo(testSyncHandle); - expect.that(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandle)) - .isEqualTo(testBroadcastId); - } + prepareConnectedDeviceGroup(); + startSearchingForSources(); + onScanResult(mSourceDevice, testBroadcastId); + onSyncEstablished(mSourceDevice, testSyncHandle); + + assertThat(mBassClientService.getSyncHandleForBroadcastId(testBroadcastIdInvalid)) + .isEqualTo(BassConstants.INVALID_SYNC_HANDLE); + assertThat(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandleInvalid)) + .isEqualTo(BassConstants.INVALID_BROADCAST_ID); + assertThat(mBassClientService.getSyncHandleForBroadcastId(testBroadcastId)) + .isEqualTo(testSyncHandle); + assertThat(mBassClientService.getBroadcastIdForSyncHandle(testSyncHandle)) + .isEqualTo(testBroadcastId); } private void verifyAllGroupMembersGettingUpdateOrAddSource(BluetoothLeBroadcastMetadata meta) { @@ -4207,20 +4048,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(); @@ -4249,12 +4085,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( @@ -4271,7 +4103,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT) public void testHandleUnicastSourceStreamStatusChange_MultipleRequests() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -4468,7 +4299,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()) { @@ -4480,7 +4310,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 { @@ -4491,7 +4320,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()) { @@ -4692,7 +4520,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void onPeriodicAdvertisingReport_withoutBaseData_cancelActiveSync() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -4783,7 +4610,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void onPeriodicAdvertisingReport_wrongBaseData_cancelActiveSync() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -4883,7 +4709,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void onPeriodicAdvertisingReport_updateBase() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -4917,7 +4742,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void onPeriodicAdvertisingReport_updateBaseAfterWrongBaseData() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5061,7 +4885,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void notifySourceFound_once_updateRssi() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5108,10 +4931,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE) public void notifySourceFound_without_public_announcement() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5208,7 +5028,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void notifySourceFound_periodic_after_big() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5252,10 +5071,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE) public void notifySourceFound_periodic_after_wrong_periodic() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5337,7 +5153,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void notifySourceFound_alreadySynced_clearFlag() throws RemoteException { // Scan prepareConnectedDeviceGroup(); @@ -5393,7 +5208,6 @@ public class BassClientServiceTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void onSyncLost_notifySourceLostAndCancelSync_noResyncFlag() throws RemoteException { prepareConnectedDeviceGroup(); @@ -5431,10 +5245,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void onSyncLost_notifySourceLostAndCancelSync() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -5472,10 +5283,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void monitorBroadcastAfterSyncMaxLimit() throws RemoteException { final BluetoothDevice device1 = mBluetoothAdapter.getRemoteLeDevice( @@ -5701,10 +5509,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_resync_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5713,10 +5518,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_resync_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5725,10 +5527,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_resyncByRemote_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5736,10 +5535,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_resyncByRemote_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5747,10 +5543,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_addNewSource() { sinkUnintentionalDuringScanning(); @@ -5783,10 +5576,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_addSameSource() { sinkUnintentionalDuringScanning(); @@ -5797,10 +5587,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_removeSource_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5812,10 +5599,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_removeSource_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5827,10 +5611,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_stopReceivers_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5843,10 +5624,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_stopReceivers_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5859,10 +5637,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_suspendReceivers_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5875,10 +5650,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_suspendReceivers_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5891,10 +5663,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_suspendAllReceivers_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5907,10 +5676,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_suspendAllReceivers_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5923,10 +5689,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_publicStopBigMonitoring_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5936,10 +5699,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_publicStopBigMonitoring_duringScanning() { sinkUnintentionalDuringScanning(); @@ -5949,10 +5709,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_unsync_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -5991,10 +5748,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_unsync_duringScanning() { sinkUnintentionalDuringScanning(); @@ -6033,10 +5787,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_disconnect_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -6057,10 +5808,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_disconnect_duringScanning() { sinkUnintentionalDuringScanning(); @@ -6081,10 +5829,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_syncLost_withoutScanning_outOfRange() { sinkUnintentionalWithoutScanning(); @@ -6113,10 +5858,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_syncLost_duringScanning_outOfRange() { sinkUnintentionalDuringScanning(); @@ -6147,10 +5889,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_bigMonitorTimeout_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -6163,10 +5902,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_bigMonitorTimeout_duringScanning() { sinkUnintentionalDuringScanning(); @@ -6181,7 +5917,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_MONITOR_UNICAST_SOURCE_WHEN_MANAGED_BY_BROADCAST_DELEGATOR }) public void sinkUnintentional_handleUnicastSourceStreamStatusChange_withoutScanning() { @@ -6203,7 +5938,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_MONITOR_UNICAST_SOURCE_WHEN_MANAGED_BY_BROADCAST_DELEGATOR }) public void sinkUnintentional_handleUnicastSourceStreamStatusChange_duringScanning() { @@ -6222,10 +5956,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_handleUnicastSourceStreamStatusChangeNoContext_withoutScanning() { sinkUnintentionalWithoutScanning(); @@ -6244,10 +5975,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkUnintentional_handleUnicastSourceStreamStatusChangeNoContext_duringScanning() { sinkUnintentionalDuringScanning(); @@ -6265,10 +5993,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION) public void sinkUnintentional_autoSyncToBroadcast_onStopSearching() { sinkUnintentionalDuringScanning(); @@ -6287,7 +6012,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void sinkUnintentional_remainEstablishedSync_onStopSearching() { @@ -6361,7 +6085,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void waitingForPast_remainPendingSync_onStopSearching() { @@ -6429,7 +6152,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void pendingSourceToAdd_remainPendingSync_onStopSearching() { @@ -6505,7 +6227,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void alreadySynced_remainSyncAndCache_onStartSearching() { @@ -6598,7 +6319,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void alreadySyncedWithSinks_syncAndRemainCache_onStartSearching() { @@ -6677,7 +6397,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void waitingForPast_remainPendingSyncAndCache_onStartSearching() { @@ -6762,7 +6481,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void pendingSourcesToAdd_remainPendingSyncAndCache_onStartSearching() { @@ -6857,7 +6575,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, Flags.FLAG_LEAUDIO_BROADCAST_PREVENT_RESUME_INTERRUPTION }) public void hostIntentional_SyncAndRemainCache_onStartSearching() { @@ -6948,10 +6665,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_addSameSource() { prepareSynchronizedPair(); @@ -6968,10 +6682,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_removeSource_withoutScanning() { prepareSynchronizedPairAndStopSearching(); @@ -6982,10 +6693,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_removeSource_duringScanning() { prepareSynchronizedPair(); @@ -6996,10 +6704,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_stopReceivers_withoutScanning() { prepareSynchronizedPairAndStopSearching(); @@ -7010,10 +6715,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_stopReceivers_duringScanning() { prepareSynchronizedPair(); @@ -7024,78 +6726,51 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_suspendReceivers_withoutScanning() { prepareSynchronizedPairAndStopSearching(); // Suspend receivers, HOST_INTENTIONAL mBassClientService.suspendReceiversSourceSynchronization(TEST_BROADCAST_ID); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_suspendReceivers_duringScanning() { prepareSynchronizedPair(); // Suspend receivers, HOST_INTENTIONAL mBassClientService.suspendReceiversSourceSynchronization(TEST_BROADCAST_ID); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_suspendAllReceivers_withoutScanning() { prepareSynchronizedPairAndStopSearching(); // Suspend all receivers, HOST_INTENTIONAL mBassClientService.suspendAllReceiversSourceSynchronization(); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_suspendAllReceivers_duringScanning() { prepareSynchronizedPair(); // Suspend all receivers, HOST_INTENTIONAL mBassClientService.suspendAllReceiversSourceSynchronization(); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } checkResumeSynchronizationByHost(); } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_handleUnicastSourceStreamStatusChange_withoutScanning() { prepareSynchronizedPairAndStopSearching(); @@ -7103,9 +6778,6 @@ public class BassClientServiceTest { mBassClientService.handleUnicastSourceStreamStatusChange( 0 /* STATUS_LOCAL_STREAM_REQUESTED */); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } /* Unicast finished streaming */ mBassClientService.handleUnicastSourceStreamStatusChange( @@ -7115,10 +6787,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_handleUnicastSourceStreamStatusChange_duringScanning() { prepareSynchronizedPair(); @@ -7126,9 +6795,6 @@ public class BassClientServiceTest { mBassClientService.handleUnicastSourceStreamStatusChange( 0 /* STATUS_LOCAL_STREAM_REQUESTED */); checkNoSinkPause(); - if (!Flags.leaudioBroadcastAssistantPeripheralEntrustment()) { - verifyRemoveMessageAndInjectSourceRemoval(); - } /* Unicast finished streaming */ mBassClientService.handleUnicastSourceStreamStatusChange( @@ -7139,8 +6805,6 @@ public class BassClientServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE, - Flags.FLAG_LEAUDIO_BROADCAST_ASSISTANT_PERIPHERAL_ENTRUSTMENT, Flags.FLAG_LEAUDIO_MONITOR_UNICAST_SOURCE_WHEN_MANAGED_BY_BROADCAST_DELEGATOR }) public void hostIntentional_handleUnicastSourceStreamStatusChange_beforeResumeCompleted() { @@ -7175,10 +6839,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_handleUnicastSourceStreamStatusChangeNoContext_withoutScanning() { prepareSynchronizedPairAndStopSearching(); @@ -7196,10 +6857,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void hostIntentional_handleUnicastSourceStreamStatusChangeNoContext_duringScanning() { prepareSynchronizedPair(); @@ -7216,10 +6874,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void outOfRange_syncEstablishedFailed_stopMonitoringAfterTimeout() { prepareSynchronizedPairAndStopSearching(); @@ -7254,10 +6909,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void outOfRange_syncEstablishedFailed_clearTimeout() { prepareSynchronizedPairAndStopSearching(); @@ -7289,10 +6941,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void outOfRange_syncEstablishedFailed_restartSearching() { prepareSynchronizedPairAndStopSearching(); @@ -7358,10 +7007,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void outOfRange_syncEstablishedFailed_allowSyncAnotherBroadcaster() { prepareSynchronizedPairAndStopSearching(); @@ -7408,10 +7054,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void autoSyncToBroadcast_AlreadySyncedToSink_onStartSearching() { prepareSynchronizedPairAndStopSearching(); @@ -7428,10 +7071,7 @@ public class BassClientServiceTest { * source */ @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkBassStateReady_addSourceIfPeerDeviceSynced() throws RemoteException { // Imitate broadcast being active doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID); @@ -7447,11 +7087,7 @@ public class BassClientServiceTest { } // Remove source on the mCurrentDevice - for (BassClientStateMachine sm : mStateMachines.values()) { - if (sm.getDevice().equals(mCurrentDevice)) { - injectRemoteSourceStateRemoval(sm, TEST_SOURCE_ID); - } - } + injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID); mBassClientService.getCallbacks().notifyBassStateReady(mCurrentDevice); TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); @@ -7479,10 +7115,7 @@ public class BassClientServiceTest { /** Test add pending source when BASS state get ready */ @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkBassStateReady_addPendingSource() throws RemoteException { prepareConnectedDeviceGroup(); BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); @@ -7550,6 +7183,70 @@ public class BassClientServiceTest { } } + /** Test add pending source when BASS state get ready */ + @Test + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) + public void sinkBassStateReady_addPendingSourceGroup_oneByOneReady() throws RemoteException { + prepareConnectedDeviceGroup(); + BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID); + // Verify adding source when Bass state not ready + for (BassClientStateMachine sm : mStateMachines.values()) { + doReturn(false).when(sm).isBassStateReady(); + } + doReturn(true).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID); + doReturn(new ArrayList<BluetoothLeBroadcastMetadata>(Arrays.asList(meta))) + .when(mLeAudioService) + .getAllBroadcastMetadata(); + // Add broadcast source and got queued due to BASS not ready + mBassClientService.addSource(mCurrentDevice, meta, /* isGroupOp */ true); + + // First BASS ready + doReturn(true).when(mStateMachines.get(mCurrentDevice)).isBassStateReady(); + mBassClientService.getCallbacks().notifyBassStateReady(mCurrentDevice); + TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); + + // Verify adding source is resumed once BASS state ready + for (BassClientStateMachine sm : mStateMachines.values()) { + if (sm.getDevice().equals(mCurrentDevice)) { + ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); + verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); + + Message msg = + messageCaptor.getAllValues().stream() + .filter(m -> (m.what == BassClientStateMachine.ADD_BCAST_SOURCE)) + .findFirst() + .orElse(null); + assertThat(msg).isNotNull(); + clearInvocations(sm); + } else if (sm.getDevice().equals(mCurrentDevice1)) { + verify(sm, never()).sendMessage(any()); + } + } + + // Second BASS ready + doReturn(true).when(mStateMachines.get(mCurrentDevice1)).isBassStateReady(); + mBassClientService.getCallbacks().notifyBassStateReady(mCurrentDevice1); + TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper()); + + // Verify adding source is resumed once BASS state ready + for (BassClientStateMachine sm : mStateMachines.values()) { + if (sm.getDevice().equals(mCurrentDevice)) { + verify(sm, never()).sendMessage(any()); + } else if (sm.getDevice().equals(mCurrentDevice1)) { + ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); + verify(sm, atLeast(1)).sendMessage(messageCaptor.capture()); + + Message msg = + messageCaptor.getAllValues().stream() + .filter(m -> (m.what == BassClientStateMachine.ADD_BCAST_SOURCE)) + .findFirst() + .orElse(null); + assertThat(msg).isNotNull(); + clearInvocations(sm); + } + } + } + @Test public void testIsLocalBroadacst() { int broadcastId = 12345; @@ -7646,10 +7343,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void initiatePaSyncTransfer() { prepareSynchronizedPairAndStopSearching(); @@ -7668,10 +7362,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void InitiatePaSyncTransfer_concurrentWithResume() { prepareSynchronizedPairAndStopSearching(); @@ -7700,10 +7391,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void resumeSourceSynchronization_omitWhenPaSyncedOrRequested() { prepareSynchronizedPair(); @@ -7733,10 +7421,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void removeSource_duringSuspend() { prepareSynchronizedPair(); @@ -7752,10 +7437,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void stopReceivers_duringSuspend() { prepareSynchronizedPair(); @@ -7771,10 +7453,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenSourceAddFailed() throws RemoteException { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -7820,10 +7499,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenSwitch() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -7857,10 +7533,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenSwitch_duringSuspend() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -7902,10 +7575,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenRemove() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -7965,10 +7635,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenAllDisconnected() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -7982,20 +7649,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); @@ -8008,35 +7669,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); @@ -8050,10 +7699,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenAllDisconnected_duringSuspend() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -8075,20 +7721,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); @@ -8109,35 +7749,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); @@ -8151,10 +7779,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenRemove_oneDisconnectedFirst() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -8169,14 +7794,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 @@ -8187,9 +7808,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); @@ -8203,10 +7822,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void multipleSinkMetadata_clearWhenRemove_oneDisconnectedFirst_duringSuspend() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -8229,14 +7845,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 @@ -8247,9 +7859,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); @@ -8263,10 +7873,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void clearPendingSourceToAdd_oneByOne_whenDisconnected() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -8282,14 +7889,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 @@ -8316,10 +7919,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void clearPendingSourceToAdd_group_whenDisconnected() { prepareConnectedDeviceGroup(); startSearchingForSources(); @@ -8334,14 +7934,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 @@ -8368,10 +7964,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void doNotAllowDuplicatesInAddSelectSource() { prepareSynchronizedPairAndStopSearching(); @@ -8395,10 +7988,7 @@ public class BassClientServiceTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkDisconnectionDuringReasuming() { prepareSynchronizedPairAndStopSearching(); 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 6578fa6a45..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; @@ -35,13 +39,10 @@ import static com.android.bluetooth.bass_client.BassClientStateMachine.DISCONNEC import static com.android.bluetooth.bass_client.BassClientStateMachine.GATT_TXN_PROCESSED; import static com.android.bluetooth.bass_client.BassClientStateMachine.GATT_TXN_TIMEOUT; import static com.android.bluetooth.bass_client.BassClientStateMachine.INITIATE_PA_SYNC_TRANSFER; -import static com.android.bluetooth.bass_client.BassClientStateMachine.PSYNC_ACTIVE_TIMEOUT; -import static com.android.bluetooth.bass_client.BassClientStateMachine.REACHED_MAX_SOURCE_LIMIT; import static com.android.bluetooth.bass_client.BassClientStateMachine.READ_BASS_CHARACTERISTICS; import static com.android.bluetooth.bass_client.BassClientStateMachine.REMOTE_SCAN_START; import static com.android.bluetooth.bass_client.BassClientStateMachine.REMOTE_SCAN_STOP; import static com.android.bluetooth.bass_client.BassClientStateMachine.REMOVE_BCAST_SOURCE; -import static com.android.bluetooth.bass_client.BassClientStateMachine.SELECT_BCAST_SOURCE; import static com.android.bluetooth.bass_client.BassClientStateMachine.SET_BCAST_CODE; import static com.android.bluetooth.bass_client.BassClientStateMachine.START_SCAN_OFFLOAD; import static com.android.bluetooth.bass_client.BassClientStateMachine.STOP_SCAN_OFFLOAD; @@ -87,9 +88,6 @@ import android.bluetooth.BluetoothLeBroadcastSubgroup; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothStatusCodes; -import android.bluetooth.le.PeriodicAdvertisingCallback; -import android.bluetooth.le.ScanRecord; -import android.bluetooth.le.ScanResult; import android.content.Context; import android.content.Intent; import android.os.HandlerThread; @@ -110,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; @@ -150,7 +149,6 @@ public class BassClientStateMachineTest { private static final int TEST_BROADCAST_ID = 42; private static final int TEST_SOURCE_ID = 1; private static final int TEST_CHANNEL_INDEX = 1; - private static final String TEST_BROADCAST_NAME = "Test"; private static final String EMPTY_BLUETOOTH_DEVICE_ADDRESS = "00:00:00:00:00:00"; private static final byte OPCODE_UPDATE_SOURCE = 0x03; private static final int UPDATE_SOURCE_FIXED_LENGTH = 6; @@ -197,14 +195,14 @@ public class BassClientStateMachineTest { mBassClientStateMachine.start(); } - private int classTypeToConnectionState(Class type) { + private static int classTypeToConnectionState(Class type) { if (type == BassClientStateMachine.Disconnected.class) { - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } else if (type == BassClientStateMachine.Connecting.class) { - return BluetoothProfile.STATE_CONNECTING; + return STATE_CONNECTING; } else if (type == BassClientStateMachine.Connected.class || type == BassClientStateMachine.ConnectedProcessing.class) { - return BluetoothProfile.STATE_CONNECTED; + return STATE_CONNECTED; } else { assertWithMessage("Invalid class type given: " + type).fail(); return 0; @@ -220,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); } /** @@ -295,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 @@ -333,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); @@ -346,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); @@ -360,8 +357,6 @@ public class BassClientStateMachineTest { BassClientStateMachine.BluetoothGattTestableWrapper btGatt = Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class); mBassClientStateMachine.mBluetoothGatt = btGatt; - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); assertThat(mBassClientStateMachine.getCurrentState()) .isInstanceOf(BassClientStateMachine.Disconnected.class); @@ -385,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 @@ -395,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 @@ -410,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 @@ -420,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 @@ -542,122 +533,6 @@ public class BassClientStateMachineTest { assertThat(mBassClientStateMachine.isPendingRemove(invalidSourceId)).isFalse(); } - @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void parseScanRecord_withoutBaseData_callCancelActiveSync() { - byte[] scanRecord = - new byte[] { - 0x02, - 0x01, - 0x1a, // advertising flags - 0x05, - 0x02, - 0x0b, - 0x11, - 0x0a, - 0x11, // 16 bit service uuids - 0x04, - 0x09, - 0x50, - 0x65, - 0x64, // name - 0x02, - 0x0A, - (byte) 0xec, // tx power level - 0x05, - 0x16, - 0x0b, - 0x11, - 0x50, - 0x64, // service data - 0x05, - (byte) 0xff, - (byte) 0xe0, - 0x00, - 0x02, - 0x15, // manufacturer specific data - 0x03, - 0x50, - 0x01, - 0x02, // an unknown data type won't cause trouble - }; - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - - ScanRecord data = ScanRecord.parseFromBytes(scanRecord); - mBassClientStateMachine.parseScanRecord(0, data); - // verify getActiveSyncedSource got called in CancelActiveSync - verify(mBassClientService).getActiveSyncedSources(any()); - } - - @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void parseScanRecord_withBaseData_callsUpdateBase() { - byte[] scanRecordWithBaseData = - new byte[] { - (byte) 0x02, - (byte) 0x01, - (byte) 0x1a, // advertising flags - (byte) 0x05, - (byte) 0x02, - (byte) 0x51, - (byte) 0x18, - (byte) 0x0a, - (byte) 0x11, // 16 bit service uuids - (byte) 0x04, - (byte) 0x09, - (byte) 0x50, - (byte) 0x65, - (byte) 0x64, // name - (byte) 0x02, - (byte) 0x0A, - (byte) 0xec, // tx power level - (byte) 0x19, - (byte) 0x16, - (byte) 0x51, - (byte) 0x18, // service data (base data with 18 bytes) - // LEVEL 1 - (byte) 0x01, - (byte) 0x02, - (byte) 0x03, // presentationDelay - (byte) 0x01, // numSubGroups - // LEVEL 2 - (byte) 0x01, // numSubGroups - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, // UNKNOWN_CODEC - (byte) 0x02, // codecConfigLength - (byte) 0x01, - (byte) 'A', // codecConfigInfo - (byte) 0x03, // metaDataLength - (byte) 0x06, - (byte) 0x07, - (byte) 0x08, // metaData - // LEVEL 3 - (byte) 0x04, // index - (byte) 0x03, // codecConfigLength - (byte) 0x02, - (byte) 'B', - (byte) 'C', // codecConfigInfo - (byte) 0x05, - (byte) 0xff, - (byte) 0xe0, - (byte) 0x00, - (byte) 0x02, - (byte) 0x15, // manufacturer specific data - (byte) 0x03, - (byte) 0x50, - (byte) 0x01, - (byte) 0x02, // an unknown data type won't cause trouble - }; - ScanRecord data = ScanRecord.parseFromBytes(scanRecordWithBaseData); - assertThat(data.getServiceUuids()).contains(BassConstants.BASIC_AUDIO_UUID); - assertThat(data.getServiceData(BassConstants.BASIC_AUDIO_UUID)).isNotNull(); - mBassClientStateMachine.parseScanRecord(0, data); - verify(mBassClientService).updateBase(anyInt(), any()); - } @Test public void gattCallbackOnConnectionStateChange_changedToConnected() @@ -670,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()); @@ -684,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()); @@ -706,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()); @@ -1488,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()); @@ -1496,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); } @@ -1504,9 +1379,6 @@ public class BassClientStateMachineTest { public void sendOtherMessages_inDisconnectedState_doesNotChangeState() { initToDisconnectedState(); - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - mBassClientStateMachine.sendMessage(STOP_SCAN_OFFLOAD); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); @@ -1545,20 +1417,11 @@ public class BassClientStateMachineTest { } @Test - public void sendPsyncActiveTimeoutMessage_inConnectingState_defersMessage() { - initToConnectingState(); - - mBassClientStateMachine.sendMessage(PSYNC_ACTIVE_TIMEOUT); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(PSYNC_ACTIVE_TIMEOUT)).isTrue(); - } - - @Test public void sendStateChangedToNonConnectedMessage_inConnectingState_movesToDisconnected() { 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; @@ -1572,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); } @@ -1617,8 +1480,6 @@ public class BassClientStateMachineTest { initToConnectedState(); mBassClientStateMachine.mBluetoothGatt = null; - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); mBassClientStateMachine.sendMessage(DISCONNECT); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1639,10 +1500,7 @@ public class BassClientStateMachineTest { initToConnectedState(); Message connectedMsg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - connectedMsg.obj = BluetoothProfile.STATE_CONNECTED; - - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); + connectedMsg.obj = STATE_CONNECTED; mBassClientStateMachine.sendMessage(connectedMsg); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -1652,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(); @@ -1722,19 +1580,6 @@ public class BassClientStateMachineTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void sendPsyncActiveMessage_inConnectedState() { - initToConnectedState(); - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - - mBassClientStateMachine.sendMessage(PSYNC_ACTIVE_TIMEOUT); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - // verify getActiveSyncedSource got called in CancelActiveSync - verify(mBassClientService).getActiveSyncedSources(any()); - } - - @Test public void sendInvalidMessage_inConnectedState_doesNotChangeState() { initToConnectedState(); @@ -1744,87 +1589,6 @@ public class BassClientStateMachineTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void sendSelectBcastSourceMessage_inConnectedState() { - initToConnectedState(); - - byte[] scanRecord = - new byte[] { - 0x02, - 0x01, - 0x1a, // advertising flags - 0x05, - 0x02, - 0x52, - 0x18, - 0x0a, - 0x11, // 16 bit service uuids - 0x04, - 0x09, - 0x50, - 0x65, - 0x64, // name - 0x02, - 0x0A, - (byte) 0xec, // tx power level - 0x05, - 0x30, - 0x54, - 0x65, - 0x73, - 0x74, // broadcast name: Test - 0x06, - 0x16, - 0x52, - 0x18, - 0x50, - 0x64, - 0x65, // service data - 0x08, - 0x16, - 0x56, - 0x18, - 0x07, - 0x03, - 0x06, - 0x07, - 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, - (byte) 0xff, - (byte) 0xe0, - 0x00, - 0x02, - 0x15, // manufacturer specific data - 0x03, - 0x50, - 0x01, - 0x02, // an unknown data type won't cause trouble - }; - ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - - doNothing() - .when(mMethodProxy) - .periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); - ScanResult scanResult = new ScanResult(mTestDevice, 0, 0, 0, 0, 0, 0, 0, record, 0); - mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mBassClientService) - .updatePeriodicAdvertisementResultMap( - any(), - anyInt(), - anyInt(), - anyInt(), - anyInt(), - anyInt(), - any(), - eq(TEST_BROADCAST_NAME)); - } - - @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void sendAddBcastSourceMessage_inConnectedState() { initToConnectedState(); @@ -1858,19 +1622,6 @@ public class BassClientStateMachineTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void sendReachedMaxSourceLimitMessage_inConnectedState() { - initToConnectedState(); - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - - mBassClientStateMachine.sendMessage(REACHED_MAX_SOURCE_LIMIT); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - // verify getActiveSyncedSource got called in CancelActiveSync - verify(mBassClientService).getActiveSyncedSources(any()); - } - - @Test public void sendSwitchSourceMessage_inConnectedState() { initToConnectedState(); BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata(); @@ -2181,8 +1932,6 @@ public class BassClientStateMachineTest { // Mock instance of btGatt was created in initToConnectedProcessingState(). BassClientStateMachine.BluetoothGattTestableWrapper btGatt = mBassClientStateMachine.mBluetoothGatt; - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); mBassClientStateMachine.mBluetoothGatt = null; mBassClientStateMachine.sendMessage(DISCONNECT); @@ -2203,10 +1952,7 @@ public class BassClientStateMachineTest { Message msgToConnectedState = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED); - msgToConnectedState.obj = BluetoothProfile.STATE_CONNECTED; - - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); + msgToConnectedState.obj = STATE_CONNECTED; mBassClientStateMachine.sendMessage(msgToConnectedState); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); @@ -2217,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(); @@ -2230,30 +1976,13 @@ public class BassClientStateMachineTest { initToConnectedProcessingState(); BassClientService.Callbacks callbacks = Mockito.mock(BassClientService.Callbacks.class); when(mBassClientService.getCallbacks()).thenReturn(callbacks); - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); // Test sendPendingCallbacks(START_SCAN_OFFLOAD, ERROR_UNKNOWN) mBassClientStateMachine.mPendingOperation = START_SCAN_OFFLOAD; - mBassClientStateMachine.mAutoTriggered = false; sendMessageAndVerifyTransition( mBassClientStateMachine.obtainMessage(GATT_TXN_PROCESSED, GATT_FAILURE), BassClientStateMachine.Connected.class); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - // verify getActiveSyncedSource got called in CancelActiveSync - verify(mBassClientService).getActiveSyncedSources(any()); - - // Test sendPendingCallbacks(START_SCAN_OFFLOAD, ERROR_UNKNOWN) - moveConnectedStateToConnectedProcessingState(); - mBassClientStateMachine.mPendingOperation = START_SCAN_OFFLOAD; - mBassClientStateMachine.mAutoTriggered = true; - sendMessageAndVerifyTransition( - mBassClientStateMachine.obtainMessage(GATT_TXN_PROCESSED, GATT_FAILURE), - BassClientStateMachine.Connected.class); - assertThat(mBassClientStateMachine.mAutoTriggered).isFalse(); - } - // Test sendPendingCallbacks(ADD_BCAST_SOURCE, ERROR_UNKNOWN) moveConnectedStateToConnectedProcessingState(); mBassClientStateMachine.mPendingMetadata = createBroadcastMetadata(); @@ -2263,17 +1992,6 @@ public class BassClientStateMachineTest { BassClientStateMachine.Connected.class); verify(callbacks).notifySourceAddFailed(any(), any(), anyInt()); - if (!Flags.leaudioBroadcastExtractPeriodicScannerFromStateMachine()) { - // Test sendPendingCallbacks(UPDATE_BCAST_SOURCE, REASON_LOCAL_APP_REQUEST) - moveConnectedStateToConnectedProcessingState(); - mBassClientStateMachine.mPendingOperation = UPDATE_BCAST_SOURCE; - mBassClientStateMachine.mAutoTriggered = true; - sendMessageAndVerifyTransition( - mBassClientStateMachine.obtainMessage(GATT_TXN_PROCESSED, GATT_SUCCESS), - BassClientStateMachine.Connected.class); - assertThat(mBassClientStateMachine.mAutoTriggered).isFalse(); - } - // Test sendPendingCallbacks(UPDATE_BCAST_SOURCE, ERROR_UNKNOWN) moveConnectedStateToConnectedProcessingState(); mBassClientStateMachine.mPendingOperation = UPDATE_BCAST_SOURCE; @@ -2337,10 +2055,6 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(STOP_SCAN_OFFLOAD)).isTrue(); - mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SELECT_BCAST_SOURCE)).isTrue(); - mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(ADD_BCAST_SOURCE)).isTrue(); @@ -2353,15 +2067,6 @@ public class BassClientStateMachineTest { TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(REMOVE_BCAST_SOURCE)).isTrue(); - mBassClientStateMachine.sendMessage(PSYNC_ACTIVE_TIMEOUT); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(PSYNC_ACTIVE_TIMEOUT)).isTrue(); - - mBassClientStateMachine.sendMessage(REACHED_MAX_SOURCE_LIMIT); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(REACHED_MAX_SOURCE_LIMIT)) - .isTrue(); - mBassClientStateMachine.sendMessage(SWITCH_BCAST_SOURCE); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); assertThat(mBassClientStateMachine.hasDeferredMessagesSuper(SWITCH_BCAST_SOURCE)).isTrue(); @@ -2456,206 +2161,6 @@ public class BassClientStateMachineTest { verify(btGatt).writeCharacteristic(any()); } - @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void selectBcastSource_withSameBroadcastId() { - final int testSyncHandle = 1; - initToConnectedState(); - - byte[] scanRecord = - new byte[] { - 0x02, - 0x01, - 0x1a, // advertising flags - 0x05, - 0x02, - 0x52, - 0x18, - 0x0a, - 0x11, // 16 bit service uuids - 0x04, - 0x09, - 0x50, - 0x65, - 0x64, // name - 0x02, - 0x0A, - (byte) 0xec, // tx power level - 0x05, - 0x30, - 0x54, - 0x65, - 0x73, - 0x74, // broadcast name: Test - 0x06, - 0x16, - 0x52, - 0x18, - 0x2A, - 0x00, - 0x00, // service data, broadcast id TEST_BROADCAST_ID - 0x08, - 0x16, - 0x56, - 0x18, - 0x07, - 0x03, - 0x06, - 0x07, - 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, - (byte) 0xff, - (byte) 0xe0, - 0x00, - 0x02, - 0x15, // manufacturer specific data - 0x03, - 0x50, - 0x01, - 0x02, // an unknown data type won't cause trouble - }; - ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - ScanResult scanResult = new ScanResult(mTestDevice, 0, 0, 0, 0, 0, 0, 0, record, 0); - - List<Integer> activeSyncedSrc = new ArrayList<>(); - activeSyncedSrc.add(testSyncHandle); - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(activeSyncedSrc); - when(mBassClientService.getSyncHandleForBroadcastId(anyInt())).thenReturn(testSyncHandle); - doNothing() - .when(mMethodProxy) - .periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); - - mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - // validate syncing to the same broadcast id will be skipped - verify(mBassClientService, never()) - .updatePeriodicAdvertisementResultMap( - any(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), any(), any()); - - // need this to ensure expected mock behavior for getActiveSyncedSource - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - - mBassClientStateMachine.sendMessage(SELECT_BCAST_SOURCE, BassConstants.AUTO, 0, scanResult); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mBassClientService) - .updatePeriodicAdvertisementResultMap( - any(), - anyInt(), - anyInt(), - anyInt(), - anyInt(), - anyInt(), - any(), - eq(TEST_BROADCAST_NAME)); - } - - @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void addBcastSource_withCachedScanResults() { - initToConnectedState(); - - BassClientService.Callbacks callbacks = Mockito.mock(BassClientService.Callbacks.class); - when(mBassClientService.getCallbacks()).thenReturn(callbacks); - - BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata(); - when(mBassClientService.isLocalBroadcast(any(BluetoothLeBroadcastMetadata.class))) - .thenReturn(false); - when(mBassClientService.getActiveSyncedSources(any())).thenReturn(null); - when(mBassClientService.getCachedBroadcast(anyInt())).thenReturn(null); - mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - - verify(mBassClientService).getCallbacks(); - verify(callbacks).notifySourceAddFailed(any(), any(), anyInt()); - - byte[] scanRecord = - new byte[] { - 0x02, - 0x01, - 0x1a, // advertising flags - 0x05, - 0x02, - 0x52, - 0x18, - 0x0a, - 0x11, // 16 bit service uuids - 0x04, - 0x09, - 0x50, - 0x65, - 0x64, // name - 0x02, - 0x0A, - (byte) 0xec, // tx power level - 0x05, - 0x30, - 0x54, - 0x65, - 0x73, - 0x74, // broadcast name: Test - 0x06, - 0x16, - 0x52, - 0x18, - 0x2A, - 0x00, - 0x00, // service data, broadcast id TEST_BROADCAST_ID - 0x08, - 0x16, - 0x56, - 0x18, - 0x07, - 0x03, - 0x06, - 0x07, - 0x08, - // service data - public broadcast, - // feature - 0x7, metadata len - 0x3, metadata - 0x6, 0x7, 0x8 - 0x05, - (byte) 0xff, - (byte) 0xe0, - 0x00, - 0x02, - 0x15, // manufacturer specific data - 0x03, - 0x50, - 0x01, - 0x02, // an unknown data type won't cause trouble - }; - ScanRecord record = ScanRecord.parseFromBytes(scanRecord); - ScanResult scanResult = - new ScanResult( - mAdapter.getRemoteLeDevice( - "00:11:22:33:44:55", BluetoothDevice.ADDRESS_TYPE_RANDOM), - 0, - 0, - 0, - 0, - 0, - 0, - 0, - record, - 0); - when(mBassClientService.getCachedBroadcast(anyInt())).thenReturn(scanResult); - doNothing() - .when(mMethodProxy) - .periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); - // validate add source will trigger select source and update mPendingSourceToAdd - mBassClientStateMachine.sendMessage(ADD_BCAST_SOURCE, metadata); - TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - - verify(mMethodProxy, timeout(TIMEOUT_MS)) - .periodicAdvertisingManagerRegisterSync( - any(), any(), anyInt(), anyInt(), any(), any()); - assertThat(mBassClientStateMachine.mPendingSourceToAdd).isEqualTo(metadata); - verify(mBassClientService, never()).sendBroadcast(any(Intent.class), anyString(), any()); - } - private void initToDisconnectedState() { allowConnection(true); allowConnectGatt(true); @@ -2664,125 +2169,6 @@ public class BassClientStateMachineTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void periodicAdvertisingCallbackOnSyncLost_notifySourceLost() { - PeriodicAdvertisingCallback cb = mBassClientStateMachine.mLocalPeriodicAdvCallback; - BassClientService.Callbacks callbacks = Mockito.mock(BassClientService.Callbacks.class); - int syncHandle = 1; - int broadcastId = 2; - when(mBassClientService.getBroadcastIdForSyncHandle(syncHandle)).thenReturn(broadcastId); - when(mBassClientService.getCallbacks()).thenReturn(callbacks); - cb.onSyncLost(syncHandle); - - verify(callbacks).notifySourceLost(broadcastId); - } - - @Test - @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) - public void periodicAdvertisingCallbackOnBigInfoAdvertisingReport_updateRssi() { - PeriodicAdvertisingCallback cb = mBassClientStateMachine.mLocalPeriodicAdvCallback; - BassClientService.Callbacks callbacks = Mockito.mock(BassClientService.Callbacks.class); - int testRssi = -40; - int syncHandle = 1; - final String testMacAddress = "00:11:22:33:44:55"; - BluetoothDevice testDevice = - mAdapter.getRemoteLeDevice(testMacAddress, BluetoothDevice.ADDRESS_TYPE_RANDOM); - - byte[] scanRecordWithBaseData = - new byte[] { - (byte) 0x02, - (byte) 0x01, - (byte) 0x1a, // advertising flags - (byte) 0x05, - (byte) 0x02, - (byte) 0x51, - (byte) 0x18, - (byte) 0x0a, - (byte) 0x11, // 16 bit service uuids - (byte) 0x04, - (byte) 0x09, - (byte) 0x50, - (byte) 0x65, - (byte) 0x64, // name - (byte) 0x02, - (byte) 0x0A, - (byte) 0xec, // tx power level - (byte) 0x19, - (byte) 0x16, - (byte) 0x51, - (byte) 0x18, // service data (base data with 18 bytes) - // LEVEL 1 - (byte) 0x01, - (byte) 0x02, - (byte) 0x03, // presentationDelay - (byte) 0x01, // numSubGroups - // LEVEL 2 - (byte) 0x01, // numSubGroups - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, - (byte) 0x00, // UNKNOWN_CODEC - (byte) 0x02, // codecConfigLength - (byte) 0x01, - (byte) 'A', // codecConfigInfo - (byte) 0x03, // metaDataLength - (byte) 0x06, - (byte) 0x07, - (byte) 0x08, // metaData - // LEVEL 3 - (byte) 0x04, // index - (byte) 0x03, // codecConfigLength - (byte) 0x02, - (byte) 'B', - (byte) 'C', // codecConfigInfo - (byte) 0x05, - (byte) 0xff, - (byte) 0xe0, - (byte) 0x00, - (byte) 0x02, - (byte) 0x15, // manufacturer specific data - (byte) 0x03, - (byte) 0x50, - (byte) 0x01, - (byte) 0x02, // an unknown data type won't cause trouble - }; - - ScanRecord record = ScanRecord.parseFromBytes(scanRecordWithBaseData); - ScanResult scanResult = - new ScanResult( - mAdapter.getRemoteLeDevice( - "00:11:22:33:44:55", BluetoothDevice.ADDRESS_TYPE_RANDOM), - 0, - 0, - 0, - 0, - 0, - testRssi, - 0, - record, - 0); - BaseData data = - BaseData.parseBaseData(record.getServiceData(BassConstants.BASIC_AUDIO_UUID)); - - when(mBassClientService.getDeviceForSyncHandle(syncHandle)).thenReturn(testDevice); - PeriodicAdvertisementResult paResult = Mockito.mock(PeriodicAdvertisementResult.class); - when(mBassClientService.getPeriodicAdvertisementResult(any(), anyInt())) - .thenReturn(paResult); - when(paResult.isNotified()).thenReturn(false); - when(mBassClientService.getBase(anyInt())).thenReturn(data); - when(mBassClientService.getCachedBroadcast(anyInt())).thenReturn(scanResult); - when(mBassClientService.getCallbacks()).thenReturn(callbacks); - - cb.onBigInfoAdvertisingReport(syncHandle, true); - ArgumentCaptor<BluetoothLeBroadcastMetadata> metaData = - ArgumentCaptor.forClass(BluetoothLeBroadcastMetadata.class); - verify(callbacks).notifySourceFound(metaData.capture()); - - assertThat(metaData.getValue().getRssi()).isEqualTo(testRssi); - } - - @Test public void cancelPendingAddBcastSourceMessage_inConnectedState() { initToConnectedState(); @@ -2924,7 +2310,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void receiveSinkReceiveStateChange_logSyncMetricsWhenSyncNoPast() { prepareInitialReceiveStateForGatt(); @@ -2947,7 +2332,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void receiveSinkReceiveStateChange_logSyncMetricsWhenBigEncryptFailed() { prepareInitialReceiveStateForGatt(); @@ -2970,7 +2354,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void receiveSinkReceiveStateChange_logSyncMetricsWhenAudioSyncFailed() { prepareInitialReceiveStateForGatt(); @@ -2993,7 +2376,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void receiveSinkReceiveStateChange_logSyncMetricsWhenSourceRemoved() { prepareInitialReceiveStateForGatt(); @@ -3030,7 +2412,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void sinkDisconnected_logSyncMetricsWhenSourceRemoved() { prepareInitialReceiveStateForGatt(); @@ -3059,10 +2440,7 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags({ - Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER, - Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE - }) + @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER) public void sinkConnected_queueAddingSourceForReceiveStateReady() { mBassClientStateMachine.connectGatt(true); BluetoothGattCallback cb = mBassClientStateMachine.mGattCallback; @@ -3093,7 +2471,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void updateBroadcastSource_withoutMetadata() { int sourceId = 1; int paSync = BassConstants.PA_SYNC_DO_NOT_SYNC; @@ -3127,7 +2504,6 @@ public class BassClientStateMachineTest { } @Test - @EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_EXTRACT_PERIODIC_SCANNER_FROM_STATE_MACHINE) public void updateBroadcastSource_pendingSourceToRemove() { prepareInitialReceiveStateForGatt(); @@ -3257,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); } @@ -3280,7 +2656,7 @@ public class BassClientStateMachineTest { Mockito.clearInvocations(mBassClientService); } - private boolean isConnectionIntentExpected(Class currentType, Class nextType) { + private static boolean isConnectionIntentExpected(Class currentType, Class nextType) { if (currentType == nextType) { return false; // Same state, no intent expected } @@ -3349,7 +2725,8 @@ public class BassClientStateMachineTest { return builder.build(); } - private byte[] convertMetadataToUpdateSourceByteArray(BluetoothLeBroadcastMetadata metaData) { + private static byte[] convertMetadataToUpdateSourceByteArray( + BluetoothLeBroadcastMetadata metaData) { int numSubGroups = metaData.getSubgroups().size(); byte[] res = new byte[UPDATE_SOURCE_FIXED_LENGTH + numSubGroups * 5]; @@ -3388,7 +2765,7 @@ public class BassClientStateMachineTest { return res; } - private BluetoothLeBroadcastMetadata getMetadataToPauseStream( + private static BluetoothLeBroadcastMetadata getMetadataToPauseStream( BluetoothLeBroadcastMetadata metadata) { BluetoothLeBroadcastMetadata.Builder metadataToUpdateBuilder = new BluetoothLeBroadcastMetadata.Builder(metadata); @@ -3545,7 +2922,7 @@ public class BassClientStateMachineTest { .isEqualTo(Bytes.concat(metadataHeader, metadataPayload)); } - private BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { + private static BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { final long testAudioLocationFrontLeft = 0x01; final long testAudioLocationFrontRight = 0x02; // For BluetoothLeAudioContentMetadata diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java index ff5324e4b0..e86952a165 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PeriodicAdvertisementResultTest.java @@ -138,7 +138,7 @@ public class PeriodicAdvertisementResultTest { } /** Helper to generate test data for public broadcast. */ - private PublicBroadcastData generatePublicBroadcastData() { + private static PublicBroadcastData generatePublicBroadcastData() { PublicBroadcastData.PublicBroadcastInfo info = new PublicBroadcastData.PublicBroadcastInfo(); info.isEncrypted = true; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java index ec629ddf46..a2b57f9792 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,9 @@ package com.android.bluetooth.btservice; +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; @@ -42,6 +45,7 @@ import android.bluetooth.BluetoothLeBroadcastMetadata; import android.bluetooth.BluetoothProfile; import android.bluetooth.BluetoothSinkAudioPolicy; import android.content.Context; +import android.media.AudioDeviceInfo; import android.media.AudioManager; import android.platform.test.annotations.DisableFlags; import android.platform.test.annotations.EnableFlags; @@ -1714,44 +1718,39 @@ public class ActiveDeviceManagerTest { verify(mHearingAidService).removeActiveDevice(false); } - // TODO: b/393810023 - re-enable when AudioDeviceInfo can be mocked - // /** A wired audio device is disconnected. Check if falls back to connected A2DP. */ - // @Test - // @DisableFlags(Flags.FLAG_ADM_REMOVE_HANDLING_WIRED) - // public void wiredAudioDeviceDisconnected_setFallbackDevice() throws Exception { - // AudioDevicePort a2dpPort = mock(AudioDevicePort.class); - // doReturn(AudioDeviceInfo.TYPE_BLUETOOTH_A2DP).when(a2dpPort).type(); - // doReturn("a2dp").when(a2dpPort).name(); + /** A wired audio device is disconnected. Check if falls back to connected A2DP. */ + @Test + @DisableFlags(Flags.FLAG_ADM_REMOVE_HANDLING_WIRED) + public void wiredAudioDeviceDisconnected_setFallbackDevice() throws Exception { + AudioDeviceInfo a2dpDevice = mock(AudioDeviceInfo.class); + doReturn(AudioDeviceInfo.TYPE_BLUETOOTH_A2DP).when(a2dpDevice).getType(); - // AudioDevicePort usbPort = mock(AudioDevicePort.class); - // doReturn(AudioDeviceInfo.TYPE_USB_HEADSET).when(usbPort).type(); - // doReturn("usb").when(usbPort).name(); + AudioDeviceInfo usbDevice = mock(AudioDeviceInfo.class); + doReturn(AudioDeviceInfo.TYPE_USB_HEADSET).when(usbDevice).getType(); - // AudioDeviceInfo a2dpDevice = new AudioDeviceInfo(a2dpPort); - // AudioDeviceInfo usbDevice = new AudioDeviceInfo(usbPort); - // return new AudioDeviceInfo[] {a2dpDevice, usbDevice}; + AudioDeviceInfo[] testDevices = new AudioDeviceInfo[] {a2dpDevice, usbDevice}; - // // Connect A2DP headphones - // a2dpConnected(mA2dpDevice, false); - // mTestLooper.dispatchAll(); - // verify(mA2dpService).setActiveDevice(mA2dpDevice); - // verify(mLeAudioService).removeActiveDevice(true); + // Connect A2DP headphones + a2dpConnected(mA2dpDevice, false); + mTestLooper.dispatchAll(); + verify(mA2dpService).setActiveDevice(mA2dpDevice); + verify(mLeAudioService).removeActiveDevice(true); - // // Connect wired audio device - // mActiveDeviceManager.mAudioManagerAudioDeviceCallback.onAudioDevicesAdded(testDevices); + // Connect wired audio device + mActiveDeviceManager.mAudioManagerAudioDeviceCallback.onAudioDevicesAdded(testDevices); - // // Check wiredAudioDeviceConnected invoked properly - // verify(mA2dpService).removeActiveDevice(false); - // verify(mHeadsetService).setActiveDevice(isNull()); - // verify(mHearingAidService).removeActiveDevice(false); - // verify(mLeAudioService, times(2)).removeActiveDevice(true); + // Check wiredAudioDeviceConnected invoked properly + verify(mA2dpService).removeActiveDevice(false); + verify(mHeadsetService).setActiveDevice(isNull()); + verify(mHearingAidService).removeActiveDevice(false); + verify(mLeAudioService, times(2)).removeActiveDevice(true); - // // Disconnect wired audio device - // mActiveDeviceManager.mAudioManagerAudioDeviceCallback.onAudioDevicesRemoved(testDevices); + // Disconnect wired audio device + mActiveDeviceManager.mAudioManagerAudioDeviceCallback.onAudioDevicesRemoved(testDevices); - // // Verify fallback to A2DP device - // verify(mA2dpService, times(2)).setActiveDevice(mA2dpDevice); - // } + // Verify fallback to A2DP device + verify(mA2dpService, times(2)).setActiveDevice(mA2dpDevice); + } /** * Verifies if Le Audio Broadcast is streaming, connected a2dp device should not be set as @@ -1841,10 +1840,7 @@ public class ActiveDeviceManagerTest { 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. */ @@ -1856,10 +1852,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. */ @@ -1884,10 +1877,7 @@ public class ActiveDeviceManagerTest { 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. */ @@ -1899,10 +1889,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. */ @@ -1920,10 +1907,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. */ @@ -1935,10 +1919,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. */ @@ -1955,10 +1936,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. */ @@ -1970,10 +1948,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. */ @@ -1991,10 +1966,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. */ @@ -2006,10 +1978,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 { diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterPropertiesTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterPropertiesTest.java index 93f3f5f824..3e6180f336 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterPropertiesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterPropertiesTest.java @@ -84,7 +84,6 @@ public class AdapterPropertiesTest { when(mNativeInterface.removeBond(any(byte[].class))).thenReturn(true); mRemoteDevices = new RemoteDevices(mAdapterService, mHandlerThread.getLooper()); - verify(mAdapterService).getSystemService(Context.BLUETOOTH_SERVICE); verify(mAdapterService).getSystemService(BluetoothManager.class); mRemoteDevices.reset(); 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 854317fb06..e1f27b55ea 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,8 @@ 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.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -66,7 +68,6 @@ import android.platform.test.annotations.EnableFlags; import android.platform.test.flag.junit.FlagsParameterization; import android.platform.test.flag.junit.SetFlagsRule; import android.provider.Settings; -import android.sysprop.BluetoothProperties; import android.test.mock.MockContentProvider; import android.test.mock.MockContentResolver; import android.util.Log; @@ -102,9 +103,6 @@ import platform.test.runner.parameterized.Parameters; import java.io.FileDescriptor; import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.List; @@ -117,6 +115,7 @@ import javax.crypto.spec.SecretKeySpec; @RunWith(ParameterizedAndroidJunit4.class) public class AdapterServiceTest { private static final String TAG = AdapterServiceTest.class.getSimpleName(); + private static final String TEST_BT_ADDR_1 = "00:11:22:33:44:55"; private static final String TEST_BT_ADDR_2 = "00:11:22:33:44:66"; @@ -288,12 +287,7 @@ public class AdapterServiceTest { doReturn(false).when(dpm).isCommonCriteriaModeEnabled(any()); mockGetSystemService(Context.USER_SERVICE, UserManager.class); - // BatteryStatsManager is final and cannot be mocked with regular mockito, so just return - // real implementation - mockGetSystemService( - Context.BATTERY_STATS_SERVICE, - BatteryStatsManager.class, - targetContext.getSystemService(BatteryStatsManager.class)); + mockGetSystemService(Context.BATTERY_STATS_SERVICE, BatteryStatsManager.class); mockGetSystemService(Context.BLUETOOTH_SERVICE, BluetoothManager.class, mBluetoothManager); mockGetSystemService( Context.COMPANION_DEVICE_SERVICE, @@ -896,55 +890,6 @@ public class AdapterServiceTest { assertThat(mLooper.nextMessage()).isNull(); } - /** Test: Toggle snoop logging setting Check whether the AdapterService restarts fully */ - @Test - public void testSnoopLoggingChange() { - BluetoothProperties.snoop_log_mode_values snoopSetting = - BluetoothProperties.snoop_log_mode() - .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY); - BluetoothProperties.snoop_log_mode(BluetoothProperties.snoop_log_mode_values.DISABLED); - doEnable(false); - - assertThat( - BluetoothProperties.snoop_log_mode() - .orElse(BluetoothProperties.snoop_log_mode_values.EMPTY)) - .isNotEqualTo(BluetoothProperties.snoop_log_mode_values.FULL); - - BluetoothProperties.snoop_log_mode(BluetoothProperties.snoop_log_mode_values.FULL); - - onToBleOn( - mLooper, - mAdapterService, - mMockContext, - mIBluetoothCallback, - false, - listOfMockServices()); - - // Do not call bleOnToOff(). The Adapter should turn itself off. - syncHandler(AdapterState.BLE_TURN_OFF); - verifyStateChange(STATE_BLE_ON, STATE_BLE_TURNING_OFF, CONTEXT_SWITCH_MS); - - if (!Flags.scanManagerRefactor()) { - syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); // stop GATT - syncHandler(MESSAGE_PROFILE_SERVICE_UNREGISTERED); - } - - verify(mNativeInterface).disable(); - - mAdapterService.stateChangeCallback(AbstractionLayer.BT_STATE_OFF); - syncHandler(AdapterState.BLE_STOPPED); - // When reaching the OFF state, the cleanup is called that will destroy the state machine of - // the adapterService. Destroying state machine send a -1 event on the handler - syncHandler(-1); - - verifyStateChange(STATE_BLE_TURNING_OFF, STATE_OFF); - assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF); - - // Restore earlier setting - BluetoothProperties.snoop_log_mode(snoopSetting); - assertThat(mLooper.nextMessage()).isNull(); - } - /** * Test: Obfuscate a null Bluetooth Check if returned value from {@link * AdapterService#obfuscateAddress(BluetoothDevice)} is an empty array when device address is @@ -1081,44 +1026,6 @@ public class AdapterServiceTest { assertThat(mLooper.nextMessage()).isNull(); } - @Test - @EnableFlags(Flags.FLAG_GATT_CLEAR_CACHE_ON_FACTORY_RESET) - public void testClearStorage() throws Exception { - // clearStorage should remove all files under /data/misc/bluetooth/ && /data/misc/bluedroid/ - final Path testCachePath = Paths.get("/data/misc/bluetooth/gatt_cache_a475b9a23d72"); - final Path testHashPath = - Paths.get("/data/misc/bluetooth/gatt_hash_400D017CB2563A6FB62A2DC4C2AEFD6F"); - final Path randomFileUnderBluedroidPath = - Paths.get("/data/misc/bluedroid/random_test_file.txt"); - final Path randomFileUnderBluetoothPath = - Paths.get("/data/misc/bluetooth/random_test_file.txt"); - - try { - Files.createFile(testCachePath); - Files.createFile(testHashPath); - Files.createFile(randomFileUnderBluedroidPath); - Files.createFile(randomFileUnderBluetoothPath); - - assertThat(Files.exists(testCachePath)).isTrue(); - assertThat(Files.exists(testHashPath)).isTrue(); - assertThat(Files.exists(randomFileUnderBluedroidPath)).isTrue(); - assertThat(Files.exists(randomFileUnderBluetoothPath)).isTrue(); - - mAdapterService.clearStorage(); - - assertThat(Files.exists(testCachePath)).isFalse(); - assertThat(Files.exists(testHashPath)).isFalse(); - assertThat(Files.exists(randomFileUnderBluedroidPath)).isFalse(); - assertThat(Files.exists(randomFileUnderBluetoothPath)).isFalse(); - } finally { - Files.deleteIfExists(testCachePath); - Files.deleteIfExists(testHashPath); - Files.deleteIfExists(randomFileUnderBluedroidPath); - Files.deleteIfExists(randomFileUnderBluetoothPath); - } - assertThat(mLooper.nextMessage()).isNull(); - } - InOrder prepareLeAudioWithConnectedDevices( List<BluetoothDevice> devices, int groupId, @@ -1148,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; @@ -1170,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; @@ -1192,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; @@ -1219,7 +1126,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; @@ -1247,7 +1154,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( @@ -1274,7 +1181,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; @@ -1306,7 +1213,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; @@ -1354,7 +1261,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; @@ -1403,7 +1310,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/DataMigrationTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java index b7d10c518b..ce49c79d12 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java @@ -64,7 +64,7 @@ import java.util.List; @SmallTest @RunWith(AndroidJUnit4.class) public class DataMigrationTest { - private static final String TAG = "DataMigrationTest"; + private static final String TAG = DataMigrationTest.class.getSimpleName(); private static final String AUTHORITY = "bluetooth_legacy.provider"; diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java index 6c5586a6d0..dd7d46d661 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ProfileServiceTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.btservice; +import static android.Manifest.permission.MEDIA_CONTENT_CONTROL; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.google.common.truth.Truth.assertThat; @@ -45,6 +47,7 @@ import com.android.bluetooth.hfp.HeadsetNativeInterface; import com.android.bluetooth.hfpclient.NativeInterface; import com.android.bluetooth.hid.HidHostNativeInterface; import com.android.bluetooth.le_audio.LeAudioNativeInterface; +import com.android.bluetooth.sdp.SdpManagerNativeInterface; import org.junit.After; import org.junit.Before; @@ -84,6 +87,7 @@ public class ProfileServiceTest { @Mock private HeadsetNativeInterface mHeadsetNativeInterface; @Mock private NativeInterface mHeadsetClientNativeInterface; @Mock private HearingAidNativeInterface mHearingAidNativeInterface; + @Mock private SdpManagerNativeInterface mSdpManagerNativeInterface; @Mock private HidHostNativeInterface mHidHostNativeInterface; @Mock private LeAudioNativeInterface mLeAudioInterface; @@ -122,6 +126,9 @@ public class ProfileServiceTest { @Before public void setUp() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .adoptShellPermissionIdentity(MEDIA_CONTENT_CONTROL); if (Looper.myLooper() == null) { Looper.prepare(); } @@ -162,6 +169,7 @@ public class ProfileServiceTest { HeadsetNativeInterface.setInstance(mHeadsetNativeInterface); /* HeadsetClient */ NativeInterface.setInstance(mHeadsetClientNativeInterface); HearingAidNativeInterface.setInstance(mHearingAidNativeInterface); + SdpManagerNativeInterface.setInstance(mSdpManagerNativeInterface); HidHostNativeInterface.setInstance(mHidHostNativeInterface); LeAudioNativeInterface.setInstance(mLeAudioInterface); } @@ -178,8 +186,12 @@ public class ProfileServiceTest { HeadsetNativeInterface.setInstance(null); /* HeadsetClient */ NativeInterface.setInstance(null); HearingAidNativeInterface.setInstance(null); + SdpManagerNativeInterface.setInstance(null); HidHostNativeInterface.setInstance(null); LeAudioNativeInterface.setInstance(null); + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .dropShellPermissionIdentity(); } /** 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 c94ae6ab2b..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 = @@ -82,7 +94,6 @@ public class RemoteDevicesTest { mBluetoothManager); mRemoteDevices = new RemoteDevices(mAdapterService, mHandlerThread.getLooper()); - verify(mAdapterService).getSystemService(Context.BLUETOOTH_SERVICE); verify(mAdapterService).getSystemService(BluetoothManager.class); } @@ -267,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( @@ -316,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()) @@ -582,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)) @@ -633,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()) @@ -847,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(); @@ -859,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/bluetoothKeystore/BluetoothKeystoreServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java index 9ddb69c4f1..30374d57ae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java @@ -44,7 +44,8 @@ import java.util.Map; @RunWith(JUnit4.class) public final class BluetoothKeystoreServiceTest { - private static final String TAG = "BluetoothKeystoreServiceTest"; + private static final String TAG = BluetoothKeystoreServiceTest.class.getSimpleName(); + private BluetoothKeystoreService mBluetoothKeystoreService; @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @@ -126,11 +127,11 @@ public final class BluetoothKeystoreServiceTest { mBluetoothKeystoreService = null; } - private boolean isPrimaryUser() { + private static boolean isPrimaryUser() { return Binder.getCallingUid() == Process.BLUETOOTH_UID; } - private void overwriteConfigFile(List<String> data) { + private static void overwriteConfigFile(List<String> data) { try { Files.write(Paths.get(CONFIG_FILE_PATH), data); } catch (IOException e) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java index 6ea19c5477..6d3f8845ee 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,8 @@ package com.android.bluetooth.csip; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java index ba9de2c181..ac64b097ae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorServiceTest.java @@ -443,7 +443,7 @@ public class CsipSetCoordinatorServiceTest { } /** Helper function to get byte array for a device address */ - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { return Utils.getBytesFromAddress(device.getAddress()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java index 48eb568b8c..4c9cd6fb5e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachineTest.java @@ -36,7 +36,6 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Intent; import android.os.HandlerThread; -import android.os.Looper; import android.os.Message; import androidx.test.filters.MediumTest; @@ -55,34 +54,29 @@ import org.mockito.Mockito; @MediumTest @RunWith(AndroidJUnit4.class) public class CsipSetCoordinatorStateMachineTest { - private final String mFlagDexmarker = System.getProperty("dexmaker.share_classloader", "false"); - - private final BluetoothDevice mDevice = getTestDevice(89); - private HandlerThread mHandlerThread; - private CsipSetCoordinatorStateMachineWrapper mStateMachine; - private static final int TIMEOUT_MS = 1000; - @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private AdapterService mAdapterService; @Mock private CsipSetCoordinatorService mService; @Mock private CsipSetCoordinatorNativeInterface mNativeInterface; + private static final int TIMEOUT_MS = 1000; + + private final BluetoothDevice mDevice = getTestDevice(89); + + private HandlerThread mHandlerThread; + private CsipSetCoordinatorStateMachine mStateMachine; + @Before public void setUp() throws Exception { - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", "true"); - } - TestUtils.setAdapterService(mAdapterService); - // Set up thread and looper mHandlerThread = new HandlerThread("CsipSetCoordinatorServiceTestHandlerThread"); mHandlerThread.start(); mStateMachine = spy( - new CsipSetCoordinatorStateMachineWrapper( + new CsipSetCoordinatorStateMachine( mDevice, mService, mNativeInterface, mHandlerThread.getLooper())); // Override the timeout value to speed up the test @@ -92,9 +86,6 @@ public class CsipSetCoordinatorStateMachineTest { @After public void tearDown() throws Exception { - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", mFlagDexmarker); - } mStateMachine.doQuit(); mHandlerThread.quit(); TestUtils.clearAdapterService(mAdapterService); @@ -526,7 +517,10 @@ public class CsipSetCoordinatorStateMachineTest { Message msg = mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.CONNECT); mStateMachine.sendMessage(msg); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mStateMachine).deferMessage(msg); + assertThat( + mStateMachine.doesSuperHaveDeferredMessages( + CsipSetCoordinatorStateMachine.CONNECT)) + .isTrue(); } @Test @@ -542,7 +536,10 @@ public class CsipSetCoordinatorStateMachineTest { Message msg = mStateMachine.obtainMessage(CsipSetCoordinatorStateMachine.DISCONNECT); mStateMachine.sendMessage(msg); TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper()); - verify(mStateMachine).deferMessage(msg); + assertThat( + mStateMachine.doesSuperHaveDeferredMessages( + CsipSetCoordinatorStateMachine.DISCONNECT)) + .isTrue(); } @Test @@ -682,20 +679,4 @@ public class CsipSetCoordinatorStateMachineTest { verify(mService, timeout(TIMEOUT_MS)).sendBroadcast(any(Intent.class), anyString()); assertThat(mStateMachine.getCurrentState()).isInstanceOf(type); } - - public static class CsipSetCoordinatorStateMachineWrapper - extends CsipSetCoordinatorStateMachine { - - CsipSetCoordinatorStateMachineWrapper( - BluetoothDevice device, - CsipSetCoordinatorService svc, - CsipSetCoordinatorNativeInterface nativeInterface, - Looper looper) { - super(device, svc, nativeInterface, looper); - } - - public boolean doesSuperHaveDeferredMessages(int what) { - return super.hasDeferredMessages(what); - } - } } 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/HapClientNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java index 85ba8fdb4e..a67995ffae 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java @@ -16,12 +16,13 @@ package com.android.bluetooth.hap; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothHapPresetInfo; -import android.bluetooth.BluetoothProfile; import com.android.bluetooth.btservice.AdapterService; @@ -51,7 +52,7 @@ public class HapClientNativeCallbackTest { @Test public void onConnectionStateChanged() { - int state = BluetoothProfile.STATE_CONNECTED; + int state = STATE_CONNECTED; mNativeCallback.onConnectionStateChanged(state, null); verify(mHapClientService).messageFromNative(mEvent.capture()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java index 86923a6ca6..272e2e0b45 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java @@ -710,7 +710,7 @@ public class HapClientServiceTest { } /** Helper function to get byte array for a device address */ - private byte[] getByteAddress(BluetoothDevice device) { + private static byte[] getByteAddress(BluetoothDevice device) { if (device == null) { return Utils.getBytesFromAddress("00:00:00:00:00:00"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java index 0dff31a1c0..ac7c90a213 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.hearingaid; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -27,7 +29,6 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import com.android.bluetooth.Utils; @@ -73,19 +74,19 @@ public class HearingAidNativeInterfaceTest { public void onConnectionStateChanged() { BluetoothDevice device = getTestDevice(0); mNativeInterface.onConnectionStateChanged( - BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); + STATE_CONNECTED, mNativeInterface.getByteAddress(device)); ArgumentCaptor<HearingAidStackEvent> event = ArgumentCaptor.forClass(HearingAidStackEvent.class); verify(mService).messageFromNative(event.capture()); assertThat(event.getValue().type) .isEqualTo(HearingAidStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED); - assertThat(event.getValue().valueInt1).isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(event.getValue().valueInt1).isEqualTo(STATE_CONNECTED); Mockito.clearInvocations(mService); HearingAidService.setHearingAidService(null); mNativeInterface.onConnectionStateChanged( - BluetoothProfile.STATE_CONNECTED, mNativeInterface.getByteAddress(device)); + STATE_CONNECTED, mNativeInterface.getByteAddress(device)); verify(mService, never()).messageFromNative(any()); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java index 9126577e39..dc6345b039 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java @@ -29,9 +29,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import android.app.admin.DevicePolicyManager; import android.bluetooth.BluetoothDevice; import android.content.Context; import android.database.Cursor; +import android.net.Uri; +import android.os.UserManager; import android.provider.CallLog; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.telephony.PhoneNumberUtils; @@ -41,7 +44,6 @@ import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.BluetoothMethodProxy; import com.android.bluetooth.R; -import com.android.bluetooth.TestUtils; import com.android.bluetooth.btservice.AdapterService; import com.android.bluetooth.util.DevicePolicyUtils; import com.android.bluetooth.util.GsmAlphabet; @@ -56,31 +58,40 @@ import org.mockito.Spy; @RunWith(AndroidJUnit4.class) public class AtPhonebookTest { - private static final String INVALID_COMMAND = "invalid_command"; - private Context mTargetContext; - private BluetoothDevice mDevice = getTestDevice(198); - @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private AdapterService mAdapterService; @Mock private HeadsetNativeInterface mNativeInterface; - private AtPhonebook mAtPhonebook; @Spy private BluetoothMethodProxy mHfpMethodProxy = BluetoothMethodProxy.getInstance(); + private static final String INVALID_COMMAND = "invalid_command"; + + private final Context mTargetContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + private final BluetoothDevice mDevice = getTestDevice(198); + + private AtPhonebook mAtPhonebook; + @Before public void setUp() throws Exception { - mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); - TestUtils.setAdapterService(mAdapterService); + doReturn(mTargetContext.getSystemService(UserManager.class)) + .when(mAdapterService) + .getSystemService(UserManager.class); + doReturn(mTargetContext.getSystemService(DevicePolicyManager.class)) + .when(mAdapterService) + .getSystemService(DevicePolicyManager.class); + doReturn(mTargetContext.getContentResolver()).when(mAdapterService).getContentResolver(); + doReturn(mTargetContext.getString(R.string.unknownNumber)) + .when(mAdapterService) + .getString(R.string.unknownNumber); BluetoothMethodProxy.setInstanceForTesting(mHfpMethodProxy); - // Spy on native interface - mAtPhonebook = new AtPhonebook(mTargetContext, mNativeInterface); + mAtPhonebook = new AtPhonebook(mAdapterService, mNativeInterface); } @After public void tearDown() throws Exception { - TestUtils.clearAdapterService(mAdapterService); BluetoothMethodProxy.setInstanceForTesting(null); } @@ -339,6 +350,8 @@ public class AtPhonebookTest { public void processCpbrCommand_doesNotCrashWithEncodingNeededNumber() { final String encodingNeededNumber = "###0102124"; + Uri uri = DevicePolicyUtils.getEnterprisePhoneUri(mAdapterService); + Cursor mockCursorOne = mock(Cursor.class); when(mockCursorOne.getCount()).thenReturn(1); when(mockCursorOne.getColumnIndex(Phone.TYPE)).thenReturn(1); // TypeColumn @@ -349,12 +362,7 @@ public class AtPhonebookTest { when(mockCursorOne.moveToNext()).thenReturn(false); doReturn(mockCursorOne) .when(mHfpMethodProxy) - .contentResolverQuery( - any(), - eq(DevicePolicyUtils.getEnterprisePhoneUri(mTargetContext)), - any(), - any(), - any()); + .contentResolverQuery(any(), eq(uri), any(), any(), any()); mAtPhonebook.mCurrentPhonebook = "ME"; mAtPhonebook.mCpbrIndex1 = 1; 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..a0bcdb5e25 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,6 +16,8 @@ package com.android.bluetooth.hfp; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); } 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 4e38f9e714..2411f21f75 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,10 @@ package com.android.bluetooth.hfp; +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; @@ -86,6 +90,8 @@ import java.util.Set; @MediumTest @RunWith(AndroidJUnit4.class) public class HeadsetServiceAndStateMachineTest { + private static final String TAG = HeadsetServiceAndStateMachineTest.class.getSimpleName(); + @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @@ -105,7 +111,6 @@ public class HeadsetServiceAndStateMachineTest { @Mock private RemoteDevices mRemoteDevices; @Mock private SystemProperties.MockableSystemProperties mProperties; - private static final String TAG = HeadsetServiceAndStateMachineTest.class.getSimpleName(); private static final int MAX_HEADSET_CONNECTIONS = 5; private static final ParcelUuid[] FAKE_HEADSET_UUID = {BluetoothUuid.HFP}; private static final String TEST_PHONE_NUMBER = "1234567890"; @@ -126,6 +131,7 @@ public class HeadsetServiceAndStateMachineTest { doReturn(mTargetContext.getPackageName()).when(mAdapterService).getPackageName(); doReturn(mTargetContext.getPackageManager()).when(mAdapterService).getPackageManager(); doReturn(mTargetContext.getResources()).when(mAdapterService).getResources(); + doReturn(mTargetContext.getContentResolver()).when(mAdapterService).getContentResolver(); PowerManager powerManager = mTargetContext.getSystemService(PowerManager.class); mVoiceRecognitionWakeLock = @@ -213,8 +219,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); } @@ -240,14 +245,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 = @@ -257,13 +258,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); } @@ -289,8 +286,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 = @@ -300,8 +296,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); @@ -336,8 +331,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( @@ -346,10 +340,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 @@ -365,8 +357,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 = @@ -390,7 +381,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(); @@ -429,7 +420,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(); @@ -473,7 +464,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(); @@ -524,7 +515,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(); @@ -618,7 +609,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(); @@ -1185,7 +1176,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(); @@ -1810,20 +1801,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 = @@ -1835,17 +1817,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..8fb5fb3dc1 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,10 @@ package com.android.bluetooth.hfp; +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 +164,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 +199,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); } @@ -297,14 +299,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 +338,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 +351,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(); } @@ -439,16 +435,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 +461,7 @@ public class HeadsetServiceTest { eq(mNativeInterface), eq(mSystemInterface)); assertThat(mHeadsetService.getConnectionState(mCurrentDevice)) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .isEqualTo(STATE_DISCONNECTED); assertThat(mHeadsetService.getConnectedDevices()) .containsExactlyElementsIn(connectedDevices); } @@ -493,17 +489,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)) @@ -567,26 +559,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 @@ -663,26 +651,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); } @@ -763,28 +747,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); @@ -829,14 +809,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); @@ -903,29 +881,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, @@ -1013,28 +984,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 @@ -1076,10 +1043,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); @@ -1111,7 +1076,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); @@ -1135,7 +1100,7 @@ public class HeadsetServiceTest { 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); } @@ -1174,8 +1139,7 @@ public class HeadsetServiceTest { 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); @@ -1264,15 +1228,12 @@ public class HeadsetServiceTest { 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()) @@ -1307,8 +1268,7 @@ public class HeadsetServiceTest { 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); @@ -1352,14 +1312,10 @@ public class HeadsetServiceTest { .thenReturn(BluetoothProfile.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 +1346,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 3f205cbc88..26c30642a8 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 @@ -17,6 +17,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.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; @@ -68,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; @@ -118,8 +125,9 @@ public class HeadsetStateMachineTest { @Before public void setUp() throws Exception { - // Setup mocks and test assets - TestUtils.setAdapterService(mAdapterService); + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .adoptShellPermissionIdentity(READ_PRIVILEGED_PHONE_STATE); // Stub system interface doReturn(mPhoneState).when(mSystemInterface).getHeadsetPhoneState(); doReturn(mAudioManager).when(mSystemInterface).getAudioManager(); @@ -174,14 +182,16 @@ public class HeadsetStateMachineTest { public void tearDown() throws Exception { HeadsetObjectsFactory.getInstance().destroyStateMachine(mHeadsetStateMachine); mHandlerThread.quit(); - TestUtils.clearAdapterService(mAdapterService); + Uninterruptibles.joinUninterruptibly(mHandlerThread); + InstrumentationRegistry.getInstrumentation() + .getUiAutomation() + .dropShellPermissionIdentity(); } /** 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); } @@ -190,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); } @@ -207,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); } @@ -233,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); } @@ -259,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); } @@ -304,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); } @@ -325,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); } @@ -382,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); } @@ -412,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); } @@ -435,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); } @@ -465,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); } @@ -487,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); } @@ -517,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); } @@ -547,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); } @@ -735,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); @@ -770,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); @@ -905,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); @@ -937,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); @@ -1088,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); @@ -1123,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); @@ -1534,8 +1507,8 @@ public class HeadsetStateMachineTest { @Test public void testProcessAtClcc_withVirtualCallNotStarted() { - when(mHeadsetService.isVirtualCallStarted()).thenReturn(false); - when(mSystemInterface.listCurrentCalls()).thenReturn(false); + doReturn(false).when(mHeadsetService).isVirtualCallStarted(); + doReturn(false).when(mSystemInterface).listCurrentCalls(any()); mHeadsetStateMachine.processAtClcc(mDevice); @@ -2094,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; @@ -2123,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( @@ -2142,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; @@ -2225,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..bffd93865a 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,6 +16,8 @@ package com.android.bluetooth.hfpclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java index 43659c2422..cf9aaecf49 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java @@ -946,7 +946,7 @@ public class HeadsetClientStateMachineTest { assertThat(currentCalls.get(0)).isEqualTo(call); } - private void assertName(int message, String message_name) { + private static void assertName(int message, String message_name) { assertThat(HeadsetClientStateMachine.getMessageName(message)).isEqualTo(message_name); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java index 6bd0681322..d622a00666 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientCallTest.java @@ -36,7 +36,7 @@ public class HfpClientCallTest { private final BluetoothDevice mDevice = getTestDevice(32); - private void assertCall( + private static void assertCall( BluetoothDevice device, int id, int state, diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java index 7940c63073..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; @@ -24,16 +28,20 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; 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; import android.net.Uri; +import android.os.Bundle; +import android.os.ParcelUuid; +import android.telecom.Connection; +import android.telecom.ConnectionRequest; import android.telecom.PhoneAccount; import android.telecom.PhoneAccountHandle; import android.telecom.TelecomManager; @@ -141,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); @@ -167,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(); } @@ -206,210 +214,203 @@ public class HfpClientConnectionServiceTest { .isEqualTo(HeadsetClientHalConstants.AUDIO_STATE_CONNECTED); } - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateIncomingConnection() throws Exception { - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ false, - // /* inBandRing= */ true); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder().setExtras(extras).build(); - - // HfpClientConnectionService.onCallChanged(mDevice, call); - - // Connection connection = - // mHfpClientConnectionService.onCreateIncomingConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNotNull(); - // assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); - // assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); - // } - - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateOutgoingConnection() throws Exception { - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ true, - // /* inBandRing= */ true); - - // doReturn(call).when(mMockHeadsetClientService).dial(mDevice, TEST_NUMBER); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder() - // .setExtras(extras) - // .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) - // .build(); - - // Connection connection = - // mHfpClientConnectionService.onCreateOutgoingConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNotNull(); - // assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); - // assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); - // } - - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateUnknownConnection() throws Exception { - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ true, - // /* inBandRing= */ true); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder() - // .setExtras(extras) - // .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) - // .build(); - - // HfpClientConnectionService.onCallChanged(mDevice, call); - - // Connection connection = - // mHfpClientConnectionService.onCreateUnknownConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNotNull(); - // assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); - // assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); - // } - - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateIncomingConnection_phoneAccountIsNull_returnsNull() throws Exception { - // doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ false, - // /* inBandRing= */ true); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder().setExtras(extras).build(); - - // HfpClientConnectionService.onCallChanged(mDevice, call); - - // Connection connection = - // mHfpClientConnectionService.onCreateIncomingConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNull(); - // } - - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateOutgoingConnection_phoneAccountIsNull_returnsNull() throws Exception { - // doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ true, - // /* inBandRing= */ true); - - // doReturn(call).when(mMockHeadsetClientService).dial(mDevice, TEST_NUMBER); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder() - // .setExtras(extras) - // .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) - // .build(); - - // Connection connection = - // mHfpClientConnectionService.onCreateOutgoingConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNull(); - // } - - // TODO: b/393810023 - re-enable when ConnectionRequest can be mocked - // @Test - // public void onCreateUnknownConnection_phoneAccountIsNull_returnsNull() throws Exception { - // doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); - // createService(); - // setupDeviceConnection(mDevice); - - // HfpClientCall call = - // new HfpClientCall( - // mDevice, - // /* id= */ 0, - // HfpClientCall.CALL_STATE_ACTIVE, - // /* number= */ TEST_NUMBER, - // /* multiParty= */ false, - // /* outgoing= */ true, - // /* inBandRing= */ true); - - // Bundle extras = new Bundle(); - // extras.putParcelable( - // TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); - // ConnectionRequest connectionRequest = - // new ConnectionRequest.Builder() - // .setExtras(extras) - // .setAddress(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) - // .build(); - - // HfpClientConnectionService.onCallChanged(mDevice, call); - - // Connection connection = - // mHfpClientConnectionService.onCreateUnknownConnection( - // getPhoneAccountHandle(mDevice), connectionRequest); - - // assertThat(connection).isNull(); - // } + @Test + public void onCreateIncomingConnection() throws Exception { + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + + HfpClientConnectionService.onCallChanged(mDevice, call); + + Connection connection = + mHfpClientConnectionService.onCreateIncomingConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).isNotNull(); + assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); + assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); + } + + @Test + public void onCreateOutgoingConnection() throws Exception { + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); + doReturn(call).when(mMockHeadsetClientService).dial(mDevice, TEST_NUMBER); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + doReturn(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .when(connectionRequest) + .getAddress(); + + Connection connection = + mHfpClientConnectionService.onCreateOutgoingConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).isNotNull(); + assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); + assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); + } + + @Test + public void onCreateUnknownConnection() throws Exception { + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + doReturn(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .when(connectionRequest) + .getAddress(); + + HfpClientConnectionService.onCallChanged(mDevice, call); + + Connection connection = + mHfpClientConnectionService.onCreateUnknownConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).isNotNull(); + assertThat(((HfpClientConnection) connection).getDevice()).isEqualTo(mDevice); + assertThat(((HfpClientConnection) connection).getUUID()).isEqualTo(call.getUUID()); + } + + @Test + public void onCreateIncomingConnection_phoneAccountIsNull_returnsNull() throws Exception { + doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ false, + /* inBandRing= */ true); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_INCOMING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + + HfpClientConnectionService.onCallChanged(mDevice, call); + + Connection connection = + mHfpClientConnectionService.onCreateIncomingConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).isNull(); + } + + @Test + public void onCreateOutgoingConnection_phoneAccountIsNull_returnsNull() throws Exception { + doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); + + doReturn(call).when(mMockHeadsetClientService).dial(mDevice, TEST_NUMBER); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + doReturn(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .when(connectionRequest) + .getAddress(); + + Connection connection = + mHfpClientConnectionService.onCreateOutgoingConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).isNull(); + } + + @Test + public void onCreateUnknownConnection_phoneAccountIsNull_returnsNull() throws Exception { + doReturn(null).when(mMockTelecomManager).getPhoneAccount(any()); + createService(); + setupDeviceConnection(mDevice); + + HfpClientCall call = + new HfpClientCall( + mDevice, + /* id= */ 0, + HfpClientCall.CALL_STATE_ACTIVE, + /* number= */ TEST_NUMBER, + /* multiParty= */ false, + /* outgoing= */ true, + /* inBandRing= */ true); + + Bundle extras = new Bundle(); + extras.putParcelable( + TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID())); + ConnectionRequest connectionRequest = mock(ConnectionRequest.class); + doReturn(extras).when(connectionRequest).getExtras(); + doReturn(Uri.fromParts(PhoneAccount.SCHEME_TEL, TEST_NUMBER, null)) + .when(connectionRequest) + .getAddress(); + + HfpClientConnectionService.onCallChanged(mDevice, call); + + Connection connection = + mHfpClientConnectionService.onCreateUnknownConnection( + getPhoneAccountHandle(mDevice), connectionRequest); + + assertThat(connection).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..636fbcb203 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,8 @@ package com.android.bluetooth.hid; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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..7175eab9e9 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,6 +16,8 @@ package com.android.bluetooth.hid; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java index 923a9cb7bc..56006812f5 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,8 @@ package com.android.bluetooth.le_audio; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); @@ -339,7 +341,7 @@ public class LeAudioBinderTest { verify(mService).setCodecConfigPreference(groupId, inputConfig, outputConfig); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata() { + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata() { BluetoothLeAudioContentMetadata metadata = new BluetoothLeAudioContentMetadata.Builder().build(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java index 2321ba477b..c89dd20667 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java @@ -642,7 +642,7 @@ public class LeAudioBroadcastServiceTest { verify(mCallbacks).onBroadcastUpdateFailed(anyInt(), anyInt()); } - private BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { + private static BluetoothLeBroadcastSubgroup createBroadcastSubgroup() { BluetoothLeAudioCodecConfigMetadata codecMetadata = new BluetoothLeAudioCodecConfigMetadata.Builder() .setAudioLocation(TEST_AUDIO_LOCATION_FRONT_LEFT) @@ -1042,92 +1042,7 @@ public class LeAudioBroadcastServiceTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_RECORDING_LISTENER) - public void testInCallDrivenBroadcastSwitch() { - mSetFlagsRule.disableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER); - int groupId = 1; - int broadcastId = 243; - byte[] code = {0x00, 0x01, 0x00, 0x02}; - List<BluetoothDevice> devices = new ArrayList<>(); - - when(mDatabaseManager.getMostRecentlyConnectedDevices()).thenReturn(devices); - - devices.add(mDevice); - prepareHandoverStreamingBroadcast(groupId, broadcastId, code); - - /* Imitate setting device in call */ - mService.setInCall(true); - - assertThat(mService.mBroadcastIdDeactivatedForUnicastTransition.isPresent()).isTrue(); - - /* Check if broadcast is paused by InCall handling */ - verify(mLeAudioBroadcasterNativeInterface).pauseBroadcast(eq(broadcastId)); - - LeAudioStackEvent state_event = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE); - state_event.valueInt1 = broadcastId; - state_event.valueInt2 = LeAudioStackEvent.BROADCAST_STATE_PAUSED; - mService.messageFromNative(state_event); - - verify(mLeAudioNativeInterface).setInCall(eq(true)); - - LeAudioStackEvent create_event = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); - create_event.valueInt1 = groupId; - create_event.valueInt2 = LeAudioStackEvent.GROUP_STATUS_ACTIVE; - mService.messageFromNative(create_event); - - if (Flags.leaudioUseAudioRecordingListener()) { - verify(mAudioManager, times(2)) - .handleBluetoothActiveDeviceChanged( - eq(mDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - } else { - /* Only one Unicast device should become inactive due to Sink monitor mode */ - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(mDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - } - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mBroadcastDevice), any(BluetoothProfileConnectionInfo.class)); - - /* Active group should become the one that was active before broadcasting */ - int activeGroup = mService.getActiveGroupId(); - assertThat(activeGroup).isEqualTo(groupId); - - /* Imitate setting device not in call */ - mService.setInCall(false); - - verify(mLeAudioNativeInterface, times(2)).groupSetActive(eq(LE_AUDIO_GROUP_ID_INVALID)); - - /* Imitate group inactivity to cause start broadcast */ - create_event = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); - create_event.valueInt1 = groupId; - create_event.valueInt2 = LeAudioStackEvent.GROUP_STATUS_INACTIVE; - mService.messageFromNative(create_event); - - if (Flags.leaudioUseAudioRecordingListener()) { - verify(mAudioManager, times(2)) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mDevice), any(BluetoothProfileConnectionInfo.class)); - } else { - /* Only one Unicast device should become active due to Sink monitor mode */ - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mDevice), any(BluetoothProfileConnectionInfo.class)); - } - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(mBroadcastDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - - /* Verify if broadcast triggers transition */ - assertThat(mService.mBroadcastIdDeactivatedForUnicastTransition.isPresent()).isFalse(); - } - - @Test public void testAudioModeDrivenBroadcastSwitch() { - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER); - int groupId = 1; int broadcastId = 243; byte[] code = {0x00, 0x01, 0x00, 0x02}; @@ -1305,93 +1220,7 @@ public class LeAudioBroadcastServiceTest { } @Test - @DisableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_RECORDING_LISTENER) - public void testInCallDrivenBroadcastSwitchDuringInternalPause() { - mSetFlagsRule.disableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER); - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE); - int groupId = 1; - int broadcastId = 243; - byte[] code = {0x00, 0x01, 0x00, 0x02}; - List<BluetoothDevice> devices = new ArrayList<>(); - - when(mDatabaseManager.getMostRecentlyConnectedDevices()).thenReturn(devices); - - devices.add(mDevice); - prepareHandoverStreamingBroadcast(groupId, broadcastId, code); - - /* Internal broadcast paused due to onAudioSuspend */ - LeAudioStackEvent state_event = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE); - state_event.valueInt1 = broadcastId; - state_event.valueInt2 = LeAudioStackEvent.BROADCAST_STATE_PAUSED; - mService.messageFromNative(state_event); - - /* Imitate setting device in call */ - mService.setInCall(true); - - assertThat(mService.mBroadcastIdDeactivatedForUnicastTransition.isPresent()).isTrue(); - - /* Broadcast already paused, not call pause again by InCall handling */ - verify(mLeAudioBroadcasterNativeInterface, never()).pauseBroadcast(eq(broadcastId)); - - verify(mLeAudioNativeInterface).setInCall(eq(true)); - - LeAudioStackEvent create_event = - new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); - create_event.valueInt1 = groupId; - create_event.valueInt2 = LeAudioStackEvent.GROUP_STATUS_ACTIVE; - mService.messageFromNative(create_event); - - if (Flags.leaudioUseAudioRecordingListener()) { - verify(mAudioManager, times(2)) - .handleBluetoothActiveDeviceChanged( - eq(mDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - } else { - /* Only one Unicast device should become inactive due to Sink monitor mode */ - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(mDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - } - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mBroadcastDevice), any(BluetoothProfileConnectionInfo.class)); - - /* Active group should become the one that was active before broadcasting */ - int activeGroup = mService.getActiveGroupId(); - assertThat(activeGroup).isEqualTo(groupId); - - /* Imitate setting device not in call */ - mService.setInCall(false); - - verify(mLeAudioNativeInterface, times(2)).groupSetActive(eq(LE_AUDIO_GROUP_ID_INVALID)); - - /* Imitate group inactivity to cause start broadcast */ - create_event = new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_GROUP_STATUS_CHANGED); - create_event.valueInt1 = groupId; - create_event.valueInt2 = LeAudioStackEvent.GROUP_STATUS_INACTIVE; - mService.messageFromNative(create_event); - - if (Flags.leaudioUseAudioRecordingListener()) { - verify(mAudioManager, times(2)) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mDevice), any(BluetoothProfileConnectionInfo.class)); - } else { - /* Only one Unicast device should become active due to Sink monitor mode */ - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(null), eq(mDevice), any(BluetoothProfileConnectionInfo.class)); - } - verify(mAudioManager) - .handleBluetoothActiveDeviceChanged( - eq(mBroadcastDevice), eq(null), any(BluetoothProfileConnectionInfo.class)); - - /* Verify if broadcast triggers transition */ - assertThat(mService.mBroadcastIdDeactivatedForUnicastTransition.isPresent()).isFalse(); - } - - @Test public void testAudioModeDrivenBroadcastSwitchDuringInternalPause() { - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER); mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE); int groupId = 1; int broadcastId = 243; @@ -1576,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; @@ -1592,7 +1417,6 @@ public class LeAudioBroadcastServiceTest { @Test @DisableFlags(Flags.FLAG_LEAUDIO_BROADCAST_PRIMARY_GROUP_SELECTION) public void testUpdateFallbackInputDevice() { - mSetFlagsRule.disableFlags(Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER); int groupId = 1; int groupId2 = 2; int broadcastId = 243; @@ -1686,8 +1510,7 @@ public class LeAudioBroadcastServiceTest { @Test @EnableFlags({ Flags.FLAG_LEAUDIO_BROADCAST_PRIMARY_GROUP_SELECTION, - Flags.FLAG_LEAUDIO_BROADCAST_API_MANAGE_PRIMARY_GROUP, - Flags.FLAG_LEAUDIO_USE_AUDIO_MODE_LISTENER + Flags.FLAG_LEAUDIO_BROADCAST_API_MANAGE_PRIMARY_GROUP }) public void testManageBroadcastToUnicastFallbackGroup() { int groupId = 1; @@ -1862,7 +1685,7 @@ public class LeAudioBroadcastServiceTest { } } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode, int numOfGroups) { diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java index a8b880b816..0ec418e49a 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 @@ -1286,7 +1286,7 @@ public class LeAudioServiceTest { verify(mTbsService, times(0)).clearInbandRingtoneSupport(mSingleDevice); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode, int numOfGroups) { @@ -2230,9 +2230,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; @@ -3061,8 +3058,6 @@ public class LeAudioServiceTest { /** Test setting allowed contexts for active group */ @Test public void testSetAllowedContextsForActiveGroup() { - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_GETTING_ACTIVE_STATE_SUPPORT); - mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_ALLOWED_CONTEXT_MASK); int groupId = 1; /* AUDIO_DIRECTION_OUTPUT_BIT = 0x01 */ int direction = 1; 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/AppScanStatsTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java index d7dd369ced..dc823ca412 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/AppScanStatsTest.java @@ -28,7 +28,6 @@ import android.os.BatteryStatsManager; import android.os.WorkSource; import androidx.test.filters.SmallTest; -import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.rule.ServiceTestRule; import androidx.test.runner.AndroidJUnit4; @@ -52,20 +51,17 @@ public class AppScanStatsTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private ScannerMap map; + @Mock private BatteryStatsManager mBatteryStatsManager; @Mock private ScanController mMockScanController; @Mock private AdapterService mAdapterService; @Before - public void setUp() throws Exception { - // BatteryStatsManager is final and cannot be mocked with regular mockito, so just return - // real implementation + public void setUp() { TestUtils.mockGetSystemService( mAdapterService, Context.BATTERY_STATS_SERVICE, BatteryStatsManager.class, - InstrumentationRegistry.getInstrumentation() - .getTargetContext() - .getSystemService(BatteryStatsManager.class)); + mBatteryStatsManager); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java index 5e8f59fef5..2beee25a7e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/BatchScanThrottlerTest.java @@ -164,7 +164,8 @@ public class BatchScanThrottlerTest { .isEqualTo(backoffIntervals[backoffIntervals.length - 1]); } - private long adjustExpectedInterval(long interval, boolean isFiltered, boolean isScreenOn) { + private static long adjustExpectedInterval( + long interval, boolean isFiltered, boolean isScreenOn) { if (isFiltered) { return interval; } @@ -175,13 +176,13 @@ public class BatchScanThrottlerTest { return Math.max(interval, threshold); } - private long[] getBackoffIntervals(long baseInterval) { + private static long[] getBackoffIntervals(long baseInterval) { return LongStream.range(0, BatchScanThrottler.BACKOFF_MULTIPLIERS.length) .map(x -> BatchScanThrottler.BACKOFF_MULTIPLIERS[(int) x] * baseInterval) .toArray(); } - private ScanClient createBatchScanClient(long reportDelayMillis, boolean isFiltered) { + private static ScanClient createBatchScanClient(long reportDelayMillis, boolean isFiltered) { ScanSettings scanSettings = new ScanSettings.Builder() .setScanMode(SCAN_MODE_BALANCED) @@ -191,7 +192,7 @@ public class BatchScanThrottlerTest { return new ScanClient(1, scanSettings, createScanFilterList(isFiltered), 1); } - private List<ScanFilter> createScanFilterList(boolean isFiltered) { + private static List<ScanFilter> createScanFilterList(boolean isFiltered) { List<ScanFilter> scanFilterList = null; if (isFiltered) { scanFilterList = List.of(new ScanFilter.Builder().setDeviceName("TestName").build()); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java index 68d37a8e9c..6e396df67e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorTest.java @@ -28,6 +28,7 @@ import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public final class MsftAdvMonitorTest { private static final String TAG = MsftAdvMonitorTest.class.getSimpleName(); + // Hardcoded values taken from CrOS defaults private static final byte RSSI_THRESHOLD_HIGH = (byte) 0xBF; // 191 private static final byte RSSI_THRESHOLD_LOW = (byte) 0xB0; // 176 @@ -43,7 +44,7 @@ public final class MsftAdvMonitorTest { private static final byte[] FAST_PAIR_SERVICE_DATA = new byte[] {(byte) 0xfc, (byte) 0x12, (byte) 0x8e}; - private void assertMonitorConstants(MsftAdvMonitor monitor) { + private static void assertMonitorConstants(MsftAdvMonitor monitor) { MsftAdvMonitor.Monitor mMonitor = monitor.getMonitor(); assertThat(mMonitor.rssi_threshold_high).isEqualTo(RSSI_THRESHOLD_HIGH); assertThat(mMonitor.rssi_threshold_low).isEqualTo(RSSI_THRESHOLD_LOW); diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java index d25f67b2d8..5765b8357e 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java @@ -16,6 +16,9 @@ package com.android.bluetooth.le_scan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -59,6 +62,7 @@ import com.android.bluetooth.btservice.CompanionManager; import com.android.bluetooth.gatt.GattNativeInterface; import com.android.bluetooth.gatt.GattObjectsFactory; +import com.google.protobuf.ByteString; import com.google.testing.junit.testparameterinjector.TestParameter; import com.google.testing.junit.testparameterinjector.TestParameterInjector; @@ -191,7 +195,7 @@ public class ScanControllerTest { new ArgumentMatcher<ScanClient>() { @Override public boolean matches(ScanClient client) { - return mPiInfo.callingUid == client.appUid; + return mPiInfo.callingUid == client.mAppUid; } })); } @@ -210,14 +214,13 @@ public class ScanControllerTest { Set<ScanClient> scanClientSet = new HashSet<>(); ScanClient scanClient = new ScanClient(scannerId); - scanClient.associatedDevices = new ArrayList<>(); - scanClient.scannerId = scannerId; + scanClient.mAssociatedDevices = new ArrayList<>(); if (expectResults) { - scanClient.hasScanWithoutLocationPermission = true; + scanClient.mHasScanWithoutLocationPermission = true; } scanClientSet.add(scanClient); doReturn(scanClientSet).when(mScanManager).getFullBatchScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); IScannerCallback callback = mock(IScannerCallback.class); mApp.mCallback = callback; @@ -245,14 +248,13 @@ public class ScanControllerTest { Set<ScanClient> scanClientSet = new HashSet<>(); ScanClient scanClient = new ScanClient(scannerId); - scanClient.associatedDevices = new ArrayList<>(); + scanClient.mAssociatedDevices = new ArrayList<>(); if (expectResults) { - scanClient.associatedDevices.add("02:00:00:00:00:00"); + scanClient.mAssociatedDevices.add("02:00:00:00:00:00"); } - scanClient.scannerId = scannerId; scanClientSet.add(scanClient); doReturn(scanClientSet).when(mScanManager).getBatchScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); IScannerCallback callback = mock(IScannerCallback.class); mApp.mCallback = callback; @@ -330,9 +332,8 @@ public class ScanControllerTest { byte[] advData = new byte[0]; ScanClient scanClient = new ScanClient(scannerId); - scanClient.scannerId = scannerId; - scanClient.hasNetworkSettingsPermission = true; - scanClient.settings = + scanClient.mHasNetworkSettingsPermission = true; + scanClient.mSettings = new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) .setLegacy(false) @@ -343,13 +344,13 @@ public class ScanControllerTest { mApp.mCallback = callback; mApp.mAppScanStats = appScanStats; - scanClient.stats = appScanStats; + scanClient.mStats = appScanStats; Set<ScanClient> scanClientSet = Collections.singleton(scanClient); doReturn(address).when(mAdapterService).getIdentityAddress(anyString()); doReturn(scanClientSet).when(mScanManager).getRegularScanQueue(); - doReturn(mApp).when(mScannerMap).getById(scanClient.scannerId); - doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scanClient.scannerId); + doReturn(mApp).when(mScannerMap).getById(scanClient.mScannerId); + doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scanClient.mScannerId); // Simulate remote client crash doThrow(new RemoteException()).when(callback).onScanResult(any()); @@ -367,7 +368,7 @@ public class ScanControllerTest { advData, address); - assertThat(scanClient.appDied).isTrue(); + assertThat(scanClient.mAppDied).isTrue(); verify(appScanStats).recordScanStop(scannerId); } @@ -413,23 +414,19 @@ public class ScanControllerTest { @Test public void profileConnectionStateChanged_notifyScanManager() { mScanController.notifyProfileConnectionStateChange( - BluetoothProfile.A2DP, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.A2DP, STATE_CONNECTING, STATE_CONNECTED); verify(mScanManager) .handleBluetoothProfileConnectionStateChanged( - BluetoothProfile.A2DP, - BluetoothProfile.STATE_CONNECTING, - BluetoothProfile.STATE_CONNECTED); + BluetoothProfile.A2DP, STATE_CONNECTING, STATE_CONNECTED); } @Test public void onTrackAdvFoundLost() throws Exception { int scannerId = 1; - int advPktLen = 1; - byte[] advPkt = new byte[] {0x02}; - int scanRspLen = 3; - byte[] scanRsp = new byte[] {0x04}; + int advPacketLen = 1; + byte[] advPacket = new byte[] {0x02}; + int scanResponseLen = 3; + byte[] scanResponse = new byte[] {0x04}; int filtIndex = 5; int advState = ScanController.ADVT_STATE_ONFOUND; @@ -441,8 +438,8 @@ public class ScanControllerTest { int timeStamp = 11; ScanClient scanClient = new ScanClient(scannerId); - scanClient.hasNetworkSettingsPermission = true; - scanClient.settings = + scanClient.mHasNetworkSettingsPermission = true; + scanClient.mSettings = new ScanSettings.Builder() .setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH) .setLegacy(false) @@ -461,10 +458,10 @@ public class ScanControllerTest { AdvtFilterOnFoundOnLostInfo advtFilterOnFoundOnLostInfo = new AdvtFilterOnFoundOnLostInfo( scannerId, - advPktLen, - advPkt, - scanRspLen, - scanRsp, + advPacketLen, + ByteString.copyFrom(advPacket), + scanResponseLen, + ByteString.copyFrom(scanResponse), filtIndex, advState, advInfoPresent, diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java index 08952664e7..3359c2b48a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java @@ -240,7 +240,8 @@ public class ScanFilterQueueTest { testServiceDataFilter(filter, true); } - private void testServiceDataFilter(ScanFilter filter, boolean partialServiceDataMatchResult) { + private static void testServiceDataFilter( + ScanFilter filter, boolean partialServiceDataMatchResult) { ScanFilterQueue queue = new ScanFilterQueue(); queue.addScanFilter(filter); ScanFilterQueue.Entry entry = queue.pop(); @@ -288,7 +289,7 @@ public class ScanFilterQueueTest { .isEqualTo(partialServiceDataMatchResult); } - private boolean serviceDataMatches(byte[] filterData, byte[] resultData, byte[] mask) { + private static boolean serviceDataMatches(byte[] filterData, byte[] resultData, byte[] mask) { if (filterData.length > resultData.length || filterData.length != mask.length) { return false; } diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java index 2351accf89..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 @@ -123,6 +123,8 @@ import java.util.UUID; @SmallTest @RunWith(TestParameterInjector.class) public class ScanManagerTest { + private static final String TAG = ScanManagerTest.class.getSimpleName(); + @Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule(); @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @@ -138,7 +140,6 @@ public class ScanManagerTest { @Spy private GattObjectsFactory mGattObjectsFactory = GattObjectsFactory.getInstance(); @Spy private ScanObjectsFactory mScanObjectsFactory = ScanObjectsFactory.getInstance(); - private static final String TAG = ScanManagerTest.class.getSimpleName(); private static final int DEFAULT_REGULAR_SCAN_REPORT_DELAY_MS = 0; private static final int DEFAULT_BATCH_SCAN_REPORT_DELAY_MS = 100; private static final int DEFAULT_NUM_OFFLOAD_SCAN_FILTER = 16; @@ -209,10 +210,7 @@ public class ScanManagerTest { DisplayManager.class, mTargetContext.getSystemService(DisplayManager.class)); TestUtils.mockGetSystemService( - mAdapterService, - Context.BATTERY_STATS_SERVICE, - BatteryStatsManager.class, - mTargetContext.getSystemService(BatteryStatsManager.class)); + mAdapterService, Context.BATTERY_STATS_SERVICE, BatteryStatsManager.class); TestUtils.mockGetSystemService(mAdapterService, Context.ALARM_SERVICE, AlarmManager.class); mMockContentResolver = new MockContentResolver(mTargetContext); @@ -306,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; } @@ -364,7 +362,8 @@ public class ScanManagerTest { mMockAppScanStats); } - private List<ScanFilter> createScanFilterList(boolean isFiltered, boolean isEmptyFilter) { + private static List<ScanFilter> createScanFilterList( + boolean isFiltered, boolean isEmptyFilter) { List<ScanFilter> scanFilterList = null; if (isFiltered) { scanFilterList = new ArrayList<>(); @@ -400,7 +399,7 @@ public class ScanManagerTest { return scanSettings; } - private ScanSettings createScanSettingsWithPhy(int scanMode, int phy) { + private static ScanSettings createScanSettingsWithPhy(int scanMode, int phy) { ScanSettings scanSettings; scanSettings = new ScanSettings.Builder().setScanMode(scanMode).setPhy(phy).build(); @@ -413,37 +412,37 @@ public class ScanManagerTest { ScanSettings scanSettings = createScanSettingsWithPhy(scanMode, phy); ScanClient client = new ScanClient(id, scanSettings, scanFilterList); - client.stats = mMockAppScanStats; - client.stats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null); + client.mStats = mMockAppScanStats; + client.mStats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null); return client; } - private Message createStartStopScanMessage(boolean isStartScan, Object obj) { + private static Message createStartStopScanMessage(boolean isStartScan, Object obj) { Message message = new Message(); message.what = isStartScan ? ScanManager.MSG_START_BLE_SCAN : ScanManager.MSG_STOP_BLE_SCAN; message.obj = obj; return message; } - private Message createScreenOnOffMessage(boolean isScreenOn) { + private static Message createScreenOnOffMessage(boolean isScreenOn) { Message message = new Message(); message.what = isScreenOn ? ScanManager.MSG_SCREEN_ON : ScanManager.MSG_SCREEN_OFF; message.obj = null; return message; } - private Message createLocationOnOffMessage(boolean isLocationOn) { + private static Message createLocationOnOffMessage(boolean isLocationOn) { Message message = new Message(); message.what = isLocationOn ? ScanManager.MSG_RESUME_SCANS : ScanManager.MSG_SUSPEND_SCANS; message.obj = null; return message; } - private Message createImportanceMessage(boolean isForeground) { + private static Message createImportanceMessage(boolean isForeground) { return createImportanceMessage(isForeground, Binder.getCallingUid()); } - private Message createImportanceMessage(boolean isForeground, int uid) { + private static Message createImportanceMessage(boolean isForeground, int uid) { final int importance = isForeground ? ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE @@ -454,7 +453,7 @@ public class ScanManagerTest { return message; } - private Message createConnectingMessage(boolean isConnectingOn) { + private static Message createConnectingMessage(boolean isConnectingOn) { Message message = new Message(); message.what = isConnectingOn ? ScanManager.MSG_START_CONNECTING : ScanManager.MSG_STOP_CONNECTING; @@ -480,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); }); } @@ -508,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); } } @@ -531,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); }); } @@ -553,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); }); } @@ -575,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); }); } @@ -603,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); } } @@ -636,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); } } @@ -662,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); }); } @@ -700,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 @@ -708,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); }); } @@ -772,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); }); } @@ -805,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); }); } @@ -848,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); } } @@ -886,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 @@ -895,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); }); } @@ -929,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); } } @@ -970,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 @@ -981,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); } } @@ -1010,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 @@ -1020,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); }); } @@ -1125,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(); @@ -1168,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(); @@ -1293,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( @@ -1495,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), @@ -1803,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 @@ -1827,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 @@ -1945,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), @@ -1977,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), @@ -1996,7 +1995,7 @@ public class ScanManagerTest { // Start scan on coded sendMessageWaitForProcessed(createStartStopScanMessage(true, clientCoded)); - assertThat(clientCoded.settings.getPhy()).isEqualTo(PHY_LE_CODED); + assertThat(clientCoded.mSettings.getPhy()).isEqualTo(PHY_LE_CODED); verify(mScanNativeInterface) .gattSetScanParameters( eq(clientId1m), diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java index 520c678294..a336954afe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentObserverTest.java @@ -259,7 +259,7 @@ public class BluetoothMapContentObserverTest { mObserver.sendEvent(event); verify(mClient, never()).sendEvent(any(), anyInt()); - event.eventType = BluetoothMapContentObserver.EVENT_TYPE_DELEVERY_SUCCESS; + event.eventType = BluetoothMapContentObserver.EVENT_TYPE_DELIVERY_SUCCESS; mObserver.sendEvent(event); verify(mClient, never()).sendEvent(any(), anyInt()); @@ -2413,15 +2413,16 @@ public class BluetoothMapContentObserverTest { verify(mProviderClient, never()).query(any(), any(), any(), any(), any(), any()); } - private BluetoothMapContentObserver.Msg createSimpleMsg() { + private static BluetoothMapContentObserver.Msg createSimpleMsg() { return new BluetoothMapContentObserver.Msg(1, 1L, 1); } - private BluetoothMapContentObserver.Msg createMsgWithTypeAndThreadId(int type, int threadId) { + private static BluetoothMapContentObserver.Msg createMsgWithTypeAndThreadId( + int type, int threadId) { return new BluetoothMapContentObserver.Msg(1, type, threadId, 1); } - private void setFolderStructureWithTelecomAndMsg( + private static void setFolderStructureWithTelecomAndMsg( BluetoothMapFolderElement folderElement, String folderName, long folderId) { folderElement.addFolder("telecom"); folderElement.getSubFolder("telecom").addFolder("msg"); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java index 691ff23e95..6b8a010934 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapContentTest.java @@ -27,7 +27,6 @@ import static org.mockito.Mockito.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import android.content.ContentResolver; @@ -807,8 +806,7 @@ public class BluetoothMapContentTest { @Test public void setters_withConvoList() { - BluetoothMapMasInstance instance = spy(BluetoothMapMasInstance.class); - BluetoothMapContent content = new BluetoothMapContent(mContext, mAccountItem, instance); + BluetoothMapContent content = new BluetoothMapContent(mContext, mAccountItem, mMasInstance); HashMap<Long, BluetoothMapConvoListingElement> emailMap = new HashMap<Long, BluetoothMapConvoListingElement>(); HashMap<Long, BluetoothMapConvoListingElement> smsMap = @@ -1564,7 +1562,7 @@ public class BluetoothMapContentTest { BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, BluetoothMapContract.MessageColumns.FLAG_PROTECTED, BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.DELIVERY_STATE, BluetoothMapContract.MessageColumns.THREAD_ID, BluetoothMapContract.MessageColumns.CC_LIST, BluetoothMapContract.MessageColumns.BCC_LIST, @@ -1657,7 +1655,7 @@ public class BluetoothMapContentTest { BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, BluetoothMapContract.MessageColumns.FLAG_PROTECTED, BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.DELIVERY_STATE, BluetoothMapContract.MessageColumns.THREAD_ID, BluetoothMapContract.MessageColumns.THREAD_NAME, BluetoothMapContract.MessageColumns.ATTACHMENT_MINE_TYPES, diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java index b2c3d00c54..4d53d787b6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapObexServerTest.java @@ -290,7 +290,7 @@ public class BluetoothMapObexServerTest { assertThat(mParams.getFilterMessageType()).isEqualTo(expectedMask); } - private void setUpBluetoothMapAppParams(BluetoothMapAppParams params) { + private static void setUpBluetoothMapAppParams(BluetoothMapAppParams params) { params.setPresenceAvailability(1); params.setPresenceStatus("test_presence_status"); params.setLastActivity(0); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java index 72a3c75168..af0ae3a9c4 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,6 +16,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; @@ -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); 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/BluetoothMapbMessageSmsTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java index 6a10925ac1..9ef731fd90 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapbMessageSmsTest.java @@ -45,17 +45,17 @@ public class BluetoothMapbMessageSmsTest { private static final String TEST_MESSAGE = "test"; private static final String TEST_ADDRESS = "12"; - private Context mTargetContext; + private final Context mTargetContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + private List<SmsPdu> TEST_SMS_BODY_PDUS; @Before - public void setUp() throws Exception { + public void setUp() { // Do not run test if sms is not supported - PackageManager packageManager = - InstrumentationRegistry.getInstrumentation().getTargetContext().getPackageManager(); + PackageManager packageManager = mTargetContext.getPackageManager(); Assume.assumeTrue(packageManager.hasSystemFeature(FEATURE_TELEPHONY_MESSAGING)); - mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); TEST_SMS_BODY_PDUS = BluetoothMapSmsPdu.getSubmitPdus(mTargetContext, TEST_MESSAGE, TEST_ADDRESS); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java index 7be1a37d48..170c9e762f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/ConvoContactInfoTest.java @@ -52,7 +52,7 @@ public class ConvoContactInfoTest { BluetoothMapContract.ConvoContactColumns.LAST_ONLINE }); - info.setConvoColunms(cursor); + info.setConvoColumns(cursor); assertThat(info.mContactColConvoId).isEqualTo(0); assertThat(info.mContactColName).isEqualTo(1); diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java index bb713ae35c..09183cab1f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/map/FilterInfoTest.java @@ -60,7 +60,7 @@ public class FilterInfoTest { BluetoothMapContract.MessageColumns.FLAG_HIGH_PRIORITY, BluetoothMapContract.MessageColumns.FLAG_PROTECTED, BluetoothMapContract.MessageColumns.RECEPTION_STATE, - BluetoothMapContract.MessageColumns.DEVILERY_STATE, + BluetoothMapContract.MessageColumns.DELIVERY_STATE, BluetoothMapContract.MessageColumns.THREAD_ID }); diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java index c808bca43b..8462d664f6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapContractTest.java @@ -52,7 +52,7 @@ public class BluetoothMapContractTest { + "/" + ACCOUNT_ID; - Uri result = BluetoothMapContract.buildAccountUriwithId(TEST_AUTHORITY, ACCOUNT_ID); + Uri result = BluetoothMapContract.buildAccountUriWithId(TEST_AUTHORITY, ACCOUNT_ID); assertThat(result.toString()).isEqualTo(expectedUriString); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java index 3cf4856ef1..26913ee0a2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapapi/BluetoothMapIMProviderTest.java @@ -58,8 +58,7 @@ import java.util.Set; @RunWith(AndroidJUnit4.class) public class BluetoothMapIMProviderTest { - - private static final String TAG = "MapIMProviderTest"; + private static final String TAG = BluetoothMapIMProviderTest.class.getSimpleName(); private static final String AUTHORITY = "com.test"; private static final String ACCOUNT_ID = "12345"; @@ -573,7 +572,7 @@ public class BluetoothMapIMProviderTest { Mockito.clearInvocations(resolver); String accountId = "32608910"; - expectedUri = BluetoothMapContract.buildAccountUriwithId(AUTHORITY, accountId); + expectedUri = BluetoothMapContract.buildAccountUriWithId(AUTHORITY, accountId); mProvider.onAccountChanged(accountId); verify(resolver).notifyChange(expectedUri, null); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java index 2366add7d0..06d66600d7 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/BmessageTest.java @@ -30,6 +30,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class BmessageTest { private static final String TAG = BmessageTest.class.getSimpleName(); + private static final String SIMPLE_MMS_MESSAGE = "BEGIN:BMSG\r\nVERSION:1.0\r\nSTATUS:READ\r\nTYPE:MMS\r\nFOLDER:null\r\nBEGIN:BENV\r\n" + "BEGIN:VCARD\r\nVERSION:2.1\r\nN:null;;;;\r\nTEL:555-5555\r\nEND:VCARD\r\n" diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java index c2e4d92c8f..bfabc8081a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java @@ -68,8 +68,8 @@ import java.util.Map; @MediumTest @RunWith(AndroidJUnit4.class) public class MapClientContentTest { + private static final String TAG = MapClientContentTest.class.getSimpleName(); - private static final String TAG = "MapClientContentTest"; private static final int READ = 1; private final BluetoothDevice mDevice = getTestDevice(68); 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..6f578fe3b1 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,6 +15,8 @@ */ package com.android.bluetooth.mapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); 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/mapclient/MapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java index 3c8705172a..1f8cfb4a5d 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java @@ -104,6 +104,8 @@ import java.util.concurrent.TimeUnit; @MediumTest @RunWith(ParameterizedAndroidJunit4.class) public class MapClientStateMachineTest { + private static final String TAG = MapClientStateMachineTest.class.getSimpleName(); + @Rule public final SetFlagsRule mSetFlagsRule; @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Rule public final ServiceTestRule mServiceRule = new ServiceTestRule(); @@ -119,8 +121,6 @@ public class MapClientStateMachineTest { @Mock private RequestGetMessage mRequestGetMessage; @Mock private RequestGetMessagesListing mRequestGetMessagesListing; - private static final String TAG = "MapClientStateMachineTest"; - private static final long PENDING_INTENT_TIMEOUT_MS = 3_000; private static final boolean MESSAGE_SEEN = true; private static final boolean MESSAGE_NOT_SEEN = false; diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java index e302f48beb..d5117cb896 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlProfileTest.java @@ -55,8 +55,6 @@ import java.util.UUID; @MediumTest @RunWith(AndroidJUnit4.class) public class MediaControlProfileTest { - private final String mFlagDexmarker = System.getProperty("dexmaker.share_classloader", "false"); - private MediaControlProfile mMediaControlProfile; private String packageName = "TestPackage"; @@ -83,10 +81,6 @@ public class MediaControlProfileTest { @Before public void setUp() throws Exception { - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", "true"); - } - MediaControlProfile.ListCallback listCallback; TestUtils.setAdapterService(mAdapterService); @@ -136,10 +130,6 @@ public class MediaControlProfileTest { mMediaControlProfile.cleanup(); mMediaControlProfile = null; reset(mMockMediaPlayerList); - - if (!mFlagDexmarker.equals("true")) { - System.setProperty("dexmaker.share_classloader", mFlagDexmarker); - } } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java index 5fb0108b24..4990c5315b 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppBatchTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.opp; +import static com.android.bluetooth.TestUtils.MockitoRule; + import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; @@ -31,36 +33,40 @@ import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.BluetoothMethodProxy; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; +import org.mockito.Mock; @MediumTest @RunWith(AndroidJUnit4.class) public class BluetoothOppBatchTest { + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); + @Mock private Context mContext; + + private final Context mTargetContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + private final BluetoothOppShareInfo mInitShareInfo = + new BluetoothOppShareInfo( + 0, + null, + null, + null, + null, + 0, + "00:11:22:33:44:55", + 0, + 0, + BluetoothShare.STATUS_PENDING, + 0, + 0, + 0, + false); private BluetoothOppBatch mBluetoothOppBatch; - private Context mContext; - - private BluetoothOppShareInfo mInitShareInfo; @Before public void setUp() throws Exception { - mInitShareInfo = - new BluetoothOppShareInfo( - 0, - null, - null, - null, - null, - 0, - "00:11:22:33:44:55", - 0, - 0, - BluetoothShare.STATUS_PENDING, - 0, - 0, - 0, - false); - mContext = InstrumentationRegistry.getInstrumentation().getContext(); + doReturn(mTargetContext.getContentResolver()).when(mContext).getContentResolver(); mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java index 38bcb6a802..77fb3991a9 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java @@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -68,7 +69,6 @@ public class BluetoothOppObexServerSessionTest { @Mock BluetoothMethodProxy mMethodProxy; @Mock BluetoothObexTransport mTransport; @Mock BluetoothOppService mBluetoothOppService; - @Mock NotificationManager mNotificationManager; @Mock Operation mOperation; @Mock Context mContext; @@ -295,6 +295,7 @@ public class BluetoothOppObexServerSessionTest { mServerSession.unblock(); mServerSession.mAccepted = BluetoothShare.USER_CONFIRMATION_CONFIRMED; Handler handler = mock(Handler.class); + doCallRealMethod().when(handler).obtainMessage(anyInt()); doAnswer( arg -> { mServerSession.unblock(); @@ -303,7 +304,7 @@ public class BluetoothOppObexServerSessionTest { return true; }) .when(handler) - .sendMessageAtTime( + .sendMessageDelayed( argThat(arg -> arg.what == BluetoothOppObexSession.MSG_CONNECT_TIMEOUT), anyLong()); mServerSession.start(handler, 0); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java index 3dfe6cc5d9..28ece7fcb3 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppReceiverTest.java @@ -22,6 +22,8 @@ import static com.android.bluetooth.TestUtils.getTestDevice; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -32,10 +34,11 @@ import static org.mockito.Mockito.verify; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevicePicker; import android.content.Context; -import android.content.ContextWrapper; import android.content.Intent; +import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; +import android.os.Looper; import android.sysprop.BluetoothProperties; import androidx.test.espresso.intent.Intents; @@ -60,20 +63,29 @@ import java.util.List; @RunWith(AndroidJUnit4.class) public class BluetoothOppReceiverTest { + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); - Context mContext; + @Mock private BluetoothMethodProxy mBluetoothMethodProxy; + @Mock private Context mContext; - @Rule public final MockitoRule mMockitoRule = new MockitoRule(); + private static final String TEST_PREF = "BluetoothOppReceiverTest"; + + private final Context mTargetContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + private SharedPreferences mPrefs; - @Mock BluetoothMethodProxy mBluetoothMethodProxy; BluetoothOppReceiver mReceiver; @Before public void setUp() throws Exception { - mContext = - spy( - new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); + doReturn(mTargetContext.getContentResolver()).when(mContext).getContentResolver(); + doReturn(mTargetContext.getResources()).when(mContext).getResources(); + doReturn("").when(mContext).getString(anyInt(), any()); + + mTargetContext.deleteSharedPreferences(TEST_PREF); + mPrefs = mTargetContext.getSharedPreferences(TEST_PREF, Context.MODE_PRIVATE); + mPrefs.edit().clear().apply(); + doReturn(mPrefs).when(mContext).getSharedPreferences(anyString(), anyInt()); // mock instance so query/insert/update/etc. will not be executed BluetoothMethodProxy.setInstanceForTesting(mBluetoothMethodProxy); @@ -90,12 +102,18 @@ public class BluetoothOppReceiverTest { BluetoothMethodProxy.setInstanceForTesting(null); Intents.release(); + mPrefs.edit().clear().apply(); + mTargetContext.deleteSharedPreferences(TEST_PREF); } @Test public void onReceive_withActionDeviceSelected_callsStartTransfer() { Assume.assumeTrue(BluetoothProperties.isProfileOppEnabled().orElse(false)); + if (Looper.myLooper() == null) { + Looper.prepare(); + } + BluetoothOppManager bluetoothOppManager = spy(BluetoothOppManager.getInstance(mContext)); BluetoothOppManager.setInstance(bluetoothOppManager); BluetoothDevice device = getTestDevice(43); @@ -103,16 +121,10 @@ public class BluetoothOppReceiverTest { intent.setAction(BluetoothDevicePicker.ACTION_DEVICE_SELECTED); intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device); - try { - doNothing().when(bluetoothOppManager).startTransfer(eq(device)); - InstrumentationRegistry.getInstrumentation() - .runOnMainSync(() -> mReceiver.onReceive(mContext, intent)); - verify(bluetoothOppManager).startTransfer(eq(device)); - BluetoothOppManager.setInstance(null); - } finally { - BluetoothOppTestUtils.enableActivity( - BluetoothOppBtEnableActivity.class, false, mContext); - } + doNothing().when(bluetoothOppManager).startTransfer(eq(device)); + mReceiver.onReceive(mContext, intent); + verify(bluetoothOppManager).startTransfer(eq(device)); + BluetoothOppManager.setInstance(null); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java index 3cd31dfc32..8055882546 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppServiceTest.java @@ -16,6 +16,7 @@ package com.android.bluetooth.opp; import static com.android.bluetooth.TestUtils.MockitoRule; +import static com.android.bluetooth.TestUtils.mockGetSystemService; import static com.android.bluetooth.opp.BluetoothOppService.WHERE_INVISIBLE_UNCONFIRMED; import static com.google.common.truth.Truth.assertThat; @@ -30,6 +31,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; +import android.app.NotificationManager; import android.content.ContentResolver; import android.content.Context; import android.database.MatrixCursor; @@ -56,15 +58,22 @@ public class BluetoothOppServiceTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private BluetoothMethodProxy mBluetoothMethodProxy; + @Mock private AdapterService mAdapterService; private final Context mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); private BluetoothOppService mService; - private boolean mIsBluetoothOppServiceStarted; @Before public void setUp() throws Exception { + mockGetSystemService( + mAdapterService, Context.NOTIFICATION_SERVICE, NotificationManager.class); + doReturn(mTargetContext.getPackageName()).when(mAdapterService).getPackageName(); + doReturn(mTargetContext.getPackageManager()).when(mAdapterService).getPackageManager(); + doReturn(mTargetContext.getResources()).when(mAdapterService).getResources(); + doReturn(mTargetContext.getContentResolver()).when(mAdapterService).getContentResolver(); + BluetoothMethodProxy.setInstanceForTesting(mBluetoothMethodProxy); // BluetoothOppService can create a UpdateThread, which will call @@ -78,10 +87,8 @@ public class BluetoothOppServiceTest { Looper.prepare(); } - AdapterService adapterService = new AdapterService(mTargetContext); - mService = new BluetoothOppService(adapterService); + mService = new BluetoothOppService(mAdapterService); mService.setAvailable(true); - mIsBluetoothOppServiceStarted = true; // Wait until the initial trimDatabase operation is done. verify(mBluetoothMethodProxy, timeout(3_000)) @@ -101,19 +108,14 @@ public class BluetoothOppServiceTest { // Since the update thread is not run (we mocked it), it will not clean itself on interrupt // (normally, the service will wait for the update thread to clean itself after // being interrupted). We clean it manually here - BluetoothOppService service = mService; - if (service != null) { - service.mUpdateThread = null; - Thread updateNotificationThread = service.mNotifier.mUpdateNotificationThread; - if (updateNotificationThread != null) { - updateNotificationThread.join(); - } + mService.mUpdateThread = null; + Thread updateNotificationThread = mService.mNotifier.mUpdateNotificationThread; + if (updateNotificationThread != null) { + updateNotificationThread.join(); } BluetoothMethodProxy.setInstanceForTesting(null); - if (mIsBluetoothOppServiceStarted) { - service.cleanup(); - } + mService.cleanup(); } @Test diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java index 3433c9e323..80ef0232ec 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java @@ -17,6 +17,7 @@ package com.android.bluetooth.opp; import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; +import static com.android.bluetooth.TestUtils.mockGetSystemService; import static com.android.bluetooth.opp.BluetoothOppTransfer.TRANSPORT_CONNECTED; import static com.android.bluetooth.opp.BluetoothOppTransfer.TRANSPORT_ERROR; @@ -29,15 +30,14 @@ import static org.mockito.Mockito.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import android.app.NotificationManager; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothUuid; import android.content.ContentValues; import android.content.Context; -import android.content.ContextWrapper; import android.content.Intent; import android.content.IntentFilter; import android.net.Uri; @@ -71,6 +71,7 @@ public class BluetoothOppTransferTest { @Mock BluetoothOppObexSession mSession; @Mock BluetoothMethodProxy mCallProxy; + @Mock Context mContext; private final Uri mUri = Uri.parse("file://Idontknow/Justmadeitup"); private final String mHintString = "this is a object that take 4 bytes"; @@ -86,7 +87,6 @@ public class BluetoothOppTransferTest { private final int mTimestamp = 123456789; private final boolean mMediaScanned = false; - Context mContext; BluetoothOppBatch mBluetoothOppBatch; BluetoothOppTransfer mTransfer; BluetoothOppTransfer.EventHandler mEventHandler; @@ -94,6 +94,8 @@ public class BluetoothOppTransferTest { @Before public void setUp() throws Exception { + mockGetSystemService(mContext, Context.NOTIFICATION_SERVICE, NotificationManager.class); + BluetoothMethodProxy.setInstanceForTesting(mCallProxy); doReturn(0) .when(mCallProxy) @@ -127,11 +129,7 @@ public class BluetoothOppTransferTest { mCurrentBytes, mTimestamp, mMediaScanned); - mContext = - spy( - new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); - mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo)); + mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo); mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession); mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper()); } @@ -253,11 +251,7 @@ public class BluetoothOppTransferTest { mCurrentBytes, mTimestamp, mMediaScanned); - mContext = - spy( - new ContextWrapper( - InstrumentationRegistry.getInstrumentation().getTargetContext())); - mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo)); + mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo); mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession); mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper()); mEventHandler.handleMessage(message); @@ -305,7 +299,7 @@ public class BluetoothOppTransferTest { mCurrentBytes, mTimestamp, mMediaScanned); - mBluetoothOppBatch = spy(new BluetoothOppBatch(mContext, mInitShareInfo)); + mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo); mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession); mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper()); @@ -389,7 +383,9 @@ public class BluetoothOppTransferTest { @Test public void oppConnectionReceiver_onReceiveWithActionAclDisconnected_sendsConnectTimeout() { BluetoothDevice device = - (mContext.getSystemService(BluetoothManager.class)) + InstrumentationRegistry.getInstrumentation() + .getTargetContext() + .getSystemService(BluetoothManager.class) .getAdapter() .getRemoteDevice(mDestination); BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch); @@ -410,7 +406,9 @@ public class BluetoothOppTransferTest { public void oppConnectionReceiver_onReceiveWithActionSdpRecord_withoutSdpRecord() { mSetFlagRule.enableFlags(Flags.FLAG_IDENTITY_ADDRESS_NULL_IF_NOT_KNOWN); BluetoothDevice device = - (mContext.getSystemService(BluetoothManager.class)) + InstrumentationRegistry.getInstrumentation() + .getTargetContext() + .getSystemService(BluetoothManager.class) .getAdapter() .getRemoteDevice(mDestination); diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java index 4607569b83..842a0aeacd 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppUtilityTest.java @@ -64,21 +64,21 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; public class BluetoothOppUtilityTest { - - private static final Uri CORRECT_FORMAT_BUT_INVALID_FILE_URI = - Uri.parse("content://com.android.bluetooth.opp/btopp/0123455343467"); - private static final Uri INCORRECT_FORMAT_URI = Uri.parse("www.google.com"); - - Context mContext; @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock Cursor mCursor; @Spy BluetoothMethodProxy mCallProxy = BluetoothMethodProxy.getInstance(); + private static final Uri CORRECT_FORMAT_BUT_INVALID_FILE_URI = + Uri.parse("content://com.android.bluetooth.opp/btopp/0123455343467"); + private static final Uri INCORRECT_FORMAT_URI = Uri.parse("www.google.com"); + + private final Context mContext = + InstrumentationRegistry.getInstrumentation().getTargetContext(); + @Before public void setUp() throws Exception { - mContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); BluetoothMethodProxy.setInstanceForTesting(mCallProxy); TestUtils.setUpUiTest(); } @@ -281,11 +281,7 @@ public class BluetoothOppUtilityTest { @Test public void fillRecord_filledAllProperties() { - BluetoothAdapter adapter = - InstrumentationRegistry.getInstrumentation() - .getTargetContext() - .getSystemService(BluetoothManager.class) - .getAdapter(); + BluetoothAdapter adapter = mContext.getSystemService(BluetoothManager.class).getAdapter(); int idValue = 1234; int directionValue = BluetoothShare.DIRECTION_OUTBOUND; long totalBytesValue = 10; @@ -332,12 +328,6 @@ public class BluetoothOppUtilityTest { } @Test - public void fileExists_returnFalse() { - assertThat(BluetoothOppUtility.fileExists(mContext, CORRECT_FORMAT_BUT_INVALID_FILE_URI)) - .isFalse(); - } - - @Test public void isRecognizedFileType_withWrongFileUriAndMimeType_returnFalse() { assertThat( BluetoothOppUtility.isRecognizedFileType( diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java b/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java index 3d3321838b..7bbcbd0968 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java +++ b/android/app/tests/unit/src/com/android/bluetooth/opp/TestActivity.java @@ -369,8 +369,8 @@ public class TestActivity extends Activity { /** This class listens on OPUSH channel for incoming connection */ class TestTcpListener { - - private static final String TAG = "BtOppRfcommListener"; + private static final String TAG = + Constants.TAG_PREFIX_BLUETOOTH_OPP + TestTcpListener.class.getSimpleName(); private static final boolean D = Log.isLoggable(TAG, Log.DEBUG); @@ -494,7 +494,7 @@ class TestTcpListener { } class TestTcpServer extends ServerRequestHandler implements Runnable { - private static final String TAG = "ServerRequestHandler"; + private static final String TAG = ServerRequestHandler.class.getSimpleName(); private static final boolean V = Log.isLoggable(TAG, Log.VERBOSE); @@ -608,15 +608,14 @@ class TestTcpServer extends ServerRequestHandler implements Runnable { } } +/* implements SessionNotifier */ class TestTcpSessionNotifier { - /* implements SessionNotifier */ + private static final String TAG = TestTcpSessionNotifier.class.getSimpleName(); ServerSocket mServer = null; Socket mConn = null; - private static final String TAG = "TestTcpSessionNotifier"; - TestTcpSessionNotifier(int port) throws IOException { mServer = new ServerSocket(port); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java index d148cde55d..ddabada6bc 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pan/BluetoothTetheringNetworkFactoryTest.java @@ -17,18 +17,12 @@ package com.android.bluetooth.pan; import static com.android.bluetooth.TestUtils.MockitoRule; -import static com.android.bluetooth.TestUtils.getTestDevice; import static com.google.common.truth.Truth.assertThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import android.bluetooth.BluetoothDevice; import android.content.Context; import android.os.Looper; -import androidx.test.core.app.ApplicationProvider; import androidx.test.filters.SmallTest; import androidx.test.runner.AndroidJUnit4; @@ -37,9 +31,6 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import java.util.ArrayList; -import java.util.List; - /** Test cases for {@link BluetoothTetheringNetworkFactory}. */ @SmallTest @RunWith(AndroidJUnit4.class) @@ -48,8 +39,7 @@ public class BluetoothTetheringNetworkFactoryTest { @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private PanService mPanService; - - private Context mContext = ApplicationProvider.getApplicationContext(); + @Mock Context mContext; @Test public void networkStartReverseTetherEmptyIface() { @@ -67,47 +57,6 @@ public class BluetoothTetheringNetworkFactoryTest { } @Test - public void networkStartReverseTether() { - if (Looper.myLooper() == null) { - Looper.prepare(); - } - - BluetoothTetheringNetworkFactory bluetoothTetheringNetworkFactory = - new BluetoothTetheringNetworkFactory(mContext, Looper.myLooper(), mPanService); - - String iface = "iface"; - bluetoothTetheringNetworkFactory.startReverseTether(iface); - - assertThat(bluetoothTetheringNetworkFactory.getProvider()).isNotNull(); - } - - @Test - public void networkStartReverseTetherStop() { - if (Looper.myLooper() == null) { - Looper.prepare(); - } - - BluetoothTetheringNetworkFactory bluetoothTetheringNetworkFactory = - new BluetoothTetheringNetworkFactory(mContext, Looper.myLooper(), mPanService); - - String iface = "iface"; - bluetoothTetheringNetworkFactory.startReverseTether(iface); - - assertThat(bluetoothTetheringNetworkFactory.getProvider()).isNotNull(); - - List<BluetoothDevice> bluetoothDevices = new ArrayList<>(); - BluetoothDevice bluetoothDevice = getTestDevice(11); - bluetoothDevices.add(bluetoothDevice); - - when(mPanService.getConnectedDevices()).thenReturn(bluetoothDevices); - - bluetoothTetheringNetworkFactory.stopReverseTether(); - - verify(mPanService).getConnectedDevices(); - verify(mPanService).disconnect(bluetoothDevice); - } - - @Test public void networkStopEmptyIface() { if (Looper.myLooper() == null) { Looper.prepare(); 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..306ed41eed 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,6 +16,8 @@ package com.android.bluetooth.pan; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -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); 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..8fe983ece6 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,16 @@ package com.android.bluetooth.pan; import static android.bluetooth.BluetoothPan.PAN_ROLE_NONE; +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 +46,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 +68,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 +80,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 +110,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 +120,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 +135,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()); } @@ -230,8 +229,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/BluetoothPbapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java index 48ffaaad29..0730f6fd40 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java @@ -80,7 +80,6 @@ import java.io.OutputStream; @SmallTest @RunWith(AndroidJUnit4.class) public class BluetoothPbapObexServerTest { - private static final String TAG = BluetoothPbapObexServerTest.class.getSimpleName(); @Rule public final MockitoRule mMockitoRule = new MockitoRule(); 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..2029f3ad4a 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,6 +16,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; @@ -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); 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 2e0fae0b15..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; @@ -24,6 +26,9 @@ import static org.junit.Assert.assertThrows; import static org.junit.Assume.assumeNotNull; import static org.junit.Assume.assumeTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -35,6 +40,7 @@ import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.Context; import android.content.Intent; +import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Message; import android.os.UserManager; @@ -49,6 +55,7 @@ import com.android.bluetooth.TestLooper; import com.android.bluetooth.TestUtils; import com.android.bluetooth.btservice.AdapterService; import com.android.bluetooth.btservice.storage.DatabaseManager; +import com.android.bluetooth.sdp.SdpManagerNativeInterface; import org.junit.After; import org.junit.Before; @@ -64,12 +71,13 @@ import java.util.List; @MediumTest @RunWith(AndroidJUnit4.class) public class BluetoothPbapServiceTest { - @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private AdapterService mAdapterService; @Mock private DatabaseManager mDatabaseManager; @Mock private NotificationManager mNotificationManager; + @Mock private SdpManagerNativeInterface mSdpManagerNativeInterface; + @Mock private SharedPreferences mSharedPreferences; @Spy private BluetoothMethodProxy mMethodProxy = BluetoothMethodProxy.getInstance(); private final BluetoothDevice mRemoteDevice = getTestDevice(42); @@ -83,6 +91,9 @@ public class BluetoothPbapServiceTest { @Before public void setUp() throws Exception { + doReturn(mSharedPreferences) + .when(mAdapterService) + .getSharedPreferences(anyString(), anyInt()); doReturn(mTargetContext.getPackageName()).when(mAdapterService).getPackageName(); doReturn(mTargetContext.getPackageManager()).when(mAdapterService).getPackageManager(); doReturn(mMockContentResolver).when(mAdapterService).getContentResolver(); @@ -92,6 +103,7 @@ public class BluetoothPbapServiceTest { doReturn(List.of()).when(manager).getAllProfiles(); mTestLooper = new TestLooper(); + SdpManagerNativeInterface.setInstance(mSdpManagerNativeInterface); BluetoothMethodProxy.setInstanceForTesting(mMethodProxy); doReturn(mTestLooper.getLooper()).when(mMethodProxy).handlerThreadGetLooper(any()); doNothing().when(mMethodProxy).threadStart(any()); @@ -109,6 +121,7 @@ public class BluetoothPbapServiceTest { public void tearDown() throws Exception { mTestLooper.stopAutoDispatchAndIgnoreExceptions(); BluetoothMethodProxy.setInstanceForTesting(null); + SdpManagerNativeInterface.setInstance(null); mService.cleanup(); assertThat(BluetoothPbapService.getBluetoothPbapService()).isNull(); } @@ -157,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); } @@ -200,6 +213,7 @@ public class BluetoothPbapServiceTest { intent.putExtra(BluetoothPbapService.EXTRA_SESSION_KEY, sessionKey); intent.putExtra(BluetoothPbapService.EXTRA_DEVICE, mRemoteDevice); PbapStateMachine sm = mock(PbapStateMachine.class); + doCallRealMethod().when(sm).obtainMessage(anyInt(), any()); mService.mPbapStateMachineMap.put(mRemoteDevice, sm); mService.mPbapReceiver.onReceive(null, intent); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java index 2142da1431..86fd898d2f 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java @@ -59,7 +59,6 @@ import java.util.concurrent.atomic.AtomicInteger; @SmallTest @RunWith(AndroidJUnit4.class) public class BluetoothPbapSimVcardManagerTest { - private static final String TAG = BluetoothPbapSimVcardManagerTest.class.getSimpleName(); @Rule public final MockitoRule mMockitoRule = new MockitoRule(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java index 1302bb4c08..b696cef960 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerNestedClassesTest.java @@ -235,7 +235,7 @@ public class BluetoothPbapVcardManagerNestedClassesTest { assertThat(getContactsIdFromCursor(resultCursor, 2)).isEqualTo(1004); } - private long getContactsIdFromCursor(Cursor cursor, int position) { + private static long getContactsIdFromCursor(Cursor cursor, int position) { int index = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID); cursor.moveToPosition(position); return cursor.getLong(index); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java index e4defeeff8..308a40b282 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapVcardManagerTest.java @@ -22,6 +22,7 @@ import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.any; +import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -54,7 +55,6 @@ import java.util.concurrent.atomic.AtomicInteger; @SmallTest @RunWith(AndroidJUnit4.class) public class BluetoothPbapVcardManagerTest { - private static final String TAG = BluetoothPbapVcardManagerTest.class.getSimpleName(); @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @@ -198,6 +198,7 @@ public class BluetoothPbapVcardManagerTest { final int expectedSize = 10; when(cursor.getCount()).thenReturn(expectedSize); BluetoothPbapSimVcardManager simVcardManager = mock(BluetoothPbapSimVcardManager.class); + doCallRealMethod().when(simVcardManager).getSIMContactsSize(); assertThat( mManager.getPhonebookSize( 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 e33e2a30bf..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; @@ -73,15 +76,15 @@ public class PbapStateMachineTest { } @After - public void tearDown() { + public void tearDown() throws InterruptedException { mHandlerThread.quitSafely(); + mHandlerThread.join(); } /** 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); } @@ -91,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); } @@ -102,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); } @@ -113,15 +114,13 @@ public class PbapStateMachineTest { @Test public void testStateTransition_ConnectedToFinished() { mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Connected.class); // PBAP OBEX transport is done. mPbapStateMachine.sendMessage(PbapStateMachine.DISCONNECT); - assertThat(mPbapStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); assertThat(mPbapStateMachine.getCurrentState()) .isInstanceOf(PbapStateMachine.Finished.class); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java index fdadac66b8..b3669a14f6 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/CallLogPullRequestTest.java @@ -198,7 +198,7 @@ public class CallLogPullRequestTest { assertThat(contact.getTimesContacted()).isEqualTo(1); } - private VCardProperty createProperty(String name, String value) { + private static VCardProperty createProperty(String name, String value) { VCardProperty property = new VCardProperty(); property.setName(name); property.setValues(value); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java index 5126cd500e..4fc428ebbe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java @@ -402,7 +402,7 @@ public class PbapClientAccountManagerTest { mBroadcastReceiver.onReceive(mMockContext, intent); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), "com.android.bluetooth.pbabclient.account"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java index 21f4d58849..9bb91de414 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,9 @@ package com.android.bluetooth.pbapclient; +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; @@ -93,7 +96,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)); } @@ -148,7 +151,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,7 +163,7 @@ 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 diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java index 2d90f7e178..d3ebddfa18 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientConnectionHandlerTest.java @@ -29,7 +29,6 @@ import static org.mockito.Mockito.when; import android.bluetooth.BluetoothDevice; import android.content.ContentResolver; -import android.content.res.Resources; import android.os.HandlerThread; import android.os.Looper; @@ -48,15 +47,14 @@ import org.mockito.Mock; @SmallTest @RunWith(AndroidJUnit4.class) public class PbapClientConnectionHandlerTest { + private static final String TAG = PbapClientConnectionHandlerTest.class.getSimpleName(); + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private PbapClientService mService; - @Mock private Resources mMockResources; @Mock private ContentResolver mMockContentResolver; @Mock private PbapClientStateMachineOld mStateMachine; - private static final String TAG = "ConnHandlerTest"; - // Normal supported features for our client private static final int SUPPORTED_FEATURES = PbapSdpRecord.FEATURE_DOWNLOADING | PbapSdpRecord.FEATURE_DEFAULT_IMAGE_FORMAT; @@ -79,8 +77,7 @@ public class PbapClientConnectionHandlerTest { doReturn(mService).when(mStateMachine).getContext(); doReturn(mMockContentResolver).when(mService).getContentResolver(); - doReturn(mMockResources).when(mService).getResources(); - doReturn("com.android.bluetooth.pbapclient").when(mMockResources).getString(anyInt()); + doReturn("com.android.bluetooth.pbapclient").when(mService).getString(anyInt()); mHandler = new PbapClientConnectionHandler.Builder() diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java index 168f9b782c..66070377ed 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientContactsStorageTest.java @@ -552,11 +552,11 @@ public class PbapClientContactsStorageTest { assertThat(mStorage.isStorageReady()).isTrue(); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), ACCOUNT_TYPE); } - private List<VCardEntry> getMockContacts(int numContacts) { + private static List<VCardEntry> getMockContacts(int numContacts) { List<VCardEntry> contacts = new ArrayList<VCardEntry>(); for (int i = 0; i < numContacts; i++) { VCardEntry card = new VCardEntry(VCardConfig.VCARD_TYPE_V21_GENERIC); @@ -570,7 +570,7 @@ public class PbapClientContactsStorageTest { return contacts; } - private List<VCardEntry> getMockCallHistory(int type, int numEntries) { + private static List<VCardEntry> getMockCallHistory(int type, int numEntries) { String typeIndicator = ""; if (type == CallLog.Calls.INCOMING_TYPE) { typeIndicator = "RECEIVED"; diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java index 0db11cbb38..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); } // ********************************************************************************************* @@ -502,6 +478,7 @@ public class PbapClientObexClientTest { private static class FakePbapObexServer extends FakeObexServer { private static final String TAG = FakePbapObexServer.class.getSimpleName(); + private static final String TYPE_GET_PHONEBOOK = "x-bt/phonebook"; private static final byte SIZE_BYTES = 2; private static final byte DATABASE_IDENTIFIER_BYTES = 4; 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 38fdc4f370..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; @@ -22,14 +26,16 @@ import static com.android.bluetooth.TestUtils.mockGetSystemService; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.any; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.timeout; 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; @@ -50,33 +56,40 @@ import org.mockito.Mockito; @MediumTest @RunWith(AndroidJUnit4.class) public class PbapClientStateMachineOldTest { + private static final String TAG = PbapClientStateMachineOldTest.class.getSimpleName(); + @Rule public final MockitoRule mMockitoRule = new MockitoRule(); @Mock private PbapClientService mMockPbapClientService; @Mock private PbapClientConnectionHandler mMockHandler; - private static final String TAG = "PbapClientStateMachineOldTest"; private static final int DISCONNECT_TIMEOUT = 5000; 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 */ @@ -87,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); } /** @@ -97,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); @@ -114,7 +124,6 @@ public class PbapClientStateMachineOldTest { mIntentArgument.capture(), any(String[].class), any(BroadcastOptions.class)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java index d8dc5d4e4b..4620f7467c 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java @@ -16,6 +16,11 @@ package com.android.bluetooth.pbapclient; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.TestUtils.getTestDevice; @@ -38,7 +43,6 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import android.accounts.Account; import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothProfile; import android.bluetooth.SdpPseRecord; import android.content.Context; @@ -168,8 +172,7 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.disconnect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, never()).onConnectionStateChanged(anyInt(), anyInt()); } @@ -178,12 +181,9 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.connect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTED), - eq(BluetoothProfile.STATE_CONNECTING)); + .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING)); } // ********************************************************************************************* @@ -237,15 +237,10 @@ public class PbapClientStateMachineTest { verify(mMockObexClient, never()).connectL2cap(eq(L2CAP_PSM)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -260,8 +255,7 @@ public class PbapClientStateMachineTest { // We can't currently mock a BluetoothDevice to verify the sdpSearch() call, but we can // validate that the state machine stays in the same state and will adequately receive the // next valid SDP record that arrives. - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING); mPbapClientStateMachine.onSdpResultReceived( SDP_SUCCESS, @@ -283,32 +277,22 @@ public class PbapClientStateMachineTest { verify(mMockObexClient, never()).connectL2cap(eq(L2CAP_PSM)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test public void testConnecting_receivedObexConnection_transitionToConnected() { testConnecting_receivedSdpResultWithTransportL2cap_connectionReqOnL2cap(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); } @Test @@ -318,15 +302,10 @@ public class PbapClientStateMachineTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test @@ -336,36 +315,24 @@ public class PbapClientStateMachineTest { mTestLooper.dispatchAll(); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); } @Test public void testConnecting_receivedObexDisconnection_transitionToDisconnected() { testConnecting_receivedSdpResultWithTransportL2cap_connectionReqOnL2cap(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } // ********************************************************************************************* @@ -434,33 +401,23 @@ public class PbapClientStateMachineTest { mStorageCallback.onStorageAccountsChanged(mMockedAccounts, new ArrayList<Account>()); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); } @Test public void testConnected_receivedObexDisconnection_transitionToDisconnected() { testConnecting_receivedObexConnection_transitionToConnected(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -469,12 +426,9 @@ public class PbapClientStateMachineTest { mPbapClientStateMachine.disconnect(); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTING); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTING); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTED), - eq(BluetoothProfile.STATE_DISCONNECTING)); + .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING)); } // ********************************************************************************************* @@ -520,10 +474,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertFavorites(any(Account.class), anyList()); @@ -547,10 +499,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_LOCAL_PHONEBOOK)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertLocalContacts(any(Account.class), anyList()); @@ -574,10 +524,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_LOCAL_PHONEBOOK)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, never()).insertLocalContacts(any(Account.class), anyList()); @@ -604,10 +552,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_SIM_CARD)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertSimContacts(any(Account.class), anyList()); @@ -631,10 +577,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_SIM_CARD)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(1)).insertMissedCallHistory(any(Account.class), anyList()); @@ -656,10 +600,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); verify(mMockStorage, times(4)).insertFavorites(any(Account.class), anyList()); @@ -676,19 +618,14 @@ public class PbapClientStateMachineTest { SDP_SUCCESS, makeSdpRecord( L2CAP_PSM, INVALID_RFCOMM, SUPPORTED_FEATURES, NO_REPOSITORIES_SUPPORTED)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); // Verify we're connected - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_CONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_CONNECTING), - eq(BluetoothProfile.STATE_CONNECTED)); + .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED)); // Verify storage not hit verify(mMockStorage, never()).insertFavorites(any(Account.class), anyList()); @@ -712,10 +649,8 @@ public class PbapClientStateMachineTest { INVALID_RFCOMM, SUPPORTED_FEATURES, PbapSdpRecord.REPOSITORY_FAVORITES)); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED); + setAndNotifyObexClientStatus(STATE_DISCONNECTED, STATE_CONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_CONNECTED); mTestLooper.dispatchAll(); // Get storage callback @@ -757,18 +692,13 @@ public class PbapClientStateMachineTest { @Test public void testDisconnecting_clientDisconnects_transitionToDisconnected() { testEnterDisconnecting_clientConnected_disconnectIssued(); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTING); - setAndNotifyObexClientStatus( - BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED); + setAndNotifyObexClientStatus(STATE_CONNECTED, STATE_DISCONNECTING); + setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -777,12 +707,9 @@ public class PbapClientStateMachineTest { mTestLooper.moveTimeForward(PbapClientStateMachine.DISCONNECT_TIMEOUT_MS); mTestLooper.dispatchAll(); - assertThat(mPbapClientStateMachine.getConnectionState()) - .isEqualTo(BluetoothProfile.STATE_DISCONNECTED); + assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED); verify(mMockCallback, times(1)) - .onConnectionStateChanged( - eq(BluetoothProfile.STATE_DISCONNECTING), - eq(BluetoothProfile.STATE_DISCONNECTED)); + .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED)); } @Test @@ -829,7 +756,7 @@ public class PbapClientStateMachineTest { return new PbapSdpRecord(mTestDevice, sdpRecord); } - private Account getAccountForDevice(BluetoothDevice device) { + private static Account getAccountForDevice(BluetoothDevice device) { return new Account(device.getAddress(), "com.android.bluetooth.pbabclient.account"); } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java index 214a08bf27..6537f475b5 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java @@ -548,7 +548,7 @@ public class PbapPhonebookTest { // * Utilities // ********************************************************************************************* - private InputStream toUtf8Stream(String s) { + private static InputStream toUtf8Stream(String s) { return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } } diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java index 77a5453bdf..d0e462ca66 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PhonebookPullRequestTest.java @@ -71,14 +71,14 @@ public class PhonebookPullRequestTest { assertThat(mRequest.complete).isTrue(); } - private VCardProperty createProperty(String name, String value) { + private static VCardProperty createProperty(String name, String value) { VCardProperty property = new VCardProperty(); property.setName(name); property.setValues(value); return property; } - private VCardEntry createEntry(int propertyCount) { + private static VCardEntry createEntry(int propertyCount) { VCardEntry entry = new VCardEntry(); for (int i = 0; i < propertyCount; i++) { entry.addProperty(createProperty(VCardConstants.PROPERTY_TEL, Integer.toString(i))); diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java index 5f50e76ca2..44744c837a 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/RequestPullPhonebookMetadataTest.java @@ -168,7 +168,7 @@ public class RequestPullPhonebookMetadataTest { return sendResponse(op, replyHeaders, null); } - public byte[] shortToByteArray(short s) { + public static byte[] shortToByteArray(short s) { ByteBuffer ret = ByteBuffer.allocate(2); ret.putShort(s); return ret.array(); diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java index c87956cfb4..fc4e44c9fe 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java @@ -50,6 +50,7 @@ import static org.mockito.Mockito.eq; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; +import android.hardware.radio.V1_0.ISap; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; @@ -57,8 +58,6 @@ import android.os.Message; import androidx.test.filters.LargeTest; import androidx.test.runner.AndroidJUnit4; -import com.android.bluetooth.jarjar.android.hardware.radio.V1_0.ISap; - import org.junit.After; import org.junit.Before; import org.junit.Rule; diff --git a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java index ce797f2d30..c9c3c238e2 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/sdp/DipTest.java @@ -82,7 +82,7 @@ public class DipTest { SdpManagerNativeInterface.setInstance(null); } - private void verifyDipSdpRecordIntent( + private static void verifyDipSdpRecordIntent( ArgumentCaptor<Intent> intentArgument, int status, BluetoothDevice device, diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java index 7a727f5d7f..4045cb9bfb 100644 --- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java +++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java @@ -16,6 +16,8 @@ package com.android.bluetooth.vc; +import static android.bluetooth.BluetoothProfile.STATE_CONNECTED; + import static com.android.bluetooth.TestUtils.MockitoRule; import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED; import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_DEVICE_AVAILABLE; @@ -29,8 +31,6 @@ import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.verify; -import android.bluetooth.BluetoothProfile; - import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.btservice.AdapterService; @@ -65,7 +65,7 @@ public class VolumeControlNativeCallbackTest { @Test public void onConnectionStateChanged() { - int state = BluetoothProfile.STATE_CONNECTED; + int state = STATE_CONNECTED; mNativeCallback.onConnectionStateChanged(state, null); verify(mService).messageFromNative(mEvent.capture()); diff --git a/android/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..71afc4951b 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,9 @@ package com.android.bluetooth.leaudio; +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 +554,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 +1067,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); } } @@ -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..cb69d88bd2 100644 --- a/android/pandora/server/src/A2dpSink.kt +++ b/android/pandora/server/src/A2dpSink.kt @@ -20,6 +20,8 @@ import android.bluetooth.BluetoothA2dpSink import android.bluetooth.BluetoothAdapter 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 @@ -67,13 +69,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 +85,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 +103,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") } @@ -116,11 +115,9 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable { bluetoothA2dpSink.setConnectionPolicy( device, - BluetoothProfile.CONNECTION_POLICY_FORBIDDEN + BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, ) - a2dpConnectionStateChangedFlow - .filter { it == BluetoothProfile.STATE_DISCONNECTED } - .first() + 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/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/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/android/pandora/test/AndroidPhyTest.xml b/android/pandora/test/AndroidPhyTest.xml index fa9df40a10..baba06ddf4 100644 --- a/android/pandora/test/AndroidPhyTest.xml +++ b/android/pandora/test/AndroidPhyTest.xml @@ -28,7 +28,7 @@ <option name="run-command" value="cmd bluetooth_manager wait-for-state:STATE_ON" /> </target_preparer> <target_preparer class="com.android.tradefed.targetprep.PythonVirtualenvPreparer"> - <option name="dep-module" value="grpcio==1.51.1" /> + <option name="dep-module" value="grpcio==1.70.0" /> <option name="dep-module" value="cryptography==35" /> <option name="dep-module" value="numpy" /> <option name="dep-module" value="pyusb" /> diff --git a/android/pandora/test/AndroidTest.xml b/android/pandora/test/AndroidTest.xml index 3b7b26fdf1..d89338bd65 100644 --- a/android/pandora/test/AndroidTest.xml +++ b/android/pandora/test/AndroidTest.xml @@ -36,10 +36,9 @@ </target_preparer> <target_preparer class="com.android.tradefed.targetprep.PythonVirtualenvPreparer"> <!-- TODO(b/267785204): Import python dependencies --> - <option name="dep-module" value="grpcio==1.51.1" /> + <option name="dep-module" value="grpcio==1.70.0" /> <option name="dep-module" value="cryptography==35" /> <option name="dep-module" value="numpy" /> - <option name="dep-module" value="pytruth" /> </target_preparer> <test class="com.android.tradefed.testtype.mobly.MoblyBinaryHostTest"> <option name="mobly-par-file-name" value="avatar" /> diff --git a/android/pandora/test/a2dp/signaling_channel.py b/android/pandora/test/a2dp/signaling_channel.py index aaa0df91f9..9075e16440 100644 --- a/android/pandora/test/a2dp/signaling_channel.py +++ b/android/pandora/test/a2dp/signaling_channel.py @@ -68,6 +68,8 @@ class SignalingChannel(EventEmitter): avdtp_server: Optional[l2cap.ClassicChannelServer] = None role: RoleType = None any: Any = Any() + acp_seid: int = 0 + int_seid: int = 0 def __init__(self, connection: Connection): super().__init__() @@ -214,12 +216,14 @@ class SignalingChannel(EventEmitter): av.GetAllCapabilitiesResponse(transaction_label=cmd.transaction_label, service_capabilities=service_capabilities)) - async def accept_set_configuration(self): + async def accept_set_configuration(self, expected_configuration: List[ServiceCapability]): cmd = await self.expect_signal( av.SetConfigurationCommand(transaction_label=self.any, acp_seid=self.any, int_seid=self.any, - service_capabilities=[MediaTransportCapability(), self.any])) + service_capabilities=expected_configuration)) + self.acp_seid = cmd.acp_seid + self.int_seid = cmd.int_seid self.send_signal(SetConfigurationResponse(transaction_label=cmd.transaction_label)) async def accept_open(self, timeout: float = 3.0): @@ -252,9 +256,28 @@ class SignalingChannel(EventEmitter): self.on('connection', on_avdtp_connection) + expected_configuration: List[ServiceCapability] = [] + for capability in service_capabilities: + if isinstance(capability, av.MediaTransportCapability) or isinstance(capability, + av.DelayReportingCapability): + expected_configuration.append(capability) + else: + expected_configuration.append(self.any) + await self.accept_discover(seid_information) await self.accept_get_all_capabilities(service_capabilities) - await self.accept_set_configuration() + await self.accept_set_configuration(expected_configuration) await self.accept_open() await asyncio.wait_for(avdtp_future, timeout=timeout) + + async def initiate_delay_report(self, delay_ms: int = 100, timeout: float = 3.0): + delay_one_tenth = delay_ms * 10 + delay_msb = (delay_one_tenth >> 8) & 0xff + delay_lsb = delay_one_tenth & 0xff + self.send_signal( + av.DelayReportCommand(transaction_label=0x01, + acp_seid=self.acp_seid, + delay_msb=delay_msb, + delay_lsb=delay_lsb)) + await self.expect_signal(av.DelayReportResponse(transaction_label=self.any), timeout=timeout) diff --git a/android/pandora/test/a2dp_test.py b/android/pandora/test/a2dp_test.py index 236f8b8b99..1c2c4c9e84 100644 --- a/android/pandora/test/a2dp_test.py +++ b/android/pandora/test/a2dp_test.py @@ -19,6 +19,7 @@ import dataclasses import itertools import logging import numpy as np +import time from a2dp.packets.avdtp import * from a2dp.signaling_channel import Any, SignalingChannel @@ -63,8 +64,10 @@ from bumble.l2cap import ( from bumble.pairing import PairingDelegate from mobly import base_test, test_runner from mobly.asserts import assert_equal # type: ignore +from mobly.asserts import assert_greater_equal # type: ignore from mobly.asserts import assert_in # type: ignore from mobly.asserts import assert_is_not_none # type: ignore +from mobly.asserts import assert_less_equal # type: ignore from mobly.asserts import fail # type: ignore from pandora.a2dp_grpc_aio import A2DP from pandora.a2dp_pb2 import STEREO, Configuration, PlaybackAudioRequest, Source @@ -77,6 +80,7 @@ logger = logging.getLogger(__name__) AVDTP_HANDLE_SUSPEND_CFM_BAD_STATE = 'com.android.bluetooth.flags.avdt_handle_suspend_cfm_bad_state' AVDTP_HANDLE_SIGNALING_ON_PEER_FAILURE = 'com.android.bluetooth.flags.avdt_handle_signaling_on_peer_failure' A2DP_SM_IGNORE_CONNECT_EVENTS_IN_CONNECTING_STATE = 'com.android.bluetooth.flags.a2dp_sm_ignore_connect_events_in_connecting_state' +AVDT_WAIT_FOR_INITIAL_DELAY_REPORT_AS_INITIATOR = 'com.android.bluetooth.flags.avdt_wait_for_initial_delay_report_as_initiator' async def initiate_pairing(device, address) -> Connection: @@ -879,6 +883,135 @@ class A2dpTest(base_test.BaseTestClass): # type: ignore[misc] logger.info("<< 6. DUT A2DP source configured and connected >>") + @avatar.asynchronous + @enableFlag(AVDT_WAIT_FOR_INITIAL_DELAY_REPORT_AS_INITIATOR) + async def test_avdt_wait_before_sending_open_command__no_delay_report_sent(self) -> None: + """Test if AOSP DUT will wait for 2 seconds before sending AVDT Open command. + DUT should wait for that time to allow RD1 sink device to send AVDT Delay Report command + before it receives Open command. If the RD1 will send AVDT Delay Report the Open command + will be sent immediately after. In this test the AVDT Delay Report is not sent. + + 1. Pair and connect RD1 + 2. Setup the acceptor expectations on signalling channel + 3. Wait for the RD1 device to send the set configuration response and start timer + 4. Receive open command and assert that it was received after 2s from the timer start + 5. Start streaming - to confirm channel established properly + 6. Stop streaming - to confirm channel established properly + """ + + # Connect and pair RD1. + dut_ref1, ref1_dut = await asyncio.gather( + initiate_pairing(self.dut, self.ref1.address), + accept_pairing(self.ref1, self.dut.address), + ) + + connection = pandora_snippet.get_raw_connection(device=self.ref1, connection=ref1_dut) + channel = SignalingChannel.accept(connection) + + async def accept_open(channel: SignalingChannel): + seid_information = [SeidInformation(acp_seid=0x01, tsep=Tsep.SINK, media_type=AVDTP_AUDIO_MEDIA_TYPE)] + acceptor_service_capabilities = [ + MediaTransportCapability(), + MediaCodecCapability(service_category=ServiceCategory.MEDIA_CODEC, + media_codec_specific_information_elements=[255, 255, 2, 53]), + DelayReportingCapability() + ] + + await channel.accept_discover(seid_information) + await channel.accept_get_all_capabilities(acceptor_service_capabilities) + await channel.accept_set_configuration( + expected_configuration=[MediaTransportCapability(), channel.any, + DelayReportingCapability()]) + + start_time = time.perf_counter() + + cmd = await channel.expect_signal(OpenCommand(transaction_label=channel.any, acp_seid=channel.any)) + + elapsed_time = time.perf_counter() - start_time + assert_greater_equal(elapsed_time, 2.0) + + channel.send_signal(OpenResponse(transaction_label=cmd.transaction_label)) + + # Connect AVDTP to RD1. + _, dut_ref1_source = await asyncio.gather(accept_open(channel), open_source(self.dut, dut_ref1)) + + # Start streaming to RD1. + await asyncio.gather(self.dut.a2dp.Start(source=dut_ref1_source), channel.accept_start()) + + audio = AudioSignal(self.dut.a2dp, dut_ref1_source, 0.8, 44100) + + # Verify that at least one audio frame is received on the transport channel. + await asyncio.wait_for(channel.expect_media(), 5.0) + + # Stop streaming to RD1. + await asyncio.gather(self.dut.a2dp.Suspend(source=dut_ref1_source), channel.accept_suspend()) + + @avatar.asynchronous + @enableFlag(AVDT_WAIT_FOR_INITIAL_DELAY_REPORT_AS_INITIATOR) + async def test_avdt_wait_before_sending_open_command__delay_report_sent(self) -> None: + """Test if AOSP DUT will wait for 2 seconds before sending AVDT Open command. + DUT should wait for that time to allow REF sink device to send AVDT Delay Report command + before it receives Open command. If the REF will send AVDT Delay Report the Open command + will be sent immediately after. In this test the AVDT Delay Report is sent. + + 1. Pair and connect RD1 + 2. Setup the acceptor expectations on signalling channel + 3. Wait for the RD1 device to send the set configuration response and start timer + 4. Wait for the RD1 device to send AVDT Delay Report and expect response + 5. Receive open command on RD1 and assert that it was received before 2s from the timer start + 6. Start streaming - to confirm channel established properly + 7. Stop streaming - to confirm channel established properly + """ + + # Connect and pair RD1. + dut_ref1, ref1_dut = await asyncio.gather( + initiate_pairing(self.dut, self.ref1.address), + accept_pairing(self.ref1, self.dut.address), + ) + + connection = pandora_snippet.get_raw_connection(device=self.ref1, connection=ref1_dut) + channel = SignalingChannel.accept(connection) + + async def accept_open(channel: SignalingChannel): + seid_information = [SeidInformation(acp_seid=0x01, tsep=Tsep.SINK, media_type=AVDTP_AUDIO_MEDIA_TYPE)] + acceptor_service_capabilities = [ + MediaTransportCapability(), + MediaCodecCapability(service_category=ServiceCategory.MEDIA_CODEC, + media_codec_specific_information_elements=[255, 255, 2, 53]), + DelayReportingCapability() + ] + + await channel.accept_discover(seid_information) + await channel.accept_get_all_capabilities(acceptor_service_capabilities) + await channel.accept_set_configuration( + expected_configuration=[MediaTransportCapability(), channel.any, + DelayReportingCapability()]) + + start_time = time.perf_counter() + + await channel.initiate_delay_report() + + cmd = await channel.expect_signal(OpenCommand(transaction_label=channel.any, acp_seid=channel.any)) + + elapsed_time = time.perf_counter() - start_time + assert_less_equal(elapsed_time, 2.0) + + channel.send_signal(OpenResponse(transaction_label=cmd.transaction_label)) + + # Connect AVDTP to RD1. + _, dut_ref1_source = await asyncio.gather(accept_open(channel), open_source(self.dut, dut_ref1)) + + # Start streaming to RD1. + await asyncio.gather(self.dut.a2dp.Start(source=dut_ref1_source), channel.accept_start()) + + audio = AudioSignal(self.dut.a2dp, dut_ref1_source, 0.8, 44100) + + # Verify that at least one audio frame is received on the transport channel. + await asyncio.wait_for(channel.expect_media(), 5.0) + + # Stop streaming to RD1. + await asyncio.gather(self.dut.a2dp.Suspend(source=dut_ref1_source), channel.accept_suspend()) + if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) diff --git a/android/pandora/test/avatar.sh b/android/pandora/test/avatar.sh index cc40cb330b..39c809208d 100755 --- a/android/pandora/test/avatar.sh +++ b/android/pandora/test/avatar.sh @@ -43,7 +43,7 @@ if [[ "$1" =~ ^('format'|'lint'|'run')$ ]]; then [ ! -d "${_VENV_DIR}" ] && python3 -m venv "${_VENV_DIR}" source "${_VENV_DIR}"/bin/activate pip install \ - 'grpcio==1.57' \ + 'grpcio==1.70' \ 'cryptography==35' \ 'numpy==1.25.2' \ 'protobuf==4.24.2' \ diff --git a/android/pandora/test/hap_test.py b/android/pandora/test/hap_test.py index b3d670f852..cc5c1ac7b0 100644 --- a/android/pandora/test/hap_test.py +++ b/android/pandora/test/hap_test.py @@ -26,7 +26,6 @@ from pandora._utils import AioStream from pandora.security_pb2 import LE_LEVEL3 from pandora.host_pb2 import RANDOM, AdvertiseResponse, Connection, DataTypes, ScanningResponse from mobly import base_test, signals -from truth.truth import AssertThat # type: ignore from typing import List, Tuple COMPLETE_LOCAL_NAME: str = "Bumble" @@ -130,9 +129,8 @@ class HapTest(base_test.BaseTestClass): self.dut.aio.host.ConnectLE(own_address_type=RANDOM, **ref.address_asdict()), anext(aiter(advertisement)), ) - AssertThat(dut_ref_res.result_variant()).IsEqualTo('connection') # type: ignore + assert dut_ref_res.result_variant() == 'connection' # type: ignore dut_ref, ref_dut = dut_ref_res.connection, ref_dut_res.connection - AssertThat(dut_ref).IsNotNone() # type: ignore assert dut_ref advertisement.cancel() return dut_ref, ref_dut @@ -149,8 +147,8 @@ class HapTest(base_test.BaseTestClass): self.ref_left.aio.security.WaitSecurity(connection=ref_connection_to_dut, le=LE_LEVEL3), ) - AssertThat(secure.result_variant()).IsEqualTo('success') # type: ignore - AssertThat(wait_security.result_variant()).IsEqualTo('success') # type: ignore + assert secure.result_variant() == 'success' # type: ignore + assert wait_security.result_variant() == 'success' # type: ignore await self.hap_grpc.WaitPeripheral(connection=dut_connection_to_ref) # type: ignore advertisement.cancel() @@ -160,8 +158,7 @@ class HapTest(base_test.BaseTestClass): async def assertIdenticalPreset(self, dut_connection_to_ref: Connection) -> None: remote_preset = toBumblePresetList( (await self.hap_grpc.GetAllPresetRecords(connection=dut_connection_to_ref)).preset_record_list) - AssertThat(remote_preset).ContainsExactlyElementsIn( # type: ignore - get_server_preset_sorted(self.has)).InOrder() # type: ignore + assert remote_preset == get_server_preset_sorted(self.has) async def verify_no_crash(self, dut_connection_to_ref: Connection) -> None: ''' Periodically check that there is no android crash ''' @@ -176,7 +173,7 @@ class HapTest(base_test.BaseTestClass): features = hap.HearingAidFeatures_from_bytes( (await self.hap_grpc.GetFeatures(connection=dut_connection_to_ref)).features) - AssertThat(features).IsEqualTo(self.has.server_features) # type: ignore + assert features == self.has.server_features # type: ignore @asynchronous async def test_get_preset(self) -> None: @@ -220,12 +217,10 @@ class HapTest(base_test.BaseTestClass): async def test__set_non_existing_preset_as_active__verify_no_crash_and_no_update(self) -> None: await self.logcat.Log("test__set_non_existing_preset_as_active__verify_no_crash_and_no_update") non_existing_preset_index = 79 - AssertThat(non_existing_preset_index).IsNotIn(self.has.preset_records.keys()) # type: ignore + assert non_existing_preset_index not in self.has.preset_records.keys() # type: ignore dut_connection_to_ref = await self.setupHapConnection() - AssertThat( - toBumblePreset( # type: ignore - (await self.hap_grpc.GetActivePresetRecord(connection=dut_connection_to_ref - )).preset_record)).IsEqualTo(foo_preset) + assert foo_preset == toBumblePreset( # type: ignore + (await self.hap_grpc.GetActivePresetRecord(connection=dut_connection_to_ref)).preset_record) await self.logcat.Log("Notify active update to non existing index") # bypass the set_active_preset checks by sending an invalid index on purpose @@ -233,16 +228,14 @@ class HapTest(base_test.BaseTestClass): await self.has.notify_active_preset() await self.verify_no_crash(dut_connection_to_ref) - AssertThat( - toBumblePreset( # type: ignore - (await self.hap_grpc.GetActivePresetRecord(connection=dut_connection_to_ref - )).preset_record)).IsEqualTo(foo_preset) + assert foo_preset == toBumblePreset( + (await self.hap_grpc.GetActivePresetRecord(connection=dut_connection_to_ref)).preset_record) @asynchronous async def test__set_non_existing_preset_as_available__verify_no_crash_and_no_update(self) -> None: await self.logcat.Log("test__set_non_existing_preset_as_available__verify_no_crash_and_no_update") non_existing_preset_index = 79 - AssertThat(non_existing_preset_index).IsNotIn(self.has.preset_records.keys()) # type: ignore + assert non_existing_preset_index not in self.has.preset_records.keys() dut_connection_to_ref = await self.setupHapConnection() await self.logcat.Log("Notify available preset to non existing index") diff --git a/apex/Android.bp b/apex/Android.bp index d8f4603a8c..9d8393da78 100644 --- a/apex/Android.bp +++ b/apex/Android.bp @@ -123,7 +123,6 @@ bootclasspath_fragment { // Additional hidden API flag files to override the defaults. This must only be // modified by the Soong or platform compat team. hidden_api: { - max_target_o_low_priority: ["hiddenapi/hiddenapi-max-target-o-low-priority.txt"], max_target_r_low_priority: ["hiddenapi/hiddenapi-max-target-r-low-priority.txt"], unsupported: ["hiddenapi/hiddenapi-unsupported.txt"], 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/apex/hiddenapi/hiddenapi-max-target-o-low-priority.txt b/apex/hiddenapi/hiddenapi-max-target-o-low-priority.txt deleted file mode 100644 index 994008b9ea..0000000000 --- a/apex/hiddenapi/hiddenapi-max-target-o-low-priority.txt +++ /dev/null @@ -1,2806 +0,0 @@ -Landroid/bluetooth/BluetoothA2dp;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothA2dp;->ACTION_AVRCP_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dp;->DBG:Z -Landroid/bluetooth/BluetoothA2dp;->doBind()Z -Landroid/bluetooth/BluetoothA2dp;->enableDisableOptionalCodecs(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/BluetoothA2dp;->isAvrcpAbsoluteVolumeSupported()Z -Landroid/bluetooth/BluetoothA2dp;->isEnabled()Z -Landroid/bluetooth/BluetoothA2dp;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothA2dp;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothA2dp;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothA2dp;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothA2dp;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothA2dp;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothA2dp;->mService:Landroid/bluetooth/IBluetoothA2dp; -Landroid/bluetooth/BluetoothA2dp;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothA2dp;->mServiceLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; -Landroid/bluetooth/BluetoothA2dp;->setAvrcpAbsoluteVolume(I)V -Landroid/bluetooth/BluetoothA2dp;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothA2dp;->shouldSendVolumeKeys(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothA2dp;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dp;->VDBG:Z -Landroid/bluetooth/BluetoothA2dpSink;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothA2dpSink;->ACTION_AUDIO_CONFIG_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->ACTION_PLAYING_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->close()V -Landroid/bluetooth/BluetoothA2dpSink;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothA2dpSink;->DBG:Z -Landroid/bluetooth/BluetoothA2dpSink;->doBind()Z -Landroid/bluetooth/BluetoothA2dpSink;->EXTRA_AUDIO_CONFIG:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->getAudioConfig(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAudioConfig; -Landroid/bluetooth/BluetoothA2dpSink;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothA2dpSink;->isA2dpPlaying(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothA2dpSink;->isEnabled()Z -Landroid/bluetooth/BluetoothA2dpSink;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothA2dpSink;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothA2dpSink;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothA2dpSink;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothA2dpSink;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothA2dpSink;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothA2dpSink;->mService:Landroid/bluetooth/IBluetoothA2dpSink; -Landroid/bluetooth/BluetoothA2dpSink;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothA2dpSink;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothA2dpSink;->stateToString(I)Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->STATE_NOT_PLAYING:I -Landroid/bluetooth/BluetoothA2dpSink;->STATE_PLAYING:I -Landroid/bluetooth/BluetoothA2dpSink;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothA2dpSink;->VDBG:Z -Landroid/bluetooth/BluetoothActivityEnergyInfo;-><init>(JIJJJJ)V -Landroid/bluetooth/BluetoothActivityEnergyInfo;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothActivityEnergyInfo;->BT_STACK_STATE_INVALID:I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->BT_STACK_STATE_STATE_ACTIVE:I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->BT_STACK_STATE_STATE_IDLE:I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->BT_STACK_STATE_STATE_SCANNING:I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getBluetoothStackState()I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getControllerEnergyUsed()J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getControllerIdleTimeMillis()J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getControllerRxTimeMillis()J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getControllerTxTimeMillis()J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getTimeStamp()J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->getUidTraffic()[Landroid/bluetooth/UidTraffic; -Landroid/bluetooth/BluetoothActivityEnergyInfo;->isValid()Z -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mBluetoothStackState:I -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mControllerEnergyUsed:J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mControllerIdleTimeMs:J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mControllerRxTimeMs:J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mControllerTxTimeMs:J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mTimestamp:J -Landroid/bluetooth/BluetoothActivityEnergyInfo;->mUidTraffic:[Landroid/bluetooth/UidTraffic; -Landroid/bluetooth/BluetoothActivityEnergyInfo;->setUidTraffic([Landroid/bluetooth/UidTraffic;)V -Landroid/bluetooth/BluetoothAdapter$BluetoothStateChangeCallback;->onBluetoothStateChange(Z)V -Landroid/bluetooth/BluetoothAdapter$StateChangeCallbackWrapper;->mCallback:Landroid/bluetooth/BluetoothAdapter$BluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothAdapter$StateChangeCallbackWrapper;->onBluetoothStateChange(Z)V -Landroid/bluetooth/BluetoothAdapter;-><init>(Landroid/bluetooth/IBluetoothManager;)V -Landroid/bluetooth/BluetoothAdapter;->ACTION_BLE_ACL_CONNECTED:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->ACTION_BLE_ACL_DISCONNECTED:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->ACTION_BLUETOOTH_ADDRESS_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->ACTION_REQUEST_DISABLE:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->ADDRESS_LENGTH:I -Landroid/bluetooth/BluetoothAdapter;->BLUETOOTH_MANAGER_SERVICE:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->changeApplicationBluetoothState(ZLandroid/bluetooth/BluetoothAdapter$BluetoothStateChangeCallback;)Z -Landroid/bluetooth/BluetoothAdapter;->createNewRfcommSocketAndRecord(Ljava/lang/String;Ljava/util/UUID;ZZ)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->DBG:Z -Landroid/bluetooth/BluetoothAdapter;->DEFAULT_MAC_ADDRESS:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->EXTRA_BLUETOOTH_ADDRESS:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->getBluetoothClass()Landroid/bluetooth/BluetoothClass; -Landroid/bluetooth/BluetoothAdapter;->getControllerActivityEnergyInfo(I)Landroid/bluetooth/BluetoothActivityEnergyInfo; -Landroid/bluetooth/BluetoothAdapter;->getDiscoveryEndMillis()J -Landroid/bluetooth/BluetoothAdapter;->getLeAccess()Z -Landroid/bluetooth/BluetoothAdapter;->getMaxConnectedAudioDevices()I -Landroid/bluetooth/BluetoothAdapter;->getPeriodicAdvertisingManager()Landroid/bluetooth/le/PeriodicAdvertisingManager; -Landroid/bluetooth/BluetoothAdapter;->getSupportedProfiles()Ljava/util/List; -Landroid/bluetooth/BluetoothAdapter;->isHardwareTrackingFiltersAvailable()Z -Landroid/bluetooth/BluetoothAdapter;->LE_PSM_CHARACTERISTIC_UUID:Ljava/util/UUID; -Landroid/bluetooth/BluetoothAdapter;->listenUsingEncryptedRfcommOn(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingInsecureL2capCoc(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingInsecureL2capOn(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingInsecureRfcommOn(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingL2capCoc(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingL2capOn(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingL2capOn(IZZ)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingRfcommOn(I)Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->listenUsingScoOn()Landroid/bluetooth/BluetoothServerSocket; -Landroid/bluetooth/BluetoothAdapter;->mLeScanClients:Ljava/util/Map; -Landroid/bluetooth/BluetoothAdapter;->mLock:Ljava/lang/Object; -Landroid/bluetooth/BluetoothAdapter;->mManagerCallback:Landroid/bluetooth/IBluetoothManagerCallback; -Landroid/bluetooth/BluetoothAdapter;->mManagerService:Landroid/bluetooth/IBluetoothManager; -Landroid/bluetooth/BluetoothAdapter;->mProxyServiceStateCallbacks:Ljava/util/ArrayList; -Landroid/bluetooth/BluetoothAdapter;->mServiceLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; -Landroid/bluetooth/BluetoothAdapter;->mToken:Landroid/os/IBinder; -Landroid/bluetooth/BluetoothAdapter;->nameForState(I)Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->readOutOfBandData()Landroid/util/Pair; -Landroid/bluetooth/BluetoothAdapter;->removeServiceStateCallback(Landroid/bluetooth/IBluetoothManagerCallback;)V -Landroid/bluetooth/BluetoothAdapter;->requestControllerActivityEnergyInfo(Landroid/os/ResultReceiver;)V -Landroid/bluetooth/BluetoothAdapter;->sAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothAdapter;->sBluetoothLeAdvertiser:Landroid/bluetooth/le/BluetoothLeAdvertiser; -Landroid/bluetooth/BluetoothAdapter;->sBluetoothLeScanner:Landroid/bluetooth/le/BluetoothLeScanner; -Landroid/bluetooth/BluetoothAdapter;->setBluetoothClass(Landroid/bluetooth/BluetoothClass;)Z -Landroid/bluetooth/BluetoothAdapter;->SOCKET_CHANNEL_AUTO_STATIC_NO_SDP:I -Landroid/bluetooth/BluetoothAdapter;->sPeriodicAdvertisingManager:Landroid/bluetooth/le/PeriodicAdvertisingManager; -Landroid/bluetooth/BluetoothAdapter;->STATE_BLE_ON:I -Landroid/bluetooth/BluetoothAdapter;->STATE_BLE_TURNING_OFF:I -Landroid/bluetooth/BluetoothAdapter;->STATE_BLE_TURNING_ON:I -Landroid/bluetooth/BluetoothAdapter;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothAdapter;->toDeviceSet([Landroid/bluetooth/BluetoothDevice;)Ljava/util/Set; -Landroid/bluetooth/BluetoothAdapter;->VDBG:Z -Landroid/bluetooth/BluetoothAssignedNumbers;-><init>()V -Landroid/bluetooth/BluetoothAudioConfig;-><init>(III)V -Landroid/bluetooth/BluetoothAudioConfig;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothAudioConfig;->getAudioFormat()I -Landroid/bluetooth/BluetoothAudioConfig;->getChannelConfig()I -Landroid/bluetooth/BluetoothAudioConfig;->getSampleRate()I -Landroid/bluetooth/BluetoothAudioConfig;->mAudioFormat:I -Landroid/bluetooth/BluetoothAudioConfig;->mChannelConfig:I -Landroid/bluetooth/BluetoothAudioConfig;->mSampleRate:I -Landroid/bluetooth/BluetoothAvrcp;-><init>()V -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_0:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_1:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_2:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_3:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_4:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_5:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_6:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_7:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_8:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_9:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_ANGLE:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_BACKWARD:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_CHAN_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_CHAN_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_CLEAR:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_CONT_MENU:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_DISP_INFO:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_DOT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_EJECT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_ENTER:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_EXIT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_F1:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_F2:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_F3:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_F4:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_F5:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_FAST_FOR:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_FAV_MENU:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_FORWARD:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_HELP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_INPUT_SEL:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_LEFT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_LEFT_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_LEFT_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_MUTE:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_PAGE_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_PAGE_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_PAUSE:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_PLAY:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_POWER:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_PREV_CHAN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_RECORD:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_REWIND:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_RIGHT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_RIGHT_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_RIGHT_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_ROOT_MENU:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_SELECT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_SETUP_MENU:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_SOUND_SEL:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_STOP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_SUBPICT:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_VENDOR:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_VOL_DOWN:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_ID_VOL_UP:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_KEYPRESSED_RELEASE:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_STATE_PRESS:I -Landroid/bluetooth/BluetoothAvrcp;->PASSTHROUGH_STATE_RELEASE:I -Landroid/bluetooth/BluetoothAvrcpController;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothAvrcpController;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothAvrcpController;->ACTION_PLAYER_SETTING:Ljava/lang/String; -Landroid/bluetooth/BluetoothAvrcpController;->close()V -Landroid/bluetooth/BluetoothAvrcpController;->DBG:Z -Landroid/bluetooth/BluetoothAvrcpController;->doBind()Z -Landroid/bluetooth/BluetoothAvrcpController;->EXTRA_PLAYER_SETTING:Ljava/lang/String; -Landroid/bluetooth/BluetoothAvrcpController;->getPlayerSettings(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAvrcpPlayerSettings; -Landroid/bluetooth/BluetoothAvrcpController;->isEnabled()Z -Landroid/bluetooth/BluetoothAvrcpController;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothAvrcpController;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothAvrcpController;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothAvrcpController;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothAvrcpController;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothAvrcpController;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothAvrcpController;->mService:Landroid/bluetooth/IBluetoothAvrcpController; -Landroid/bluetooth/BluetoothAvrcpController;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothAvrcpController;->sendGroupNavigationCmd(Landroid/bluetooth/BluetoothDevice;II)V -Landroid/bluetooth/BluetoothAvrcpController;->setPlayerApplicationSetting(Landroid/bluetooth/BluetoothAvrcpPlayerSettings;)Z -Landroid/bluetooth/BluetoothAvrcpController;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothAvrcpController;->VDBG:Z -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;-><init>(I)V -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->addSettingValue(II)V -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->getSettings()I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->getSettingValue(I)I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->mSettings:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->mSettingsValue:Ljava/util/Map; -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->SETTING_EQUALIZER:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->SETTING_REPEAT:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->SETTING_SCAN:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->SETTING_SHUFFLE:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_ALL_TRACK:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_GROUP:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_INVALID:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_OFF:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_ON:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->STATE_SINGLE_TRACK:I -Landroid/bluetooth/BluetoothAvrcpPlayerSettings;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothClass$Device$Major;->BITMASK:I -Landroid/bluetooth/BluetoothClass$Device;->BITMASK:I -Landroid/bluetooth/BluetoothClass$Device;->PERIPHERAL_KEYBOARD:I -Landroid/bluetooth/BluetoothClass$Device;->PERIPHERAL_KEYBOARD_POINTING:I -Landroid/bluetooth/BluetoothClass$Device;->PERIPHERAL_NON_KEYBOARD_NON_POINTING:I -Landroid/bluetooth/BluetoothClass$Device;->PERIPHERAL_POINTING:I -Landroid/bluetooth/BluetoothClass$Service;->BITMASK:I -Landroid/bluetooth/BluetoothClass;->ERROR:I -Landroid/bluetooth/BluetoothClass;->getClassOfDevice()I -Landroid/bluetooth/BluetoothClass;->getClassOfDeviceBytes()[B -Landroid/bluetooth/BluetoothClass;->mClass:I -Landroid/bluetooth/BluetoothClass;->PROFILE_A2DP_SINK:I -Landroid/bluetooth/BluetoothClass;->PROFILE_HID:I -Landroid/bluetooth/BluetoothClass;->PROFILE_NAP:I -Landroid/bluetooth/BluetoothClass;->PROFILE_OPP:I -Landroid/bluetooth/BluetoothClass;->PROFILE_PANU:I -Landroid/bluetooth/BluetoothCodecConfig;->appendCapabilityToString(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String; -Landroid/bluetooth/BluetoothCodecConfig;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothCodecConfig;->getCodecName()Ljava/lang/String; -Landroid/bluetooth/BluetoothCodecConfig;->isMandatoryCodec()Z -Landroid/bluetooth/BluetoothCodecConfig;->isValid()Z -Landroid/bluetooth/BluetoothCodecConfig;->mBitsPerSample:I -Landroid/bluetooth/BluetoothCodecConfig;->mChannelMode:I -Landroid/bluetooth/BluetoothCodecConfig;->mCodecPriority:I -Landroid/bluetooth/BluetoothCodecConfig;->mCodecSpecific1:J -Landroid/bluetooth/BluetoothCodecConfig;->mCodecSpecific2:J -Landroid/bluetooth/BluetoothCodecConfig;->mCodecSpecific3:J -Landroid/bluetooth/BluetoothCodecConfig;->mCodecSpecific4:J -Landroid/bluetooth/BluetoothCodecConfig;->mCodecType:I -Landroid/bluetooth/BluetoothCodecConfig;->mSampleRate:I -Landroid/bluetooth/BluetoothCodecConfig;->sameAudioFeedingParameters(Landroid/bluetooth/BluetoothCodecConfig;)Z -Landroid/bluetooth/BluetoothCodecStatus;-><init>(Landroid/bluetooth/BluetoothCodecConfig;[Landroid/bluetooth/BluetoothCodecConfig;[Landroid/bluetooth/BluetoothCodecConfig;)V -Landroid/bluetooth/BluetoothCodecStatus;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothCodecStatus;->mCodecConfig:Landroid/bluetooth/BluetoothCodecConfig; -Landroid/bluetooth/BluetoothCodecStatus;->mCodecsLocalCapabilities:[Landroid/bluetooth/BluetoothCodecConfig; -Landroid/bluetooth/BluetoothCodecStatus;->mCodecsSelectableCapabilities:[Landroid/bluetooth/BluetoothCodecConfig; -Landroid/bluetooth/BluetoothCodecStatus;->sameCapabilities([Landroid/bluetooth/BluetoothCodecConfig;[Landroid/bluetooth/BluetoothCodecConfig;)Z -Landroid/bluetooth/BluetoothDevice;->ACTION_BATTERY_LEVEL_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->ACTION_CONNECTION_ACCESS_CANCEL:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->ACTION_CONNECTION_ACCESS_REPLY:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->ACTION_CONNECTION_ACCESS_REQUEST:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->ACTION_MAS_INSTANCE:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->ACTION_NAME_FAILED:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->BATTERY_LEVEL_UNKNOWN:I -Landroid/bluetooth/BluetoothDevice;->BOND_SUCCESS:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_ACCESS_NO:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_ACCESS_YES:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_STATE_CONNECTED:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_STATE_DISCONNECTED:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_STATE_ENCRYPTED_BREDR:I -Landroid/bluetooth/BluetoothDevice;->CONNECTION_STATE_ENCRYPTED_LE:I -Landroid/bluetooth/BluetoothDevice;->createBondOutOfBand(ILandroid/bluetooth/OobData;)Z -Landroid/bluetooth/BluetoothDevice;->createInsecureL2capCocSocket(II)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothDevice;->createInsecureL2capSocket(I)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothDevice;->createL2capCocSocket(II)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothDevice;->createL2capSocket(I)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothDevice;->DBG:Z -Landroid/bluetooth/BluetoothDevice;->EXTRA_ACCESS_REQUEST_TYPE:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_ALWAYS_ALLOWED:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_BATTERY_LEVEL:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_CLASS_NAME:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_CONNECTION_ACCESS_RESULT:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_MAS_INSTANCE:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_PACKAGE_NAME:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->EXTRA_SDP_RECORD:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->getSimAccessPermission()I -Landroid/bluetooth/BluetoothDevice;->isBluetoothEnabled()Z -Landroid/bluetooth/BluetoothDevice;->mAddress:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_CONSENT:I -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_DISPLAY_PASSKEY:I -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_DISPLAY_PIN:I -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_OOB_CONSENT:I -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_PASSKEY:I -Landroid/bluetooth/BluetoothDevice;->PAIRING_VARIANT_PIN_16_DIGITS:I -Landroid/bluetooth/BluetoothDevice;->REQUEST_TYPE_MESSAGE_ACCESS:I -Landroid/bluetooth/BluetoothDevice;->REQUEST_TYPE_PHONEBOOK_ACCESS:I -Landroid/bluetooth/BluetoothDevice;->REQUEST_TYPE_PROFILE_CONNECTION:I -Landroid/bluetooth/BluetoothDevice;->REQUEST_TYPE_SIM_ACCESS:I -Landroid/bluetooth/BluetoothDevice;->sdpSearch(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothDevice;->setDeviceOutOfBandData([B[B)Z -Landroid/bluetooth/BluetoothDevice;->setRemoteOutOfBandData()Z -Landroid/bluetooth/BluetoothDevice;->sService:Landroid/bluetooth/IBluetooth; -Landroid/bluetooth/BluetoothDevice;->sStateChangeCallback:Landroid/bluetooth/IBluetoothManagerCallback; -Landroid/bluetooth/BluetoothDevice;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevice;->UNBOND_REASON_AUTH_CANCELED:I -Landroid/bluetooth/BluetoothDevice;->UNBOND_REASON_REMOVED:I -Landroid/bluetooth/BluetoothDevicePicker;->ACTION_DEVICE_SELECTED:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->ACTION_LAUNCH:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->EXTRA_FILTER_TYPE:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->EXTRA_LAUNCH_CLASS:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->EXTRA_LAUNCH_PACKAGE:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->EXTRA_NEED_AUTH:Ljava/lang/String; -Landroid/bluetooth/BluetoothDevicePicker;->FILTER_TYPE_ALL:I -Landroid/bluetooth/BluetoothDevicePicker;->FILTER_TYPE_AUDIO:I -Landroid/bluetooth/BluetoothDevicePicker;->FILTER_TYPE_NAP:I -Landroid/bluetooth/BluetoothDevicePicker;->FILTER_TYPE_PANU:I -Landroid/bluetooth/BluetoothDevicePicker;->FILTER_TYPE_TRANSFER:I -Landroid/bluetooth/BluetoothGatt;-><init>(Landroid/bluetooth/IBluetoothGatt;Landroid/bluetooth/BluetoothDevice;IZI)V -Landroid/bluetooth/BluetoothGatt;->AUTHENTICATION_MITM:I -Landroid/bluetooth/BluetoothGatt;->AUTHENTICATION_NONE:I -Landroid/bluetooth/BluetoothGatt;->AUTHENTICATION_NO_MITM:I -Landroid/bluetooth/BluetoothGatt;->AUTH_RETRY_STATE_IDLE:I -Landroid/bluetooth/BluetoothGatt;->AUTH_RETRY_STATE_MITM:I -Landroid/bluetooth/BluetoothGatt;->AUTH_RETRY_STATE_NO_MITM:I -Landroid/bluetooth/BluetoothGatt;->CONN_STATE_CLOSED:I -Landroid/bluetooth/BluetoothGatt;->CONN_STATE_CONNECTED:I -Landroid/bluetooth/BluetoothGatt;->CONN_STATE_CONNECTING:I -Landroid/bluetooth/BluetoothGatt;->CONN_STATE_DISCONNECTING:I -Landroid/bluetooth/BluetoothGatt;->CONN_STATE_IDLE:I -Landroid/bluetooth/BluetoothGatt;->DBG:Z -Landroid/bluetooth/BluetoothGatt;->discoverServiceByUuid(Ljava/util/UUID;)Z -Landroid/bluetooth/BluetoothGatt;->getCharacteristicById(Landroid/bluetooth/BluetoothDevice;I)Landroid/bluetooth/BluetoothGattCharacteristic; -Landroid/bluetooth/BluetoothGatt;->getDescriptorById(Landroid/bluetooth/BluetoothDevice;I)Landroid/bluetooth/BluetoothGattDescriptor; -Landroid/bluetooth/BluetoothGatt;->getService(Landroid/bluetooth/BluetoothDevice;Ljava/util/UUID;I)Landroid/bluetooth/BluetoothGattService; -Landroid/bluetooth/BluetoothGatt;->mBluetoothGattCallback:Landroid/bluetooth/IBluetoothGattCallback; -Landroid/bluetooth/BluetoothGatt;->mConnState:I -Landroid/bluetooth/BluetoothGatt;->mDevice:Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothGatt;->mHandler:Landroid/os/Handler; -Landroid/bluetooth/BluetoothGatt;->mOpportunistic:Z -Landroid/bluetooth/BluetoothGatt;->mPhy:I -Landroid/bluetooth/BluetoothGatt;->mServices:Ljava/util/List; -Landroid/bluetooth/BluetoothGatt;->mStateLock:Ljava/lang/Object; -Landroid/bluetooth/BluetoothGatt;->readUsingCharacteristicUuid(Ljava/util/UUID;II)Z -Landroid/bluetooth/BluetoothGatt;->registerApp(Landroid/bluetooth/BluetoothGattCallback;Landroid/os/Handler;)Z -Landroid/bluetooth/BluetoothGatt;->requestLeConnectionUpdate(IIIIII)Z -Landroid/bluetooth/BluetoothGatt;->runOrQueueCallback(Ljava/lang/Runnable;)V -Landroid/bluetooth/BluetoothGatt;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothGatt;->VDBG:Z -Landroid/bluetooth/BluetoothGattCallback;->onConnectionUpdated(Landroid/bluetooth/BluetoothGatt;IIII)V -Landroid/bluetooth/BluetoothGattCharacteristic;-><init>(Landroid/bluetooth/BluetoothGattService;Ljava/util/UUID;III)V -Landroid/bluetooth/BluetoothGattCharacteristic;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothGattCharacteristic;-><init>(Ljava/util/UUID;III)V -Landroid/bluetooth/BluetoothGattCharacteristic;->bytesToFloat(BB)F -Landroid/bluetooth/BluetoothGattCharacteristic;->bytesToFloat(BBBB)F -Landroid/bluetooth/BluetoothGattCharacteristic;->getDescriptor(Ljava/util/UUID;I)Landroid/bluetooth/BluetoothGattDescriptor; -Landroid/bluetooth/BluetoothGattCharacteristic;->getKeySize()I -Landroid/bluetooth/BluetoothGattCharacteristic;->getTypeLen(I)I -Landroid/bluetooth/BluetoothGattCharacteristic;->initCharacteristic(Landroid/bluetooth/BluetoothGattService;Ljava/util/UUID;III)V -Landroid/bluetooth/BluetoothGattCharacteristic;->intToSignedBits(II)I -Landroid/bluetooth/BluetoothGattCharacteristic;->mKeySize:I -Landroid/bluetooth/BluetoothGattCharacteristic;->mPermissions:I -Landroid/bluetooth/BluetoothGattCharacteristic;->mProperties:I -Landroid/bluetooth/BluetoothGattCharacteristic;->mUuid:Ljava/util/UUID; -Landroid/bluetooth/BluetoothGattCharacteristic;->mValue:[B -Landroid/bluetooth/BluetoothGattCharacteristic;->mWriteType:I -Landroid/bluetooth/BluetoothGattCharacteristic;->setInstanceId(I)V -Landroid/bluetooth/BluetoothGattCharacteristic;->unsignedBytesToInt(BB)I -Landroid/bluetooth/BluetoothGattCharacteristic;->unsignedBytesToInt(BBBB)I -Landroid/bluetooth/BluetoothGattCharacteristic;->unsignedByteToInt(B)I -Landroid/bluetooth/BluetoothGattCharacteristic;->unsignedToSigned(II)I -Landroid/bluetooth/BluetoothGattDescriptor;-><init>(Landroid/bluetooth/BluetoothGattCharacteristic;Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattDescriptor;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothGattDescriptor;-><init>(Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattDescriptor;->getInstanceId()I -Landroid/bluetooth/BluetoothGattDescriptor;->initDescriptor(Landroid/bluetooth/BluetoothGattCharacteristic;Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattDescriptor;->mPermissions:I -Landroid/bluetooth/BluetoothGattDescriptor;->mUuid:Ljava/util/UUID; -Landroid/bluetooth/BluetoothGattDescriptor;->mValue:[B -Landroid/bluetooth/BluetoothGattDescriptor;->setInstanceId(I)V -Landroid/bluetooth/BluetoothGattIncludedService;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothGattIncludedService;-><init>(Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattIncludedService;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothGattIncludedService;->getInstanceId()I -Landroid/bluetooth/BluetoothGattIncludedService;->getType()I -Landroid/bluetooth/BluetoothGattIncludedService;->getUuid()Ljava/util/UUID; -Landroid/bluetooth/BluetoothGattIncludedService;->mInstanceId:I -Landroid/bluetooth/BluetoothGattIncludedService;->mServiceType:I -Landroid/bluetooth/BluetoothGattIncludedService;->mUuid:Ljava/util/UUID; -Landroid/bluetooth/BluetoothGattServer;-><init>(Landroid/bluetooth/IBluetoothGatt;I)V -Landroid/bluetooth/BluetoothGattServer;->CALLBACK_REG_TIMEOUT:I -Landroid/bluetooth/BluetoothGattServer;->DBG:Z -Landroid/bluetooth/BluetoothGattServer;->getCharacteristicByHandle(I)Landroid/bluetooth/BluetoothGattCharacteristic; -Landroid/bluetooth/BluetoothGattServer;->getDescriptorByHandle(I)Landroid/bluetooth/BluetoothGattDescriptor; -Landroid/bluetooth/BluetoothGattServer;->getService(Ljava/util/UUID;II)Landroid/bluetooth/BluetoothGattService; -Landroid/bluetooth/BluetoothGattServer;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothGattServer;->mBluetoothGattServerCallback:Landroid/bluetooth/IBluetoothGattServerCallback; -Landroid/bluetooth/BluetoothGattServer;->mCallback:Landroid/bluetooth/BluetoothGattServerCallback; -Landroid/bluetooth/BluetoothGattServer;->mPendingService:Landroid/bluetooth/BluetoothGattService; -Landroid/bluetooth/BluetoothGattServer;->mServerIf:I -Landroid/bluetooth/BluetoothGattServer;->mServerIfLock:Ljava/lang/Object; -Landroid/bluetooth/BluetoothGattServer;->mService:Landroid/bluetooth/IBluetoothGatt; -Landroid/bluetooth/BluetoothGattServer;->mServices:Ljava/util/List; -Landroid/bluetooth/BluetoothGattServer;->mTransport:I -Landroid/bluetooth/BluetoothGattServer;->registerCallback(Landroid/bluetooth/BluetoothGattServerCallback;)Z -Landroid/bluetooth/BluetoothGattServer;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothGattServer;->unregisterCallback()V -Landroid/bluetooth/BluetoothGattServer;->VDBG:Z -Landroid/bluetooth/BluetoothGattServerCallback;->onConnectionUpdated(Landroid/bluetooth/BluetoothDevice;IIII)V -Landroid/bluetooth/BluetoothGattService;-><init>(Landroid/bluetooth/BluetoothDevice;Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattService;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/BluetoothGattService;-><init>(Ljava/util/UUID;II)V -Landroid/bluetooth/BluetoothGattService;->addIncludedService(Landroid/bluetooth/BluetoothGattService;)V -Landroid/bluetooth/BluetoothGattService;->getCharacteristic(Ljava/util/UUID;I)Landroid/bluetooth/BluetoothGattCharacteristic; -Landroid/bluetooth/BluetoothGattService;->getDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothGattService;->getHandles()I -Landroid/bluetooth/BluetoothGattService;->isAdvertisePreferred()Z -Landroid/bluetooth/BluetoothGattService;->mAdvertisePreferred:Z -Landroid/bluetooth/BluetoothGattService;->mHandles:I -Landroid/bluetooth/BluetoothGattService;->mInstanceId:I -Landroid/bluetooth/BluetoothGattService;->mServiceType:I -Landroid/bluetooth/BluetoothGattService;->mUuid:Ljava/util/UUID; -Landroid/bluetooth/BluetoothGattService;->setDevice(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/BluetoothGattService;->setHandles(I)V -Landroid/bluetooth/BluetoothHeadset;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHeadset;->ACTION_HF_INDICATORS_VALUE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->clccResponse(IIIIZLjava/lang/String;I)V -Landroid/bluetooth/BluetoothHeadset;->DBG:Z -Landroid/bluetooth/BluetoothHeadset;->doBind()Z -Landroid/bluetooth/BluetoothHeadset;->doUnbind()V -Landroid/bluetooth/BluetoothHeadset;->EXTRA_HF_INDICATORS_IND_ID:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->EXTRA_HF_INDICATORS_IND_VALUE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->getAudioRouteAllowed()Z -Landroid/bluetooth/BluetoothHeadset;->isAudioOn()Z -Landroid/bluetooth/BluetoothHeadset;->isBluetoothVoiceDialingEnabled(Landroid/content/Context;)Z -Landroid/bluetooth/BluetoothHeadset;->isDisabled()Z -Landroid/bluetooth/BluetoothHeadset;->isInbandRingingEnabled()Z -Landroid/bluetooth/BluetoothHeadset;->isInbandRingingSupported(Landroid/content/Context;)Z -Landroid/bluetooth/BluetoothHeadset;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadset;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHeadset;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHeadset;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHeadset;->mConnection:Landroid/bluetooth/IBluetoothProfileServiceConnection; -Landroid/bluetooth/BluetoothHeadset;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHeadset;->MESSAGE_HEADSET_SERVICE_CONNECTED:I -Landroid/bluetooth/BluetoothHeadset;->MESSAGE_HEADSET_SERVICE_DISCONNECTED:I -Landroid/bluetooth/BluetoothHeadset;->mHandler:Landroid/os/Handler; -Landroid/bluetooth/BluetoothHeadset;->mService:Landroid/bluetooth/IBluetoothHeadset; -Landroid/bluetooth/BluetoothHeadset;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHeadset;->setAudioRouteAllowed(Z)V -Landroid/bluetooth/BluetoothHeadset;->setForceScoAudio(Z)V -Landroid/bluetooth/BluetoothHeadset;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->VDBG:Z -Landroid/bluetooth/BluetoothHeadset;->VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->VENDOR_SPECIFIC_HEADSET_EVENT_IPHONEACCEV_BATTERY_LEVEL:I -Landroid/bluetooth/BluetoothHeadset;->VENDOR_SPECIFIC_HEADSET_EVENT_XAPL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->VENDOR_SPECIFIC_HEADSET_EVENT_XEVENT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadset;->VENDOR_SPECIFIC_HEADSET_EVENT_XEVENT_BATTERY_LEVEL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_AG_EVENT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_AUDIO_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_CALL_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_LAST_VTAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_BLACKLISTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_BUSY:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_CME:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_DELAYED:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_NO_ANSWER:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_ERROR_NO_CARRIER:I -Landroid/bluetooth/BluetoothHeadsetClient;->ACTION_RESULT_OK:I -Landroid/bluetooth/BluetoothHeadsetClient;->CALL_ACCEPT_HOLD:I -Landroid/bluetooth/BluetoothHeadsetClient;->CALL_ACCEPT_NONE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CALL_ACCEPT_TERMINATE:I -Landroid/bluetooth/BluetoothHeadsetClient;->close()V -Landroid/bluetooth/BluetoothHeadsetClient;->CME_CORPORATE_PERSONALIZATION_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_CORPORATE_PERSONALIZATION_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_DIAL_STRING_TOO_LONG:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_EAP_NOT_SUPPORTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_EMERGENCY_SERVICE_ONLY:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_HIDDEN_KEY_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_INCORRECT_PARAMETERS:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_INCORRECT_PASSWORD:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_INVALID_CHARACTER_IN_DIAL_STRING:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_INVALID_CHARACTER_IN_TEXT_STRING:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_INVALID_INDEX:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_MEMORY_FAILURE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_MEMORY_FULL:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NETWORK_PERSONALIZATION_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NETWORK_PERSONALIZATION_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NETWORK_SUBSET_PERSONALIZATION_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NETWORK_SUBSET_PERSONALIZATION_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NETWORK_TIMEOUT:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NOT_FOUND:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NOT_SUPPORTED_FOR_VOIP:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NO_CONNECTION_TO_PHONE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NO_NETWORK_SERVICE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_NO_SIMULTANOUS_VOIP_CS_CALLS:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_OPERATION_NOT_ALLOWED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_OPERATION_NOT_SUPPORTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_PHFSIM_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_PHFSIM_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_PHONE_FAILURE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_PHSIM_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SERVICE_PROVIDER_PERSONALIZATION_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SERVICE_PROVIDER_PERSONALIZATION_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_BUSY:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_FAILURE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_NOT_INSERTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_PIN2_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_PIN_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_PUK2_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_PUK_REQUIRED:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIM_WRONG:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_SIP_RESPONSE_CODE:I -Landroid/bluetooth/BluetoothHeadsetClient;->CME_TEXT_STRING_TOO_LONG:I -Landroid/bluetooth/BluetoothHeadsetClient;->connectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->DBG:Z -Landroid/bluetooth/BluetoothHeadsetClient;->dial(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Landroid/bluetooth/BluetoothHeadsetClientCall; -Landroid/bluetooth/BluetoothHeadsetClient;->disconnectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->doBind()Z -Landroid/bluetooth/BluetoothHeadsetClient;->enterPrivateMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothHeadsetClient;->explicitCallTransfer(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_3WAY_CALLING:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_ACCEPT_HELD_OR_WAITING_CALL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_ATTACH_NUMBER_TO_VT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_ECC:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_MERGE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_MERGE_AND_DETACH:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_REJECT_CALL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_RELEASE_AND_ACCEPT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_RELEASE_HELD_OR_WAITING_CALL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_RESPONSE_AND_HOLD:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AG_FEATURE_VOICE_RECOGNITION:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_AUDIO_WBS:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_BATTERY_LEVEL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_CALL:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_CME_CODE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_IN_BAND_RING:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_NETWORK_ROAMING:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_NETWORK_SIGNAL_STRENGTH:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_NETWORK_STATUS:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_NUMBER:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_OPERATOR_NAME:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_RESULT_CODE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_SUBSCRIBER_INFO:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->EXTRA_VOICE_RECOGNITION:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->getAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->getCurrentAgEvents(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/BluetoothHeadsetClient;->getCurrentAgFeatures(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/BluetoothHeadsetClient;->getCurrentCalls(Landroid/bluetooth/BluetoothDevice;)Ljava/util/List; -Landroid/bluetooth/BluetoothHeadsetClient;->getLastVoiceTagNumber(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothHeadsetClient;->holdCall(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->isEnabled()Z -Landroid/bluetooth/BluetoothHeadsetClient;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHeadsetClient;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHeadsetClient;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHeadsetClient;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothHeadsetClient;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHeadsetClient;->mService:Landroid/bluetooth/IBluetoothHeadsetClient; -Landroid/bluetooth/BluetoothHeadsetClient;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHeadsetClient;->sendDTMF(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/BluetoothHeadsetClient;->setAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/BluetoothHeadsetClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothHeadsetClient;->startVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->STATE_AUDIO_CONNECTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->STATE_AUDIO_CONNECTING:I -Landroid/bluetooth/BluetoothHeadsetClient;->STATE_AUDIO_DISCONNECTED:I -Landroid/bluetooth/BluetoothHeadsetClient;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClient;->terminateCall(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHeadsetClientCall;)Z -Landroid/bluetooth/BluetoothHeadsetClient;->VDBG:Z -Landroid/bluetooth/BluetoothHeadsetClientCall;-><init>(Landroid/bluetooth/BluetoothDevice;IILjava/lang/String;ZZZ)V -Landroid/bluetooth/BluetoothHeadsetClientCall;-><init>(Landroid/bluetooth/BluetoothDevice;ILjava/util/UUID;ILjava/lang/String;ZZZ)V -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_ACTIVE:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_ALERTING:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_DIALING:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_HELD:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_HELD_BY_RESPONSE_AND_HOLD:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_INCOMING:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_TERMINATED:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CALL_STATE_WAITING:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothHeadsetClientCall;->getCreationElapsedMilli()J -Landroid/bluetooth/BluetoothHeadsetClientCall;->getDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothHeadsetClientCall;->getUUID()Ljava/util/UUID; -Landroid/bluetooth/BluetoothHeadsetClientCall;->isInBandRing()Z -Landroid/bluetooth/BluetoothHeadsetClientCall;->mCreationElapsedMilli:J -Landroid/bluetooth/BluetoothHeadsetClientCall;->mDevice:Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothHeadsetClientCall;->mId:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->mInBandRing:Z -Landroid/bluetooth/BluetoothHeadsetClientCall;->mMultiParty:Z -Landroid/bluetooth/BluetoothHeadsetClientCall;->mNumber:Ljava/lang/String; -Landroid/bluetooth/BluetoothHeadsetClientCall;->mOutgoing:Z -Landroid/bluetooth/BluetoothHeadsetClientCall;->mState:I -Landroid/bluetooth/BluetoothHeadsetClientCall;->mUUID:Ljava/util/UUID; -Landroid/bluetooth/BluetoothHeadsetClientCall;->setMultiParty(Z)V -Landroid/bluetooth/BluetoothHeadsetClientCall;->setNumber(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHeadsetClientCall;->setState(I)V -Landroid/bluetooth/BluetoothHeadsetClientCall;->toString(Z)Ljava/lang/String; -Landroid/bluetooth/BluetoothHealth$BluetoothHealthCallbackWrapper;-><init>(Landroid/bluetooth/BluetoothHealthCallback;)V -Landroid/bluetooth/BluetoothHealth$BluetoothHealthCallbackWrapper;->mCallback:Landroid/bluetooth/BluetoothHealthCallback; -Landroid/bluetooth/BluetoothHealth$BluetoothHealthCallbackWrapper;->onHealthAppConfigurationStatusChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;I)V -Landroid/bluetooth/BluetoothHealth$BluetoothHealthCallbackWrapper;->onHealthChannelStateChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;Landroid/bluetooth/BluetoothDevice;IILandroid/os/ParcelFileDescriptor;I)V -Landroid/bluetooth/BluetoothHealth;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHealth;->CHANNEL_TYPE_ANY:I -Landroid/bluetooth/BluetoothHealth;->checkAppParam(Ljava/lang/String;IILandroid/bluetooth/BluetoothHealthCallback;)Z -Landroid/bluetooth/BluetoothHealth;->close()V -Landroid/bluetooth/BluetoothHealth;->connectChannelToSink(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;I)Z -Landroid/bluetooth/BluetoothHealth;->DBG:Z -Landroid/bluetooth/BluetoothHealth;->doBind()Z -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_ERROR:I -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_GENERIC_FAILURE:I -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_INVALID_ARGS:I -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_NOT_ALLOWED:I -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_NOT_FOUND:I -Landroid/bluetooth/BluetoothHealth;->HEALTH_OPERATION_SUCCESS:I -Landroid/bluetooth/BluetoothHealth;->isEnabled()Z -Landroid/bluetooth/BluetoothHealth;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHealth;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHealth;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHealth;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHealth;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothHealth;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHealth;->mService:Landroid/bluetooth/IBluetoothHealth; -Landroid/bluetooth/BluetoothHealth;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHealth;->registerAppConfiguration(Ljava/lang/String;IIILandroid/bluetooth/BluetoothHealthCallback;)Z -Landroid/bluetooth/BluetoothHealth;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHealth;->VDBG:Z -Landroid/bluetooth/BluetoothHealthAppConfiguration;-><init>(Ljava/lang/String;I)V -Landroid/bluetooth/BluetoothHealthAppConfiguration;-><init>(Ljava/lang/String;III)V -Landroid/bluetooth/BluetoothHealthAppConfiguration;->getChannelType()I -Landroid/bluetooth/BluetoothHealthAppConfiguration;->mChannelType:I -Landroid/bluetooth/BluetoothHealthAppConfiguration;->mDataType:I -Landroid/bluetooth/BluetoothHealthAppConfiguration;->mName:Ljava/lang/String; -Landroid/bluetooth/BluetoothHealthAppConfiguration;->mRole:I -Landroid/bluetooth/BluetoothHealthCallback;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHearingAid;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHearingAid;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHearingAid;->ACTION_PLAYING_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHearingAid;->adjustVolume(I)V -Landroid/bluetooth/BluetoothHearingAid;->close()V -Landroid/bluetooth/BluetoothHearingAid;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHearingAid;->DBG:Z -Landroid/bluetooth/BluetoothHearingAid;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHearingAid;->doBind()V -Landroid/bluetooth/BluetoothHearingAid;->getDeviceMode(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothHearingAid;->getDeviceSide(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothHearingAid;->getHiSyncId(Landroid/bluetooth/BluetoothDevice;)J -Landroid/bluetooth/BluetoothHearingAid;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothHearingAid;->getVolume()I -Landroid/bluetooth/BluetoothHearingAid;->HI_SYNC_ID_INVALID:J -Landroid/bluetooth/BluetoothHearingAid;->isEnabled()Z -Landroid/bluetooth/BluetoothHearingAid;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHearingAid;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHearingAid;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHearingAid;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHearingAid;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothHearingAid;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHearingAid;->MODE_BINAURAL:I -Landroid/bluetooth/BluetoothHearingAid;->MODE_MONAURAL:I -Landroid/bluetooth/BluetoothHearingAid;->mService:Landroid/bluetooth/IBluetoothHearingAid; -Landroid/bluetooth/BluetoothHearingAid;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHearingAid;->mServiceLock:Ljava/util/concurrent/locks/ReentrantReadWriteLock; -Landroid/bluetooth/BluetoothHearingAid;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothHearingAid;->setVolume(I)V -Landroid/bluetooth/BluetoothHearingAid;->SIDE_LEFT:I -Landroid/bluetooth/BluetoothHearingAid;->SIDE_RIGHT:I -Landroid/bluetooth/BluetoothHearingAid;->stateToString(I)Ljava/lang/String; -Landroid/bluetooth/BluetoothHearingAid;->STATE_NOT_PLAYING:I -Landroid/bluetooth/BluetoothHearingAid;->STATE_PLAYING:I -Landroid/bluetooth/BluetoothHearingAid;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHearingAid;->VDBG:Z -Landroid/bluetooth/BluetoothHidDevice$Callback;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;-><init>(Ljava/util/concurrent/Executor;Landroid/bluetooth/BluetoothHidDevice$Callback;)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->mCallback:Landroid/bluetooth/BluetoothHidDevice$Callback; -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->mExecutor:Ljava/util/concurrent/Executor; -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onAppStatusChanged(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onConnectionStateChanged(Landroid/bluetooth/BluetoothDevice;I)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onGetReport(Landroid/bluetooth/BluetoothDevice;BBI)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onInterruptData(Landroid/bluetooth/BluetoothDevice;B[B)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onSetProtocol(Landroid/bluetooth/BluetoothDevice;B)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onSetReport(Landroid/bluetooth/BluetoothDevice;BB[B)V -Landroid/bluetooth/BluetoothHidDevice$CallbackWrapper;->onVirtualCableUnplug(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/BluetoothHidDevice;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHidDevice;->close()V -Landroid/bluetooth/BluetoothHidDevice;->doBind()Z -Landroid/bluetooth/BluetoothHidDevice;->doUnbind()V -Landroid/bluetooth/BluetoothHidDevice;->getUserAppName()Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDevice;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHidDevice;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHidDevice;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothHidDevice;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHidDevice;->mService:Landroid/bluetooth/IBluetoothHidDevice; -Landroid/bluetooth/BluetoothHidDevice;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHidDevice;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mDelayVariation:I -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mLatency:I -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mPeakBandwidth:I -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mServiceType:I -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mTokenBucketSize:I -Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;->mTokenRate:I -Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;->mDescription:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;->mDescriptors:[B -Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;->mName:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;->mProvider:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;->mSubclass:B -Landroid/bluetooth/BluetoothHidHost;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothHidHost;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->ACTION_HANDSHAKE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->ACTION_IDLE_TIME_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->ACTION_PROTOCOL_MODE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->ACTION_REPORT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->ACTION_VIRTUAL_UNPLUG_STATUS:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->close()V -Landroid/bluetooth/BluetoothHidHost;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->DBG:Z -Landroid/bluetooth/BluetoothHidHost;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->doBind()Z -Landroid/bluetooth/BluetoothHidHost;->EXTRA_IDLE_TIME:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_PROTOCOL_MODE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_REPORT:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_REPORT_BUFFER_SIZE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_REPORT_ID:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_REPORT_TYPE:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_STATUS:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->EXTRA_VIRTUAL_UNPLUG_STATUS:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->getIdleTime(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothHidHost;->getProtocolMode(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->getReport(Landroid/bluetooth/BluetoothDevice;BBI)Z -Landroid/bluetooth/BluetoothHidHost;->INPUT_CONNECT_FAILED_ALREADY_CONNECTED:I -Landroid/bluetooth/BluetoothHidHost;->INPUT_CONNECT_FAILED_ATTEMPT_FAILED:I -Landroid/bluetooth/BluetoothHidHost;->INPUT_DISCONNECT_FAILED_NOT_CONNECTED:I -Landroid/bluetooth/BluetoothHidHost;->INPUT_OPERATION_GENERIC_FAILURE:I -Landroid/bluetooth/BluetoothHidHost;->INPUT_OPERATION_SUCCESS:I -Landroid/bluetooth/BluetoothHidHost;->isEnabled()Z -Landroid/bluetooth/BluetoothHidHost;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothHidHost;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothHidHost;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothHidHost;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothHidHost;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothHidHost;->mService:Landroid/bluetooth/IBluetoothHidHost; -Landroid/bluetooth/BluetoothHidHost;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothHidHost;->PROTOCOL_BOOT_MODE:I -Landroid/bluetooth/BluetoothHidHost;->PROTOCOL_REPORT_MODE:I -Landroid/bluetooth/BluetoothHidHost;->PROTOCOL_UNSUPPORTED_MODE:I -Landroid/bluetooth/BluetoothHidHost;->REPORT_TYPE_FEATURE:B -Landroid/bluetooth/BluetoothHidHost;->REPORT_TYPE_INPUT:B -Landroid/bluetooth/BluetoothHidHost;->REPORT_TYPE_OUTPUT:B -Landroid/bluetooth/BluetoothHidHost;->sendData(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Z -Landroid/bluetooth/BluetoothHidHost;->setIdleTime(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/BluetoothHidHost;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothHidHost;->setProtocolMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothHidHost;->setReport(Landroid/bluetooth/BluetoothDevice;BLjava/lang/String;)Z -Landroid/bluetooth/BluetoothHidHost;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothHidHost;->VDBG:Z -Landroid/bluetooth/BluetoothHidHost;->virtualUnplug(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothHidHost;->VIRTUAL_UNPLUG_STATUS_FAIL:I -Landroid/bluetooth/BluetoothHidHost;->VIRTUAL_UNPLUG_STATUS_SUCCESS:I -Landroid/bluetooth/BluetoothInputStream;-><init>(Landroid/bluetooth/BluetoothSocket;)V -Landroid/bluetooth/BluetoothInputStream;->mSocket:Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothManager;-><init>(Landroid/content/Context;)V -Landroid/bluetooth/BluetoothManager;->DBG:Z -Landroid/bluetooth/BluetoothManager;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothManager;->openGattServer(Landroid/content/Context;Landroid/bluetooth/BluetoothGattServerCallback;I)Landroid/bluetooth/BluetoothGattServer; -Landroid/bluetooth/BluetoothManager;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothManager;->VDBG:Z -Landroid/bluetooth/BluetoothMap;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothMap;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothMap;->close()V -Landroid/bluetooth/BluetoothMap;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMap;->DBG:Z -Landroid/bluetooth/BluetoothMap;->doBind()Z -Landroid/bluetooth/BluetoothMap;->doesClassMatchSink(Landroid/bluetooth/BluetoothClass;)Z -Landroid/bluetooth/BluetoothMap;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothMap;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothMap;->getState()I -Landroid/bluetooth/BluetoothMap;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMap;->isEnabled()Z -Landroid/bluetooth/BluetoothMap;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMap;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothMap;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothMap;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothMap;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothMap;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothMap;->mService:Landroid/bluetooth/IBluetoothMap; -Landroid/bluetooth/BluetoothMap;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothMap;->RESULT_CANCELED:I -Landroid/bluetooth/BluetoothMap;->RESULT_FAILURE:I -Landroid/bluetooth/BluetoothMap;->RESULT_SUCCESS:I -Landroid/bluetooth/BluetoothMap;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothMap;->STATE_ERROR:I -Landroid/bluetooth/BluetoothMap;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothMap;->VDBG:Z -Landroid/bluetooth/BluetoothMapClient;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothMapClient;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->ACTION_MESSAGE_DELIVERED_SUCCESSFULLY:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->ACTION_MESSAGE_RECEIVED:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->ACTION_MESSAGE_SENT_SUCCESSFULLY:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->close()V -Landroid/bluetooth/BluetoothMapClient;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMapClient;->DBG:Z -Landroid/bluetooth/BluetoothMapClient;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMapClient;->doBind()Z -Landroid/bluetooth/BluetoothMapClient;->EXTRA_MESSAGE_HANDLE:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->EXTRA_SENDER_CONTACT_NAME:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->EXTRA_SENDER_CONTACT_URI:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothMapClient;->getUnreadMessages(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMapClient;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMapClient;->isEnabled()Z -Landroid/bluetooth/BluetoothMapClient;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothMapClient;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothMapClient;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothMapClient;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothMapClient;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothMapClient;->mService:Landroid/bluetooth/IBluetoothMapClient; -Landroid/bluetooth/BluetoothMapClient;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothMapClient;->RESULT_CANCELED:I -Landroid/bluetooth/BluetoothMapClient;->RESULT_FAILURE:I -Landroid/bluetooth/BluetoothMapClient;->RESULT_SUCCESS:I -Landroid/bluetooth/BluetoothMapClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothMapClient;->STATE_ERROR:I -Landroid/bluetooth/BluetoothMapClient;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothMapClient;->VDBG:Z -Landroid/bluetooth/BluetoothMasInstance$MessageType;-><init>()V -Landroid/bluetooth/BluetoothMasInstance$MessageType;->EMAIL:I -Landroid/bluetooth/BluetoothMasInstance$MessageType;->MMS:I -Landroid/bluetooth/BluetoothMasInstance$MessageType;->SMS_CDMA:I -Landroid/bluetooth/BluetoothMasInstance$MessageType;->SMS_GSM:I -Landroid/bluetooth/BluetoothMasInstance;-><init>(ILjava/lang/String;II)V -Landroid/bluetooth/BluetoothMasInstance;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/BluetoothMasInstance;->getChannel()I -Landroid/bluetooth/BluetoothMasInstance;->getId()I -Landroid/bluetooth/BluetoothMasInstance;->getMsgTypes()I -Landroid/bluetooth/BluetoothMasInstance;->getName()Ljava/lang/String; -Landroid/bluetooth/BluetoothMasInstance;->mChannel:I -Landroid/bluetooth/BluetoothMasInstance;->mId:I -Landroid/bluetooth/BluetoothMasInstance;->mMsgTypes:I -Landroid/bluetooth/BluetoothMasInstance;->mName:Ljava/lang/String; -Landroid/bluetooth/BluetoothMasInstance;->msgSupported(I)Z -Landroid/bluetooth/BluetoothOutputStream;-><init>(Landroid/bluetooth/BluetoothSocket;)V -Landroid/bluetooth/BluetoothOutputStream;->mSocket:Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothPan;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothPan;->DBG:Z -Landroid/bluetooth/BluetoothPan;->EXTRA_LOCAL_ROLE:Ljava/lang/String; -Landroid/bluetooth/BluetoothPan;->LOCAL_NAP_ROLE:I -Landroid/bluetooth/BluetoothPan;->LOCAL_PANU_ROLE:I -Landroid/bluetooth/BluetoothPan;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothPan;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothPan;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothPan;->mPanService:Landroid/bluetooth/IBluetoothPan; -Landroid/bluetooth/BluetoothPan;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothPan;->mStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothPan;->PAN_CONNECT_FAILED_ALREADY_CONNECTED:I -Landroid/bluetooth/BluetoothPan;->PAN_CONNECT_FAILED_ATTEMPT_FAILED:I -Landroid/bluetooth/BluetoothPan;->PAN_DISCONNECT_FAILED_NOT_CONNECTED:I -Landroid/bluetooth/BluetoothPan;->PAN_OPERATION_GENERIC_FAILURE:I -Landroid/bluetooth/BluetoothPan;->PAN_OPERATION_SUCCESS:I -Landroid/bluetooth/BluetoothPan;->PAN_ROLE_NONE:I -Landroid/bluetooth/BluetoothPan;->REMOTE_NAP_ROLE:I -Landroid/bluetooth/BluetoothPan;->REMOTE_PANU_ROLE:I -Landroid/bluetooth/BluetoothPan;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothPan;->VDBG:Z -Landroid/bluetooth/BluetoothPbap$ServiceListener;->onServiceConnected(Landroid/bluetooth/BluetoothPbap;)V -Landroid/bluetooth/BluetoothPbap$ServiceListener;->onServiceDisconnected()V -Landroid/bluetooth/BluetoothPbap;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothPbap$ServiceListener;)V -Landroid/bluetooth/BluetoothPbap;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothPbap;->close()V -Landroid/bluetooth/BluetoothPbap;->DBG:Z -Landroid/bluetooth/BluetoothPbap;->doBind()Z -Landroid/bluetooth/BluetoothPbap;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothPbap;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothPbap;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothPbap;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothPbap;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothPbap;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothPbap;->mService:Landroid/bluetooth/IBluetoothPbap; -Landroid/bluetooth/BluetoothPbap;->mServiceListener:Landroid/bluetooth/BluetoothPbap$ServiceListener; -Landroid/bluetooth/BluetoothPbap;->RESULT_CANCELED:I -Landroid/bluetooth/BluetoothPbap;->RESULT_FAILURE:I -Landroid/bluetooth/BluetoothPbap;->RESULT_SUCCESS:I -Landroid/bluetooth/BluetoothPbap;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothPbapClient;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothPbapClient;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothPbapClient;->close()V -Landroid/bluetooth/BluetoothPbapClient;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothPbapClient;->DBG:Z -Landroid/bluetooth/BluetoothPbapClient;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothPbapClient;->doBind()Z -Landroid/bluetooth/BluetoothPbapClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothPbapClient;->isEnabled()Z -Landroid/bluetooth/BluetoothPbapClient;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothPbapClient;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothPbapClient;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothPbapClient;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothPbapClient;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothPbapClient;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothPbapClient;->mService:Landroid/bluetooth/IBluetoothPbapClient; -Landroid/bluetooth/BluetoothPbapClient;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothPbapClient;->RESULT_CANCELED:I -Landroid/bluetooth/BluetoothPbapClient;->RESULT_FAILURE:I -Landroid/bluetooth/BluetoothPbapClient;->RESULT_SUCCESS:I -Landroid/bluetooth/BluetoothPbapClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothPbapClient;->STATE_ERROR:I -Landroid/bluetooth/BluetoothPbapClient;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothPbapClient;->VDBG:Z -Landroid/bluetooth/BluetoothProfile;->AVRCP:I -Landroid/bluetooth/BluetoothProfile;->getConnectionStateName(I)Ljava/lang/String; -Landroid/bluetooth/BluetoothProfile;->HEADSET_CLIENT:I -Landroid/bluetooth/BluetoothProfile;->HEARING_AID:I -Landroid/bluetooth/BluetoothProfile;->HID_HOST:I -Landroid/bluetooth/BluetoothProfile;->MAP:I -Landroid/bluetooth/BluetoothProfile;->MAP_CLIENT:I -Landroid/bluetooth/BluetoothProfile;->MAX_PROFILE_ID:I -Landroid/bluetooth/BluetoothProfile;->OPP:I -Landroid/bluetooth/BluetoothProfile;->PBAP:I -Landroid/bluetooth/BluetoothProfile;->PBAP_CLIENT:I -Landroid/bluetooth/BluetoothProtoEnums;-><init>()V -Landroid/bluetooth/BluetoothProtoEnums;->CONNECTION_STATE_CONNECTED:I -Landroid/bluetooth/BluetoothProtoEnums;->CONNECTION_STATE_CONNECTING:I -Landroid/bluetooth/BluetoothProtoEnums;->CONNECTION_STATE_DISCONNECTED:I -Landroid/bluetooth/BluetoothProtoEnums;->CONNECTION_STATE_DISCONNECTING:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_AIRPLANE_MODE:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_APPLICATION_REQUEST:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_CRASH:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_DISALLOWED:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_RESTARTED:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_RESTORE_USER_SETTING:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_START_ERROR:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_SYSTEM_BOOT:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_UNSPECIFIED:I -Landroid/bluetooth/BluetoothProtoEnums;->ENABLE_DISABLE_REASON_USER_SWITCH:I -Landroid/bluetooth/BluetoothSap;-><init>(Landroid/content/Context;Landroid/bluetooth/BluetoothProfile$ServiceListener;)V -Landroid/bluetooth/BluetoothSap;->ACTION_CONNECTION_STATE_CHANGED:Ljava/lang/String; -Landroid/bluetooth/BluetoothSap;->close()V -Landroid/bluetooth/BluetoothSap;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothSap;->DBG:Z -Landroid/bluetooth/BluetoothSap;->doBind()Z -Landroid/bluetooth/BluetoothSap;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothSap;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/BluetoothSap;->getState()I -Landroid/bluetooth/BluetoothSap;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothSap;->isEnabled()Z -Landroid/bluetooth/BluetoothSap;->isValidDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/BluetoothSap;->log(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothSap;->mAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/BluetoothSap;->mBluetoothStateChangeCallback:Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/BluetoothSap;->mConnection:Landroid/content/ServiceConnection; -Landroid/bluetooth/BluetoothSap;->mContext:Landroid/content/Context; -Landroid/bluetooth/BluetoothSap;->mService:Landroid/bluetooth/IBluetoothSap; -Landroid/bluetooth/BluetoothSap;->mServiceListener:Landroid/bluetooth/BluetoothProfile$ServiceListener; -Landroid/bluetooth/BluetoothSap;->RESULT_CANCELED:I -Landroid/bluetooth/BluetoothSap;->RESULT_SUCCESS:I -Landroid/bluetooth/BluetoothSap;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/BluetoothSap;->STATE_ERROR:I -Landroid/bluetooth/BluetoothSap;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothSap;->VDBG:Z -Landroid/bluetooth/BluetoothServerSocket;-><init>(IZZI)V -Landroid/bluetooth/BluetoothServerSocket;-><init>(IZZIZZ)V -Landroid/bluetooth/BluetoothServerSocket;-><init>(IZZLandroid/os/ParcelUuid;)V -Landroid/bluetooth/BluetoothServerSocket;->DBG:Z -Landroid/bluetooth/BluetoothServerSocket;->getChannel()I -Landroid/bluetooth/BluetoothServerSocket;->getPsm()I -Landroid/bluetooth/BluetoothServerSocket;->mChannel:I -Landroid/bluetooth/BluetoothServerSocket;->mHandler:Landroid/os/Handler; -Landroid/bluetooth/BluetoothServerSocket;->mMessage:I -Landroid/bluetooth/BluetoothServerSocket;->setChannel(I)V -Landroid/bluetooth/BluetoothServerSocket;->setCloseHandler(Landroid/os/Handler;I)V -Landroid/bluetooth/BluetoothServerSocket;->setServiceName(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothServerSocket;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket$SocketState;->CLOSED:Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket$SocketState;->CONNECTED:Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket$SocketState;->INIT:Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket$SocketState;->LISTENING:Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket$SocketState;->valueOf(Ljava/lang/String;)Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket$SocketState;->values()[Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket;-><init>(IIZZLandroid/bluetooth/BluetoothDevice;ILandroid/os/ParcelUuid;)V -Landroid/bluetooth/BluetoothSocket;-><init>(IIZZLandroid/bluetooth/BluetoothDevice;ILandroid/os/ParcelUuid;ZZ)V -Landroid/bluetooth/BluetoothSocket;-><init>(IIZZLjava/lang/String;I)V -Landroid/bluetooth/BluetoothSocket;-><init>(Landroid/bluetooth/BluetoothSocket;)V -Landroid/bluetooth/BluetoothSocket;->accept(I)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothSocket;->acceptSocket(Ljava/lang/String;)Landroid/bluetooth/BluetoothSocket; -Landroid/bluetooth/BluetoothSocket;->available()I -Landroid/bluetooth/BluetoothSocket;->bindListen()I -Landroid/bluetooth/BluetoothSocket;->BTSOCK_FLAG_NO_SDP:I -Landroid/bluetooth/BluetoothSocket;->convertAddr([B)Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket;->createL2capRxBuffer()V -Landroid/bluetooth/BluetoothSocket;->DBG:Z -Landroid/bluetooth/BluetoothSocket;->EBADFD:I -Landroid/bluetooth/BluetoothSocket;->fillL2capRxBuffer()I -Landroid/bluetooth/BluetoothSocket;->getPort()I -Landroid/bluetooth/BluetoothSocket;->getSecurityFlags()I -Landroid/bluetooth/BluetoothSocket;->mAddress:Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket;->mAuth:Z -Landroid/bluetooth/BluetoothSocket;->mAuthMitm:Z -Landroid/bluetooth/BluetoothSocket;->MAX_L2CAP_PACKAGE_SIZE:I -Landroid/bluetooth/BluetoothSocket;->MAX_RFCOMM_CHANNEL:I -Landroid/bluetooth/BluetoothSocket;->mDevice:Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/BluetoothSocket;->mEncrypt:Z -Landroid/bluetooth/BluetoothSocket;->mExcludeSdp:Z -Landroid/bluetooth/BluetoothSocket;->mFd:I -Landroid/bluetooth/BluetoothSocket;->mInputStream:Landroid/bluetooth/BluetoothInputStream; -Landroid/bluetooth/BluetoothSocket;->mL2capBuffer:Ljava/nio/ByteBuffer; -Landroid/bluetooth/BluetoothSocket;->mMaxRxPacketSize:I -Landroid/bluetooth/BluetoothSocket;->mMaxTxPacketSize:I -Landroid/bluetooth/BluetoothSocket;->mMin16DigitPin:Z -Landroid/bluetooth/BluetoothSocket;->mOutputStream:Landroid/bluetooth/BluetoothOutputStream; -Landroid/bluetooth/BluetoothSocket;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket;->mSocketIS:Ljava/io/InputStream; -Landroid/bluetooth/BluetoothSocket;->mSocketOS:Ljava/io/OutputStream; -Landroid/bluetooth/BluetoothSocket;->mSocketState:Landroid/bluetooth/BluetoothSocket$SocketState; -Landroid/bluetooth/BluetoothSocket;->mType:I -Landroid/bluetooth/BluetoothSocket;->mUuid:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothSocket;->PROXY_CONNECTION_TIMEOUT:I -Landroid/bluetooth/BluetoothSocket;->read([BII)I -Landroid/bluetooth/BluetoothSocket;->readAll(Ljava/io/InputStream;[B)I -Landroid/bluetooth/BluetoothSocket;->readInt(Ljava/io/InputStream;)I -Landroid/bluetooth/BluetoothSocket;->removeChannel()V -Landroid/bluetooth/BluetoothSocket;->requestMaximumTxDataLength()V -Landroid/bluetooth/BluetoothSocket;->SEC_FLAG_AUTH:I -Landroid/bluetooth/BluetoothSocket;->SEC_FLAG_AUTH_16_DIGIT:I -Landroid/bluetooth/BluetoothSocket;->SEC_FLAG_AUTH_MITM:I -Landroid/bluetooth/BluetoothSocket;->SEC_FLAG_ENCRYPT:I -Landroid/bluetooth/BluetoothSocket;->setExcludeSdp(Z)V -Landroid/bluetooth/BluetoothSocket;->setServiceName(Ljava/lang/String;)V -Landroid/bluetooth/BluetoothSocket;->SOCK_SIGNAL_SIZE:I -Landroid/bluetooth/BluetoothSocket;->TAG:Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket;->TYPE_L2CAP_BREDR:I -Landroid/bluetooth/BluetoothSocket;->TYPE_L2CAP_LE:I -Landroid/bluetooth/BluetoothSocket;->VDBG:Z -Landroid/bluetooth/BluetoothSocket;->waitSocketSignal(Ljava/io/InputStream;)Ljava/lang/String; -Landroid/bluetooth/BluetoothSocket;->write([BII)I -Landroid/bluetooth/BluetoothUuid;-><init>()V -Landroid/bluetooth/BluetoothUuid;->AudioSource:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->AvrcpController:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->AvrcpTarget:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->BASE_UUID:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->BNEP:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->containsAllUuids([Landroid/os/ParcelUuid;[Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->getServiceIdentifierFromParcelUuid(Landroid/os/ParcelUuid;)I -Landroid/bluetooth/BluetoothUuid;->Handsfree_AG:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->HearingAid:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->Hid:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->HSP_AG:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->isAudioSink(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isAvrcpController(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isBnep(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isHandsfree(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isHeadset(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isInputDevice(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isMap(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isMas(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isMns(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isNap(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isPanu(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->isSap(Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/BluetoothUuid;->MAP:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->MAS:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->MNS:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->PANU:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->parseUuidFrom([B)Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->PBAP_PCE:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->SAP:Landroid/os/ParcelUuid; -Landroid/bluetooth/BluetoothUuid;->uuidToBytes(Landroid/os/ParcelUuid;)[B -Landroid/bluetooth/BluetoothUuid;->UUID_BYTES_128_BIT:I -Landroid/bluetooth/BluetoothUuid;->UUID_BYTES_16_BIT:I -Landroid/bluetooth/BluetoothUuid;->UUID_BYTES_32_BIT:I -Landroid/bluetooth/IBluetooth$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->cancelBondProcess(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->cancelDiscovery()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->createBond(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->createBondOutOfBand(Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/OobData;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->disable()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->enable()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->enableNoAutoConnect()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->factoryReset()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->fetchRemoteUuids(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getAdapterConnectionState()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getBatteryLevel(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getBluetoothClass()Landroid/bluetooth/BluetoothClass; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getBondedDevices()[Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getBondState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getDiscoverableTimeout()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getDiscoveryEndMillis()J -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getLeMaximumAdvertisingDataLength()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getMaxConnectedAudioDevices()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getMessageAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getName()Ljava/lang/String; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getPhonebookAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getProfileConnectionState(I)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getRemoteAlias(Landroid/bluetooth/BluetoothDevice;)Ljava/lang/String; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getRemoteClass(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getRemoteName(Landroid/bluetooth/BluetoothDevice;)Ljava/lang/String; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getRemoteType(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getRemoteUuids(Landroid/bluetooth/BluetoothDevice;)[Landroid/os/ParcelUuid; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getScanMode()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getSimAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getSocketManager()Landroid/bluetooth/IBluetoothSocketManager; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getState()I -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getSupportedProfiles()J -Landroid/bluetooth/IBluetooth$Stub$Proxy;->getUuids()[Landroid/os/ParcelUuid; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isActivityAndEnergyReportingSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isBondingInitiatedLocally(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isDiscovering()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isEnabled()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isLe2MPhySupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isLeCodedPhySupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isLeExtendedAdvertisingSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isLePeriodicAdvertisingSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isMultiAdvertisementSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isOffloadedFilteringSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->isOffloadedScanBatchingSupported()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->onBrEdrDown()V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->onLeServiceUp()V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->registerCallback(Landroid/bluetooth/IBluetoothCallback;)V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->removeBond(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->reportActivityInfo()Landroid/bluetooth/BluetoothActivityEnergyInfo; -Landroid/bluetooth/IBluetooth$Stub$Proxy;->requestActivityInfo(Landroid/os/ResultReceiver;)V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->sdpSearch(Landroid/bluetooth/BluetoothDevice;Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->sendConnectionStateChange(Landroid/bluetooth/BluetoothDevice;III)V -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setBluetoothClass(Landroid/bluetooth/BluetoothClass;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setDiscoverableTimeout(I)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setMessageAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setName(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setPairingConfirmation(Landroid/bluetooth/BluetoothDevice;Z)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setPasskey(Landroid/bluetooth/BluetoothDevice;ZI[B)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setPhonebookAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setPin(Landroid/bluetooth/BluetoothDevice;ZI[B)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setRemoteAlias(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setScanMode(II)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->setSimAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->startDiscovery()Z -Landroid/bluetooth/IBluetooth$Stub$Proxy;->unregisterCallback(Landroid/bluetooth/IBluetoothCallback;)V -Landroid/bluetooth/IBluetooth$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_cancelBondProcess:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_cancelDiscovery:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_createBond:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_createBondOutOfBand:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_disable:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_enableNoAutoConnect:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_factoryReset:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_fetchRemoteUuids:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getAdapterConnectionState:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getAddress:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getBatteryLevel:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getBluetoothClass:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getBondedDevices:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getBondState:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getDiscoverableTimeout:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getDiscoveryEndMillis:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getLeMaximumAdvertisingDataLength:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getMaxConnectedAudioDevices:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getMessageAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getName:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getPhonebookAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getProfileConnectionState:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getRemoteAlias:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getRemoteClass:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getRemoteName:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getRemoteType:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getRemoteUuids:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getScanMode:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getSimAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getSocketManager:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getState:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getSupportedProfiles:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_getUuids:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isActivityAndEnergyReportingSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isBondingInitiatedLocally:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isDiscovering:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isEnabled:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isLe2MPhySupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isLeCodedPhySupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isLeExtendedAdvertisingSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isLePeriodicAdvertisingSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isMultiAdvertisementSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isOffloadedFilteringSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_isOffloadedScanBatchingSupported:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_onBrEdrDown:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_onLeServiceUp:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_registerCallback:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_removeBond:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_reportActivityInfo:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_requestActivityInfo:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_sdpSearch:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_sendConnectionStateChange:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setBluetoothClass:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setDiscoverableTimeout:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setMessageAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setName:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setPairingConfirmation:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setPasskey:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setPhonebookAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setPin:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setRemoteAlias:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setScanMode:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_setSimAccessPermission:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_startDiscovery:I -Landroid/bluetooth/IBluetooth$Stub;->TRANSACTION_unregisterCallback:I -Landroid/bluetooth/IBluetooth;->cancelBondProcess(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth;->cancelDiscovery()Z -Landroid/bluetooth/IBluetooth;->createBond(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth;->createBondOutOfBand(Landroid/bluetooth/BluetoothDevice;ILandroid/bluetooth/OobData;)Z -Landroid/bluetooth/IBluetooth;->disable()Z -Landroid/bluetooth/IBluetooth;->enable()Z -Landroid/bluetooth/IBluetooth;->enableNoAutoConnect()Z -Landroid/bluetooth/IBluetooth;->factoryReset()Z -Landroid/bluetooth/IBluetooth;->getAdapterConnectionState()I -Landroid/bluetooth/IBluetooth;->getBatteryLevel(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getBluetoothClass()Landroid/bluetooth/BluetoothClass; -Landroid/bluetooth/IBluetooth;->getBondedDevices()[Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetooth;->getBondState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getDiscoverableTimeout()I -Landroid/bluetooth/IBluetooth;->getDiscoveryEndMillis()J -Landroid/bluetooth/IBluetooth;->getLeMaximumAdvertisingDataLength()I -Landroid/bluetooth/IBluetooth;->getMaxConnectedAudioDevices()I -Landroid/bluetooth/IBluetooth;->getMessageAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getName()Ljava/lang/String; -Landroid/bluetooth/IBluetooth;->getPhonebookAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getProfileConnectionState(I)I -Landroid/bluetooth/IBluetooth;->getRemoteClass(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getRemoteName(Landroid/bluetooth/BluetoothDevice;)Ljava/lang/String; -Landroid/bluetooth/IBluetooth;->getRemoteType(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getRemoteUuids(Landroid/bluetooth/BluetoothDevice;)[Landroid/os/ParcelUuid; -Landroid/bluetooth/IBluetooth;->getScanMode()I -Landroid/bluetooth/IBluetooth;->getSimAccessPermission(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetooth;->getSocketManager()Landroid/bluetooth/IBluetoothSocketManager; -Landroid/bluetooth/IBluetooth;->getState()I -Landroid/bluetooth/IBluetooth;->getSupportedProfiles()J -Landroid/bluetooth/IBluetooth;->getUuids()[Landroid/os/ParcelUuid; -Landroid/bluetooth/IBluetooth;->isActivityAndEnergyReportingSupported()Z -Landroid/bluetooth/IBluetooth;->isBondingInitiatedLocally(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth;->isDiscovering()Z -Landroid/bluetooth/IBluetooth;->isLe2MPhySupported()Z -Landroid/bluetooth/IBluetooth;->isLeCodedPhySupported()Z -Landroid/bluetooth/IBluetooth;->isLeExtendedAdvertisingSupported()Z -Landroid/bluetooth/IBluetooth;->isLePeriodicAdvertisingSupported()Z -Landroid/bluetooth/IBluetooth;->isMultiAdvertisementSupported()Z -Landroid/bluetooth/IBluetooth;->isOffloadedFilteringSupported()Z -Landroid/bluetooth/IBluetooth;->isOffloadedScanBatchingSupported()Z -Landroid/bluetooth/IBluetooth;->onBrEdrDown()V -Landroid/bluetooth/IBluetooth;->onLeServiceUp()V -Landroid/bluetooth/IBluetooth;->registerCallback(Landroid/bluetooth/IBluetoothCallback;)V -Landroid/bluetooth/IBluetooth;->removeBond(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetooth;->reportActivityInfo()Landroid/bluetooth/BluetoothActivityEnergyInfo; -Landroid/bluetooth/IBluetooth;->requestActivityInfo(Landroid/os/ResultReceiver;)V -Landroid/bluetooth/IBluetooth;->sdpSearch(Landroid/bluetooth/BluetoothDevice;Landroid/os/ParcelUuid;)Z -Landroid/bluetooth/IBluetooth;->setBluetoothClass(Landroid/bluetooth/BluetoothClass;)Z -Landroid/bluetooth/IBluetooth;->setDiscoverableTimeout(I)Z -Landroid/bluetooth/IBluetooth;->setMessageAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth;->setName(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetooth;->setPairingConfirmation(Landroid/bluetooth/BluetoothDevice;Z)Z -Landroid/bluetooth/IBluetooth;->setPasskey(Landroid/bluetooth/BluetoothDevice;ZI[B)Z -Landroid/bluetooth/IBluetooth;->setPhonebookAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth;->setPin(Landroid/bluetooth/BluetoothDevice;ZI[B)Z -Landroid/bluetooth/IBluetooth;->setRemoteAlias(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetooth;->setScanMode(II)Z -Landroid/bluetooth/IBluetooth;->setSimAccessPermission(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetooth;->startDiscovery()Z -Landroid/bluetooth/IBluetooth;->unregisterCallback(Landroid/bluetooth/IBluetoothCallback;)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->disableOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->enableOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getActiveDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getCodecStatus(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothCodecStatus; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getOptionalCodecsEnabled(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->isA2dpPlaying(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->isAvrcpAbsoluteVolumeSupported()Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->setAvrcpAbsoluteVolume(I)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->setCodecConfigPreference(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothCodecConfig;)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->setOptionalCodecsEnabled(Landroid/bluetooth/BluetoothDevice;I)V -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothA2dp$Stub$Proxy;->supportsOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dp$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_disableOptionalCodecs:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_enableOptionalCodecs:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getActiveDevice:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getCodecStatus:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getOptionalCodecsEnabled:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_isA2dpPlaying:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_isAvrcpAbsoluteVolumeSupported:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_setActiveDevice:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_setAvrcpAbsoluteVolume:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_setCodecConfigPreference:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_setOptionalCodecsEnabled:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothA2dp$Stub;->TRANSACTION_supportsOptionalCodecs:I -Landroid/bluetooth/IBluetoothA2dp;->disableOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothA2dp;->enableOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothA2dp;->getActiveDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothA2dp;->getCodecStatus(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothCodecStatus; -Landroid/bluetooth/IBluetoothA2dp;->getOptionalCodecsEnabled(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dp;->isA2dpPlaying(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp;->isAvrcpAbsoluteVolumeSupported()Z -Landroid/bluetooth/IBluetoothA2dp;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dp;->setAvrcpAbsoluteVolume(I)V -Landroid/bluetooth/IBluetoothA2dp;->setCodecConfigPreference(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothCodecConfig;)V -Landroid/bluetooth/IBluetoothA2dp;->setOptionalCodecsEnabled(Landroid/bluetooth/BluetoothDevice;I)V -Landroid/bluetooth/IBluetoothA2dp;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothA2dp;->supportsOptionalCodecs(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getAudioConfig(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAudioConfig; -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->isA2dpPlaying(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothA2dpSink$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothA2dpSink$Stub;-><init>()V -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothA2dpSink; -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_getAudioConfig:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_isA2dpPlaying:I -Landroid/bluetooth/IBluetoothA2dpSink$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothA2dpSink;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink;->getAudioConfig(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAudioConfig; -Landroid/bluetooth/IBluetoothA2dpSink;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dpSink;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dpSink;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothA2dpSink;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothA2dpSink;->isA2dpPlaying(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothA2dpSink;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->getPlayerSettings(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAvrcpPlayerSettings; -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->sendGroupNavigationCmd(Landroid/bluetooth/BluetoothDevice;II)V -Landroid/bluetooth/IBluetoothAvrcpController$Stub$Proxy;->setPlayerApplicationSetting(Landroid/bluetooth/BluetoothAvrcpPlayerSettings;)Z -Landroid/bluetooth/IBluetoothAvrcpController$Stub;-><init>()V -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothAvrcpController; -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_getPlayerSettings:I -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_sendGroupNavigationCmd:I -Landroid/bluetooth/IBluetoothAvrcpController$Stub;->TRANSACTION_setPlayerApplicationSetting:I -Landroid/bluetooth/IBluetoothAvrcpController;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothAvrcpController;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothAvrcpController;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothAvrcpController;->getPlayerSettings(Landroid/bluetooth/BluetoothDevice;)Landroid/bluetooth/BluetoothAvrcpPlayerSettings; -Landroid/bluetooth/IBluetoothAvrcpController;->sendGroupNavigationCmd(Landroid/bluetooth/BluetoothDevice;II)V -Landroid/bluetooth/IBluetoothAvrcpController;->setPlayerApplicationSetting(Landroid/bluetooth/BluetoothAvrcpPlayerSettings;)Z -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub$Proxy;->sendVolumeChanged(I)V -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub;-><init>()V -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothAvrcpTarget; -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothAvrcpTarget$Stub;->TRANSACTION_sendVolumeChanged:I -Landroid/bluetooth/IBluetoothAvrcpTarget;->sendVolumeChanged(I)V -Landroid/bluetooth/IBluetoothCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothCallback$Stub$Proxy;->onBluetoothStateChange(II)V -Landroid/bluetooth/IBluetoothCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothCallback; -Landroid/bluetooth/IBluetoothCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothCallback$Stub;->TRANSACTION_onBluetoothStateChange:I -Landroid/bluetooth/IBluetoothCallback;->onBluetoothStateChange(II)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->addService(ILandroid/bluetooth/BluetoothGattService;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->beginReliableWrite(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->clearServices(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->clientConnect(ILjava/lang/String;ZIZI)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->clientDisconnect(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->clientReadPhy(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->clientSetPreferredPhy(ILjava/lang/String;III)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->configureMTU(ILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->connectionParameterUpdate(ILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->disconnectAll()V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->discoverServiceByUuid(ILjava/lang/String;Landroid/os/ParcelUuid;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->discoverServices(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->enableAdvertisingSet(IZII)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->endReliableWrite(ILjava/lang/String;Z)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->flushPendingBatchResults(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->getOwnAddress(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->leConnectionUpdate(ILjava/lang/String;IIIIII)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->numHwTrackFiltersAvailable()I -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->readCharacteristic(ILjava/lang/String;II)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->readDescriptor(ILjava/lang/String;II)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->readRemoteRssi(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->readUsingCharacteristicUuid(ILjava/lang/String;Landroid/os/ParcelUuid;III)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->refreshDevice(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->registerClient(Landroid/os/ParcelUuid;Landroid/bluetooth/IBluetoothGattCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->registerForNotification(ILjava/lang/String;IZ)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->registerScanner(Landroid/bluetooth/le/IScannerCallback;Landroid/os/WorkSource;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->registerServer(Landroid/os/ParcelUuid;Landroid/bluetooth/IBluetoothGattServerCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->registerSync(Landroid/bluetooth/le/ScanResult;IILandroid/bluetooth/le/IPeriodicAdvertisingCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->removeService(II)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->sendNotification(ILjava/lang/String;IZ[B)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->sendResponse(ILjava/lang/String;III[B)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->serverConnect(ILjava/lang/String;ZI)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->serverDisconnect(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->serverReadPhy(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->serverSetPreferredPhy(ILjava/lang/String;III)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setAdvertisingData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setAdvertisingParameters(ILandroid/bluetooth/le/AdvertisingSetParameters;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setPeriodicAdvertisingData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setPeriodicAdvertisingEnable(IZ)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setPeriodicAdvertisingParameters(ILandroid/bluetooth/le/PeriodicAdvertisingParameters;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->setScanResponseData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->startAdvertisingSet(Landroid/bluetooth/le/AdvertisingSetParameters;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/PeriodicAdvertisingParameters;Landroid/bluetooth/le/AdvertiseData;IILandroid/bluetooth/le/IAdvertisingSetCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->startScan(ILandroid/bluetooth/le/ScanSettings;Ljava/util/List;Ljava/util/List;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->startScanForIntent(Landroid/app/PendingIntent;Landroid/bluetooth/le/ScanSettings;Ljava/util/List;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->stopAdvertisingSet(Landroid/bluetooth/le/IAdvertisingSetCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->stopScan(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->stopScanForIntent(Landroid/app/PendingIntent;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->unregAll()V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->unregisterClient(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->unregisterScanner(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->unregisterServer(I)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->unregisterSync(Landroid/bluetooth/le/IPeriodicAdvertisingCallback;)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->writeCharacteristic(ILjava/lang/String;III[B)V -Landroid/bluetooth/IBluetoothGatt$Stub$Proxy;->writeDescriptor(ILjava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGatt$Stub;-><init>()V -Landroid/bluetooth/IBluetoothGatt$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothGatt; -Landroid/bluetooth/IBluetoothGatt$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_addService:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_beginReliableWrite:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_clearServices:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_clientConnect:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_clientDisconnect:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_clientReadPhy:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_clientSetPreferredPhy:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_configureMTU:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_connectionParameterUpdate:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_disconnectAll:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_discoverServiceByUuid:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_discoverServices:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_enableAdvertisingSet:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_endReliableWrite:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_flushPendingBatchResults:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_getOwnAddress:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_leConnectionUpdate:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_numHwTrackFiltersAvailable:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_readCharacteristic:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_readDescriptor:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_readRemoteRssi:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_readUsingCharacteristicUuid:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_refreshDevice:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_registerClient:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_registerForNotification:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_registerScanner:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_registerServer:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_registerSync:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_removeService:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_sendNotification:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_sendResponse:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_serverConnect:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_serverDisconnect:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_serverReadPhy:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_serverSetPreferredPhy:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setAdvertisingData:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setAdvertisingParameters:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setPeriodicAdvertisingData:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setPeriodicAdvertisingEnable:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setPeriodicAdvertisingParameters:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_setScanResponseData:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_startAdvertisingSet:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_startScan:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_startScanForIntent:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_stopAdvertisingSet:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_stopScan:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_stopScanForIntent:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_unregAll:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_unregisterClient:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_unregisterScanner:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_unregisterServer:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_unregisterSync:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_writeCharacteristic:I -Landroid/bluetooth/IBluetoothGatt$Stub;->TRANSACTION_writeDescriptor:I -Landroid/bluetooth/IBluetoothGatt;->addService(ILandroid/bluetooth/BluetoothGattService;)V -Landroid/bluetooth/IBluetoothGatt;->beginReliableWrite(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->clearServices(I)V -Landroid/bluetooth/IBluetoothGatt;->clientConnect(ILjava/lang/String;ZIZI)V -Landroid/bluetooth/IBluetoothGatt;->clientDisconnect(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->clientReadPhy(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->clientSetPreferredPhy(ILjava/lang/String;III)V -Landroid/bluetooth/IBluetoothGatt;->configureMTU(ILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothGatt;->connectionParameterUpdate(ILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothGatt;->disconnectAll()V -Landroid/bluetooth/IBluetoothGatt;->discoverServiceByUuid(ILjava/lang/String;Landroid/os/ParcelUuid;)V -Landroid/bluetooth/IBluetoothGatt;->discoverServices(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->enableAdvertisingSet(IZII)V -Landroid/bluetooth/IBluetoothGatt;->endReliableWrite(ILjava/lang/String;Z)V -Landroid/bluetooth/IBluetoothGatt;->flushPendingBatchResults(I)V -Landroid/bluetooth/IBluetoothGatt;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothGatt;->getOwnAddress(I)V -Landroid/bluetooth/IBluetoothGatt;->leConnectionUpdate(ILjava/lang/String;IIIIII)V -Landroid/bluetooth/IBluetoothGatt;->numHwTrackFiltersAvailable()I -Landroid/bluetooth/IBluetoothGatt;->readCharacteristic(ILjava/lang/String;II)V -Landroid/bluetooth/IBluetoothGatt;->readDescriptor(ILjava/lang/String;II)V -Landroid/bluetooth/IBluetoothGatt;->readRemoteRssi(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->readUsingCharacteristicUuid(ILjava/lang/String;Landroid/os/ParcelUuid;III)V -Landroid/bluetooth/IBluetoothGatt;->refreshDevice(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->registerForNotification(ILjava/lang/String;IZ)V -Landroid/bluetooth/IBluetoothGatt;->registerScanner(Landroid/bluetooth/le/IScannerCallback;Landroid/os/WorkSource;)V -Landroid/bluetooth/IBluetoothGatt;->registerServer(Landroid/os/ParcelUuid;Landroid/bluetooth/IBluetoothGattServerCallback;)V -Landroid/bluetooth/IBluetoothGatt;->registerSync(Landroid/bluetooth/le/ScanResult;IILandroid/bluetooth/le/IPeriodicAdvertisingCallback;)V -Landroid/bluetooth/IBluetoothGatt;->removeService(II)V -Landroid/bluetooth/IBluetoothGatt;->sendNotification(ILjava/lang/String;IZ[B)V -Landroid/bluetooth/IBluetoothGatt;->sendResponse(ILjava/lang/String;III[B)V -Landroid/bluetooth/IBluetoothGatt;->serverConnect(ILjava/lang/String;ZI)V -Landroid/bluetooth/IBluetoothGatt;->serverDisconnect(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->serverReadPhy(ILjava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->serverSetPreferredPhy(ILjava/lang/String;III)V -Landroid/bluetooth/IBluetoothGatt;->setAdvertisingData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt;->setAdvertisingParameters(ILandroid/bluetooth/le/AdvertisingSetParameters;)V -Landroid/bluetooth/IBluetoothGatt;->setPeriodicAdvertisingData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt;->setPeriodicAdvertisingEnable(IZ)V -Landroid/bluetooth/IBluetoothGatt;->setPeriodicAdvertisingParameters(ILandroid/bluetooth/le/PeriodicAdvertisingParameters;)V -Landroid/bluetooth/IBluetoothGatt;->setScanResponseData(ILandroid/bluetooth/le/AdvertiseData;)V -Landroid/bluetooth/IBluetoothGatt;->startAdvertisingSet(Landroid/bluetooth/le/AdvertisingSetParameters;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/AdvertiseData;Landroid/bluetooth/le/PeriodicAdvertisingParameters;Landroid/bluetooth/le/AdvertiseData;IILandroid/bluetooth/le/IAdvertisingSetCallback;)V -Landroid/bluetooth/IBluetoothGatt;->startScan(ILandroid/bluetooth/le/ScanSettings;Ljava/util/List;Ljava/util/List;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->startScanForIntent(Landroid/app/PendingIntent;Landroid/bluetooth/le/ScanSettings;Ljava/util/List;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->stopAdvertisingSet(Landroid/bluetooth/le/IAdvertisingSetCallback;)V -Landroid/bluetooth/IBluetoothGatt;->stopScan(I)V -Landroid/bluetooth/IBluetoothGatt;->stopScanForIntent(Landroid/app/PendingIntent;Ljava/lang/String;)V -Landroid/bluetooth/IBluetoothGatt;->unregAll()V -Landroid/bluetooth/IBluetoothGatt;->unregisterScanner(I)V -Landroid/bluetooth/IBluetoothGatt;->unregisterServer(I)V -Landroid/bluetooth/IBluetoothGatt;->unregisterSync(Landroid/bluetooth/le/IPeriodicAdvertisingCallback;)V -Landroid/bluetooth/IBluetoothGatt;->writeCharacteristic(ILjava/lang/String;III[B)V -Landroid/bluetooth/IBluetoothGatt;->writeDescriptor(ILjava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onCharacteristicRead(Ljava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onCharacteristicWrite(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onClientConnectionState(IIZLjava/lang/String;)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onClientRegistered(II)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onConfigureMTU(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onConnectionUpdated(Ljava/lang/String;IIII)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onDescriptorRead(Ljava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onDescriptorWrite(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onExecuteWrite(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onNotify(Ljava/lang/String;I[B)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onPhyRead(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onPhyUpdate(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onReadRemoteRssi(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback$Stub$Proxy;->onSearchComplete(Ljava/lang/String;Ljava/util/List;I)V -Landroid/bluetooth/IBluetoothGattCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onCharacteristicRead:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onCharacteristicWrite:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onClientConnectionState:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onClientRegistered:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onConfigureMTU:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onConnectionUpdated:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onDescriptorRead:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onDescriptorWrite:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onExecuteWrite:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onNotify:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onPhyRead:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onPhyUpdate:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onReadRemoteRssi:I -Landroid/bluetooth/IBluetoothGattCallback$Stub;->TRANSACTION_onSearchComplete:I -Landroid/bluetooth/IBluetoothGattCallback;->onCharacteristicRead(Ljava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGattCallback;->onCharacteristicWrite(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback;->onClientConnectionState(IIZLjava/lang/String;)V -Landroid/bluetooth/IBluetoothGattCallback;->onClientRegistered(II)V -Landroid/bluetooth/IBluetoothGattCallback;->onConfigureMTU(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback;->onConnectionUpdated(Ljava/lang/String;IIII)V -Landroid/bluetooth/IBluetoothGattCallback;->onDescriptorRead(Ljava/lang/String;II[B)V -Landroid/bluetooth/IBluetoothGattCallback;->onDescriptorWrite(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback;->onExecuteWrite(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattCallback;->onNotify(Ljava/lang/String;I[B)V -Landroid/bluetooth/IBluetoothGattCallback;->onPhyRead(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattCallback;->onPhyUpdate(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattCallback;->onReadRemoteRssi(Ljava/lang/String;II)V -Landroid/bluetooth/IBluetoothGattCallback;->onSearchComplete(Ljava/lang/String;Ljava/util/List;I)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onCharacteristicReadRequest(Ljava/lang/String;IIZI)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onCharacteristicWriteRequest(Ljava/lang/String;IIIZZI[B)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onConnectionUpdated(Ljava/lang/String;IIII)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onDescriptorReadRequest(Ljava/lang/String;IIZI)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onDescriptorWriteRequest(Ljava/lang/String;IIIZZI[B)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onExecuteWrite(Ljava/lang/String;IZ)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onMtuChanged(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onNotificationSent(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onPhyRead(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onPhyUpdate(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onServerConnectionState(IIZLjava/lang/String;)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onServerRegistered(II)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub$Proxy;->onServiceAdded(ILandroid/bluetooth/BluetoothGattService;)V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;-><init>()V -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothGattServerCallback; -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onCharacteristicReadRequest:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onCharacteristicWriteRequest:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onConnectionUpdated:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onDescriptorReadRequest:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onDescriptorWriteRequest:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onExecuteWrite:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onMtuChanged:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onNotificationSent:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onPhyRead:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onPhyUpdate:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onServerConnectionState:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onServerRegistered:I -Landroid/bluetooth/IBluetoothGattServerCallback$Stub;->TRANSACTION_onServiceAdded:I -Landroid/bluetooth/IBluetoothGattServerCallback;->onCharacteristicReadRequest(Ljava/lang/String;IIZI)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onCharacteristicWriteRequest(Ljava/lang/String;IIIZZI[B)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onConnectionUpdated(Ljava/lang/String;IIII)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onDescriptorReadRequest(Ljava/lang/String;IIZI)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onDescriptorWriteRequest(Ljava/lang/String;IIIZZI[B)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onExecuteWrite(Ljava/lang/String;IZ)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onMtuChanged(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onNotificationSent(Ljava/lang/String;I)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onPhyRead(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onPhyUpdate(Ljava/lang/String;III)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onServerConnectionState(IIZLjava/lang/String;)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onServerRegistered(II)V -Landroid/bluetooth/IBluetoothGattServerCallback;->onServiceAdded(ILandroid/bluetooth/BluetoothGattService;)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->clccResponse(IIIIZLjava/lang/String;I)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->connectAudio()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->disconnectAudio()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getActiveDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getAudioRouteAllowed()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getAudioState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->isAudioConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->isAudioOn()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->isInbandRingingEnabled()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->phoneStateChanged(IIILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->sendVendorSpecificResultCode(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->setAudioRouteAllowed(Z)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->setForceScoAudio(Z)V -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->startScoUsingVirtualVoiceCall()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->startVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->stopScoUsingVirtualVoiceCall()Z -Landroid/bluetooth/IBluetoothHeadset$Stub$Proxy;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHeadset$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_clccResponse:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_connectAudio:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_disconnectAudio:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getActiveDevice:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getAudioRouteAllowed:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getAudioState:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_isAudioConnected:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_isAudioOn:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_isInbandRingingEnabled:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_phoneStateChanged:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_sendVendorSpecificResultCode:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_setActiveDevice:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_setAudioRouteAllowed:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_setForceScoAudio:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_startScoUsingVirtualVoiceCall:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_startVoiceRecognition:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_stopScoUsingVirtualVoiceCall:I -Landroid/bluetooth/IBluetoothHeadset$Stub;->TRANSACTION_stopVoiceRecognition:I -Landroid/bluetooth/IBluetoothHeadset;->clccResponse(IIIIZLjava/lang/String;I)V -Landroid/bluetooth/IBluetoothHeadset;->connectAudio()Z -Landroid/bluetooth/IBluetoothHeadset;->disconnectAudio()Z -Landroid/bluetooth/IBluetoothHeadset;->getActiveDevice()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothHeadset;->getAudioRouteAllowed()Z -Landroid/bluetooth/IBluetoothHeadset;->getAudioState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadset;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadset;->isAudioConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset;->isAudioOn()Z -Landroid/bluetooth/IBluetoothHeadset;->isInbandRingingEnabled()Z -Landroid/bluetooth/IBluetoothHeadset;->phoneStateChanged(IIILjava/lang/String;I)V -Landroid/bluetooth/IBluetoothHeadset;->sendVendorSpecificResultCode(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothHeadset;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset;->setAudioRouteAllowed(Z)V -Landroid/bluetooth/IBluetoothHeadset;->setForceScoAudio(Z)V -Landroid/bluetooth/IBluetoothHeadset;->startScoUsingVirtualVoiceCall()Z -Landroid/bluetooth/IBluetoothHeadset;->startVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadset;->stopScoUsingVirtualVoiceCall()Z -Landroid/bluetooth/IBluetoothHeadset;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->acceptCall(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->connectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->dial(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Landroid/bluetooth/BluetoothHeadsetClientCall; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->disconnectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->enterPrivateMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->explicitCallTransfer(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getAudioState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getCurrentAgEvents(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getCurrentAgFeatures(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getCurrentCalls(Landroid/bluetooth/BluetoothDevice;)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getLastVoiceTagNumber(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->holdCall(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->rejectCall(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->sendDTMF(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->setAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->startVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub$Proxy;->terminateCall(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHeadsetClientCall;)Z -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHeadsetClient; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_acceptCall:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_connectAudio:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_dial:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_disconnectAudio:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_enterPrivateMode:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_explicitCallTransfer:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getAudioRouteAllowed:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getAudioState:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getCurrentAgEvents:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getCurrentAgFeatures:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getCurrentCalls:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getLastVoiceTagNumber:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_holdCall:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_rejectCall:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_sendDTMF:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_setAudioRouteAllowed:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_startVoiceRecognition:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_stopVoiceRecognition:I -Landroid/bluetooth/IBluetoothHeadsetClient$Stub;->TRANSACTION_terminateCall:I -Landroid/bluetooth/IBluetoothHeadsetClient;->acceptCall(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->connectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->dial(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Landroid/bluetooth/BluetoothHeadsetClientCall; -Landroid/bluetooth/IBluetoothHeadsetClient;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->disconnectAudio(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->enterPrivateMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->explicitCallTransfer(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->getAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->getAudioState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient;->getCurrentAgEvents(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/IBluetoothHeadsetClient;->getCurrentAgFeatures(Landroid/bluetooth/BluetoothDevice;)Landroid/os/Bundle; -Landroid/bluetooth/IBluetoothHeadsetClient;->getCurrentCalls(Landroid/bluetooth/BluetoothDevice;)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHeadsetClient;->getLastVoiceTagNumber(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHeadsetClient;->holdCall(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->rejectCall(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->sendDTMF(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->setAudioRouteAllowed(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/IBluetoothHeadsetClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->startVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->stopVoiceRecognition(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHeadsetClient;->terminateCall(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHeadsetClientCall;)Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->answerCall()Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->cdmaSetSecondCallState(Z)V -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->cdmaSwapSecondCallState()V -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->getNetworkOperator()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->getSubscriberNumber()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->hangupCall()Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->listCurrentCalls()Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->processChld(I)Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->queryPhoneState()Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->sendDtmf(I)Z -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub$Proxy;->updateBtHandsfreeAfterRadioTechnologyChange()V -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHeadsetPhone; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_answerCall:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_cdmaSetSecondCallState:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_cdmaSwapSecondCallState:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_getNetworkOperator:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_getSubscriberNumber:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_hangupCall:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_listCurrentCalls:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_processChld:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_queryPhoneState:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_sendDtmf:I -Landroid/bluetooth/IBluetoothHeadsetPhone$Stub;->TRANSACTION_updateBtHandsfreeAfterRadioTechnologyChange:I -Landroid/bluetooth/IBluetoothHeadsetPhone;->answerCall()Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->cdmaSetSecondCallState(Z)V -Landroid/bluetooth/IBluetoothHeadsetPhone;->cdmaSwapSecondCallState()V -Landroid/bluetooth/IBluetoothHeadsetPhone;->getNetworkOperator()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone;->getSubscriberNumber()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHeadsetPhone;->hangupCall()Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->listCurrentCalls()Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->processChld(I)Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->queryPhoneState()Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->sendDtmf(I)Z -Landroid/bluetooth/IBluetoothHeadsetPhone;->updateBtHandsfreeAfterRadioTechnologyChange()V -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->connectChannelToSink(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;I)Z -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->connectChannelToSource(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;)Z -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->disconnectChannel(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;I)Z -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->getConnectedHealthDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->getHealthDeviceConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->getHealthDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->getMainChannelFd(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->registerAppConfiguration(Landroid/bluetooth/BluetoothHealthAppConfiguration;Landroid/bluetooth/IBluetoothHealthCallback;)Z -Landroid/bluetooth/IBluetoothHealth$Stub$Proxy;->unregisterAppConfiguration(Landroid/bluetooth/BluetoothHealthAppConfiguration;)Z -Landroid/bluetooth/IBluetoothHealth$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHealth$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHealth; -Landroid/bluetooth/IBluetoothHealth$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_connectChannelToSink:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_connectChannelToSource:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_disconnectChannel:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_getConnectedHealthDevices:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_getHealthDeviceConnectionState:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_getHealthDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_getMainChannelFd:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_registerAppConfiguration:I -Landroid/bluetooth/IBluetoothHealth$Stub;->TRANSACTION_unregisterAppConfiguration:I -Landroid/bluetooth/IBluetoothHealth;->connectChannelToSink(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;I)Z -Landroid/bluetooth/IBluetoothHealth;->connectChannelToSource(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;)Z -Landroid/bluetooth/IBluetoothHealth;->disconnectChannel(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;I)Z -Landroid/bluetooth/IBluetoothHealth;->getConnectedHealthDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHealth;->getHealthDeviceConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHealth;->getHealthDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHealth;->getMainChannelFd(Landroid/bluetooth/BluetoothDevice;Landroid/bluetooth/BluetoothHealthAppConfiguration;)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothHealth;->registerAppConfiguration(Landroid/bluetooth/BluetoothHealthAppConfiguration;Landroid/bluetooth/IBluetoothHealthCallback;)Z -Landroid/bluetooth/IBluetoothHealth;->unregisterAppConfiguration(Landroid/bluetooth/BluetoothHealthAppConfiguration;)Z -Landroid/bluetooth/IBluetoothHealthCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHealthCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHealthCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHealthCallback$Stub$Proxy;->onHealthAppConfigurationStatusChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;I)V -Landroid/bluetooth/IBluetoothHealthCallback$Stub$Proxy;->onHealthChannelStateChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;Landroid/bluetooth/BluetoothDevice;IILandroid/os/ParcelFileDescriptor;I)V -Landroid/bluetooth/IBluetoothHealthCallback$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHealthCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHealthCallback; -Landroid/bluetooth/IBluetoothHealthCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHealthCallback$Stub;->TRANSACTION_onHealthAppConfigurationStatusChange:I -Landroid/bluetooth/IBluetoothHealthCallback$Stub;->TRANSACTION_onHealthChannelStateChange:I -Landroid/bluetooth/IBluetoothHealthCallback;->onHealthAppConfigurationStatusChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;I)V -Landroid/bluetooth/IBluetoothHealthCallback;->onHealthChannelStateChange(Landroid/bluetooth/BluetoothHealthAppConfiguration;Landroid/bluetooth/BluetoothDevice;IILandroid/os/ParcelFileDescriptor;I)V -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->adjustVolume(I)V -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getActiveDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getDeviceMode(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getDeviceSide(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getHiSyncId(Landroid/bluetooth/BluetoothDevice;)J -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->getVolume()I -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHearingAid$Stub$Proxy;->setVolume(I)V -Landroid/bluetooth/IBluetoothHearingAid$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHearingAid$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHearingAid; -Landroid/bluetooth/IBluetoothHearingAid$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_adjustVolume:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getActiveDevices:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getDeviceMode:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getDeviceSide:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getHiSyncId:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_getVolume:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_setActiveDevice:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothHearingAid$Stub;->TRANSACTION_setVolume:I -Landroid/bluetooth/IBluetoothHearingAid;->adjustVolume(I)V -Landroid/bluetooth/IBluetoothHearingAid;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid;->getActiveDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid;->getDeviceMode(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid;->getDeviceSide(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHearingAid;->getHiSyncId(Landroid/bluetooth/BluetoothDevice;)J -Landroid/bluetooth/IBluetoothHearingAid;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHearingAid;->getVolume()I -Landroid/bluetooth/IBluetoothHearingAid;->HI_SYNC_ID_INVALID:I -Landroid/bluetooth/IBluetoothHearingAid;->MODE_BINAURAL:I -Landroid/bluetooth/IBluetoothHearingAid;->MODE_MONAURAL:I -Landroid/bluetooth/IBluetoothHearingAid;->setActiveDevice(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHearingAid;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHearingAid;->setVolume(I)V -Landroid/bluetooth/IBluetoothHearingAid;->SIDE_LEFT:I -Landroid/bluetooth/IBluetoothHearingAid;->SIDE_RIGHT:I -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->getUserAppName()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->registerApp(Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;Landroid/bluetooth/IBluetoothHidDeviceCallback;)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->replyReport(Landroid/bluetooth/BluetoothDevice;BB[B)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->reportError(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->sendReport(Landroid/bluetooth/BluetoothDevice;I[B)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->unplug(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice$Stub$Proxy;->unregisterApp()Z -Landroid/bluetooth/IBluetoothHidDevice$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHidDevice$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHidDevice; -Landroid/bluetooth/IBluetoothHidDevice$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_getUserAppName:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_registerApp:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_replyReport:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_reportError:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_sendReport:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_unplug:I -Landroid/bluetooth/IBluetoothHidDevice$Stub;->TRANSACTION_unregisterApp:I -Landroid/bluetooth/IBluetoothHidDevice;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHidDevice;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidDevice;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHidDevice;->getUserAppName()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDevice;->registerApp(Landroid/bluetooth/BluetoothHidDeviceAppSdpSettings;Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;Landroid/bluetooth/BluetoothHidDeviceAppQosSettings;Landroid/bluetooth/IBluetoothHidDeviceCallback;)Z -Landroid/bluetooth/IBluetoothHidDevice;->replyReport(Landroid/bluetooth/BluetoothDevice;BB[B)Z -Landroid/bluetooth/IBluetoothHidDevice;->reportError(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHidDevice;->sendReport(Landroid/bluetooth/BluetoothDevice;I[B)Z -Landroid/bluetooth/IBluetoothHidDevice;->unplug(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidDevice;->unregisterApp()Z -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onAppStatusChanged(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onConnectionStateChanged(Landroid/bluetooth/BluetoothDevice;I)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onGetReport(Landroid/bluetooth/BluetoothDevice;BBI)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onInterruptData(Landroid/bluetooth/BluetoothDevice;B[B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onSetProtocol(Landroid/bluetooth/BluetoothDevice;B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onSetReport(Landroid/bluetooth/BluetoothDevice;BB[B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub$Proxy;->onVirtualCableUnplug(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHidDeviceCallback; -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onAppStatusChanged:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onConnectionStateChanged:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onGetReport:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onInterruptData:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onSetProtocol:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onSetReport:I -Landroid/bluetooth/IBluetoothHidDeviceCallback$Stub;->TRANSACTION_onVirtualCableUnplug:I -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onAppStatusChanged(Landroid/bluetooth/BluetoothDevice;Z)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onConnectionStateChanged(Landroid/bluetooth/BluetoothDevice;I)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onGetReport(Landroid/bluetooth/BluetoothDevice;BBI)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onInterruptData(Landroid/bluetooth/BluetoothDevice;B[B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onSetProtocol(Landroid/bluetooth/BluetoothDevice;B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onSetReport(Landroid/bluetooth/BluetoothDevice;BB[B)V -Landroid/bluetooth/IBluetoothHidDeviceCallback;->onVirtualCableUnplug(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getIdleTime(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getProtocolMode(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->getReport(Landroid/bluetooth/BluetoothDevice;BBI)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->sendData(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->setIdleTime(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->setProtocolMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->setReport(Landroid/bluetooth/BluetoothDevice;BLjava/lang/String;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub$Proxy;->virtualUnplug(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost$Stub;-><init>()V -Landroid/bluetooth/IBluetoothHidHost$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothHidHost; -Landroid/bluetooth/IBluetoothHidHost$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getIdleTime:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getProtocolMode:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_getReport:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_sendData:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_setIdleTime:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_setProtocolMode:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_setReport:I -Landroid/bluetooth/IBluetoothHidHost$Stub;->TRANSACTION_virtualUnplug:I -Landroid/bluetooth/IBluetoothHidHost;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothHidHost;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidHost;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothHidHost;->getIdleTime(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothHidHost;->getProtocolMode(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothHidHost;->getReport(Landroid/bluetooth/BluetoothDevice;BBI)Z -Landroid/bluetooth/IBluetoothHidHost;->sendData(Landroid/bluetooth/BluetoothDevice;Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothHidHost;->setIdleTime(Landroid/bluetooth/BluetoothDevice;B)Z -Landroid/bluetooth/IBluetoothHidHost;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHidHost;->setProtocolMode(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothHidHost;->setReport(Landroid/bluetooth/BluetoothDevice;BLjava/lang/String;)Z -Landroid/bluetooth/IBluetoothHidHost;->virtualUnplug(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->bindBluetoothProfileService(ILandroid/bluetooth/IBluetoothProfileServiceConnection;)Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->disable(Ljava/lang/String;Z)Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->enable(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->enableNoAutoConnect(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->getAddress()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->getBluetoothGatt()Landroid/bluetooth/IBluetoothGatt; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->getName()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->getState()I -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->isBleAppPresent()Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->isBleScanAlwaysAvailable()Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->isEnabled()Z -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->registerAdapter(Landroid/bluetooth/IBluetoothManagerCallback;)Landroid/bluetooth/IBluetooth; -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->registerStateChangeCallback(Landroid/bluetooth/IBluetoothStateChangeCallback;)V -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->unbindBluetoothProfileService(ILandroid/bluetooth/IBluetoothProfileServiceConnection;)V -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->unregisterAdapter(Landroid/bluetooth/IBluetoothManagerCallback;)V -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->unregisterStateChangeCallback(Landroid/bluetooth/IBluetoothStateChangeCallback;)V -Landroid/bluetooth/IBluetoothManager$Stub$Proxy;->updateBleAppCount(Landroid/os/IBinder;ZLjava/lang/String;)I -Landroid/bluetooth/IBluetoothManager$Stub;-><init>()V -Landroid/bluetooth/IBluetoothManager$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_bindBluetoothProfileService:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_disable:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_enableNoAutoConnect:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_getAddress:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_getBluetoothGatt:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_getName:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_getState:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_isBleAppPresent:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_isBleScanAlwaysAvailable:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_isEnabled:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_registerAdapter:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_registerStateChangeCallback:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_unbindBluetoothProfileService:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_unregisterAdapter:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_unregisterStateChangeCallback:I -Landroid/bluetooth/IBluetoothManager$Stub;->TRANSACTION_updateBleAppCount:I -Landroid/bluetooth/IBluetoothManager;->bindBluetoothProfileService(ILandroid/bluetooth/IBluetoothProfileServiceConnection;)Z -Landroid/bluetooth/IBluetoothManager;->disable(Ljava/lang/String;Z)Z -Landroid/bluetooth/IBluetoothManager;->enable(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothManager;->enableNoAutoConnect(Ljava/lang/String;)Z -Landroid/bluetooth/IBluetoothManager;->getAddress()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager;->getName()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManager;->getState()I -Landroid/bluetooth/IBluetoothManager;->isBleAppPresent()Z -Landroid/bluetooth/IBluetoothManager;->isBleScanAlwaysAvailable()Z -Landroid/bluetooth/IBluetoothManager;->isEnabled()Z -Landroid/bluetooth/IBluetoothManager;->registerAdapter(Landroid/bluetooth/IBluetoothManagerCallback;)Landroid/bluetooth/IBluetooth; -Landroid/bluetooth/IBluetoothManager;->unbindBluetoothProfileService(ILandroid/bluetooth/IBluetoothProfileServiceConnection;)V -Landroid/bluetooth/IBluetoothManager;->unregisterAdapter(Landroid/bluetooth/IBluetoothManagerCallback;)V -Landroid/bluetooth/IBluetoothManager;->updateBleAppCount(Landroid/os/IBinder;ZLjava/lang/String;)I -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;->onBluetoothServiceDown()V -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;->onBluetoothServiceUp(Landroid/bluetooth/IBluetooth;)V -Landroid/bluetooth/IBluetoothManagerCallback$Stub$Proxy;->onBrEdrDown()V -Landroid/bluetooth/IBluetoothManagerCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothManagerCallback; -Landroid/bluetooth/IBluetoothManagerCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothManagerCallback$Stub;->TRANSACTION_onBluetoothServiceDown:I -Landroid/bluetooth/IBluetoothManagerCallback$Stub;->TRANSACTION_onBluetoothServiceUp:I -Landroid/bluetooth/IBluetoothManagerCallback$Stub;->TRANSACTION_onBrEdrDown:I -Landroid/bluetooth/IBluetoothManagerCallback;->onBluetoothServiceDown()V -Landroid/bluetooth/IBluetoothManagerCallback;->onBluetoothServiceUp(Landroid/bluetooth/IBluetooth;)V -Landroid/bluetooth/IBluetoothManagerCallback;->onBrEdrDown()V -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->getState()I -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothMap$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothMap$Stub;-><init>()V -Landroid/bluetooth/IBluetoothMap$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothMap; -Landroid/bluetooth/IBluetoothMap$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getClient:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_getState:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_isConnected:I -Landroid/bluetooth/IBluetoothMap$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothMap;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothMap;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothMap;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMap;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothMap;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMap;->getState()I -Landroid/bluetooth/IBluetoothMap;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMap;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->getUnreadMessages(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->sendMessage(Landroid/bluetooth/BluetoothDevice;[Landroid/net/Uri;Ljava/lang/String;Landroid/app/PendingIntent;Landroid/app/PendingIntent;)Z -Landroid/bluetooth/IBluetoothMapClient$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothMapClient$Stub;-><init>()V -Landroid/bluetooth/IBluetoothMapClient$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothMapClient; -Landroid/bluetooth/IBluetoothMapClient$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_getUnreadMessages:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_isConnected:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_sendMessage:I -Landroid/bluetooth/IBluetoothMapClient$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothMapClient;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothMapClient;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMapClient;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothMapClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothMapClient;->getUnreadMessages(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothMapClient;->sendMessage(Landroid/bluetooth/BluetoothDevice;[Landroid/net/Uri;Ljava/lang/String;Landroid/app/PendingIntent;Landroid/app/PendingIntent;)Z -Landroid/bluetooth/IBluetoothMapClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->isTetheringOn()Z -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothPan$Stub$Proxy;->setBluetoothTethering(Z)V -Landroid/bluetooth/IBluetoothPan$Stub;-><init>()V -Landroid/bluetooth/IBluetoothPan$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothPan; -Landroid/bluetooth/IBluetoothPan$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_isTetheringOn:I -Landroid/bluetooth/IBluetoothPan$Stub;->TRANSACTION_setBluetoothTethering:I -Landroid/bluetooth/IBluetoothPan;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPan;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPan;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPan;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPan;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPan;->isTetheringOn()Z -Landroid/bluetooth/IBluetoothPan;->setBluetoothTethering(Z)V -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothPbap$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothPbap$Stub;-><init>()V -Landroid/bluetooth/IBluetoothPbap$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothPbap$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothPbap$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothPbap$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothPbap$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothPbap;->disconnect(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothPbap;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPbap;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbap;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothPbapClient$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothPbapClient$Stub;-><init>()V -Landroid/bluetooth/IBluetoothPbapClient$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothPbapClient; -Landroid/bluetooth/IBluetoothPbapClient$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothPbapClient$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothPbapClient;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPbapClient;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothPbapClient;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothPbapClient;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbapClient;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothPbapClient;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothPbapClient;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub$Proxy;->onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub$Proxy;->onServiceDisconnected(Landroid/content/ComponentName;)V -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub;-><init>()V -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothProfileServiceConnection; -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub;->TRANSACTION_onServiceConnected:I -Landroid/bluetooth/IBluetoothProfileServiceConnection$Stub;->TRANSACTION_onServiceDisconnected:I -Landroid/bluetooth/IBluetoothProfileServiceConnection;->onServiceConnected(Landroid/content/ComponentName;Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothProfileServiceConnection;->onServiceDisconnected(Landroid/content/ComponentName;)V -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->getState()I -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothSap$Stub$Proxy;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothSap$Stub;-><init>()V -Landroid/bluetooth/IBluetoothSap$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothSap; -Landroid/bluetooth/IBluetoothSap$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_connect:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_disconnect:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getClient:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getConnectedDevices:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getConnectionState:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getDevicesMatchingConnectionStates:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getPriority:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_getState:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_isConnected:I -Landroid/bluetooth/IBluetoothSap$Stub;->TRANSACTION_setPriority:I -Landroid/bluetooth/IBluetoothSap;->connect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap;->disconnect(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap;->getClient()Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/IBluetoothSap;->getConnectedDevices()Ljava/util/List; -Landroid/bluetooth/IBluetoothSap;->getConnectionState(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothSap;->getDevicesMatchingConnectionStates([I)Ljava/util/List; -Landroid/bluetooth/IBluetoothSap;->getPriority(Landroid/bluetooth/BluetoothDevice;)I -Landroid/bluetooth/IBluetoothSap;->getState()I -Landroid/bluetooth/IBluetoothSap;->isConnected(Landroid/bluetooth/BluetoothDevice;)Z -Landroid/bluetooth/IBluetoothSap;->setPriority(Landroid/bluetooth/BluetoothDevice;I)Z -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;->connectSocket(Landroid/bluetooth/BluetoothDevice;ILandroid/os/ParcelUuid;II)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;->createSocketChannel(ILjava/lang/String;Landroid/os/ParcelUuid;II)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothSocketManager$Stub$Proxy;->requestMaximumTxDataLength(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothSocketManager$Stub;-><init>()V -Landroid/bluetooth/IBluetoothSocketManager$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothSocketManager; -Landroid/bluetooth/IBluetoothSocketManager$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothSocketManager$Stub;->TRANSACTION_connectSocket:I -Landroid/bluetooth/IBluetoothSocketManager$Stub;->TRANSACTION_createSocketChannel:I -Landroid/bluetooth/IBluetoothSocketManager$Stub;->TRANSACTION_requestMaximumTxDataLength:I -Landroid/bluetooth/IBluetoothSocketManager;->connectSocket(Landroid/bluetooth/BluetoothDevice;ILandroid/os/ParcelUuid;II)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothSocketManager;->createSocketChannel(ILjava/lang/String;Landroid/os/ParcelUuid;II)Landroid/os/ParcelFileDescriptor; -Landroid/bluetooth/IBluetoothSocketManager;->requestMaximumTxDataLength(Landroid/bluetooth/BluetoothDevice;)V -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub$Proxy;->onBluetoothStateChange(Z)V -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/IBluetoothStateChangeCallback; -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/IBluetoothStateChangeCallback$Stub;->TRANSACTION_onBluetoothStateChange:I -Landroid/bluetooth/IBluetoothStateChangeCallback;->onBluetoothStateChange(Z)V -Landroid/bluetooth/le/AdvertiseCallback;->ADVERTISE_SUCCESS:I -Landroid/bluetooth/le/AdvertiseData$Builder;->mIncludeDeviceName:Z -Landroid/bluetooth/le/AdvertiseData$Builder;->mIncludeTxPowerLevel:Z -Landroid/bluetooth/le/AdvertiseData$Builder;->mManufacturerSpecificData:Landroid/util/SparseArray; -Landroid/bluetooth/le/AdvertiseData$Builder;->mServiceData:Ljava/util/Map; -Landroid/bluetooth/le/AdvertiseData$Builder;->mServiceUuids:Ljava/util/List; -Landroid/bluetooth/le/AdvertiseData;-><init>(Ljava/util/List;Landroid/util/SparseArray;Ljava/util/Map;ZZ)V -Landroid/bluetooth/le/AdvertiseData;->mIncludeDeviceName:Z -Landroid/bluetooth/le/AdvertiseData;->mIncludeTxPowerLevel:Z -Landroid/bluetooth/le/AdvertiseData;->mManufacturerSpecificData:Landroid/util/SparseArray; -Landroid/bluetooth/le/AdvertiseData;->mServiceData:Ljava/util/Map; -Landroid/bluetooth/le/AdvertiseData;->mServiceUuids:Ljava/util/List; -Landroid/bluetooth/le/AdvertiseSettings$Builder;->mConnectable:Z -Landroid/bluetooth/le/AdvertiseSettings$Builder;->mMode:I -Landroid/bluetooth/le/AdvertiseSettings$Builder;->mTimeoutMillis:I -Landroid/bluetooth/le/AdvertiseSettings$Builder;->mTxPowerLevel:I -Landroid/bluetooth/le/AdvertiseSettings;-><init>(IIZI)V -Landroid/bluetooth/le/AdvertiseSettings;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/AdvertiseSettings;->LIMITED_ADVERTISING_MAX_MILLIS:I -Landroid/bluetooth/le/AdvertiseSettings;->mAdvertiseConnectable:Z -Landroid/bluetooth/le/AdvertiseSettings;->mAdvertiseMode:I -Landroid/bluetooth/le/AdvertiseSettings;->mAdvertiseTimeoutMillis:I -Landroid/bluetooth/le/AdvertiseSettings;->mAdvertiseTxPowerLevel:I -Landroid/bluetooth/le/AdvertisingSet;-><init>(ILandroid/bluetooth/IBluetoothManager;)V -Landroid/bluetooth/le/AdvertisingSet;->getAdvertiserId()I -Landroid/bluetooth/le/AdvertisingSet;->getOwnAddress()V -Landroid/bluetooth/le/AdvertisingSet;->mAdvertiserId:I -Landroid/bluetooth/le/AdvertisingSet;->mGatt:Landroid/bluetooth/IBluetoothGatt; -Landroid/bluetooth/le/AdvertisingSet;->setAdvertiserId(I)V -Landroid/bluetooth/le/AdvertisingSet;->TAG:Ljava/lang/String; -Landroid/bluetooth/le/AdvertisingSetCallback;->onOwnAddressRead(Landroid/bluetooth/le/AdvertisingSet;ILjava/lang/String;)V -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mConnectable:Z -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mIncludeTxPower:Z -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mInterval:I -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mIsAnonymous:Z -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mIsLegacy:Z -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mPrimaryPhy:I -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mScannable:Z -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mSecondaryPhy:I -Landroid/bluetooth/le/AdvertisingSetParameters$Builder;->mTxPowerLevel:I -Landroid/bluetooth/le/AdvertisingSetParameters;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/AdvertisingSetParameters;-><init>(ZZZZZIIII)V -Landroid/bluetooth/le/AdvertisingSetParameters;->LIMITED_ADVERTISING_MAX_MILLIS:I -Landroid/bluetooth/le/AdvertisingSetParameters;->mConnectable:Z -Landroid/bluetooth/le/AdvertisingSetParameters;->mIncludeTxPower:Z -Landroid/bluetooth/le/AdvertisingSetParameters;->mInterval:I -Landroid/bluetooth/le/AdvertisingSetParameters;->mIsAnonymous:Z -Landroid/bluetooth/le/AdvertisingSetParameters;->mIsLegacy:Z -Landroid/bluetooth/le/AdvertisingSetParameters;->mPrimaryPhy:I -Landroid/bluetooth/le/AdvertisingSetParameters;->mScannable:Z -Landroid/bluetooth/le/AdvertisingSetParameters;->mSecondaryPhy:I -Landroid/bluetooth/le/AdvertisingSetParameters;->mTxPowerLevel:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;-><init>(Landroid/bluetooth/IBluetoothManager;)V -Landroid/bluetooth/le/BluetoothLeAdvertiser;->byteLength([B)I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->cleanup()V -Landroid/bluetooth/le/BluetoothLeAdvertiser;->FLAGS_FIELD_BYTES:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mAdvertisingSets:Ljava/util/Map; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->MANUFACTURER_SPECIFIC_DATA_LENGTH:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->MAX_ADVERTISING_DATA_BYTES:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->MAX_LEGACY_ADVERTISING_DATA_BYTES:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mBluetoothAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mBluetoothManager:Landroid/bluetooth/IBluetoothManager; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mCallbackWrappers:Ljava/util/Map; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mHandler:Landroid/os/Handler; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->mLegacyAdvertisers:Ljava/util/Map; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->OVERHEAD_BYTES_PER_FIELD:I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->postStartFailure(Landroid/bluetooth/le/AdvertiseCallback;I)V -Landroid/bluetooth/le/BluetoothLeAdvertiser;->postStartSetFailure(Landroid/os/Handler;Landroid/bluetooth/le/AdvertisingSetCallback;I)V -Landroid/bluetooth/le/BluetoothLeAdvertiser;->postStartSuccess(Landroid/bluetooth/le/AdvertiseCallback;Landroid/bluetooth/le/AdvertiseSettings;)V -Landroid/bluetooth/le/BluetoothLeAdvertiser;->TAG:Ljava/lang/String; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->totalBytes(Landroid/bluetooth/le/AdvertiseData;Z)I -Landroid/bluetooth/le/BluetoothLeAdvertiser;->wrap(Landroid/bluetooth/le/AdvertisingSetCallback;Landroid/os/Handler;)Landroid/bluetooth/le/IAdvertisingSetCallback; -Landroid/bluetooth/le/BluetoothLeAdvertiser;->wrapOldCallback(Landroid/bluetooth/le/AdvertiseCallback;Landroid/bluetooth/le/AdvertiseSettings;)Landroid/bluetooth/le/AdvertisingSetCallback; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->flushPendingBatchResults()V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mBluetoothGatt:Landroid/bluetooth/IBluetoothGatt; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mFilters:Ljava/util/List; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mResultStorages:Ljava/util/List; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mScanCallback:Landroid/bluetooth/le/ScanCallback; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mScannerId:I -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mSettings:Landroid/bluetooth/le/ScanSettings; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->mWorkSource:Landroid/os/WorkSource; -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->onBatchScanResults(Ljava/util/List;)V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->onFoundOrLost(ZLandroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->onScanManagerErrorCallback(I)V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->onScannerRegistered(II)V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->onScanResult(Landroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->REGISTRATION_CALLBACK_TIMEOUT_MILLIS:I -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->startRegistration()V -Landroid/bluetooth/le/BluetoothLeScanner$BleScanCallbackWrapper;->stopLeScan()V -Landroid/bluetooth/le/BluetoothLeScanner;-><init>(Landroid/bluetooth/IBluetoothManager;)V -Landroid/bluetooth/le/BluetoothLeScanner;->cleanup()V -Landroid/bluetooth/le/BluetoothLeScanner;->DBG:Z -Landroid/bluetooth/le/BluetoothLeScanner;->isHardwareResourcesAvailableForScan(Landroid/bluetooth/le/ScanSettings;)Z -Landroid/bluetooth/le/BluetoothLeScanner;->isSettingsAndFilterComboAllowed(Landroid/bluetooth/le/ScanSettings;Ljava/util/List;)Z -Landroid/bluetooth/le/BluetoothLeScanner;->isSettingsConfigAllowedForScan(Landroid/bluetooth/le/ScanSettings;)Z -Landroid/bluetooth/le/BluetoothLeScanner;->mBluetoothAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/le/BluetoothLeScanner;->mBluetoothManager:Landroid/bluetooth/IBluetoothManager; -Landroid/bluetooth/le/BluetoothLeScanner;->mHandler:Landroid/os/Handler; -Landroid/bluetooth/le/BluetoothLeScanner;->mLeScanClients:Ljava/util/Map; -Landroid/bluetooth/le/BluetoothLeScanner;->postCallbackError(Landroid/bluetooth/le/ScanCallback;I)V -Landroid/bluetooth/le/BluetoothLeScanner;->postCallbackErrorOrReturn(Landroid/bluetooth/le/ScanCallback;I)I -Landroid/bluetooth/le/BluetoothLeScanner;->startScan(Ljava/util/List;Landroid/bluetooth/le/ScanSettings;Landroid/os/WorkSource;Landroid/bluetooth/le/ScanCallback;Landroid/app/PendingIntent;Ljava/util/List;)I -Landroid/bluetooth/le/BluetoothLeScanner;->TAG:Ljava/lang/String; -Landroid/bluetooth/le/BluetoothLeScanner;->VDBG:Z -Landroid/bluetooth/le/BluetoothLeUtils;-><init>()V -Landroid/bluetooth/le/BluetoothLeUtils;->checkAdapterStateOn(Landroid/bluetooth/BluetoothAdapter;)V -Landroid/bluetooth/le/BluetoothLeUtils;->equals(Landroid/util/SparseArray;Landroid/util/SparseArray;)Z -Landroid/bluetooth/le/BluetoothLeUtils;->equals(Ljava/util/Map;Ljava/util/Map;)Z -Landroid/bluetooth/le/BluetoothLeUtils;->toString(Landroid/util/SparseArray;)Ljava/lang/String; -Landroid/bluetooth/le/BluetoothLeUtils;->toString(Ljava/util/Map;)Ljava/lang/String; -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onAdvertisingDataSet(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onAdvertisingEnabled(IZI)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onAdvertisingParametersUpdated(III)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onAdvertisingSetStarted(III)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onAdvertisingSetStopped(I)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onOwnAddressRead(IILjava/lang/String;)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onPeriodicAdvertisingDataSet(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onPeriodicAdvertisingEnabled(IZI)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onPeriodicAdvertisingParametersUpdated(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub$Proxy;->onScanResponseDataSet(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;-><init>()V -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/le/IAdvertisingSetCallback; -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onAdvertisingDataSet:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onAdvertisingEnabled:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onAdvertisingParametersUpdated:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onAdvertisingSetStarted:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onAdvertisingSetStopped:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onOwnAddressRead:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onPeriodicAdvertisingDataSet:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onPeriodicAdvertisingEnabled:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onPeriodicAdvertisingParametersUpdated:I -Landroid/bluetooth/le/IAdvertisingSetCallback$Stub;->TRANSACTION_onScanResponseDataSet:I -Landroid/bluetooth/le/IAdvertisingSetCallback;->onAdvertisingDataSet(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onAdvertisingEnabled(IZI)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onAdvertisingParametersUpdated(III)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onAdvertisingSetStarted(III)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onAdvertisingSetStopped(I)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onOwnAddressRead(IILjava/lang/String;)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onPeriodicAdvertisingDataSet(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onPeriodicAdvertisingEnabled(IZI)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onPeriodicAdvertisingParametersUpdated(II)V -Landroid/bluetooth/le/IAdvertisingSetCallback;->onScanResponseDataSet(II)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;->onPeriodicAdvertisingReport(Landroid/bluetooth/le/PeriodicAdvertisingReport;)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;->onSyncEstablished(ILandroid/bluetooth/BluetoothDevice;IIII)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub$Proxy;->onSyncLost(I)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;-><init>()V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/le/IPeriodicAdvertisingCallback; -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;->TRANSACTION_onPeriodicAdvertisingReport:I -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;->TRANSACTION_onSyncEstablished:I -Landroid/bluetooth/le/IPeriodicAdvertisingCallback$Stub;->TRANSACTION_onSyncLost:I -Landroid/bluetooth/le/IPeriodicAdvertisingCallback;->onPeriodicAdvertisingReport(Landroid/bluetooth/le/PeriodicAdvertisingReport;)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback;->onSyncEstablished(ILandroid/bluetooth/BluetoothDevice;IIII)V -Landroid/bluetooth/le/IPeriodicAdvertisingCallback;->onSyncLost(I)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;-><init>(Landroid/os/IBinder;)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->getInterfaceDescriptor()Ljava/lang/String; -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->mRemote:Landroid/os/IBinder; -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->onBatchScanResults(Ljava/util/List;)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->onFoundOrLost(ZLandroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->onScanManagerErrorCallback(I)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->onScannerRegistered(II)V -Landroid/bluetooth/le/IScannerCallback$Stub$Proxy;->onScanResult(Landroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/IScannerCallback$Stub;-><init>()V -Landroid/bluetooth/le/IScannerCallback$Stub;->asInterface(Landroid/os/IBinder;)Landroid/bluetooth/le/IScannerCallback; -Landroid/bluetooth/le/IScannerCallback$Stub;->DESCRIPTOR:Ljava/lang/String; -Landroid/bluetooth/le/IScannerCallback$Stub;->TRANSACTION_onBatchScanResults:I -Landroid/bluetooth/le/IScannerCallback$Stub;->TRANSACTION_onFoundOrLost:I -Landroid/bluetooth/le/IScannerCallback$Stub;->TRANSACTION_onScanManagerErrorCallback:I -Landroid/bluetooth/le/IScannerCallback$Stub;->TRANSACTION_onScannerRegistered:I -Landroid/bluetooth/le/IScannerCallback$Stub;->TRANSACTION_onScanResult:I -Landroid/bluetooth/le/IScannerCallback;->onBatchScanResults(Ljava/util/List;)V -Landroid/bluetooth/le/IScannerCallback;->onFoundOrLost(ZLandroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/IScannerCallback;->onScanManagerErrorCallback(I)V -Landroid/bluetooth/le/IScannerCallback;->onScannerRegistered(II)V -Landroid/bluetooth/le/IScannerCallback;->onScanResult(Landroid/bluetooth/le/ScanResult;)V -Landroid/bluetooth/le/PeriodicAdvertisingCallback;-><init>()V -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->onPeriodicAdvertisingReport(Landroid/bluetooth/le/PeriodicAdvertisingReport;)V -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->onSyncEstablished(ILandroid/bluetooth/BluetoothDevice;IIII)V -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->onSyncLost(I)V -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->SYNC_NO_RESOURCES:I -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->SYNC_NO_RESPONSE:I -Landroid/bluetooth/le/PeriodicAdvertisingCallback;->SYNC_SUCCESS:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;-><init>(Landroid/bluetooth/IBluetoothManager;)V -Landroid/bluetooth/le/PeriodicAdvertisingManager;->mBluetoothAdapter:Landroid/bluetooth/BluetoothAdapter; -Landroid/bluetooth/le/PeriodicAdvertisingManager;->mBluetoothManager:Landroid/bluetooth/IBluetoothManager; -Landroid/bluetooth/le/PeriodicAdvertisingManager;->mCallbackWrappers:Ljava/util/Map; -Landroid/bluetooth/le/PeriodicAdvertisingManager;->registerSync(Landroid/bluetooth/le/ScanResult;IILandroid/bluetooth/le/PeriodicAdvertisingCallback;)V -Landroid/bluetooth/le/PeriodicAdvertisingManager;->registerSync(Landroid/bluetooth/le/ScanResult;IILandroid/bluetooth/le/PeriodicAdvertisingCallback;Landroid/os/Handler;)V -Landroid/bluetooth/le/PeriodicAdvertisingManager;->SKIP_MAX:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;->SKIP_MIN:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;->SYNC_STARTING:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;->TAG:Ljava/lang/String; -Landroid/bluetooth/le/PeriodicAdvertisingManager;->TIMEOUT_MAX:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;->TIMEOUT_MIN:I -Landroid/bluetooth/le/PeriodicAdvertisingManager;->unregisterSync(Landroid/bluetooth/le/PeriodicAdvertisingCallback;)V -Landroid/bluetooth/le/PeriodicAdvertisingManager;->wrap(Landroid/bluetooth/le/PeriodicAdvertisingCallback;Landroid/os/Handler;)Landroid/bluetooth/le/IPeriodicAdvertisingCallback; -Landroid/bluetooth/le/PeriodicAdvertisingParameters$Builder;->mIncludeTxPower:Z -Landroid/bluetooth/le/PeriodicAdvertisingParameters$Builder;->mInterval:I -Landroid/bluetooth/le/PeriodicAdvertisingParameters;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/PeriodicAdvertisingParameters;-><init>(ZI)V -Landroid/bluetooth/le/PeriodicAdvertisingParameters;->INTERVAL_MAX:I -Landroid/bluetooth/le/PeriodicAdvertisingParameters;->INTERVAL_MIN:I -Landroid/bluetooth/le/PeriodicAdvertisingParameters;->mIncludeTxPower:Z -Landroid/bluetooth/le/PeriodicAdvertisingParameters;->mInterval:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;-><init>(IIIILandroid/bluetooth/le/ScanRecord;)V -Landroid/bluetooth/le/PeriodicAdvertisingReport;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/PeriodicAdvertisingReport;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/le/PeriodicAdvertisingReport;->DATA_COMPLETE:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->DATA_INCOMPLETE_TRUNCATED:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getData()Landroid/bluetooth/le/ScanRecord; -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getDataStatus()I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getRssi()I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getSyncHandle()I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getTimestampNanos()J -Landroid/bluetooth/le/PeriodicAdvertisingReport;->getTxPower()I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mData:Landroid/bluetooth/le/ScanRecord; -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mDataStatus:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mRssi:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mSyncHandle:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mTimestampNanos:J -Landroid/bluetooth/le/PeriodicAdvertisingReport;->mTxPower:I -Landroid/bluetooth/le/PeriodicAdvertisingReport;->readFromParcel(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ResultStorageDescriptor;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ResultStorageDescriptor;->mLength:I -Landroid/bluetooth/le/ResultStorageDescriptor;->mOffset:I -Landroid/bluetooth/le/ResultStorageDescriptor;->mType:I -Landroid/bluetooth/le/ResultStorageDescriptor;->ReadFromParcel(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ScanCallback;->NO_ERROR:I -Landroid/bluetooth/le/ScanCallback;->SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES:I -Landroid/bluetooth/le/ScanCallback;->SCAN_FAILED_SCANNING_TOO_FREQUENTLY:I -Landroid/bluetooth/le/ScanFilter$Builder;->mDeviceAddress:Ljava/lang/String; -Landroid/bluetooth/le/ScanFilter$Builder;->mDeviceName:Ljava/lang/String; -Landroid/bluetooth/le/ScanFilter$Builder;->mManufacturerData:[B -Landroid/bluetooth/le/ScanFilter$Builder;->mManufacturerDataMask:[B -Landroid/bluetooth/le/ScanFilter$Builder;->mManufacturerId:I -Landroid/bluetooth/le/ScanFilter$Builder;->mServiceData:[B -Landroid/bluetooth/le/ScanFilter$Builder;->mServiceDataMask:[B -Landroid/bluetooth/le/ScanFilter$Builder;->mServiceDataUuid:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanFilter$Builder;->mServiceUuid:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanFilter$Builder;->mUuidMask:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanFilter;-><init>(Ljava/lang/String;Ljava/lang/String;Landroid/os/ParcelUuid;Landroid/os/ParcelUuid;Landroid/os/ParcelUuid;[B[BI[B[B)V -Landroid/bluetooth/le/ScanFilter;->EMPTY:Landroid/bluetooth/le/ScanFilter; -Landroid/bluetooth/le/ScanFilter;->isAllFieldsEmpty()Z -Landroid/bluetooth/le/ScanFilter;->matchesPartialData([B[B[B)Z -Landroid/bluetooth/le/ScanFilter;->matchesServiceUuid(Ljava/util/UUID;Ljava/util/UUID;Ljava/util/UUID;)Z -Landroid/bluetooth/le/ScanFilter;->matchesServiceUuids(Landroid/os/ParcelUuid;Landroid/os/ParcelUuid;Ljava/util/List;)Z -Landroid/bluetooth/le/ScanFilter;->mDeviceAddress:Ljava/lang/String; -Landroid/bluetooth/le/ScanFilter;->mDeviceName:Ljava/lang/String; -Landroid/bluetooth/le/ScanFilter;->mManufacturerData:[B -Landroid/bluetooth/le/ScanFilter;->mManufacturerDataMask:[B -Landroid/bluetooth/le/ScanFilter;->mManufacturerId:I -Landroid/bluetooth/le/ScanFilter;->mServiceData:[B -Landroid/bluetooth/le/ScanFilter;->mServiceDataMask:[B -Landroid/bluetooth/le/ScanFilter;->mServiceDataUuid:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanFilter;->mServiceUuid:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanFilter;->mServiceUuidMask:Landroid/os/ParcelUuid; -Landroid/bluetooth/le/ScanRecord;-><init>(Ljava/util/List;Landroid/util/SparseArray;Ljava/util/Map;IILjava/lang/String;[B)V -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_FLAGS:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_LOCAL_NAME_COMPLETE:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_LOCAL_NAME_SHORT:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_MANUFACTURER_SPECIFIC_DATA:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_DATA_128_BIT:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_DATA_16_BIT:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_DATA_32_BIT:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_128_BIT_COMPLETE:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_128_BIT_PARTIAL:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_16_BIT_COMPLETE:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_16_BIT_PARTIAL:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_32_BIT_COMPLETE:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_SERVICE_UUIDS_32_BIT_PARTIAL:I -Landroid/bluetooth/le/ScanRecord;->DATA_TYPE_TX_POWER_LEVEL:I -Landroid/bluetooth/le/ScanRecord;->extractBytes([BII)[B -Landroid/bluetooth/le/ScanRecord;->mAdvertiseFlags:I -Landroid/bluetooth/le/ScanRecord;->mBytes:[B -Landroid/bluetooth/le/ScanRecord;->mDeviceName:Ljava/lang/String; -Landroid/bluetooth/le/ScanRecord;->mManufacturerSpecificData:Landroid/util/SparseArray; -Landroid/bluetooth/le/ScanRecord;->mServiceData:Ljava/util/Map; -Landroid/bluetooth/le/ScanRecord;->mServiceUuids:Ljava/util/List; -Landroid/bluetooth/le/ScanRecord;->mTxPowerLevel:I -Landroid/bluetooth/le/ScanRecord;->parseServiceUuid([BIIILjava/util/List;)I -Landroid/bluetooth/le/ScanRecord;->TAG:Ljava/lang/String; -Landroid/bluetooth/le/ScanResult;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ScanResult;->ET_CONNECTABLE_MASK:I -Landroid/bluetooth/le/ScanResult;->ET_LEGACY_MASK:I -Landroid/bluetooth/le/ScanResult;->mAdvertisingSid:I -Landroid/bluetooth/le/ScanResult;->mDevice:Landroid/bluetooth/BluetoothDevice; -Landroid/bluetooth/le/ScanResult;->mEventType:I -Landroid/bluetooth/le/ScanResult;->mPeriodicAdvertisingInterval:I -Landroid/bluetooth/le/ScanResult;->mPrimaryPhy:I -Landroid/bluetooth/le/ScanResult;->mRssi:I -Landroid/bluetooth/le/ScanResult;->mScanRecord:Landroid/bluetooth/le/ScanRecord; -Landroid/bluetooth/le/ScanResult;->mSecondaryPhy:I -Landroid/bluetooth/le/ScanResult;->mTimestampNanos:J -Landroid/bluetooth/le/ScanResult;->mTxPower:I -Landroid/bluetooth/le/ScanResult;->readFromParcel(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ScanSettings$Builder;->isValidCallbackType(I)Z -Landroid/bluetooth/le/ScanSettings$Builder;->mCallbackType:I -Landroid/bluetooth/le/ScanSettings$Builder;->mLegacy:Z -Landroid/bluetooth/le/ScanSettings$Builder;->mMatchMode:I -Landroid/bluetooth/le/ScanSettings$Builder;->mNumOfMatchesPerFilter:I -Landroid/bluetooth/le/ScanSettings$Builder;->mPhy:I -Landroid/bluetooth/le/ScanSettings$Builder;->mReportDelayMillis:J -Landroid/bluetooth/le/ScanSettings$Builder;->mScanMode:I -Landroid/bluetooth/le/ScanSettings$Builder;->mScanResultType:I -Landroid/bluetooth/le/ScanSettings;-><init>(IIIJIIZI)V -Landroid/bluetooth/le/ScanSettings;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/le/ScanSettings;->getMatchMode()I -Landroid/bluetooth/le/ScanSettings;->getNumOfMatches()I -Landroid/bluetooth/le/ScanSettings;->mCallbackType:I -Landroid/bluetooth/le/ScanSettings;->mLegacy:Z -Landroid/bluetooth/le/ScanSettings;->mMatchMode:I -Landroid/bluetooth/le/ScanSettings;->mNumOfMatchesPerFilter:I -Landroid/bluetooth/le/ScanSettings;->mPhy:I -Landroid/bluetooth/le/ScanSettings;->mReportDelayMillis:J -Landroid/bluetooth/le/ScanSettings;->mScanMode:I -Landroid/bluetooth/le/ScanSettings;->mScanResultType:I -Landroid/bluetooth/le/TruncatedFilter;->mFilter:Landroid/bluetooth/le/ScanFilter; -Landroid/bluetooth/le/TruncatedFilter;->mStorageDescriptors:Ljava/util/List; -Landroid/bluetooth/OobData;-><init>()V -Landroid/bluetooth/OobData;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/OobData;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/OobData;->getLeBluetoothDeviceAddress()[B -Landroid/bluetooth/OobData;->getLeSecureConnectionsConfirmation()[B -Landroid/bluetooth/OobData;->getLeSecureConnectionsRandom()[B -Landroid/bluetooth/OobData;->getSecurityManagerTk()[B -Landroid/bluetooth/OobData;->mLeBluetoothDeviceAddress:[B -Landroid/bluetooth/OobData;->mLeSecureConnectionsConfirmation:[B -Landroid/bluetooth/OobData;->mLeSecureConnectionsRandom:[B -Landroid/bluetooth/OobData;->mSecurityManagerTk:[B -Landroid/bluetooth/OobData;->setLeBluetoothDeviceAddress([B)V -Landroid/bluetooth/OobData;->setLeSecureConnectionsConfirmation([B)V -Landroid/bluetooth/OobData;->setLeSecureConnectionsRandom([B)V -Landroid/bluetooth/OobData;->setSecurityManagerTk([B)V -Landroid/bluetooth/SdpMasRecord$MessageType;-><init>()V -Landroid/bluetooth/SdpMasRecord$MessageType;->EMAIL:I -Landroid/bluetooth/SdpMasRecord$MessageType;->MMS:I -Landroid/bluetooth/SdpMasRecord$MessageType;->SMS_CDMA:I -Landroid/bluetooth/SdpMasRecord$MessageType;->SMS_GSM:I -Landroid/bluetooth/SdpMasRecord;-><init>(IIIIIILjava/lang/String;)V -Landroid/bluetooth/SdpMasRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpMasRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpMasRecord;->getL2capPsm()I -Landroid/bluetooth/SdpMasRecord;->getMasInstanceId()I -Landroid/bluetooth/SdpMasRecord;->getProfileVersion()I -Landroid/bluetooth/SdpMasRecord;->getRfcommCannelNumber()I -Landroid/bluetooth/SdpMasRecord;->getServiceName()Ljava/lang/String; -Landroid/bluetooth/SdpMasRecord;->getSupportedFeatures()I -Landroid/bluetooth/SdpMasRecord;->getSupportedMessageTypes()I -Landroid/bluetooth/SdpMasRecord;->mL2capPsm:I -Landroid/bluetooth/SdpMasRecord;->mMasInstanceId:I -Landroid/bluetooth/SdpMasRecord;->mProfileVersion:I -Landroid/bluetooth/SdpMasRecord;->mRfcommChannelNumber:I -Landroid/bluetooth/SdpMasRecord;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/SdpMasRecord;->msgSupported(I)Z -Landroid/bluetooth/SdpMasRecord;->mSupportedFeatures:I -Landroid/bluetooth/SdpMasRecord;->mSupportedMessageTypes:I -Landroid/bluetooth/SdpMnsRecord;-><init>(IIIILjava/lang/String;)V -Landroid/bluetooth/SdpMnsRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpMnsRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpMnsRecord;->getL2capPsm()I -Landroid/bluetooth/SdpMnsRecord;->getProfileVersion()I -Landroid/bluetooth/SdpMnsRecord;->getRfcommChannelNumber()I -Landroid/bluetooth/SdpMnsRecord;->getServiceName()Ljava/lang/String; -Landroid/bluetooth/SdpMnsRecord;->getSupportedFeatures()I -Landroid/bluetooth/SdpMnsRecord;->mL2capPsm:I -Landroid/bluetooth/SdpMnsRecord;->mProfileVersion:I -Landroid/bluetooth/SdpMnsRecord;->mRfcommChannelNumber:I -Landroid/bluetooth/SdpMnsRecord;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/SdpMnsRecord;->mSupportedFeatures:I -Landroid/bluetooth/SdpOppOpsRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpOppOpsRecord;-><init>(Ljava/lang/String;III[B)V -Landroid/bluetooth/SdpOppOpsRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpOppOpsRecord;->getFormatsList()[B -Landroid/bluetooth/SdpOppOpsRecord;->getL2capPsm()I -Landroid/bluetooth/SdpOppOpsRecord;->getProfileVersion()I -Landroid/bluetooth/SdpOppOpsRecord;->getRfcommChannel()I -Landroid/bluetooth/SdpOppOpsRecord;->getServiceName()Ljava/lang/String; -Landroid/bluetooth/SdpOppOpsRecord;->mFormatsList:[B -Landroid/bluetooth/SdpOppOpsRecord;->mL2capPsm:I -Landroid/bluetooth/SdpOppOpsRecord;->mProfileVersion:I -Landroid/bluetooth/SdpOppOpsRecord;->mRfcommChannel:I -Landroid/bluetooth/SdpOppOpsRecord;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/SdpPseRecord;-><init>(IIIIILjava/lang/String;)V -Landroid/bluetooth/SdpPseRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpPseRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpPseRecord;->getL2capPsm()I -Landroid/bluetooth/SdpPseRecord;->getProfileVersion()I -Landroid/bluetooth/SdpPseRecord;->getRfcommChannelNumber()I -Landroid/bluetooth/SdpPseRecord;->getServiceName()Ljava/lang/String; -Landroid/bluetooth/SdpPseRecord;->getSupportedFeatures()I -Landroid/bluetooth/SdpPseRecord;->getSupportedRepositories()I -Landroid/bluetooth/SdpPseRecord;->mL2capPsm:I -Landroid/bluetooth/SdpPseRecord;->mProfileVersion:I -Landroid/bluetooth/SdpPseRecord;->mRfcommChannelNumber:I -Landroid/bluetooth/SdpPseRecord;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/SdpPseRecord;->mSupportedFeatures:I -Landroid/bluetooth/SdpPseRecord;->mSupportedRepositories:I -Landroid/bluetooth/SdpRecord;-><init>(I[B)V -Landroid/bluetooth/SdpRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpRecord;->getRawData()[B -Landroid/bluetooth/SdpRecord;->getRawSize()I -Landroid/bluetooth/SdpRecord;->mRawData:[B -Landroid/bluetooth/SdpRecord;->mRawSize:I -Landroid/bluetooth/SdpSapsRecord;-><init>(IILjava/lang/String;)V -Landroid/bluetooth/SdpSapsRecord;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/SdpSapsRecord;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/SdpSapsRecord;->getProfileVersion()I -Landroid/bluetooth/SdpSapsRecord;->getRfcommCannelNumber()I -Landroid/bluetooth/SdpSapsRecord;->getServiceName()Ljava/lang/String; -Landroid/bluetooth/SdpSapsRecord;->mProfileVersion:I -Landroid/bluetooth/SdpSapsRecord;->mRfcommChannelNumber:I -Landroid/bluetooth/SdpSapsRecord;->mServiceName:Ljava/lang/String; -Landroid/bluetooth/UidTraffic;-><init>(I)V -Landroid/bluetooth/UidTraffic;-><init>(IJJ)V -Landroid/bluetooth/UidTraffic;-><init>(Landroid/os/Parcel;)V -Landroid/bluetooth/UidTraffic;->addRxBytes(J)V -Landroid/bluetooth/UidTraffic;->addTxBytes(J)V -Landroid/bluetooth/UidTraffic;->CREATOR:Landroid/os/Parcelable$Creator; -Landroid/bluetooth/UidTraffic;->getRxBytes()J -Landroid/bluetooth/UidTraffic;->getTxBytes()J -Landroid/bluetooth/UidTraffic;->getUid()I -Landroid/bluetooth/UidTraffic;->mAppUid:I -Landroid/bluetooth/UidTraffic;->mRxBytes:J -Landroid/bluetooth/UidTraffic;->mTxBytes:J -Landroid/bluetooth/UidTraffic;->setRxBytes(J)V -Landroid/bluetooth/UidTraffic;->setTxBytes(J)V diff --git a/flags/framework.aconfig b/flags/framework.aconfig index 9e38015d0b..bac9c95a26 100644 --- a/flags/framework.aconfig +++ b/flags/framework.aconfig @@ -99,3 +99,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "fix_unhandled_bqr_subevent" + namespace: "bluetooth" + description: "Fix Unhandled BQR subevent on bqr report" + bug: "397854116" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/gap.aconfig b/flags/gap.aconfig index e3e99414ce..1f2241ab6d 100644 --- a/flags/gap.aconfig +++ b/flags/gap.aconfig @@ -294,3 +294,23 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "distance_measurement_thread" + namespace: "bluetooth" + description: "Makes distance measurement operations run on one thread." + bug: "397809459" + metadata { + purpose: PURPOSE_BUGFIX + } +} + +flag { + name: "scan_controller_thread" + namespace: "bluetooth" + description: "Makes scan controller operations run on one thread." + bug: "397863857" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/hfp.aconfig b/flags/hfp.aconfig index f138d94690..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" @@ -128,3 +122,23 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "check_peer_hf_indicator" + namespace: "bluetooth" + description: "Flag to check the peer HF indicator before setting feature mask" + bug: "383933502" + metadata { + 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/hid.aconfig b/flags/hid.aconfig index 6742370525..e59a93c926 100644 --- a/flags/hid.aconfig +++ b/flags/hid.aconfig @@ -145,3 +145,13 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "early_incoming_hid_connection" + namespace: "bluetooth" + description: "Allow early incoming HID connection" + bug: "398105207" + metadata { + purpose: PURPOSE_BUGFIX + } +} diff --git a/flags/leaudio.aconfig b/flags/leaudio.aconfig index 6e8e104ab4..4535d65a98 100644 --- a/flags/leaudio.aconfig +++ b/flags/leaudio.aconfig @@ -79,16 +79,6 @@ flag { } flag { - name: "leaudio_getting_active_state_support" - namespace: "bluetooth" - description: "Introduce getting active state for LE Audio to avoid unnecessary broadcast handover when changing active group" - bug: "331387253" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { name: "le_audio_support_unidirectional_voice_assistant" namespace: "bluetooth" description: "Allow to create unidirectional stream for VOICEASSISTANT" @@ -96,36 +86,6 @@ flag { } flag { - name: "leaudio_start_request_state_mutex_check" - namespace: "bluetooth" - description: "Check mutex before getting start request state" - bug: "332847150" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -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" @@ -136,46 +96,6 @@ flag { } flag { - name: "leaudio_broadcast_extract_periodic_scanner_from_state_machine" - namespace: "bluetooth" - description: "Extract periodic scanner from state machine to make it independent from remote devices" - bug: "333691526" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { - name: "leaudio_allowed_context_mask" - namespace: "bluetooth" - description: "Set allowed context mask to filter stream requests in native" - bug: "336468573" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { - name: "leaudio_no_context_validate_streaming_request" - namespace: "bluetooth" - description: "Request streaming would be send without available cotext validation" - bug: "336466406" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { - name: "leaudio_use_audio_mode_listener" - namespace: "bluetooth" - description: "Use Audio Mode listener instead of Telecom in call callback" - bug: "339612732" - metadata { - purpose: PURPOSE_BUGFIX - } -} - -flag { name: "leaudio_big_depends_on_audio_state" namespace: "bluetooth" description: "BIG creation/termination depends on audio resume/pause" @@ -186,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" @@ -226,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 79c3cda8da..22f5d2b3d0 100644 --- a/flags/pairing.aconfig +++ b/flags/pairing.aconfig @@ -260,3 +260,23 @@ flag { purpose: PURPOSE_BUGFIX } } + +flag { + name: "temporary_pairing_tracking" + namespace: "bluetooth" + description: "Correctly track temporary pairing status" + bug: "397705157" + metadata { + 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..f6ad45ef68 100644 --- a/flags/rfcomm.aconfig +++ b/flags/rfcomm.aconfig @@ -30,3 +30,13 @@ 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 + } +}
\ No newline at end of file diff --git a/framework/java/android/bluetooth/BluetoothA2dp.java b/framework/java/android/bluetooth/BluetoothA2dp.java index 54f2c702aa..b2f5e3777c 100644 --- a/framework/java/android/bluetooth/BluetoothA2dp.java +++ b/framework/java/android/bluetooth/BluetoothA2dp.java @@ -18,6 +18,10 @@ 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_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.annotation.IntDef; import android.annotation.NonNull; @@ -56,7 +60,8 @@ import java.util.List; * with its appropriate permission. */ public final class BluetoothA2dp implements BluetoothProfile { - private static final String TAG = "BluetoothA2dp"; + private static final String TAG = BluetoothA2dp.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -445,7 +450,7 @@ public final class BluetoothA2dp implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -1124,6 +1129,7 @@ public final class BluetoothA2dp implements BluetoothProfile { return false; } + @SuppressWarnings("MethodCanBeStatic") private void verifyDeviceNotNull(BluetoothDevice device, String methodName) { if (device == null) { Log.e(TAG, methodName + ": device param is null"); @@ -1131,7 +1137,7 @@ public final class BluetoothA2dp implements BluetoothProfile { } } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothA2dpSink.java b/framework/java/android/bluetooth/BluetoothA2dpSink.java index ecaa9d33d7..3d07687294 100644 --- a/framework/java/android/bluetooth/BluetoothA2dpSink.java +++ b/framework/java/android/bluetooth/BluetoothA2dpSink.java @@ -18,6 +18,10 @@ 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_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -50,7 +54,8 @@ import java.util.List; */ @SystemApi public final class BluetoothA2dpSink implements BluetoothProfile { - private static final String TAG = "BluetoothA2dpSink"; + private static final String TAG = BluetoothA2dpSink.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -265,7 +270,7 @@ public final class BluetoothA2dpSink 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/BluetoothAdapter.java b/framework/java/android/bluetooth/BluetoothAdapter.java index 3fcda779e6..bf5ec5ae21 100644 --- a/framework/java/android/bluetooth/BluetoothAdapter.java +++ b/framework/java/android/bluetooth/BluetoothAdapter.java @@ -138,7 +138,8 @@ import java.util.function.Consumer; * @see BluetoothServerSocket */ public final class BluetoothAdapter { - private static final String TAG = "BluetoothAdapter"; + private static final String TAG = BluetoothAdapter.class.getSimpleName(); + private static final String DESCRIPTOR = "android.bluetooth.BluetoothAdapter"; private static final boolean DBG = true; private static final boolean VDBG = false; @@ -1124,7 +1125,7 @@ public final class BluetoothAdapter { mServiceLock.writeLock().lock(); try { - mService = registerBlueoothManagerCallback(mManagerCallback); + mService = registerBluetoothManagerCallback(mManagerCallback); } finally { mServiceLock.writeLock().unlock(); } @@ -1921,7 +1922,7 @@ public final class BluetoothAdapter { } /** - * Set the local Bluetooth adapter connectablility and discoverability. + * Set the local Bluetooth adapter connectability and discoverability. * * <p>If the scan mode is set to {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}, it will change to * {@link #SCAN_MODE_CONNECTABLE} after the discoverable timeout. The discoverable timeout can @@ -3336,7 +3337,7 @@ public final class BluetoothAdapter { @RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) - private BluetoothServerSocket createNewRfcommSocketAndRecord( + private static BluetoothServerSocket createNewRfcommSocketAndRecord( String name, UUID uuid, boolean auth, boolean encrypt) throws IOException { BluetoothServerSocket socket; socket = @@ -4005,7 +4006,7 @@ public final class BluetoothAdapter { * <p>For example, this secret can be transferred to a remote device out of band (meaning any * other way besides using bluetooth). Once the remote device finds this device using the * information given in the data, such as the PUBLIC ADDRESS, the remote device could then - * connect to this device using this secret when the pairing sequenece asks for the secret. This + * connect to this device using this secret when the pairing sequence asks for the secret. This * device will respond by automatically accepting the pairing due to the secret being so * trustworthy. * @@ -4047,7 +4048,7 @@ public final class BluetoothAdapter { } } - private Set<BluetoothDevice> toDeviceSet(List<BluetoothDevice> devices) { + private static Set<BluetoothDevice> toDeviceSet(List<BluetoothDevice> devices) { Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(devices); return Collections.unmodifiableSet(deviceSet); } @@ -4144,7 +4145,7 @@ public final class BluetoothAdapter { } /** Registers a IBluetoothManagerCallback and returns the cached service proxy object. */ - IBluetooth registerBlueoothManagerCallback(IBluetoothManagerCallback cb) { + IBluetooth registerBluetoothManagerCallback(IBluetoothManagerCallback cb) { requireNonNull(cb); if (Flags.getProfileUseLock()) { sServiceLock.writeLock().lock(); @@ -4794,7 +4795,7 @@ public final class BluetoothAdapter { * Unregister a {@link #OnMetadataChangedListener} from a registered {@link BluetoothDevice}. * Unregistration can be done when Bluetooth is either ON or OFF. {@link * #addOnMetadataChangedListener(OnMetadataChangedListener, BluetoothDevice, Executor)} must be - * called before unregisteration. + * called before unregistration. * * @param device {@link BluetoothDevice} that will be unregistered. It should not be null or * {@link NullPointerException} will be triggered. @@ -5045,7 +5046,7 @@ public final class BluetoothAdapter { /** * Sets the preferred profiles for each audio mode for system routed audio. The audio framework - * and Telecomm will read this preference when routing system managed audio. Not supplying an + * and Telecom will read this preference when routing system managed audio. Not supplying an * audio mode in the Bundle will reset that audio mode to the default profile preference for * that mode (e.g. an empty Bundle resets all audio modes to their default profiles). * @@ -5806,7 +5807,8 @@ public final class BluetoothAdapter { } @RequiresPermission(BLUETOOTH_PRIVILEGED) - void unregisterFromService(IBluetooth service, IBluetoothHciVendorSpecificCallback stub) { + static void unregisterFromService( + IBluetooth service, IBluetoothHciVendorSpecificCallback stub) { if (service == null) { return; } diff --git a/framework/java/android/bluetooth/BluetoothAvrcpController.java b/framework/java/android/bluetooth/BluetoothAvrcpController.java index 17311d6087..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; @@ -44,7 +45,8 @@ import java.util.List; * @hide */ public final class BluetoothAvrcpController implements BluetoothProfile { - private static final String TAG = "BluetoothAvrcpController"; + private static final String TAG = BluetoothAvrcpController.class.getSimpleName(); + private static final boolean DBG = false; private static final boolean VDBG = false; @@ -193,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/BluetoothAvrcpPlayerSettings.java b/framework/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java index 8ce7da1f6e..ef220e5918 100644 --- a/framework/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java +++ b/framework/java/android/bluetooth/BluetoothAvrcpPlayerSettings.java @@ -30,7 +30,7 @@ import java.util.Map; * @hide */ public final class BluetoothAvrcpPlayerSettings implements Parcelable { - public static final String TAG = "BluetoothAvrcpPlayerSettings"; + private static final String TAG = BluetoothAvrcpPlayerSettings.class.getSimpleName(); /** Equalizer setting. */ public static final int SETTING_EQUALIZER = 0x01; diff --git a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java index 44d7b29465..c80e5ab8e0 100644 --- a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java +++ b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java @@ -19,6 +19,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.executeFromBinder; import static java.util.Objects.requireNonNull; @@ -59,7 +60,8 @@ import java.util.concurrent.Executor; * proxy object. */ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, AutoCloseable { - private static final String TAG = "BluetoothCsipSetCoordinator"; + private static final String TAG = BluetoothCsipSetCoordinator.class.getSimpleName(); + private static final boolean DBG = false; private static final boolean VDBG = false; @@ -82,7 +84,7 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto @interface Status {} /** - * Callback is invoken as a result on {@link #groupLock()}. + * Callback is invoked as a result on {@link #groupLock()}. * * @param groupId group identifier * @param opStatus status of lock operation @@ -443,7 +445,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; } /** diff --git a/framework/java/android/bluetooth/BluetoothDevice.java b/framework/java/android/bluetooth/BluetoothDevice.java index a4cacbf0a8..0c3f4288e6 100644 --- a/framework/java/android/bluetooth/BluetoothDevice.java +++ b/framework/java/android/bluetooth/BluetoothDevice.java @@ -92,7 +92,8 @@ import java.util.UUID; * @see BluetoothSocket */ public final class BluetoothDevice implements Parcelable, Attributable { - private static final String TAG = "BluetoothDevice"; + private static final String TAG = BluetoothDevice.class.getSimpleName(); + private static final boolean DBG = false; /** @@ -849,7 +850,7 @@ public final class BluetoothDevice implements Parcelable, Attributable { public static final int METADATA_SPATIAL_AUDIO = 24; /** - * The metadata of the Fast Pair for any custmized feature. Data type should be {@link Byte} + * The metadata of the Fast Pair for any customized feature. Data type should be {@link Byte} * array. * * @hide diff --git a/framework/java/android/bluetooth/BluetoothGatt.java b/framework/java/android/bluetooth/BluetoothGatt.java index 7e211b5d5b..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; @@ -57,7 +59,8 @@ import java.util.concurrent.CopyOnWriteArrayList; * discovered using the Bluetooth device discovery or BLE scan process. */ public final class BluetoothGatt implements BluetoothProfile { - private static final String TAG = "BluetoothGatt"; + private static final String TAG = BluetoothGatt.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -267,7 +270,7 @@ public final class BluetoothGatt implements BluetoothProfile { callback.onConnectionStateChange( BluetoothGatt.this, GATT_FAILURE, - BluetoothProfile.STATE_DISCONNECTED); + STATE_DISCONNECTED); } } }); @@ -384,10 +387,7 @@ public final class BluetoothGatt implements BluetoothProfile { if (!address.equals(mDevice.getAddress())) { return; } - int profileState = - connected - ? BluetoothProfile.STATE_CONNECTED - : BluetoothProfile.STATE_DISCONNECTED; + int profileState = connected ? STATE_CONNECTED : STATE_DISCONNECTED; if (Flags.unregisterGattClientDisconnected() && !connected && !mAutoConnect) { unregisterApp(); diff --git a/framework/java/android/bluetooth/BluetoothGattCharacteristic.java b/framework/java/android/bluetooth/BluetoothGattCharacteristic.java index a6b4b96c91..15aebc083d 100644 --- a/framework/java/android/bluetooth/BluetoothGattCharacteristic.java +++ b/framework/java/android/bluetooth/BluetoothGattCharacteristic.java @@ -349,7 +349,7 @@ public class BluetoothGattCharacteristic implements Parcelable { * Returns the instance ID for this characteristic. * * <p>If a remote device offers multiple characteristics with the same UUID, the instance ID is - * used to distuinguish between characteristics. + * used to distinguish between characteristics. * * @return Instance ID of this characteristic */ @@ -681,29 +681,29 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Returns the size of a give value type. */ - private int getTypeLen(int formatType) { + private static int getTypeLen(int formatType) { return formatType & 0xF; } /** Convert a signed byte to an unsigned int. */ - private int unsignedByteToInt(byte b) { + private static int unsignedByteToInt(byte b) { return b & 0xFF; } /** Convert signed bytes to a 16-bit unsigned int. */ - private int unsignedBytesToInt(byte b0, byte b1) { + private static int unsignedBytesToInt(byte b0, byte b1) { return (unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8)); } /** Convert signed bytes to a 32-bit unsigned int. */ - private int unsignedBytesToInt(byte b0, byte b1, byte b2, byte b3) { + private static int unsignedBytesToInt(byte b0, byte b1, byte b2, byte b3) { return (unsignedByteToInt(b0) + (unsignedByteToInt(b1) << 8)) + (unsignedByteToInt(b2) << 16) + (unsignedByteToInt(b3) << 24); } /** Convert signed bytes to a 16-bit short float value. */ - private float bytesToFloat(byte b0, byte b1) { + private static float bytesToFloat(byte b0, byte b1) { int mantissa = unsignedToSigned(unsignedByteToInt(b0) + ((unsignedByteToInt(b1) & 0x0F) << 8), 12); int exponent = unsignedToSigned(unsignedByteToInt(b1) >> 4, 4); @@ -711,7 +711,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert signed bytes to a 32-bit short float value. */ - private float bytesToFloat(byte b0, byte b1, byte b2, byte b3) { + private static float bytesToFloat(byte b0, byte b1, byte b2, byte b3) { int mantissa = unsignedToSigned( unsignedByteToInt(b0) @@ -722,7 +722,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert an unsigned integer value to a two's-complement encoded signed value. */ - private int unsignedToSigned(int unsigned, int size) { + private static int unsignedToSigned(int unsigned, int size) { if ((unsigned & (1 << (size - 1))) != 0) { unsigned = -1 * ((1 << (size - 1)) - (unsigned & ((1 << (size - 1)) - 1))); } @@ -730,7 +730,7 @@ public class BluetoothGattCharacteristic implements Parcelable { } /** Convert an integer into the signed bits of a given length. */ - private int intToSignedBits(int i, int size) { + private static int intToSignedBits(int i, int size) { if (i < 0) { i = (1 << (size - 1)) + (i & ((1 << (size - 1)) - 1)); } diff --git a/framework/java/android/bluetooth/BluetoothGattDescriptor.java b/framework/java/android/bluetooth/BluetoothGattDescriptor.java index fe77740f0f..fcd6e305e2 100644 --- a/framework/java/android/bluetooth/BluetoothGattDescriptor.java +++ b/framework/java/android/bluetooth/BluetoothGattDescriptor.java @@ -39,7 +39,7 @@ public class BluetoothGattDescriptor implements Parcelable { /** Value used to enable indication for a client configuration descriptor */ public static final byte[] ENABLE_INDICATION_VALUE = {0x02, 0x00}; - /** Value used to disable notifications or indicatinos */ + /** Value used to disable notifications or indications */ public static final byte[] DISABLE_NOTIFICATION_VALUE = {0x00, 0x00}; /** Descriptor read permission */ @@ -197,7 +197,7 @@ public class BluetoothGattDescriptor implements Parcelable { * Returns the instance ID for this descriptor. * * <p>If a remote device offers multiple descriptors with the same UUID, the instance ID is used - * to distuinguish between descriptors. + * to distinguish between descriptors. * * @return Instance ID of this descriptor * @hide diff --git a/framework/java/android/bluetooth/BluetoothGattIncludedService.java b/framework/java/android/bluetooth/BluetoothGattIncludedService.java index d711073ed6..ac4e92f906 100644 --- a/framework/java/android/bluetooth/BluetoothGattIncludedService.java +++ b/framework/java/android/bluetooth/BluetoothGattIncludedService.java @@ -87,7 +87,7 @@ public class BluetoothGattIncludedService implements Parcelable { * Returns the instance ID for this service * * <p>If a remote device offers multiple services with the same UUID (ex. multiple battery - * services for different batteries), the instance ID is used to distuinguish services. + * services for different batteries), the instance ID is used to distinguish services. * * @return Instance ID of this service */ diff --git a/framework/java/android/bluetooth/BluetoothGattServer.java b/framework/java/android/bluetooth/BluetoothGattServer.java index 94bf7ae4c4..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; @@ -47,7 +49,8 @@ import java.util.UUID; * {@link BluetoothManager#openGattServer} to get an instance of this class. */ public final class BluetoothGattServer implements BluetoothProfile { - private static final String TAG = "BluetoothGattServer"; + private static final String TAG = BluetoothGattServer.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -121,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/BluetoothGattService.java b/framework/java/android/bluetooth/BluetoothGattService.java index 0461631085..f5c82313fa 100644 --- a/framework/java/android/bluetooth/BluetoothGattService.java +++ b/framework/java/android/bluetooth/BluetoothGattService.java @@ -293,7 +293,7 @@ public class BluetoothGattService implements Parcelable { * Returns the instance ID for this service * * <p>If a remote device offers multiple services with the same UUID (ex. multiple battery - * services for different batteries), the instance ID is used to distuinguish services. + * services for different batteries), the instance ID is used to distinguish services. * * @return Instance ID of this service */ diff --git a/framework/java/android/bluetooth/BluetoothHapClient.java b/framework/java/android/bluetooth/BluetoothHapClient.java index c11249bc9e..9a9d36f285 100644 --- a/framework/java/android/bluetooth/BluetoothHapClient.java +++ b/framework/java/android/bluetooth/BluetoothHapClient.java @@ -19,6 +19,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.callServiceIfEnabled; import static java.util.Objects.requireNonNull; @@ -661,7 +662,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable @Override @BluetoothProfile.BtProfileState public int getConnectionState(@NonNull BluetoothDevice device) { - int defaultValue = BluetoothProfile.STATE_DISCONNECTED; + int defaultValue = STATE_DISCONNECTED; if (!isValidDevice(device)) { return defaultValue; } @@ -1085,7 +1086,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable s -> s.setPresetNameForGroup(groupId, presetIndex, name, mAttributionSource)); } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHeadset.java b/framework/java/android/bluetooth/BluetoothHeadset.java index 188a78e0d8..5604acfab8 100644 --- a/framework/java/android/bluetooth/BluetoothHeadset.java +++ b/framework/java/android/bluetooth/BluetoothHeadset.java @@ -19,6 +19,7 @@ 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.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -60,7 +61,8 @@ import java.util.List; * its appropriate permission. */ public final class BluetoothHeadset implements BluetoothProfile { - private static final String TAG = "BluetoothHeadset"; + private static final String TAG = BluetoothHeadset.class.getSimpleName(); + private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); private static final boolean VDBG = false; @@ -546,7 +548,7 @@ public final class BluetoothHeadset implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -1156,33 +1158,6 @@ public final class BluetoothHeadset implements BluetoothProfile { } /** - * Send Headset of CLCC response - * - * @hide - */ - @RequiresBluetoothConnectPermission - @RequiresPermission( - allOf = { - BLUETOOTH_CONNECT, - MODIFY_PHONE_STATE, - }) - public void clccResponse( - int index, int direction, int status, int mode, boolean mpty, String number, int type) { - 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.clccResponse( - index, direction, status, mode, mpty, number, type, 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 e991f4c764..75fb320dcf 100644 --- a/framework/java/android/bluetooth/BluetoothHeadsetClient.java +++ b/framework/java/android/bluetooth/BluetoothHeadsetClient.java @@ -17,6 +17,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -58,7 +59,8 @@ import java.util.List; */ @SystemApi public final class BluetoothHeadsetClient implements BluetoothProfile, AutoCloseable { - private static final String TAG = "BluetoothHeadsetClient"; + private static final String TAG = BluetoothHeadsetClient.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; private final CloseGuard mCloseGuard; @@ -794,7 +796,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; } /** diff --git a/framework/java/android/bluetooth/BluetoothHealth.java b/framework/java/android/bluetooth/BluetoothHealth.java index dc35303e1e..eb52628087 100644 --- a/framework/java/android/bluetooth/BluetoothHealth.java +++ b/framework/java/android/bluetooth/BluetoothHealth.java @@ -57,7 +57,7 @@ import java.util.List; */ @Deprecated public final class BluetoothHealth implements BluetoothProfile { - private static final String TAG = "BluetoothHealth"; + private static final String TAG = BluetoothHealth.class.getSimpleName(); /** * Health Profile Source Role - the health device. diff --git a/framework/java/android/bluetooth/BluetoothHealthCallback.java b/framework/java/android/bluetooth/BluetoothHealthCallback.java index 44df21b7da..faf134115c 100644 --- a/framework/java/android/bluetooth/BluetoothHealthCallback.java +++ b/framework/java/android/bluetooth/BluetoothHealthCallback.java @@ -30,7 +30,7 @@ import android.util.Log; */ @Deprecated public abstract class BluetoothHealthCallback { - private static final String TAG = "BluetoothHealthCallback"; + private static final String TAG = BluetoothHealthCallback.class.getSimpleName(); /** * Callback to inform change in registration state of the health application. diff --git a/framework/java/android/bluetooth/BluetoothHearingAid.java b/framework/java/android/bluetooth/BluetoothHearingAid.java index 110e6f8caa..fec476b4f5 100644 --- a/framework/java/android/bluetooth/BluetoothHearingAid.java +++ b/framework/java/android/bluetooth/BluetoothHearingAid.java @@ -19,6 +19,10 @@ 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.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.IntDef; import android.annotation.NonNull; @@ -58,7 +62,8 @@ import java.util.List; * is protected with its appropriate permission. */ public final class BluetoothHearingAid implements BluetoothProfile { - private static final String TAG = "BluetoothHearingAid"; + private static final String TAG = BluetoothHearingAid.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); @@ -74,7 +79,7 @@ public final class BluetoothHearingAid implements BluetoothProfile { */ @SystemApi public static final class AdvertisementServiceData implements Parcelable { - private static final String TAG = "AdvertisementData"; + private static final String TAG = AdvertisementServiceData.class.getSimpleName(); private final int mCapability; private final int mTruncatedHiSyncId; @@ -469,7 +474,7 @@ public final class BluetoothHearingAid implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -774,14 +779,14 @@ public final class BluetoothHearingAid implements BluetoothProfile { return false; } - private void verifyDeviceNotNull(BluetoothDevice device, String methodName) { + private static void verifyDeviceNotNull(BluetoothDevice device, String methodName) { if (device == null) { Log.e(TAG, methodName + ": device param is null"); throw new IllegalArgumentException("Device cannot be null"); } } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHidDevice.java b/framework/java/android/bluetooth/BluetoothHidDevice.java index 207cab3ca8..8fd7dee6f7 100644 --- a/framework/java/android/bluetooth/BluetoothHidDevice.java +++ b/framework/java/android/bluetooth/BluetoothHidDevice.java @@ -46,6 +46,7 @@ import java.util.concurrent.Executor; */ public final class BluetoothHidDevice implements BluetoothProfile { private static final String TAG = BluetoothHidDevice.class.getSimpleName(); + private static final boolean DBG = false; /** @@ -249,8 +250,8 @@ public final class BluetoothHidDevice implements BluetoothProfile { * during app registration. */ public abstract static class Callback { - - private static final String TAG = "BluetoothHidDevCallback"; + private static final String TAG = + BluetoothHidDevice.TAG + "." + Callback.class.getSimpleName(); /** * Callback called when application registration state changes. Usually it's called due to @@ -785,7 +786,7 @@ public final class BluetoothHidDevice implements BluetoothProfile { return false; } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothHidHost.java b/framework/java/android/bluetooth/BluetoothHidHost.java index 123590a148..12f871fe1a 100644 --- a/framework/java/android/bluetooth/BluetoothHidHost.java +++ b/framework/java/android/bluetooth/BluetoothHidHost.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -53,7 +54,8 @@ import java.util.List; */ @SystemApi public final class BluetoothHidHost implements BluetoothProfile { - private static final String TAG = "BluetoothHidHost"; + private static final String TAG = BluetoothHidHost.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -385,7 +387,7 @@ public final class BluetoothHidHost implements BluetoothProfile { Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable())); } } - return BluetoothProfile.STATE_DISCONNECTED; + return STATE_DISCONNECTED; } /** @@ -789,7 +791,7 @@ public final class BluetoothHidHost implements BluetoothProfile { @RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) public boolean getIdleTime(BluetoothDevice device) { - if (DBG) log("getIdletime(" + device + ")"); + if (DBG) log("getIdleTime(" + device + ")"); final IBluetoothHidHost service = getService(); if (service == null) { Log.w(TAG, "Proxy not attached to service"); @@ -816,7 +818,7 @@ public final class BluetoothHidHost implements BluetoothProfile { @RequiresBluetoothConnectPermission @RequiresPermission(BLUETOOTH_CONNECT) public boolean setIdleTime(BluetoothDevice device, byte idleTime) { - if (DBG) log("setIdletime(" + device + "), idleTime=" + idleTime); + if (DBG) log("setIdleTime(" + device + "), idleTime=" + idleTime); final IBluetoothHidHost service = getService(); if (service == null) { Log.w(TAG, "Proxy not attached to service"); diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java index 02a93d967f..d1af1b8fc9 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudio.java +++ b/framework/java/android/bluetooth/BluetoothLeAudio.java @@ -19,6 +19,10 @@ 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_CONNECTING; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING; import static java.util.Objects.requireNonNull; @@ -66,7 +70,8 @@ import java.util.function.Consumer; * protected with its appropriate permission. */ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { - private static final String TAG = "BluetoothLeAudio"; + private static final String TAG = BluetoothLeAudio.class.getSimpleName(); + private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); private static final boolean VDBG = false; @@ -971,7 +976,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; } /** @@ -1352,7 +1357,7 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable { } } - private boolean isValidDevice(@Nullable BluetoothDevice device) { + private static boolean isValidDevice(@Nullable BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java index 0541d4898c..22453839cd 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecConfig.java @@ -304,7 +304,7 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { out.writeInt(mMaxOctetsPerFrame); } - private String sampleRateToString(@SampleRate int sampleRateBit) { + private static String sampleRateToString(@SampleRate int sampleRateBit) { switch (sampleRateBit) { case SAMPLE_RATE_NONE: return "None"; @@ -339,7 +339,7 @@ public final class BluetoothLeAudioCodecConfig implements Parcelable { } } - private String frameDurationToString(@FrameDuration int frameDurationBit) { + private static String frameDurationToString(@FrameDuration int frameDurationBit) { switch (frameDurationBit) { case FRAME_DURATION_NONE: return "None"; diff --git a/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java b/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java index 2997cba518..7089529638 100644 --- a/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java +++ b/framework/java/android/bluetooth/BluetoothLeAudioCodecStatus.java @@ -128,7 +128,7 @@ public final class BluetoothLeAudioCodecStatus implements Parcelable { return c1.containsAll(c2); } - private boolean isCodecConfigSelectable( + private static boolean isCodecConfigSelectable( BluetoothLeAudioCodecConfig codecConfig, BluetoothLeAudioCodecConfig selectableConfig) { if (codecConfig.getCodecType() != selectableConfig.getCodecType()) { return false; diff --git a/framework/java/android/bluetooth/BluetoothLeBroadcast.java b/framework/java/android/bluetooth/BluetoothLeBroadcast.java index 7ebc5cb82e..4023184fee 100644 --- a/framework/java/android/bluetooth/BluetoothLeBroadcast.java +++ b/framework/java/android/bluetooth/BluetoothLeBroadcast.java @@ -56,7 +56,8 @@ import java.util.concurrent.Executor; */ @SystemApi public final class BluetoothLeBroadcast implements AutoCloseable, BluetoothProfile { - private static final String TAG = "BluetoothLeBroadcast"; + private static final String TAG = BluetoothLeBroadcast.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -777,7 +778,7 @@ public final class BluetoothLeBroadcast implements AutoCloseable, BluetoothProfi mAdapter.closeProfileProxy(this); } - private BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( + private static BluetoothLeBroadcastSettings buildBroadcastSettingsFromMetadata( BluetoothLeAudioContentMetadata contentMetadata, @Nullable byte[] broadcastCode) { BluetoothLeBroadcastSubgroupSettings.Builder subgroupBuilder = new BluetoothLeBroadcastSubgroupSettings.Builder() diff --git a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java index f789bf73d4..3b333b8514 100644 --- a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java +++ b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java @@ -19,6 +19,7 @@ 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.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -81,7 +82,8 @@ import java.util.concurrent.Executor; */ @SystemApi public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, AutoCloseable { - private static final String TAG = "BluetoothLeBroadcastAssistant"; + private static final String TAG = BluetoothLeBroadcastAssistant.class.getSimpleName(); + private static final boolean DBG = true; private final Map<Callback, Executor> mCallbackExecutorMap = new HashMap<>(); @@ -581,7 +583,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())); diff --git a/framework/java/android/bluetooth/BluetoothLeCallControl.java b/framework/java/android/bluetooth/BluetoothLeCallControl.java index 9da2f90e82..8d54d56160 100644 --- a/framework/java/android/bluetooth/BluetoothLeCallControl.java +++ b/framework/java/android/bluetooth/BluetoothLeCallControl.java @@ -56,7 +56,7 @@ import java.util.concurrent.Executor; * @hide */ public final class BluetoothLeCallControl implements BluetoothProfile { - private static final String TAG = "BluetoothLeCallControl"; + private static final String TAG = BluetoothLeCallControl.class.getSimpleName(); /** @hide */ @IntDef( @@ -200,8 +200,8 @@ public final class BluetoothLeCallControl implements BluetoothProfile { * @hide */ public abstract static class Callback { - - private static final String TAG = "BluetoothLeCallControl.Callback"; + private static final String TAG = + BluetoothLeCallControl.TAG + "." + Callback.class.getSimpleName(); /** * Called when a remote client requested to accept the call. 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 0630fab93c..78d608761f 100644 --- a/framework/java/android/bluetooth/BluetoothMap.java +++ b/framework/java/android/bluetooth/BluetoothMap.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -48,8 +49,8 @@ import java.util.List; */ @SystemApi public final class BluetoothMap implements BluetoothProfile, AutoCloseable { + private static final String TAG = BluetoothMap.class.getSimpleName(); - private static final String TAG = "BluetoothMap"; private static final boolean DBG = true; private static final boolean VDBG = false; @@ -426,7 +427,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; } /** diff --git a/framework/java/android/bluetooth/BluetoothMapClient.java b/framework/java/android/bluetooth/BluetoothMapClient.java index 7b4feeaf6f..b9d1690ebf 100644 --- a/framework/java/android/bluetooth/BluetoothMapClient.java +++ b/framework/java/android/bluetooth/BluetoothMapClient.java @@ -20,6 +20,7 @@ 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.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.Nullable; @@ -53,8 +54,8 @@ import java.util.List; */ @SystemApi public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable { + private static final String TAG = BluetoothMapClient.class.getSimpleName(); - private static final String TAG = "BluetoothMapClient"; private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); @@ -395,7 +396,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; } /** diff --git a/framework/java/android/bluetooth/BluetoothPan.java b/framework/java/android/bluetooth/BluetoothPan.java index 15066a0297..c361ff5f0b 100644 --- a/framework/java/android/bluetooth/BluetoothPan.java +++ b/framework/java/android/bluetooth/BluetoothPan.java @@ -20,6 +20,7 @@ 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.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.executeFromBinder; import static java.util.Objects.requireNonNull; @@ -63,7 +64,8 @@ import java.util.concurrent.Executor; */ @SystemApi public final class BluetoothPan implements BluetoothProfile { - private static final String TAG = "BluetoothPan"; + private static final String TAG = BluetoothPan.class.getSimpleName(); + private static final boolean DBG = true; private static final boolean VDBG = false; @@ -477,7 +479,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 b94cbeebf8..80a16de9a3 100644 --- a/framework/java/android/bluetooth/BluetoothPbap.java +++ b/framework/java/android/bluetooth/BluetoothPbap.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -61,8 +62,8 @@ import java.util.List; */ @SystemApi public class BluetoothPbap implements BluetoothProfile { + private static final String TAG = BluetoothPbap.class.getSimpleName(); - private static final String TAG = "BluetoothPbap"; private static final boolean DBG = false; /** @@ -193,11 +194,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; } /** @@ -297,7 +298,7 @@ public class BluetoothPbap implements BluetoothProfile { return false; } - private boolean isValidDevice(BluetoothDevice device) { + private static boolean isValidDevice(BluetoothDevice device) { if (device == null) return false; if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true; diff --git a/framework/java/android/bluetooth/BluetoothPbapClient.java b/framework/java/android/bluetooth/BluetoothPbapClient.java index 38d984aa75..44065a424f 100644 --- a/framework/java/android/bluetooth/BluetoothPbapClient.java +++ b/framework/java/android/bluetooth/BluetoothPbapClient.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import android.annotation.NonNull; import android.annotation.RequiresNoPermission; @@ -44,8 +45,8 @@ import java.util.List; */ @SystemApi public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseable { + private static final String TAG = BluetoothPbapClient.class.getSimpleName(); - private static final String TAG = "BluetoothPbapClient"; private static final boolean DBG = false; private static final boolean VDBG = false; @@ -298,7 +299,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) { diff --git a/framework/java/android/bluetooth/BluetoothQualityReport.java b/framework/java/android/bluetooth/BluetoothQualityReport.java index 99a234f551..28b2f998af 100644 --- a/framework/java/android/bluetooth/BluetoothQualityReport.java +++ b/framework/java/android/bluetooth/BluetoothQualityReport.java @@ -741,7 +741,9 @@ public final class BluetoothQualityReport implements Parcelable { */ @SystemApi public static final class BqrCommon implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrCommon"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrCommon.class.getSimpleName(); + static final int BQR_COMMON_LEN = 85; private @QualityReportId int mQualityReportId; @@ -1411,7 +1413,8 @@ public final class BluetoothQualityReport implements Parcelable { */ @SystemApi public static final class BqrVsLsto implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrVsLsto"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrVsLsto.class.getSimpleName(); private int mConnState; private long mBasebandStats; @@ -1627,7 +1630,8 @@ public final class BluetoothQualityReport implements Parcelable { */ @SystemApi public static final class BqrVsA2dpChoppy implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrVsA2dpChoppy"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrVsA2dpChoppy.class.getSimpleName(); private long mArrivalTime; private long mScheduleTime; @@ -1827,7 +1831,8 @@ public final class BluetoothQualityReport implements Parcelable { */ @SystemApi public static final class BqrVsScoChoppy implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrVsScoChoppy"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrVsScoChoppy.class.getSimpleName(); private int mGlitchCount; private int mIntervalEsco; @@ -2219,7 +2224,8 @@ public final class BluetoothQualityReport implements Parcelable { */ @SystemApi public static final class BqrConnectFail implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrConnectFail"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrConnectFail.class.getSimpleName(); /** * Connect Fail reason: No error. @@ -2382,7 +2388,8 @@ public final class BluetoothQualityReport implements Parcelable { @FlaggedApi(Flags.FLAG_SUPPORT_BLUETOOTH_QUALITY_REPORT_V6) @SystemApi public static final class BqrEnergyMonitor implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrEnergyMonitor"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrEnergyMonitor.class.getSimpleName(); private int mAvgCurrentConsume; private long mIdleTotalTime; @@ -2851,7 +2858,8 @@ public final class BluetoothQualityReport implements Parcelable { @FlaggedApi(Flags.FLAG_SUPPORT_BLUETOOTH_QUALITY_REPORT_V6) @SystemApi public static final class BqrRfStats implements Parcelable { - private static final String TAG = BluetoothQualityReport.TAG + ".BqrRfStats"; + private static final String TAG = + BluetoothQualityReport.TAG + "." + BqrRfStats.class.getSimpleName(); private int mExtensionInfo; private long mReportTimePeriod; diff --git a/framework/java/android/bluetooth/BluetoothSap.java b/framework/java/android/bluetooth/BluetoothSap.java index 8d467720ff..b4ba87a36f 100644 --- a/framework/java/android/bluetooth/BluetoothSap.java +++ b/framework/java/android/bluetooth/BluetoothSap.java @@ -18,6 +18,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static java.util.Objects.requireNonNull; @@ -56,8 +57,8 @@ import java.util.List; */ @SystemApi public final class BluetoothSap implements BluetoothProfile, AutoCloseable { + private static final String TAG = BluetoothSap.class.getSimpleName(); - private static final String TAG = "BluetoothSap"; private static final boolean DBG = true; private static final boolean VDBG = false; @@ -424,7 +425,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; } /** diff --git a/framework/java/android/bluetooth/BluetoothServerSocket.java b/framework/java/android/bluetooth/BluetoothServerSocket.java index 1cf1bde3c8..e25805437a 100644 --- a/framework/java/android/bluetooth/BluetoothServerSocket.java +++ b/framework/java/android/bluetooth/BluetoothServerSocket.java @@ -71,8 +71,8 @@ import java.io.IOException; */ @SuppressLint("AndroidFrameworkBluetoothPermission") public final class BluetoothServerSocket implements Closeable { + private static final String TAG = BluetoothServerSocket.class.getSimpleName(); - private static final String TAG = "BluetoothServerSocket"; private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); @UnsupportedAppUsage( diff --git a/framework/java/android/bluetooth/BluetoothSocket.java b/framework/java/android/bluetooth/BluetoothSocket.java index cde23baf4d..7c2f524fa0 100644 --- a/framework/java/android/bluetooth/BluetoothSocket.java +++ b/framework/java/android/bluetooth/BluetoothSocket.java @@ -94,7 +94,8 @@ import java.util.UUID; * @see java.io.OutputStream */ public final class BluetoothSocket implements Closeable { - private static final String TAG = "BluetoothSocket"; + private static final String TAG = BluetoothSocket.class.getSimpleName(); + private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG); private static final boolean VDBG = Log.isLoggable(TAG, Log.VERBOSE); @@ -1282,7 +1283,7 @@ public final class BluetoothSocket implements Closeable { return mPfd; } - private String convertAddr(final byte[] addr) { + private static String convertAddr(final byte[] addr) { return String.format( Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X", @@ -1393,7 +1394,7 @@ public final class BluetoothSocket implements Closeable { } } - private int readAll(InputStream is, byte[] b) throws IOException { + private static int readAll(InputStream is, byte[] b) throws IOException { int left = b.length; while (left > 0) { int ret = is.read(b, b.length - left, left); @@ -1414,7 +1415,7 @@ public final class BluetoothSocket implements Closeable { return b.length; } - private int readInt(InputStream is) throws IOException { + private static int readInt(InputStream is) throws IOException { byte[] ibytes = new byte[4]; int ret = readAll(is, ibytes); if (VDBG) Log.d(TAG, "inputStream.read ret: " + ret); diff --git a/framework/java/android/bluetooth/BluetoothUtils.java b/framework/java/android/bluetooth/BluetoothUtils.java index b734ff2fef..67004ca889 100644 --- a/framework/java/android/bluetooth/BluetoothUtils.java +++ b/framework/java/android/bluetooth/BluetoothUtils.java @@ -36,12 +36,12 @@ import java.util.function.Supplier; /** @hide */ public final class BluetoothUtils { - private static final String TAG = "BluetoothUtils"; + private static final String TAG = BluetoothUtils.class.getSimpleName(); /** This utility class cannot be instantiated */ private BluetoothUtils() {} - /** Match with UserHandl.NULL but accessible inside bluetooth package */ + /** Match with UserHandle.NULL but accessible inside bluetooth package */ public static final UserHandle USER_HANDLE_NULL = UserHandle.of(-10000); /** Class for Length-Value-Entry array parsing */ diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java index 573a15c3d4..819796b6b6 100644 --- a/framework/java/android/bluetooth/BluetoothVolumeControl.java +++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java @@ -19,6 +19,7 @@ package android.bluetooth; import static android.Manifest.permission.BLUETOOTH_CONNECT; import static android.Manifest.permission.BLUETOOTH_PRIVILEGED; +import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; import static android.bluetooth.BluetoothUtils.callServiceIfEnabled; import static android.bluetooth.BluetoothUtils.executeFromBinder; @@ -64,7 +65,7 @@ import java.util.function.Consumer; */ @SystemApi public final class BluetoothVolumeControl implements BluetoothProfile, AutoCloseable { - private static final String TAG = "BluetoothVolumeControl"; + private static final String TAG = BluetoothVolumeControl.class.getSimpleName(); private CloseGuard mCloseGuard; @@ -376,7 +377,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; diff --git a/framework/java/android/bluetooth/BufferConstraint.java b/framework/java/android/bluetooth/BufferConstraint.java index 25fb21798a..936b17dd6c 100644 --- a/framework/java/android/bluetooth/BufferConstraint.java +++ b/framework/java/android/bluetooth/BufferConstraint.java @@ -28,8 +28,8 @@ import android.os.Parcelable; */ @SystemApi public final class BufferConstraint implements Parcelable { + private static final String TAG = BufferConstraint.class.getSimpleName(); - private static final String TAG = "BufferConstraint"; private int mDefaultMillis; private int mMaxMillis; private int mMinMillis; diff --git a/framework/java/android/bluetooth/BufferConstraints.java b/framework/java/android/bluetooth/BufferConstraints.java index 1fbebaa8b7..c8a1157849 100644 --- a/framework/java/android/bluetooth/BufferConstraints.java +++ b/framework/java/android/bluetooth/BufferConstraints.java @@ -34,9 +34,9 @@ import java.util.Map; */ @SystemApi public final class BufferConstraints implements Parcelable { - public static final int BUFFER_CODEC_MAX_NUM = 32; + private static final String TAG = BufferConstraints.class.getSimpleName(); - private static final String TAG = "BufferConstraints"; + public static final int BUFFER_CODEC_MAX_NUM = 32; private Map<Integer, BufferConstraint> mBufferConstraints; private List<BufferConstraint> mBufferConstraintList; diff --git a/framework/java/android/bluetooth/OobData.java b/framework/java/android/bluetooth/OobData.java index e6c5f945d8..48b107c7c0 100644 --- a/framework/java/android/bluetooth/OobData.java +++ b/framework/java/android/bluetooth/OobData.java @@ -53,8 +53,7 @@ import java.lang.annotation.RetentionPolicy; */ @SystemApi public final class OobData implements Parcelable { - - private static final String TAG = "OobData"; + private static final String TAG = OobData.class.getSimpleName(); /** The {@link OobData#mClassicLength} may be. (AD 3.1.1) (CSS 1.6.2) @hide */ @SystemApi public static final int OOB_LENGTH_OCTETS = 2; @@ -303,7 +302,7 @@ public final class OobData implements Parcelable { * A 1.8 for a detailed description. * @return {@link OobData#Builder} * @throws IllegalArgumentException if the leTemporaryKey is an invalid format. - * @throws NullinterException if leTemporaryKey is null. + * @throws NullPointerException if leTemporaryKey is null. * @hide */ @NonNull @@ -863,8 +862,7 @@ public final class OobData implements Parcelable { * @hide */ @Override - @NonNull - public String toString() { + public @NonNull String toString() { return "OobData: \n\t" // Both + "Device Address With Type: " @@ -901,13 +899,11 @@ public final class OobData implements Parcelable { + "\n\t"; } - @NonNull - private String toHexString(int b) { + private static @NonNull String toHexString(int b) { return toHexString(new byte[] {(byte) b}); } - @NonNull - private String toHexString(byte[] array) { + private static @NonNull String toHexString(byte[] array) { if (array == null) return "null"; StringBuilder builder = new StringBuilder(array.length * 2); for (byte b : array) { diff --git a/framework/java/android/bluetooth/le/AdvertisingSet.java b/framework/java/android/bluetooth/le/AdvertisingSet.java index 9df049bf08..2c2fce52e3 100644 --- a/framework/java/android/bluetooth/le/AdvertisingSet.java +++ b/framework/java/android/bluetooth/le/AdvertisingSet.java @@ -41,7 +41,7 @@ import android.util.Log; * @see AdvertiseData */ public final class AdvertisingSet { - private static final String TAG = "AdvertisingSet"; + private static final String TAG = AdvertisingSet.class.getSimpleName(); private final IBluetoothAdvertise mAdvertise; private int mAdvertiserId; diff --git a/framework/java/android/bluetooth/le/AdvertisingSetParameters.java b/framework/java/android/bluetooth/le/AdvertisingSetParameters.java index 9c27e48567..b8fa11c55b 100644 --- a/framework/java/android/bluetooth/le/AdvertisingSetParameters.java +++ b/framework/java/android/bluetooth/le/AdvertisingSetParameters.java @@ -116,7 +116,7 @@ public final class AdvertisingSetParameters implements Parcelable { @SystemApi public static final int ADDRESS_TYPE_PUBLIC = 0; /** - * Generate and adverise own resolvable private address. + * Generate and advertise own resolvable private address. * * @hide */ diff --git a/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java b/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java index b835580c6c..f4fee92e69 100644 --- a/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java +++ b/framework/java/android/bluetooth/le/BluetoothLeAdvertiser.java @@ -57,8 +57,7 @@ import java.util.Map; * @see AdvertiseData */ public final class BluetoothLeAdvertiser { - - private static final String TAG = "BluetoothLeAdvertiser"; + private static final String TAG = BluetoothLeAdvertiser.class.getSimpleName(); private static final int MAX_LEGACY_ADVERTISING_DATA_BYTES = 31; // Each fields need one byte for field length and another byte for field type. @@ -282,7 +281,7 @@ public final class BluetoothLeAdvertiser { * three bytes will be added for flags. * @param scanResponse Scan response associated with the advertisement data. Size must not * exceed {@link BluetoothAdapter#getLeMaximumAdvertisingDataLength}. - * @param periodicParameters periodic advertisng parameters. If null, periodic advertising will + * @param periodicParameters periodic advertising parameters. If null, periodic advertising will * not be started. * @param periodicData Periodic advertising data. Size must not exceed {@link * BluetoothAdapter#getLeMaximumAdvertisingDataLength}. @@ -332,7 +331,7 @@ public final class BluetoothLeAdvertiser { * three bytes will be added for flags. * @param scanResponse Scan response associated with the advertisement data. Size must not * exceed {@link BluetoothAdapter#getLeMaximumAdvertisingDataLength}. - * @param periodicParameters periodic advertisng parameters. If null, periodic advertising will + * @param periodicParameters periodic advertising parameters. If null, periodic advertising will * not be started. * @param periodicData Periodic advertising data. Size must not exceed {@link * BluetoothAdapter#getLeMaximumAdvertisingDataLength}. @@ -384,7 +383,7 @@ public final class BluetoothLeAdvertiser { * three bytes will be added for flags. * @param scanResponse Scan response associated with the advertisement data. Size must not * exceed {@link BluetoothAdapter#getLeMaximumAdvertisingDataLength}. - * @param periodicParameters periodic advertisng parameters. If null, periodic advertising will + * @param periodicParameters periodic advertising parameters. If null, periodic advertising will * not be started. * @param periodicData Periodic advertising data. Size must not exceed {@link * BluetoothAdapter#getLeMaximumAdvertisingDataLength}. @@ -441,7 +440,7 @@ public final class BluetoothLeAdvertiser { * three bytes will be added for flags. * @param scanResponse Scan response associated with the advertisement data. Size must not * exceed {@link BluetoothAdapter#getLeMaximumAdvertisingDataLength} - * @param periodicParameters Periodic advertisng parameters. If null, periodic advertising will + * @param periodicParameters Periodic advertising parameters. If null, periodic advertising will * not be started. * @param periodicData Periodic advertising data. Size must not exceed {@link * BluetoothAdapter#getLeMaximumAdvertisingDataLength} @@ -508,7 +507,7 @@ public final class BluetoothLeAdvertiser { * three bytes will be added for flags. * @param scanResponse Scan response associated with the advertisement data. Size must not * exceed {@link BluetoothAdapter#getLeMaximumAdvertisingDataLength} - * @param periodicParameters Periodic advertisng parameters. If null, periodic advertising will + * @param periodicParameters Periodic advertising parameters. If null, periodic advertising will * not be started. * @param periodicData Periodic advertising data. Size must not exceed {@link * BluetoothAdapter#getLeMaximumAdvertisingDataLength} @@ -781,7 +780,7 @@ public final class BluetoothLeAdvertiser { return size; } - private int byteLength(byte[] array) { + private static int byteLength(byte[] array) { return array == null ? 0 : array.length; } @@ -897,7 +896,7 @@ public final class BluetoothLeAdvertiser { } @SuppressLint("AndroidFrameworkBluetoothPermission") - private void postStartSetFailure( + private static void postStartSetFailure( Handler handler, final AdvertisingSetCallback callback, final int error) { handler.post( new Runnable() { diff --git a/framework/java/android/bluetooth/le/BluetoothLeScanner.java b/framework/java/android/bluetooth/le/BluetoothLeScanner.java index aeac2e2f0f..cd94688f2b 100644 --- a/framework/java/android/bluetooth/le/BluetoothLeScanner.java +++ b/framework/java/android/bluetooth/le/BluetoothLeScanner.java @@ -58,8 +58,8 @@ import java.util.Map; * @see ScanFilter */ public final class BluetoothLeScanner { + private static final String TAG = BluetoothLeScanner.class.getSimpleName(); - private static final String TAG = "BluetoothLeScanner"; private static final boolean DBG = true; private static final boolean VDBG = false; @@ -636,7 +636,7 @@ public final class BluetoothLeScanner { return false; } - private boolean isSettingsAndFilterComboAllowed( + private static boolean isSettingsAndFilterComboAllowed( ScanSettings settings, List<ScanFilter> filterList) { final int callbackType = settings.getCallbackType(); // If onlost/onfound is requested, a non-empty filter is expected diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementManager.java b/framework/java/android/bluetooth/le/DistanceMeasurementManager.java index 88933ae5d9..6209e31946 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementManager.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementManager.java @@ -62,7 +62,7 @@ import java.util.stream.Collectors; */ @SystemApi public final class DistanceMeasurementManager { - private static final String TAG = "DistanceMeasurementManager"; + private static final String TAG = DistanceMeasurementManager.class.getSimpleName(); private final ConcurrentHashMap<BluetoothDevice, DistanceMeasurementSession> mSessionMap = new ConcurrentHashMap<>(); diff --git a/framework/java/android/bluetooth/le/DistanceMeasurementSession.java b/framework/java/android/bluetooth/le/DistanceMeasurementSession.java index d0c9547967..3241e68b59 100644 --- a/framework/java/android/bluetooth/le/DistanceMeasurementSession.java +++ b/framework/java/android/bluetooth/le/DistanceMeasurementSession.java @@ -58,7 +58,7 @@ import java.util.concurrent.Executor; */ @SystemApi public final class DistanceMeasurementSession { - private static final String TAG = "DistanceMeasurementSession"; + private static final String TAG = DistanceMeasurementSession.class.getSimpleName(); private final IDistanceMeasurement mDistanceMeasurement; private final ParcelUuid mUuid; diff --git a/framework/java/android/bluetooth/le/PeriodicAdvertisingManager.java b/framework/java/android/bluetooth/le/PeriodicAdvertisingManager.java index 863bfffdea..581778f55d 100644 --- a/framework/java/android/bluetooth/le/PeriodicAdvertisingManager.java +++ b/framework/java/android/bluetooth/le/PeriodicAdvertisingManager.java @@ -48,8 +48,7 @@ import java.util.IdentityHashMap; * @hide */ public final class PeriodicAdvertisingManager { - - private static final String TAG = "PeriodicAdvertisingManager"; + private static final String TAG = PeriodicAdvertisingManager.class.getSimpleName(); private static final int SKIP_MIN = 0; private static final int SKIP_MAX = 499; diff --git a/framework/java/android/bluetooth/le/ScanRecord.java b/framework/java/android/bluetooth/le/ScanRecord.java index d5b3b46e4e..b5d4ab341d 100644 --- a/framework/java/android/bluetooth/le/ScanRecord.java +++ b/framework/java/android/bluetooth/le/ScanRecord.java @@ -41,8 +41,7 @@ import java.util.function.Predicate; /** Represents a scan record from Bluetooth LE scan. */ @SuppressLint("AndroidFrameworkBluetoothPermission") public final class ScanRecord { - - private static final String TAG = "ScanRecord"; + private static final String TAG = ScanRecord.class.getSimpleName(); /** @hide */ @IntDef( diff --git a/framework/java/android/bluetooth/le/ScanSettings.java b/framework/java/android/bluetooth/le/ScanSettings.java index 014df2f4f0..e78f46c8d4 100644 --- a/framework/java/android/bluetooth/le/ScanSettings.java +++ b/framework/java/android/bluetooth/le/ScanSettings.java @@ -357,7 +357,7 @@ public final class ScanSettings implements Parcelable { } // Returns true if the callbackType is valid. - private boolean isValidCallbackType(int callbackType) { + private static boolean isValidCallbackType(int callbackType) { if (callbackType == CALLBACK_TYPE_ALL_MATCHES || callbackType == CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH || callbackType == CALLBACK_TYPE_FIRST_MATCH diff --git a/framework/java/android/bluetooth/le/TransportBlock.java b/framework/java/android/bluetooth/le/TransportBlock.java index 15acafd01a..2e5789813c 100644 --- a/framework/java/android/bluetooth/le/TransportBlock.java +++ b/framework/java/android/bluetooth/le/TransportBlock.java @@ -34,7 +34,8 @@ import java.util.Arrays; * @see AdvertiseData */ public final class TransportBlock implements Parcelable { - private static final String TAG = "TransportBlock"; + private static final String TAG = TransportBlock.class.getSimpleName(); + private final int mOrgId; private final int mTdsFlags; private final int mTransportDataLength; diff --git a/framework/java/android/bluetooth/le/TransportDiscoveryData.java b/framework/java/android/bluetooth/le/TransportDiscoveryData.java index 21492e1681..c1d6abcd6e 100644 --- a/framework/java/android/bluetooth/le/TransportDiscoveryData.java +++ b/framework/java/android/bluetooth/le/TransportDiscoveryData.java @@ -37,7 +37,8 @@ import java.util.List; * @see AdvertiseData */ public final class TransportDiscoveryData implements Parcelable { - private static final String TAG = "TransportDiscoveryData"; + private static final String TAG = TransportDiscoveryData.class.getSimpleName(); + private final int mTransportDataType; private final List<TransportBlock> mTransportBlocks; diff --git a/framework/tests/bumble/AndroidPhyTest.xml b/framework/tests/bumble/AndroidPhyTest.xml index b762ec7480..9b82db095b 100644 --- a/framework/tests/bumble/AndroidPhyTest.xml +++ b/framework/tests/bumble/AndroidPhyTest.xml @@ -11,7 +11,7 @@ </target_preparer> <target_preparer class="com.android.tradefed.targetprep.PythonVirtualenvPreparer"> - <option name="dep-module" value="grpcio==1.51.1" /> + <option name="dep-module" value="grpcio==1.70.0" /> <option name="dep-module" value="cryptography==35" /> <option name="dep-module" value="libusb1>=2.0.1" /> <option name="dep-module" value="libusb-package==1.0.26.1" /> diff --git a/framework/tests/bumble/AndroidTest.xml b/framework/tests/bumble/AndroidTest.xml index ac24f9e96e..482d8d3586 100644 --- a/framework/tests/bumble/AndroidTest.xml +++ b/framework/tests/bumble/AndroidTest.xml @@ -12,7 +12,7 @@ <target_preparer class="com.android.tradefed.targetprep.PythonVirtualenvPreparer"> <!-- TODO(b/267785204): Import python dependencies --> - <option name="dep-module" value="grpcio==1.51.1" /> + <option name="dep-module" value="grpcio==1.70.0" /> <option name="dep-module" value="cryptography==35" /> </target_preparer> 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/BleOnStateTest.java b/framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java index 9efda89fca..63acc8ded0 100644 --- a/framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java +++ b/framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java @@ -61,7 +61,8 @@ import java.util.concurrent.TimeUnit; @RunWith(AndroidJUnit4.class) public class BleOnStateTest { - private static final String TAG = "BleOnTest"; + private static final String TAG = BleOnStateTest.class.getSimpleName(); + private static final int TIMEOUT_ADVERTISING_MS = 1000; private static final int TIMEOUT_SCANNING_MS = 2000; private static final String TEST_UUID_STRING = "00001805-0000-1000-8000-00805f9b34fb"; 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/DeviceDiscoveryTest.java b/framework/tests/bumble/src/android/bluetooth/DeviceDiscoveryTest.java index fc80efaac9..e54fe5b8ff 100644 --- a/framework/tests/bumble/src/android/bluetooth/DeviceDiscoveryTest.java +++ b/framework/tests/bumble/src/android/bluetooth/DeviceDiscoveryTest.java @@ -43,7 +43,7 @@ import java.util.ArrayList; /** Test cases for {@link DeviceDiscoveryManager}. */ @RunWith(AndroidJUnit4.class) public class DeviceDiscoveryTest { - private static final String TAG = "DeviceDiscoveryTest"; + private static final String TAG = DeviceDiscoveryTest.class.getSimpleName(); private final Context mContext = ApplicationProvider.getApplicationContext(); private final BluetoothManager mManager = mContext.getSystemService(BluetoothManager.class); diff --git a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java index 4496c4edaf..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; @@ -82,7 +83,8 @@ import java.util.UUID; @RunWith(TestParameterInjector.class) public class GattClientTest { - private static final String TAG = "GattClientTest"; + private static final String TAG = GattClientTest.class.getSimpleName(); + private static final int ANDROID_MTU = 517; private static final int MTU_REQUESTED = 23; private static final int ANOTHER_MTU_REQUESTED = 42; @@ -224,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)) @@ -234,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(); } @@ -361,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 @@ -561,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)); @@ -740,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)) @@ -749,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 1e718a7874..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; @@ -53,7 +55,7 @@ import java.util.concurrent.TimeUnit; /** Test cases for {@link BluetoothGattServer}. */ @RunWith(AndroidJUnit4.class) public class GattServerConnectWithScanTest { - private static final String TAG = "GattServerConnectWithScanTest"; + private static final String TAG = GattServerConnectWithScanTest.class.getSimpleName(); private static final int TIMEOUT_SCANNING_MS = 2_000; private static final int TIMEOUT_GATT_CONNECTION_MS = 2_000; @@ -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 05af3c0b0e..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; @@ -43,7 +45,8 @@ import pandora.HostProto.OwnAddressType; /** Test cases for {@link BluetoothGattServer}. */ @RunWith(AndroidJUnit4.class) public class GattServerConnectWithoutScanTest { - private static final String TAG = "GattServerConnectWithoutScanTest"; + private static final String TAG = GattServerConnectWithoutScanTest.class.getSimpleName(); + private static final int TIMEOUT_GATT_CONNECTION_MS = 2_000; @Rule(order = 1) @@ -77,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(); } @@ -103,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(); } @@ -125,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(); } @@ -147,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/LeAdvertisingTest.java b/framework/tests/bumble/src/android/bluetooth/LeAdvertisingTest.java index e60d0a493e..cc0513cbf2 100644 --- a/framework/tests/bumble/src/android/bluetooth/LeAdvertisingTest.java +++ b/framework/tests/bumble/src/android/bluetooth/LeAdvertisingTest.java @@ -48,7 +48,7 @@ import java.util.concurrent.TimeUnit; /** Test cases for {@link AdvertiseManager}. */ @RunWith(AndroidJUnit4.class) public class LeAdvertisingTest { - private static final String TAG = "LeAdvertisingTest"; + private static final String TAG = LeAdvertisingTest.class.getSimpleName(); private static final int TIMEOUT_ADVERTISING_MS = 1000; diff --git a/framework/tests/bumble/src/android/bluetooth/LeScanningTest.java b/framework/tests/bumble/src/android/bluetooth/LeScanningTest.java index aa6a4c7536..53b1cd1ca2 100644 --- a/framework/tests/bumble/src/android/bluetooth/LeScanningTest.java +++ b/framework/tests/bumble/src/android/bluetooth/LeScanningTest.java @@ -72,7 +72,8 @@ import java.util.stream.Stream; @RunWith(TestParameterInjector.class) public class LeScanningTest { - private static final String TAG = "LeScanningTest"; + private static final String TAG = LeScanningTest.class.getSimpleName(); + private static final int TIMEOUT_SCANNING_MS = 3000; private static final String TEST_UUID_STRING = "00001805-0000-1000-8000-00805f9b34fb"; private static final String TEST_ADDRESS_RANDOM_STATIC = "F0:43:A8:23:10:11"; diff --git a/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java b/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java index 7778255f2d..a8c1835641 100644 --- a/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java +++ b/framework/tests/bumble/src/android/bluetooth/PandoraDevice.java @@ -48,6 +48,7 @@ import java.util.concurrent.TimeUnit; public final class PandoraDevice extends ExternalResource { private static final String TAG = PandoraDevice.class.getSimpleName(); + private final String mNetworkAddress; private String mPublicBluetoothAddress; private final int mPort; diff --git a/framework/tests/bumble/src/android/bluetooth/PendingIntentScanReceiver.java b/framework/tests/bumble/src/android/bluetooth/PendingIntentScanReceiver.java index bafda2ece8..3b70b6bc9c 100644 --- a/framework/tests/bumble/src/android/bluetooth/PendingIntentScanReceiver.java +++ b/framework/tests/bumble/src/android/bluetooth/PendingIntentScanReceiver.java @@ -35,7 +35,7 @@ import java.util.concurrent.CompletableFuture; * future that completes when scan results are next delivered. */ public class PendingIntentScanReceiver extends BroadcastReceiver { - private static final String TAG = "PendingIntentScanReceiver"; + private static final String TAG = PendingIntentScanReceiver.class.getSimpleName(); public static final String ACTION_SCAN_RESULT = "android.bluetooth.test.ACTION_SCAN_RESULT"; diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java index 43ab25083c..26deb09327 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java @@ -99,6 +99,7 @@ import java.util.concurrent.TimeUnit; @RunWith(AndroidJUnit4.class) public class HidHeadTrackerTest { private static final String TAG = HidHeadTrackerTest.class.getSimpleName(); + private static final String BUMBLE_DEVICE_NAME = "Bumble"; private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); private static final Duration INTENT_TIMEOUT = Duration.ofSeconds(10); diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java index 81df6c3cbb..be8ca125cd 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java @@ -97,6 +97,7 @@ import java.util.Arrays; @VirtualOnly public class HidHostDualModeTest { private static final String TAG = HidHostDualModeTest.class.getSimpleName(); + private static final String BUMBLE_DEVICE_NAME = "Bumble"; private static final Duration INTENT_TIMEOUT = Duration.ofSeconds(10); private static final int KEYBD_RPT_ID = 1; diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java index 4661c98a75..6a94d6a3de 100644 --- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java +++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java @@ -94,6 +94,7 @@ import java.util.concurrent.TimeUnit; @VirtualOnly public class HidHostTest { private static final String TAG = HidHostTest.class.getSimpleName(); + private static final Duration INTENT_TIMEOUT = Duration.ofSeconds(10); private BluetoothDevice mDevice; private BluetoothHidHost mHidService; diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java index 9940d92757..ee8e54df36 100644 --- a/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java +++ b/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java @@ -19,12 +19,6 @@ package android.bluetooth.pairing; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction; import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.timeout; - -import android.annotation.SuppressLint; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter.OobDataCallback; import android.bluetooth.BluetoothDevice; @@ -36,10 +30,8 @@ import android.bluetooth.Utils; import android.bluetooth.cts.EnableBluetoothRule; import android.bluetooth.pairing.utils.IntentReceiver; import android.bluetooth.pairing.utils.TestUtil; -import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -import android.content.IntentFilter; import android.util.Log; import androidx.test.ext.junit.runners.AndroidJUnit4; @@ -52,18 +44,11 @@ import com.google.protobuf.ByteString; import io.grpc.Deadline; -import org.hamcrest.Matcher; -import org.hamcrest.core.AllOf; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.InOrder; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; -import org.mockito.hamcrest.MockitoHamcrest; -import org.mockito.stubbing.Answer; import pandora.HostProto.AdvertiseRequest; import pandora.HostProto.ConnectLERequest; @@ -78,13 +63,13 @@ import pandora.SecurityProto.SecureRequest; import pandora.SecurityProto.SecureResponse; import java.time.Duration; -import java.util.Arrays; import java.util.Iterator; import java.util.concurrent.TimeUnit; @RunWith(AndroidJUnit4.class) public class OobPairingTest { private static final String TAG = OobPairingTest.class.getSimpleName(); + private static final Duration INTENT_TIMEOUT = Duration.ofSeconds(10); private static final String CF_NAME = "Cuttlefish"; diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java index 1a7b78e035..c2fb973fba 100644 --- a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java +++ b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java @@ -21,10 +21,6 @@ import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra; import static com.google.common.truth.Truth.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.timeout; -import static org.mockito.Mockito.verify; - import android.bluetooth.BluetoothA2dp; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; @@ -37,16 +33,15 @@ import android.bluetooth.BluetoothStatusCodes; import android.bluetooth.PandoraDevice; import android.bluetooth.StreamObserverSpliterator; import android.bluetooth.Utils; -import android.bluetooth.test_utils.BlockingBluetoothAdapter; -import android.bluetooth.test_utils.EnableBluetoothRule; import android.bluetooth.pairing.utils.IntentReceiver; import android.bluetooth.pairing.utils.TestUtil; +import android.bluetooth.test_utils.BlockingBluetoothAdapter; +import android.bluetooth.test_utils.EnableBluetoothRule; import android.content.Context; import android.os.ParcelUuid; import android.platform.test.annotations.RequiresFlagsEnabled; import android.platform.test.flag.junit.CheckFlagsRule; import android.platform.test.flag.junit.DeviceFlagsValueProvider; -import android.util.Log; import androidx.test.platform.app.InstrumentationRegistry; @@ -64,7 +59,6 @@ import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -87,7 +81,8 @@ import java.util.concurrent.TimeUnit; @RunWith(TestParameterInjector.class) public class PairingTest { - private static final String TAG = "PairingTest"; + private static final String TAG = PairingTest.class.getSimpleName(); + private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); private static final int TEST_DELAY_MS = 1000; diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/utils/TestUtil.java b/framework/tests/bumble/src/android/bluetooth/pairing/utils/TestUtil.java index 9243795225..7a9c2067ee 100644 --- a/framework/tests/bumble/src/android/bluetooth/pairing/utils/TestUtil.java +++ b/framework/tests/bumble/src/android/bluetooth/pairing/utils/TestUtil.java @@ -29,7 +29,6 @@ import android.annotation.NonNull; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; -import android.bluetooth.pairing.utils.IntentReceiver; import android.content.Context; import org.mockito.ArgumentCaptor; @@ -38,6 +37,7 @@ import java.time.Duration; public class TestUtil { private static final String TAG = TestUtil.class.getSimpleName(); + private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); private final Context mTargetContext; diff --git a/framework/tests/bumble/src/android/bluetooth/service_discovery/LeAudioServiceDiscoveryTest.java b/framework/tests/bumble/src/android/bluetooth/service_discovery/LeAudioServiceDiscoveryTest.java index b5757c310f..7a8b738485 100644 --- a/framework/tests/bumble/src/android/bluetooth/service_discovery/LeAudioServiceDiscoveryTest.java +++ b/framework/tests/bumble/src/android/bluetooth/service_discovery/LeAudioServiceDiscoveryTest.java @@ -77,6 +77,7 @@ import java.util.concurrent.TimeUnit; @RunWith(AndroidJUnit4.class) public class LeAudioServiceDiscoveryTest { private static final String TAG = LeAudioServiceDiscoveryTest.class.getSimpleName(); + private static final String BUMBLE_DEVICE_NAME = "Bumble"; private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); private static final int DISCOVERY_TIMEOUT = 2000; // 2 seconds diff --git a/framework/tests/bumble/src/android/bluetooth/service_discovery/ServiceDiscoveryTest.java b/framework/tests/bumble/src/android/bluetooth/service_discovery/ServiceDiscoveryTest.java index 15a44c3f44..92271b4c8f 100644 --- a/framework/tests/bumble/src/android/bluetooth/service_discovery/ServiceDiscoveryTest.java +++ b/framework/tests/bumble/src/android/bluetooth/service_discovery/ServiceDiscoveryTest.java @@ -75,7 +75,8 @@ import java.util.Set; @RunWith(AndroidJUnit4.class) public class ServiceDiscoveryTest { - private static final String TAG = "ServiceDiscoveryTest"; + private static final String TAG = ServiceDiscoveryTest.class.getSimpleName(); + private static final Duration BOND_INTENT_TIMEOUT = Duration.ofSeconds(10); private static final ParcelUuid BATTERY_UUID = 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/framework/tests/metrics/host/AndroidTest.xml b/framework/tests/metrics/host/AndroidTest.xml index 752a6d1e11..102d5acdaa 100644 --- a/framework/tests/metrics/host/AndroidTest.xml +++ b/framework/tests/metrics/host/AndroidTest.xml @@ -12,7 +12,7 @@ <option name="force-root" value="true"/> </target_preparer> <target_preparer class="com.android.tradefed.targetprep.PythonVirtualenvPreparer"> - <option name="dep-module" value="grpcio==1.51.1" /> + <option name="dep-module" value="grpcio==1.70.0" /> <option name="dep-module" value="cryptography==35" /> <option name="dep-module" value="click>=7.1.2" /> </target_preparer> diff --git a/offload/hal/Android.bp b/offload/hal/Android.bp index 91324d0d94..87058f085f 100644 --- a/offload/hal/Android.bp +++ b/offload/hal/Android.bp @@ -32,6 +32,7 @@ rust_library { visibility: [ "//hardware/interfaces/bluetooth:__subpackages__", "//packages/modules/Bluetooth/offload:__subpackages__", + "//vendor:__subpackages__", ], } @@ -44,5 +45,6 @@ cc_library_headers { ], visibility: [ "//hardware/interfaces/bluetooth:__subpackages__", + "//vendor:__subpackages__", ], } 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/offload/leaudio/hci/Android.bp b/offload/leaudio/hci/Android.bp index 0c7839bf91..f79d98a26e 100644 --- a/offload/leaudio/hci/Android.bp +++ b/offload/leaudio/hci/Android.bp @@ -37,6 +37,7 @@ rust_library { visibility: [ "//hardware/interfaces/bluetooth:__subpackages__", "//packages/modules/Bluetooth/offload:__subpackages__", + "//vendor:__subpackages__", ], } 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/service/src/com/android/server/bluetooth/BluetoothManagerService.java b/service/src/com/android/server/bluetooth/BluetoothManagerService.java index 20d8dbf073..6cd63181da 100644 --- a/service/src/com/android/server/bluetooth/BluetoothManagerService.java +++ b/service/src/com/android/server/bluetooth/BluetoothManagerService.java @@ -692,7 +692,7 @@ class BluetoothManagerService { } /** Returns true if satellite mode is turned on. */ - private boolean isSatelliteModeOn() { + private static boolean isSatelliteModeOn() { return SatelliteModeListener.isOn(); } @@ -750,7 +750,7 @@ class BluetoothManagerService { Log.d(TAG, "loadStoredNameAndAddress: Name=" + mName + ", Address=" + logAddress(mAddress)); } - private String logAddress(String address) { + private static String logAddress(String address) { if (address == null) { return "[address is null]"; } @@ -1918,7 +1918,7 @@ class BluetoothManagerService { intent, UserHandle.ALL, null, getTempAllowlistBroadcastOptions()); } - private boolean isBleState(int state) { + private static boolean isBleState(int state) { switch (state) { case STATE_BLE_ON: case STATE_BLE_TURNING_ON: @@ -2233,7 +2233,7 @@ class BluetoothManagerService { } } - private void dumpBluetoothFlags(PrintWriter writer) { + private static void dumpBluetoothFlags(PrintWriter writer) { writer.println("🚩Flag dump:"); Arrays.stream(Flags.class.getDeclaredMethods()) .forEach( @@ -2500,8 +2500,8 @@ class BluetoothManagerService { disableComponents(pm, packageInfo.providers, packageName, null); } - private <T extends android.content.pm.ComponentInfo> void disableComponents( - PackageManager pm, T[] components, String packageName, List<String> componentsToKeep) { + private static <T extends android.content.pm.ComponentInfo> void disableComponents( + PackageManager pm, T[] components, String packageName, List<String> componentsToKeep) { if (components == null) { return; } diff --git a/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java b/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java index 40e6f4b4b7..07466e59c4 100644 --- a/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java +++ b/service/tests/src/com/android/server/bluetooth/BluetoothServiceBinderTest.java @@ -383,7 +383,7 @@ public class BluetoothServiceBinderTest { // ********************************************************************************************* // Utility method used in tests - private void verifyAndClearMock(Object o) { + private static void verifyAndClearMock(Object o) { assertThat(mockingDetails(o).isMock() || mockingDetails(o).isSpy()).isTrue(); verifyNoMoreInteractions(o); clearInvocations(o); diff --git a/sysprop/Android.bp b/sysprop/Android.bp index 241e8711f7..ef0ebad98d 100644 --- a/sysprop/Android.bp +++ b/sysprop/Android.bp @@ -13,6 +13,7 @@ sysprop_library { "device_id.sysprop", "gap.sysprop", "hardware.sysprop", + "hci.sysprop", "hfp.sysprop", ], property_owner: "Platform", diff --git a/sysprop/BUILD.gn b/sysprop/BUILD.gn index 9cdbf48530..84b21f0737 100644 --- a/sysprop/BUILD.gn +++ b/sysprop/BUILD.gn @@ -9,6 +9,7 @@ sysprop("libcom.android.sysprop.bluetooth") { "device_id.sysprop", "gap.sysprop", "hardware.sysprop", + "hci.sysprop", "hfp.sysprop", ] deps = [ "//bt/floss/android-base:android-base" ] diff --git a/sysprop/exported_include/android_bluetooth_sysprop.h b/sysprop/exported_include/android_bluetooth_sysprop.h index 24053123ac..4d3949a75f 100644 --- a/sysprop/exported_include/android_bluetooth_sysprop.h +++ b/sysprop/exported_include/android_bluetooth_sysprop.h @@ -23,4 +23,5 @@ #include <device_id.sysprop.h> #include <gap.sysprop.h> #include <hardware.sysprop.h> +#include <hci.sysprop.h> #include <hfp.sysprop.h> diff --git a/sysprop/hci.sysprop b/sysprop/hci.sysprop new file mode 100644 index 0000000000..04e7b6ccf8 --- /dev/null +++ b/sysprop/hci.sysprop @@ -0,0 +1,10 @@ +module: "android.sysprop.bluetooth.Hci" +owner: Platform + +prop { + api_name: "msft_vendor_opcode" + type: Integer + scope: Internal + access: Readonly + prop_name: "bluetooth.hci.msft_vendor_opcode" +}
\ No newline at end of file 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 40670af305..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); } @@ -293,9 +285,7 @@ bool LeAudioTransport::IsRequestCompletedAfterUpdate( } StartRequestState LeAudioTransport::GetStartRequestState(void) { - if (com::android::bluetooth::flags::leaudio_start_request_state_mutex_check()) { - std::lock_guard<std::mutex> guard(start_request_state_mutex_); - } + std::lock_guard<std::mutex> guard(start_request_state_mutex_); return start_request_state_; } void LeAudioTransport::ClearStartRequestState(void) { @@ -549,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() || @@ -578,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; } @@ -709,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) { @@ -745,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/Android.bp b/system/audio_hal_interface/fuzzer/Android.bp index f2301b6d00..422eadd711 100644 --- a/system/audio_hal_interface/fuzzer/Android.bp +++ b/system/audio_hal_interface/fuzzer/Android.bp @@ -121,6 +121,13 @@ cc_defaults { users: "multi_user", fuzzed_code_usage: "shipped", }, + target: { + android: { + static_libs: [ + "libperfetto_client_experimental", + ], + }, + }, } cc_fuzz { 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_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/Android.bp b/system/bta/Android.bp index f4685744ec..9eaf7c84b2 100644 --- a/system/bta/Android.bp +++ b/system/bta/Android.bp @@ -194,6 +194,7 @@ cc_library_static { "gatt/database_builder.cc", "jv/bta_jv_act.cc", "jv/bta_jv_api.cc", + "rfcomm/bta_rfcomm_metrics.cc", "rfcomm/bta_rfcomm_scn.cc", "sdp/bta_sdp.cc", "sdp/bta_sdp_act.cc", @@ -459,6 +460,7 @@ cc_test { srcs: [ ":TestCommonMockFunctions", ":TestFakeOsi", + ":TestMockBtaRfcMetrics", ":TestMockBtaSys", ":TestMockBtif", ":TestMockStackBtm", @@ -1462,6 +1464,7 @@ cc_test { ":TestFakeOsi", ":TestMockBtaGatt", ":TestMockBtaLeAudio", + ":TestMockBtaRfcMetrics", ":TestMockBtaScn", ":TestMockBtaSdp", ":TestMockBtaSys", diff --git a/system/bta/BUILD.gn b/system/bta/BUILD.gn index 425289338b..9c28016617 100644 --- a/system/bta/BUILD.gn +++ b/system/bta/BUILD.gn @@ -121,6 +121,7 @@ static_library("bta") { "ras/ras_client.cc", "ras/ras_server.cc", "ras/ras_utils.cc", + "rfcomm/bta_rfcomm_metrics.cc", "rfcomm/bta_rfcomm_scn.cc", "sdp/bta_sdp.cc", "sdp/bta_sdp_act.cc", 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 cdea95029b..22d291e054 100644 --- a/system/bta/ag/bta_ag_cmd.cc +++ b/system/bta/ag/bta_ag_cmd.cc @@ -19,6 +19,7 @@ #define LOG_TAG "bta_ag_cmd" #include <bluetooth/log.h> +#include <com_android_bluetooth_flags.h> #include <string.h> #include <cctype> @@ -46,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 @@ -1135,9 +1139,14 @@ void bta_ag_at_hfp_cback(tBTA_AG_SCB* p_scb, uint16_t cmd, uint8_t arg_type, cha p_scb->peer_features = (uint16_t)int_arg; if (p_scb->peer_version < HFP_VERSION_1_7) { - p_scb->masked_features &= HFP_1_6_FEAT_MASK; + if (!(com::android::bluetooth::flags::check_peer_hf_indicator() && + p_scb->peer_version == HFP_HSP_VERSION_UNKNOWN && + (p_scb->peer_features & BTA_AG_PEER_FEAT_HF_IND))) { + p_scb->masked_features &= HFP_1_6_FEAT_MASK; + } } + 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_rfc.cc b/system/bta/ag/bta_ag_rfc.cc index 58b7215a04..860709341c 100644 --- a/system/bta/ag/bta_ag_rfc.cc +++ b/system/bta/ag/bta_ag_rfc.cc @@ -29,6 +29,7 @@ #include <cstdint> #include "bta/ag/bta_ag_int.h" +#include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_sec_api.h" #include "bta_api.h" #include "stack/include/main_thread.h" @@ -257,6 +258,9 @@ void bta_ag_start_servers(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK services) { bta_ag_setup_port(p_scb, p_scb->serv_handle[i]); } else { /* TODO: CR#137125 to handle to error properly */ + bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(status), false, + tBTA_JV_STATUS::SUCCESS, p_scb->peer_addr, 0, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, true, 0); log::error( "RFCOMM_CreateConnectionWithSecurity ERROR {}, p_scb={}, " "services=0x{:x}, mgmt_cback_index={}", @@ -336,6 +340,10 @@ void bta_ag_rfc_do_open(tBTA_AG_SCB* p_scb, const tBTA_AG_DATA& data) { bta_ag_setup_port(p_scb, p_scb->conn_handle); } else { /* RFCOMM create connection failed; send ourselves RFCOMM close event */ + bta_collect_rfc_metrics_after_port_fail( + static_cast<tPORT_RESULT>(status), p_scb->sdp_metrics.sdp_initiated, + p_scb->sdp_metrics.status, p_scb->peer_addr, 0, BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, + true, p_scb->sdp_metrics.sdp_start_ms - p_scb->sdp_metrics.sdp_end_ms); log::error("RFCOMM_CreateConnection ERROR {} for {}", status, p_scb->peer_addr); bta_ag_sm_execute(p_scb, BTA_AG_RFC_CLOSE_EVT, data); } 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 3172d8d45f..9f41d2339f 100644 --- a/system/bta/ag/bta_ag_sdp.cc +++ b/system/bta/ag/bta_ag_sdp.cc @@ -32,6 +32,7 @@ #include "bta/ag/bta_ag_int.h" #include "bta/include/bta_hfp_api.h" +#include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_rfcomm_scn.h" #include "bta_ag_api.h" #include "bta_api.h" @@ -42,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" @@ -58,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. */ @@ -387,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) { @@ -540,6 +546,8 @@ void bta_ag_do_disc(tBTA_AG_SCB* p_scb, tBTA_SERVICE_MASK service) { return; } else { log::error("failed to start SDP discovery for {}", p_scb->peer_addr); + bta_collect_rfc_metrics_after_sdp_fail(tBTA_JV_STATUS::FAILURE, p_scb->peer_addr, 0, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, false, 0); } } else { log::error("failed to init SDP discovery database for {}", p_scb->peer_addr); 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 65036b1c74..1f4c68e516 100644 --- a/system/bta/hearing_aid/hearing_aid_audio_source.cc +++ b/system/bta/hearing_aid/hearing_aid_audio_source.cc @@ -16,6 +16,8 @@ * ******************************************************************************/ +#define LOG_TAG "bluetooth-asha" + #include <base/files/file_util.h> #include <bluetooth/log.h> #include <stdio.h> @@ -29,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" @@ -38,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; @@ -80,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; @@ -106,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); @@ -127,12 +94,6 @@ void send_audio_data() { } } -void hearing_aid_send_ack(tHEARING_AID_CTRL_ACK status) { - uint8_t ack = status; - log::debug("Hearing Aid audio ctrl ack: {}", status); - UIPC_Send(*uipc_hearing_aid, UIPC_CH_ID_AV_CTRL, 0, &ack, sizeof(ack)); -} - void start_audio_ticks() { if (data_interval_ms != HA_INTERVAL_10_MS && data_interval_ms != HA_INTERVAL_20_MS) { log::fatal("Unsupported data interval: {}", data_interval_ms); @@ -151,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"); @@ -412,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/hf_client/bta_hf_client_main.cc b/system/bta/hf_client/bta_hf_client_main.cc index 98528eee6c..466a1a55fc 100644 --- a/system/bta/hf_client/bta_hf_client_main.cc +++ b/system/bta/hf_client/bta_hf_client_main.cc @@ -460,28 +460,24 @@ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_handle(uint16_t handle) { * * Function bta_hf_client_find_cb_by_bda * - * Description Finds the control block by handle provided + * Description Finds the control block structure indexed by peer address * - * bda: address of the device to find the handle for. + * peer_addr: address of the device to find the handle for. * Since there can only be one HF connection for a device * we should always find a unique block * - * Returns Control block corresponding to the address and NULL if + * Returns Control block corresponding to the address or NULL if * none exists * ******************************************************************************/ tBTA_HF_CLIENT_CB* bta_hf_client_find_cb_by_bda(const RawAddress& peer_addr) { for (int i = 0; i < HF_CLIENT_MAX_DEVICES; i++) { - // Check if the associated index is allocated and that BD ADDR matches tBTA_HF_CLIENT_CB* client_cb = &bta_hf_client_cb_arr.cb[i]; if (client_cb->is_allocated && peer_addr == client_cb->peer_addr) { return client_cb; - } else { - log::warn("bdaddr mismatch for handle {} alloc {}", i, client_cb->is_allocated); } } - log::error("block not found"); - return NULL; + return nullptr; } /******************************************************************************* diff --git a/system/bta/hf_client/bta_hf_client_rfc.cc b/system/bta/hf_client/bta_hf_client_rfc.cc index 6e9655ac38..69d1525cfe 100644 --- a/system/bta/hf_client/bta_hf_client_rfc.cc +++ b/system/bta/hf_client/bta_hf_client_rfc.cc @@ -30,6 +30,7 @@ #include <cstdint> #include "bta/hf_client/bta_hf_client_int.h" +#include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_sec_api.h" #include "bta_sys.h" #include "osi/include/allocator.h" @@ -195,6 +196,9 @@ void bta_hf_client_start_server() { if (port_status == PORT_SUCCESS) { bta_hf_client_setup_port(bta_hf_client_cb_arr.serv_handle); } else { + bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(port_status), false, + tBTA_JV_STATUS::SUCCESS, RawAddress::kAny, 0, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, true, 0); log::verbose("RFCOMM_CreateConnection returned error:{}", port_status); } } @@ -240,14 +244,20 @@ void bta_hf_client_rfc_do_open(tBTA_HF_CLIENT_DATA* p_data) { return; } - if (RFCOMM_CreateConnectionWithSecurity( - UUID_SERVCLASS_HF_HANDSFREE, client_cb->peer_scn, false, BTA_HF_CLIENT_MTU, - client_cb->peer_addr, &(client_cb->conn_handle), bta_hf_client_mgmt_cback, - BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, RfcommCfgInfo{}) == PORT_SUCCESS) { + int status = RFCOMM_CreateConnectionWithSecurity( + UUID_SERVCLASS_HF_HANDSFREE, client_cb->peer_scn, false, BTA_HF_CLIENT_MTU, + client_cb->peer_addr, &(client_cb->conn_handle), bta_hf_client_mgmt_cback, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, RfcommCfgInfo{}); + if (status == PORT_SUCCESS) { bta_hf_client_setup_port(client_cb->conn_handle); log::verbose("bta_hf_client_rfc_do_open : conn_handle = {}", client_cb->conn_handle); } else { /* RFCOMM create connection failed; send ourselves RFCOMM close event */ + bta_collect_rfc_metrics_after_port_fail( + static_cast<tPORT_RESULT>(status), client_cb->sdp_metrics.sdp_initiated, + client_cb->sdp_metrics.status, client_cb->peer_addr, 0, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, true, + client_cb->sdp_metrics.sdp_start_ms - client_cb->sdp_metrics.sdp_end_ms); bta_hf_client_sm_execute(BTA_HF_CLIENT_RFC_CLOSE_EVT, p_data); } } diff --git a/system/bta/hf_client/bta_hf_client_sdp.cc b/system/bta/hf_client/bta_hf_client_sdp.cc index 02dfb37c85..c7b5ce7ceb 100644 --- a/system/bta/hf_client/bta_hf_client_sdp.cc +++ b/system/bta/hf_client/bta_hf_client_sdp.cc @@ -33,6 +33,7 @@ #include "bta/hf_client/bta_hf_client_int.h" #include "bta/include/bta_hf_client_api.h" +#include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_rfcomm_scn.h" #include "bta/sys/bta_sys.h" #include "bta_hfp_api.h" @@ -386,6 +387,8 @@ void bta_hf_client_do_disc(tBTA_HF_CLIENT_CB* client_cb) { if (!db_inited) { log::warn("Unable to start SDP service search request peer:{}", client_cb->peer_addr); + bta_collect_rfc_metrics_after_sdp_fail(tBTA_JV_STATUS::FAILURE, client_cb->peer_addr, 0, + BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT, false, 0); /*free discover db */ osi_free_and_reset((void**)&client_cb->p_disc_db); /* sent failed event */ 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_rfcomm_metrics.h b/system/bta/include/bta_rfcomm_metrics.h new file mode 100644 index 0000000000..0db35f8ba4 --- /dev/null +++ b/system/bta/include/bta_rfcomm_metrics.h @@ -0,0 +1,28 @@ +/* + * Copyright 2024 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 "bta_jv_api.h" +#include "types/raw_address.h" + +void bta_collect_rfc_metrics_after_sdp_fail(tBTA_JV_STATUS sdp_status, RawAddress addr, int app_uid, + int security, bool is_server, uint64_t sdp_duration); + +void bta_collect_rfc_metrics_after_port_fail(tPORT_RESULT port_result, bool sdp_initiated, + tBTA_JV_STATUS sdp_status, RawAddress addr, + int app_uid, int security, bool is_server, + uint64_t sdp_duration_ms); diff --git a/system/bta/jv/bta_jv_act.cc b/system/bta/jv/bta_jv_act.cc index 1182411dd5..d9eb9d0bbc 100644 --- a/system/bta/jv/bta_jv_act.cc +++ b/system/bta/jv/bta_jv_act.cc @@ -31,6 +31,7 @@ #include <unordered_set> #include "bta/include/bta_jv_co.h" +#include "bta/include/bta_rfcomm_metrics.h" #include "bta/include/bta_rfcomm_scn.h" #include "bta/jv/bta_jv_int.h" #include "bta/sys/bta_sys.h" @@ -52,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; @@ -104,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++) { @@ -217,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; @@ -259,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) && @@ -280,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; @@ -396,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) { @@ -586,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)) { @@ -1515,6 +1513,7 @@ void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, const RawAddre RfcommCfgInfo cfg, uint32_t app_uid, uint64_t sdp_duration_ms) { uint16_t handle = 0; uint32_t event_mask = BTA_JV_RFC_EV_MASK; + int port_status; PortSettings port_settings; tBTA_JV bta_jv = { @@ -1534,10 +1533,14 @@ void bta_jv_rfcomm_connect(tBTA_SEC sec_mask, uint8_t remote_scn, const RawAddre sec_mask, BT_PSM_RFCOMM, BTM_SEC_PROTO_RFCOMM, 0); - if (RFCOMM_CreateConnectionWithSecurity( - UUID_SERVCLASS_SERIAL_PORT, remote_scn, false, BTA_JV_DEF_RFC_MTU, peer_bd_addr, - &handle, bta_jv_port_mgmt_cl_cback, sec_mask, cfg) != PORT_SUCCESS) { + port_status = RFCOMM_CreateConnectionWithSecurity(UUID_SERVCLASS_SERIAL_PORT, remote_scn, false, + BTA_JV_DEF_RFC_MTU, peer_bd_addr, &handle, + bta_jv_port_mgmt_cl_cback, sec_mask, cfg); + if (port_status != PORT_SUCCESS) { log::error("RFCOMM_CreateConnection failed"); + bta_collect_rfc_metrics_after_port_fail( + static_cast<tPORT_RESULT>(port_status), sdp_duration_ms > 0, tBTA_JV_STATUS::SUCCESS, + peer_bd_addr, static_cast<int>(app_uid), sec_mask, false, sdp_duration_ms); bta_jv.rfc_cl_init.status = tBTA_JV_STATUS::FAILURE; } else { tBTA_JV_PCB* p_pcb; @@ -1765,6 +1768,7 @@ static void bta_jv_port_event_sr_cback(uint32_t code, uint16_t port_handle) { static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb_open) { uint8_t used = 0, i, listen = 0; uint32_t si = 0; + int port_status; PortSettings port_settings; uint32_t event_mask = BTA_JV_RFC_EV_MASK; tBTA_JV_PCB* p_pcb = NULL; @@ -1802,10 +1806,10 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb log::error("RFCOMM_CreateConnection failed: invalid port_handle"); } - if (RFCOMM_CreateConnectionWithSecurity(p_cb->sec_id, p_cb->scn, true, BTA_JV_DEF_RFC_MTU, - RawAddress::kAny, &(p_cb->rfc_hdl[si]), - bta_jv_port_mgmt_sr_cback, sec_mask, - RfcommCfgInfo{}) == PORT_SUCCESS) { + port_status = RFCOMM_CreateConnectionWithSecurity( + p_cb->sec_id, p_cb->scn, true, BTA_JV_DEF_RFC_MTU, RawAddress::kAny, + &(p_cb->rfc_hdl[si]), bta_jv_port_mgmt_sr_cback, sec_mask, RfcommCfgInfo{}); + if (port_status == PORT_SUCCESS) { p_cb->curr_sess++; p_pcb = &bta_jv_cb.port_cb[p_cb->rfc_hdl[si] - 1]; p_pcb->state = BTA_JV_ST_SR_LISTEN; @@ -1837,6 +1841,10 @@ static tBTA_JV_PCB* bta_jv_add_rfc_port(tBTA_JV_RFC_CB* p_cb, tBTA_JV_PCB* p_pcb log::verbose("p_pcb->handle=0x{:x}, curr_sess={}", p_pcb->handle, p_cb->curr_sess); } else { log::error("RFCOMM_CreateConnection failed"); + bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(port_status), false, + tBTA_JV_STATUS::SUCCESS, RawAddress::kAny, 0, + sec_mask, true, 0); + return NULL; } } else { @@ -1854,6 +1862,7 @@ void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t ma RfcommCfgInfo cfg, uint32_t app_uid) { uint16_t handle = 0; uint32_t event_mask = BTA_JV_RFC_EV_MASK; + int port_status; PortSettings port_settings; tBTA_JV_RFC_CB* p_cb = NULL; tBTA_JV_PCB* p_pcb; @@ -1863,10 +1872,14 @@ void bta_jv_rfcomm_start_server(tBTA_SEC sec_mask, uint8_t local_scn, uint8_t ma evt_data.status = tBTA_JV_STATUS::FAILURE; do { - if (RFCOMM_CreateConnectionWithSecurity(0, local_scn, true, BTA_JV_DEF_RFC_MTU, - RawAddress::kAny, &handle, bta_jv_port_mgmt_sr_cback, - sec_mask, cfg) != PORT_SUCCESS) { + port_status = RFCOMM_CreateConnectionWithSecurity(0, local_scn, true, BTA_JV_DEF_RFC_MTU, + RawAddress::kAny, &handle, + bta_jv_port_mgmt_sr_cback, sec_mask, cfg); + if (port_status != PORT_SUCCESS) { log::error("RFCOMM_CreateConnection failed"); + bta_collect_rfc_metrics_after_port_fail(static_cast<tPORT_RESULT>(port_status), false, + tBTA_JV_STATUS::SUCCESS, RawAddress::kAny, + static_cast<int>(app_uid), sec_mask, true, 0); break; } 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..cabdee4a64 100644 --- a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc +++ b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc @@ -30,9 +30,7 @@ #include "common/message_loop_thread.h" #include "hardware/bluetooth.h" #include "osi/include/wakelock.h" - -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" +#include "stack/include/main_thread.h" using ::testing::_; using ::testing::Assign; @@ -64,9 +62,6 @@ bt_status_t do_in_main_thread(base::OnceClosure task) { return BT_STATUS_SUCCESS; } -static base::MessageLoop* message_loop_; -base::MessageLoop* get_main_message_loop() { return message_loop_; } - static void init_message_loop_thread() { message_loop_thread.StartUp(); if (!message_loop_thread.IsRunning()) { @@ -76,17 +71,9 @@ static void init_message_loop_thread() { if (!message_loop_thread.EnableRealTimeScheduling()) { log::error("Unable to set real time scheduling"); } - - message_loop_ = message_loop_thread.message_loop(); - if (message_loop_ == nullptr) { - FAIL() << "unable to get message loop."; - } } -static void cleanup_message_loop_thread() { - message_loop_ = nullptr; - message_loop_thread.ShutDown(); -} +static void cleanup_message_loop_thread() { message_loop_thread.ShutDown(); } using bluetooth::audio::le_audio::LeAudioClientInterface; diff --git a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc index 2ee512f1fc..7ff5196256 100644 --- a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc +++ b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc @@ -310,8 +310,11 @@ bool SourceImpl::OnMetadataUpdateReq(const source_metadata_v7_t& source_metadata return false; } - std::vector<struct playback_track_metadata_v7> metadata( - source_metadata.tracks, source_metadata.tracks + source_metadata.track_count); + std::vector<struct playback_track_metadata_v7> metadata; + if (source_metadata.tracks != nullptr) { + metadata = std::vector<struct playback_track_metadata_v7>( + source_metadata.tracks, source_metadata.tracks + source_metadata.track_count); + } bt_status_t status = do_in_main_thread(base::BindOnce( &LeAudioSourceAudioHalClient::Callbacks::OnAudioMetadataUpdate, diff --git a/system/bta/le_audio/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..44e6bf7815 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 { @@ -110,9 +110,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 +120,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 51e14e9499..83f93d5634 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; @@ -172,7 +169,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 +187,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"; @@ -1115,32 +1112,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 +1191,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 +1368,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(), @@ -4136,15 +4138,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 +4216,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); } } @@ -4395,8 +4426,7 @@ public: if (!remote_contexts.sink.any() && !remote_contexts.source.any()) { log::warn("Requested context type not available on the remote side"); - if (com::android::bluetooth::flags::leaudio_no_context_validate_streaming_request() && - source_monitor_mode_) { + if (source_monitor_mode_) { notifyAudioLocalSource(UnicastMonitorModeStatus::STREAMING_REQUESTED_NO_CONTEXT_VALIDATE); return false; @@ -4409,7 +4439,7 @@ public: return false; } - return GroupStream(active_group_id_, configuration_context_type_, remote_contexts); + return GroupStream(group, configuration_context_type_, remote_contexts); } void OnAudioSuspend() { @@ -5357,11 +5387,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 = { @@ -5531,7 +5567,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 */ @@ -5546,6 +5582,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); @@ -5656,7 +5696,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; } @@ -6062,7 +6102,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); @@ -6118,17 +6159,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); @@ -6173,47 +6227,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(); } } } @@ -6848,15 +6909,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); } } @@ -6875,7 +6946,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/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..27cfd9e5e3 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; @@ -1104,7 +1101,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 +1111,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,7 +1212,7 @@ 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(); /* Simple strategy picker */ @@ -1234,8 +1231,7 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() c 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 +1239,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 +1271,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 +1371,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,9 +1593,9 @@ 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) { /* Check direction and if audio location allows to create more cises to a * single device. */ diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h index 73d537ce0e..a9114525d4 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); @@ -217,8 +219,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..ec856c8c42 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,9 @@ 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, + const AudioLocations& device_locations, + AudioLocations& group_locations) { log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}", (int)strategy, device_locations.to_ulong(), group_locations.to_ulong()); @@ -1184,7 +1181,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_test.cc b/system/bta/le_audio/devices_test.cc index 6388d7141c..bc53a5b18c 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}; } @@ -2599,6 +2592,23 @@ TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group direction_to_verify); } +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 23b85564b3..e749c574ba 100644 --- a/system/bta/le_audio/le_audio_client_test.cc +++ b/system/bta/le_audio/le_audio_client_test.cc @@ -30,6 +30,7 @@ #include "bta_groups.h" #include "bta_le_audio_api.h" #include "bta_le_audio_broadcaster_api.h" +#include "btif/include/btif_common.h" #include "btif/include/mock_core_callbacks.h" #include "btif_storage_mock.h" #include "btm_api_mock.h" @@ -51,15 +52,13 @@ #include "mock_device_groups.h" #include "mock_state_machine.h" #include "stack/include/btm_status.h" +#include "stack/include/main_thread.h" #include "test/common/mock_functions.h" #include "test/mock/mock_main_shim_entry.h" #include "test/mock/mock_stack_btm_iso.h" #define TEST_BT com::android::bluetooth::flags -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using testing::_; using testing::AnyNumber; using testing::AtLeast; @@ -107,18 +106,14 @@ static constexpr char kNotifyUpperLayerAboutGroupBeingInIdleDuringCall[] = void osi_property_set_bool(const char* key, bool value); // Disables most likely false-positives from base::SplitString() +extern "C" const char* __asan_default_options(); extern "C" const char* __asan_default_options() { return "detect_container_overflow=0"; } std::atomic<int> num_async_tasks; -static base::MessageLoop* message_loop_; bluetooth::common::MessageLoopThread message_loop_thread("test message loop"); bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; } bt_status_t do_in_main_thread(base::OnceClosure task) { - if (!message_loop_) { - return BT_STATUS_FAIL; - } - // Wrap the task with task counter so we could later know if there are // any callbacks scheduled and we should wait before performing some actions if (!message_loop_thread.DoInThread( @@ -140,8 +135,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 +145,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 +157,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 +225,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; @@ -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) { @@ -8388,19 +8414,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 +8451,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 +8586,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 +8867,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 +9085,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 +9195,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 +10749,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 +10881,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 +11440,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 @@ -13127,8 +13406,6 @@ TEST_F(UnicastTestHandoverMode, SetAllowedContextMask) { } TEST_F(UnicastTest, NoContextvalidateStreamingRequest) { - com::android::bluetooth::flags::provider_->leaudio_no_context_validate_streaming_request(true); - const RawAddress test_address0 = GetTestAddress(0); int group_id = bluetooth::groups::kGroupUnknown; @@ -13263,7 +13540,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; 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..0d40d6adf7 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 { @@ -1142,6 +1146,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 +1293,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..7e2495ffce 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; 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..89a5682b9d 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, diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc index 021b3fa811..308befe6b5 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; 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/ras/ras_client.cc b/system/bta/ras/ras_client.cc index eb78cff560..905aced68a 100644 --- a/system/bta/ras/ras_client.cc +++ b/system/bta/ras/ras_client.cc @@ -170,7 +170,7 @@ public: log::info("Initialize, client_id {}", client_id); instance->gatt_if_ = client_id; }), - true); + /*eatt_support=*/false); } void RegisterCallbacks(bluetooth::ras::RasClientCallbacks* callbacks) { callbacks_ = callbacks; } diff --git a/system/bta/rfcomm/bta_rfcomm_metrics.cc b/system/bta/rfcomm/bta_rfcomm_metrics.cc new file mode 100644 index 0000000000..5cbae01471 --- /dev/null +++ b/system/bta/rfcomm/bta_rfcomm_metrics.cc @@ -0,0 +1,152 @@ +/* + * Copyright 2024 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 "bta_rfcomm_metrics" + +#include "bta_rfcomm_metrics.h" + +#include <bluetooth/log.h> +#include <frameworks/proto_logging/stats/enums/bluetooth/rfcomm/enums.pb.h> + +#include "bta_sec_api.h" +#include "main/shim/metrics_api.h" +#include "stack/include/btm_sec_api_types.h" + +using namespace bluetooth; + +using namespace android::bluetooth; +using namespace android::bluetooth::rfcomm; + +static BtaStatus toStatus(tBTA_JV_STATUS status); +static SocketConnectionSecurity toSecurity(int security); +static PortResult toPortResult(tPORT_RESULT result); + +// logged if SDP result is either FAILED or BUSY +void bta_collect_rfc_metrics_after_sdp_fail(tBTA_JV_STATUS sdp_status, RawAddress addr, int app_uid, + int security, bool is_server, + uint64_t sdp_duration_ms) { + // We only call this function in the case where we started (and failed) sdp + bool sdp_initiated = true; + + // We didn't make it to the stage of making a port, so assign default values for these fields + PortResult close_reason = PortResult::PORT_RESULT_UNDEFINED; + RfcommPortState state_prior = RfcommPortState::PORT_STATE_UNKNOWN; + RfcommPortEvent last_event = RfcommPortEvent::PORT_EVENT_UNKNOWN; + int open_duration_ms = 0; + + shim::LogMetricRfcommConnectionAtClose( + addr, close_reason, toSecurity(security), last_event, state_prior, open_duration_ms, + app_uid, toStatus(sdp_status), is_server, sdp_initiated, sdp_duration_ms); +} + +void bta_collect_rfc_metrics_after_port_fail(tPORT_RESULT port_result, bool sdp_initiated, + tBTA_JV_STATUS sdp_status, RawAddress addr, + int app_uid, int security, bool is_server, + uint64_t sdp_duration_ms) { + BtaStatus reported_status; + if (sdp_status == tBTA_JV_STATUS::SUCCESS && !sdp_initiated) { + reported_status = BtaStatus::BTA_STATUS_UNKNOWN; + } else { + reported_status = toStatus(sdp_status); + } + RfcommPortState state_prior = RfcommPortState::PORT_STATE_UNKNOWN; + RfcommPortEvent last_event = RfcommPortEvent::PORT_EVENT_UNKNOWN; + int open_duration_ms = 0; + + shim::LogMetricRfcommConnectionAtClose( + addr, toPortResult(port_result), toSecurity(security), last_event, state_prior, + open_duration_ms, app_uid, reported_status, is_server, sdp_initiated, sdp_duration_ms); +} + +static BtaStatus toStatus(tBTA_JV_STATUS status) { + switch (status) { + case tBTA_JV_STATUS::SUCCESS: + return BtaStatus::BTA_STATUS_SUCCESS; + case tBTA_JV_STATUS::FAILURE: + return BtaStatus::BTA_STATUS_FAILURE; + case tBTA_JV_STATUS::BUSY: + return BtaStatus::BTA_STATUS_BUSY; + } + return BtaStatus::BTA_STATUS_UNKNOWN; +} + +static SocketConnectionSecurity toSecurity(int security) { + if ((security == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) || + (security == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT)) || + (security == (BTA_SEC_AUTHENTICATE | BTA_SEC_ENCRYPT))) { + return SocketConnectionSecurity::SOCKET_SECURITY_SECURE; + } else if (security == BTM_SEC_NONE) { + return SocketConnectionSecurity::SOCKET_SECURITY_INSECURE; + } + return SocketConnectionSecurity::SOCKET_SECURITY_UNKNOWN; +} + +static PortResult toPortResult(tPORT_RESULT result) { + switch (result) { + case PORT_SUCCESS: + return PortResult::PORT_RESULT_SUCCESS; + case PORT_UNKNOWN_ERROR: + return PortResult::PORT_RESULT_UNKNOWN_ERROR; + case PORT_ALREADY_OPENED: + return PortResult::PORT_RESULT_ALREADY_OPENED; + case PORT_CMD_PENDING: + return PortResult::PORT_RESULT_CMD_PENDING; + case PORT_APP_NOT_REGISTERED: + return PortResult::PORT_RESULT_APP_NOT_REGISTERED; + case PORT_NO_MEM: + return PortResult::PORT_RESULT_NO_MEM; + case PORT_NO_RESOURCES: + return PortResult::PORT_RESULT_NO_RESOURCES; + case PORT_BAD_BD_ADDR: + return PortResult::PORT_RESULT_BAD_BD_ADDR; + case PORT_BAD_HANDLE: + return PortResult::PORT_RESULT_BAD_HANDLE; + case PORT_NOT_OPENED: + return PortResult::PORT_RESULT_NOT_OPENED; + case PORT_LINE_ERR: + return PortResult::PORT_RESULT_LINE_ERR; + case PORT_START_FAILED: + return PortResult::PORT_RESULT_START_FAILED; + case PORT_PAR_NEG_FAILED: + return PortResult::PORT_RESULT_PAR_NEG_FAILED; + case PORT_PORT_NEG_FAILED: + return PortResult::PORT_RESULT_PORT_NEG_FAILED; + case PORT_SEC_FAILED: + return PortResult::PORT_RESULT_SEC_FAILED; + case PORT_PEER_CONNECTION_FAILED: + return PortResult::PORT_RESULT_PEER_CONNECTION_FAILED; + case PORT_PEER_FAILED: + return PortResult::PORT_RESULT_PEER_FAILED; + case PORT_PEER_TIMEOUT: + return PortResult::PORT_RESULT_PEER_TIMEOUT; + case PORT_CLOSED: + return PortResult::PORT_RESULT_CLOSED; + case PORT_TX_FULL: + return PortResult::PORT_RESULT_TX_FULL; + case PORT_LOCAL_CLOSED: + return PortResult::PORT_RESULT_LOCAL_CLOSED; + case PORT_LOCAL_TIMEOUT: + return PortResult::PORT_RESULT_LOCAL_TIMEOUT; + case PORT_TX_QUEUE_DISABLED: + return PortResult::PORT_RESULT_TX_QUEUE_DISABLED; + case PORT_PAGE_TIMEOUT: + return PortResult::PORT_RESULT_PAGE_TIMEOUT; + case PORT_INVALID_SCN: + return PortResult::PORT_RESULT_INVALID_SCN; + case PORT_ERR_MAX: + return PortResult::PORT_RESULT_ERR_MAX; + } + return PortResult::PORT_RESULT_UNDEFINED; +} 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..9df26fe0a6 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; 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/btcore/include/module.h b/system/btcore/include/module.h index 6ea11c163b..7402ca161c 100644 --- a/system/btcore/include/module.h +++ b/system/btcore/include/module.h @@ -55,3 +55,6 @@ void module_shut_down(const module_t* module); // Clean up the provided module. |module| may not be NULL. // If not initialized, does nothing. void module_clean_up(const module_t* module); + +// Returns true if the module is started. +bool is_module_started(const module_t* module); diff --git a/system/btcore/src/module.cc b/system/btcore/src/module.cc index ec34b32636..62ab21ab34 100644 --- a/system/btcore/src/module.cc +++ b/system/btcore/src/module.cc @@ -160,3 +160,9 @@ static void set_module_state(const module_t* module, module_state_t state) { std::lock_guard<std::mutex> lock(metadata_mutex); metadata[module] = state; } + +bool is_module_started(const module_t* module) { + std::lock_guard<std::mutex> lock(metadata_mutex); + auto map_ptr = metadata.find(module); + return map_ptr != metadata.end() && map_ptr->second == MODULE_STATE_STARTED; +} diff --git a/system/btif/Android.bp b/system/btif/Android.bp index 498d0c1048..cbb42f1587 100644 --- a/system/btif/Android.bp +++ b/system/btif/Android.bp @@ -347,6 +347,7 @@ cc_test { "android.system.suspend-V1-ndk", "android.system.suspend.control-V1-ndk", "libexpresslog", + "libperfetto_client_experimental", "libstatslog_express", "libtextclassifier_hash_static", ], @@ -541,6 +542,7 @@ cc_test { ":TestMockBtaLeAudioHalVerifier", ":TestMockBtaPan", ":TestMockBtaRas", + ":TestMockBtaRfcMetrics", ":TestMockBtaScn", ":TestMockBtaSdp", ":TestMockBtaSys", @@ -660,6 +662,7 @@ cc_test { ":TestMockBtaLeAudioHalVerifier", ":TestMockBtaPan", ":TestMockBtaRas", + ":TestMockBtaRfcMetrics", ":TestMockBtaScn", ":TestMockBtaSdp", ":TestMockBtaSys", 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_api.h b/system/btif/include/btif_api.h index bd50b86124..63357a2b09 100644 --- a/system/btif/include/btif_api.h +++ b/system/btif/include/btif_api.h @@ -222,6 +222,8 @@ void btif_dm_start_discovery(void); void btif_dm_cancel_discovery(void); bool btif_dm_pairing_is_busy(); +bool btif_dm_is_pairing(const RawAddress& bdaddr); + /******************************************************************************* * * Function btif_dm_create_bond diff --git a/system/btif/include/btif_dm.h b/system/btif/include/btif_dm.h index 9069c97b76..9d942d381d 100644 --- a/system/btif/include/btif_dm.h +++ b/system/btif/include/btif_dm.h @@ -118,6 +118,8 @@ void btif_dm_metadata_changed(const RawAddress& remote_bd_addr, int key, void btif_dm_hh_open_failed(RawAddress* bdaddr); +bool btif_dm_is_pairing(const RawAddress& bdaddr); + /*callout for reading SMP properties from Text file*/ bool btif_dm_get_smp_config(tBTE_APPL_CFG* p_cfg); @@ -153,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 edadbdbbe8..38dfc7761d 100644 --- a/system/btif/include/btif_hh.h +++ b/system/btif/include/btif_hh.h @@ -133,6 +133,9 @@ typedef struct { bool service_dereg_active; std::list<tAclLinkSpec> new_connection_requests; + + 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/gd/os/mgmt_stub.cc b/system/btif/include/btif_iot_config.h index 308838818b..72a2d68cd8 100644 --- a/system/gd/os/mgmt_stub.cc +++ b/system/btif/include/btif_iot_config.h @@ -1,6 +1,6 @@ /****************************************************************************** * - * Copyright 2024 The Android Open Source Project + * 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. @@ -16,21 +16,8 @@ * ******************************************************************************/ -/* - * MGMT stub - */ +#pragma once -#include <bluetooth/log.h> +#include "bta/include/bta_sec_api.h" -#include "os/mgmt.h" - -namespace bluetooth { -namespace os { - -uint16_t Management::getVendorSpecificCode(uint16_t vendor_specification) { - log::debug("Using stub for vendor opcode 0x{:04x}", vendor_specification); - return 0; -} - -} // namespace os -} // namespace bluetooth +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..681ea2b0af 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); /******************************************************************************* * 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/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_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_bqr.cc b/system/btif/src/btif_bqr.cc index eaaef220e6..93ce1d542b 100644 --- a/system/btif/src/btif_bqr.cc +++ b/system/btif/src/btif_bqr.cc @@ -1069,6 +1069,19 @@ static void vendor_specific_event_callback( // The stream currently points to the BQR sub-event parameters switch (quality_report_id) { + case QUALITY_REPORT_ID_MONITOR_MODE: + case QUALITY_REPORT_ID_APPROACH_LSTO: + case QUALITY_REPORT_ID_A2DP_AUDIO_CHOPPY: + case QUALITY_REPORT_ID_SCO_VOICE_CHOPPY: + case QUALITY_REPORT_ID_LE_AUDIO_CHOPPY: + case QUALITY_REPORT_ID_CONNECT_FAIL: + case QUALITY_REPORT_ID_ENERGY_MONITOR: + case QUALITY_REPORT_ID_RF_STATS: + if (com::android::bluetooth::flags::fix_unhandled_bqr_subevent()) { + CategorizeBqrEvent(bytes.size(), bytes.data()); + } + break; + case bluetooth::bqr::QUALITY_REPORT_ID_LMP_LL_MESSAGE_TRACE: { auto lmp_view = hci::BqrLogDumpEventView::Create(*bqr); } @@ -1092,7 +1105,9 @@ static void vendor_specific_event_callback( log::info("Unhandled BQR subevent 0x{:02x}", quality_report_id); } - CategorizeBqrEvent(bytes.size(), bytes.data()); + if (!com::android::bluetooth::flags::fix_unhandled_bqr_subevent()) { + CategorizeBqrEvent(bytes.size(), bytes.data()); + } } void register_vse() { 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 d169837c23..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}); @@ -2376,6 +2383,11 @@ void btif_dm_cancel_discovery(void) { bool btif_dm_pairing_is_busy() { return pairing_cb.state != BT_BOND_STATE_NONE; } +bool btif_dm_is_pairing(const RawAddress& bdaddr) { + return btif_dm_pairing_is_busy() && + (pairing_cb.bd_addr == bdaddr || pairing_cb.static_bdaddr == bdaddr); +} + /******************************************************************************* * * Function btif_dm_create_bond @@ -3836,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_hh.cc b/system/btif/src/btif_hh.cc index c021e3de0c..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) { @@ -575,6 +602,38 @@ 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() && + 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; + } + log::warn("Reject Incoming HID Connection, device: {}, state: {}", conn.link_spec, bthh_connection_state_text(dev_status)); log_counter_metrics_btif( @@ -634,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); } } @@ -645,6 +704,16 @@ static void hh_open_handler(tBTA_HH_CONN& conn) { static void hh_close_handler(tBTA_HH_CBDATA& dev_status) { btif_hh_device_t* p_dev = btif_hh_find_connected_dev_by_handle(dev_status.handle); if (p_dev == nullptr) { + if (com::android::bluetooth::flags::early_incoming_hid_connection() && + btif_hh_cb.pending_incoming_connection.handle == dev_status.handle && + !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(btif_hh_cb.pending_incoming_connection.handle); + alarm_cancel(btif_hh_cb.incoming_connection_timer); + btif_hh_cb.pending_incoming_connection = {}; + return; + } log::warn("Unknown device handle {}", dev_status.handle); return; } @@ -863,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); @@ -914,6 +983,16 @@ void btif_hh_disconnected(const RawAddress& addr, tBT_TRANSPORT transport) { link_spec.addrt.type = BLE_ADDR_PUBLIC; link_spec.transport = BT_TRANSPORT_LE; + if (com::android::bluetooth::flags::early_incoming_hid_connection() && + btif_hh_cb.pending_incoming_connection.link_spec == link_spec) { + log::warn("Pending incoming connection {} closed, handle: {} ", + 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 = {}; + } + btif_hh_device_t* p_dev = btif_hh_find_dev_by_link_spec(link_spec); if (p_dev == nullptr) { return; @@ -940,6 +1019,16 @@ void btif_hh_remove_device(const tAclLinkSpec& link_spec) { BTHH_LOG_LINK(link_spec); bool announce_vup = false; + if (com::android::bluetooth::flags::early_incoming_hid_connection() && + btif_hh_cb.pending_incoming_connection.link_spec == link_spec) { + log::warn("Pending incoming connection {} closed, handle: {} ", + 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 = {}; + } + for (int i = 0; i < BTIF_HH_MAX_ADDED_DEV; i++) { btif_hh_added_device_t* p_added_dev = &btif_hh_cb.added_devices[i]; if (p_added_dev->link_spec == link_spec) { @@ -961,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--; @@ -986,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 * @@ -1007,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); @@ -1031,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; } @@ -1119,15 +1249,25 @@ bt_status_t btif_hh_connect(const tAclLinkSpec& link_spec) { btif_hh_cb.new_connection_requests.push_back(link_spec); } + do_in_jni_thread(base::Bind( + [](tAclLinkSpec link_spec) { BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_CONNECTING); }, + 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); + 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; + } + /* Not checking the NORMALLY_Connectible flags from sdp record, and anyways sending this request from host, for subsequent user initiated connection. If the remote is not in pagescan mode, we will do 2 retries to connect before giving up */ BTA_HhOpen(link_spec, true); - - do_in_jni_thread(base::Bind( - [](tAclLinkSpec link_spec) { BTHH_STATE_UPDATE(link_spec, BTHH_CONN_STATE_CONNECTING); }, - link_spec)); return BT_STATUS_SUCCESS; } @@ -1481,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); @@ -2087,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]; @@ -2195,6 +2340,13 @@ void DumpsysHid(int fd) { p_dev->reconnect_allowed ? "T" : "F"); } } + + if (com::android::bluetooth::flags::hid_report_queuing() && + !btif_hh_cb.pending_incoming_connection.link_spec.addrt.bda.IsEmpty()) { + LOG_DUMPSYS( + fd, " Pending incoming connection: %s", + btif_hh_cb.pending_incoming_connection.link_spec.ToRedactedStringForLogging().c_str()); + } BTA_HhDump(fd); } 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_le_audio.cc b/system/btif/src/btif_le_audio.cc index 0e6d377698..9b4fdc81fc 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; 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..4a8d13d59d 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 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 27db388700..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,8 @@ #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" #include "btif/include/btif_sock.h" @@ -50,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; @@ -1086,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. @@ -1134,6 +1136,8 @@ static void handle_discovery_comp(tBTA_JV_STATUS status, int scn, uint32_t id) { "SDP service discovery completed for slot_id: {} with the result " "status: {}, scn: {}", id, bta_jv_status_text(status), scn); + bta_collect_rfc_metrics_after_sdp_fail(status, slot->addr, slot->app_uid, slot->security, + static_cast<bool>(slot->f.server), sdp_duration_ms); cleanup_rfc_slot(slot); return; } @@ -1149,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..430ed84d23 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; 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/common/benchmark/thread_performance_benchmark.cc b/system/common/benchmark/thread_performance_benchmark.cc index 97f0c93b2d..3ae5033c69 100644 --- a/system/common/benchmark/thread_performance_benchmark.cc +++ b/system/common/benchmark/thread_performance_benchmark.cc @@ -30,9 +30,6 @@ #include "osi/include/fixed_queue.h" #include "osi/include/thread.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using ::benchmark::State; using bluetooth::common::MessageLoopThread; @@ -41,7 +38,7 @@ using bluetooth::common::MessageLoopThread; static std::atomic<int> g_counter = 0; static std::unique_ptr<std::promise<void>> g_counter_promise = nullptr; -void pthread_callback_batch(void* context) { +static void pthread_callback_batch(void* context) { auto queue = static_cast<fixed_queue_t*>(context); bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); @@ -51,15 +48,15 @@ void pthread_callback_batch(void* context) { } } -void callback_sequential(void* /* context */) { g_counter_promise->set_value(); } +static void callback_sequential(void* /* context */) { g_counter_promise->set_value(); } -void callback_sequential_queue(fixed_queue_t* queue, void* /* context */) { +static void callback_sequential_queue(fixed_queue_t* queue, void* /* context */) { bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter_promise->set_value(); } -void callback_batch(fixed_queue_t* queue, void* /* data */) { +static void callback_batch(fixed_queue_t* queue, void* /* data */) { bluetooth::log::assert_that(queue != nullptr, "assert failed: queue != nullptr"); fixed_queue_dequeue(queue); g_counter++; diff --git a/system/common/metric_id_allocator_unittest.cc b/system/common/metric_id_allocator_unittest.cc index 778163c62d..8172d57319 100644 --- a/system/common/metric_id_allocator_unittest.cc +++ b/system/common/metric_id_allocator_unittest.cc @@ -25,14 +25,11 @@ #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::MetricIdAllocator; -RawAddress kthAddress(uint32_t k) { +static RawAddress kthAddress(uint32_t k) { uint8_t array[6] = {0, 0, 0, 0, 0, 0}; for (int i = 5; i >= 2; i--) { array[i] = k % 256; @@ -42,7 +39,7 @@ RawAddress kthAddress(uint32_t k) { return addr; } -std::unordered_map<RawAddress, int> generateAddresses(const uint32_t num) { +static std::unordered_map<RawAddress, int> generateAddresses(const uint32_t num) { // generate first num of mac address -> id pairs // input may is always valid 256^6 = 2^48 > 2^32 std::unordered_map<RawAddress, int> device_map; diff --git a/system/common/metrics_linux.cc b/system/common/metrics_linux.cc index bbd411b11e..009d16878e 100644 --- a/system/common/metrics_linux.cc +++ b/system/common/metrics_linux.cc @@ -21,9 +21,6 @@ #include "common/metrics.h" #include "types/raw_address.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace bluetooth { namespace common { @@ -134,10 +131,11 @@ void LogLinkLayerConnectionEvent(const RawAddress* /* address */, uint32_t /* co uint16_t /* cmd_status */, uint16_t /* reason_code */) {} void LogManufacturerInfo(const RawAddress& /* address */, + android::bluetooth::AddressTypeEnum /* address_type */, android::bluetooth::DeviceInfoSrcEnum /* source_type */, const std::string& /* source_name */, - /* const */ std::string& /* manufacturer */, - const std::string& /* model */, const std::string& /* hardware_version */, + const std::string& /* manufacturer */, const std::string& /* model */, + const std::string& /* hardware_version */, const std::string& /* software_version */) {} void LogSdpAttribute(const RawAddress& /* address */, uint16_t /* protocol_uuid */, diff --git a/system/common/metrics_unittest.cc b/system/common/metrics_unittest.cc index 86e2ec7a13..4bbabb242a 100644 --- a/system/common/metrics_unittest.cc +++ b/system/common/metrics_unittest.cc @@ -32,9 +32,6 @@ #define BTM_COD_MAJOR_AUDIO_TEST 0x04 -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - namespace testing { using bluetooth::common::A2dpSessionMetrics; @@ -63,14 +60,15 @@ const size_t kMaxEventGenerationLimit = 5000; static void sleep_ms(int64_t t) { std::this_thread::sleep_for(std::chrono::milliseconds(t)); } -DeviceInfo* MakeDeviceInfo(int32_t device_class, DeviceInfo_DeviceType device_type) { +static DeviceInfo* MakeDeviceInfo(int32_t device_class, DeviceInfo_DeviceType device_type) { DeviceInfo* info = new DeviceInfo(); info->set_device_class(device_class); info->set_device_type(device_type); return info; } -PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, DeviceInfo* device_info) { +static PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, + DeviceInfo* device_info) { PairEvent* event = new PairEvent(); event->set_disconnect_reason(disconnect_reason); event->set_event_time_millis(timestamp_ms); @@ -80,8 +78,8 @@ PairEvent* MakePairEvent(int32_t disconnect_reason, int64_t timestamp_ms, Device return event; } -WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& requestor, - const std::string& name, int64_t timestamp_ms) { +static WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& requestor, + const std::string& name, int64_t timestamp_ms) { WakeEvent* event = new WakeEvent(); event->set_wake_event_type(event_type); event->set_requestor(requestor); @@ -90,9 +88,9 @@ WakeEvent* MakeWakeEvent(WakeEvent_WakeEventType event_type, const std::string& return event; } -ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& initiator, - ScanEvent_ScanTechnologyType tech_type, int32_t num_results, - int64_t timestamp_ms) { +static ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& initiator, + ScanEvent_ScanTechnologyType tech_type, int32_t num_results, + int64_t timestamp_ms) { ScanEvent* event = new ScanEvent(); event->set_scan_event_type(event_type); event->set_initiator(initiator); @@ -102,7 +100,8 @@ ScanEvent* MakeScanEvent(ScanEvent_ScanEventType event_type, const std::string& return event; } -A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, A2dpSourceCodec source_codec) { +static A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, + A2dpSourceCodec source_codec) { A2DPSession* session = new A2DPSession(); session->set_media_timer_min_millis(metrics.media_timer_min_ms); session->set_media_timer_max_millis(metrics.media_timer_max_ms); @@ -117,11 +116,10 @@ A2DPSession* MakeA2DPSession(const A2dpSessionMetrics& metrics, A2dpSourceCodec return session; } -BluetoothSession* MakeBluetoothSession(int64_t session_duration_sec, - BluetoothSession_ConnectionTechnologyType conn_type, - BluetoothSession_DisconnectReasonType disconnect_reason, - DeviceInfo* device_info, RFCommSession* rfcomm_session, - A2DPSession* a2dp_session) { +static BluetoothSession* MakeBluetoothSession( + int64_t session_duration_sec, BluetoothSession_ConnectionTechnologyType conn_type, + BluetoothSession_DisconnectReasonType disconnect_reason, DeviceInfo* device_info, + RFCommSession* rfcomm_session, A2DPSession* a2dp_session) { BluetoothSession* session = new BluetoothSession(); if (a2dp_session) { session->set_allocated_a2dp_session(a2dp_session); @@ -138,31 +136,7 @@ BluetoothSession* MakeBluetoothSession(int64_t session_duration_sec, return session; } -BluetoothLog* MakeBluetoothLog(std::vector<BluetoothSession*> bt_sessions, - std::vector<PairEvent*> pair_events, - std::vector<WakeEvent*> wake_events, - std::vector<ScanEvent*> scan_events) { - BluetoothLog* bt_log = new BluetoothLog(); - for (BluetoothSession* session : bt_sessions) { - bt_log->mutable_session()->AddAllocated(session); - } - bt_sessions.clear(); - for (PairEvent* event : pair_events) { - bt_log->mutable_pair_event()->AddAllocated(event); - } - pair_events.clear(); - for (WakeEvent* event : wake_events) { - bt_log->mutable_wake_event()->AddAllocated(event); - } - wake_events.clear(); - for (ScanEvent* event : scan_events) { - bt_log->mutable_scan_event()->AddAllocated(event); - } - scan_events.clear(); - return bt_log; -} - -void GenerateWakeEvents(size_t start, size_t end, std::vector<WakeEvent*>* wake_events) { +static void GenerateWakeEvents(size_t start, size_t end, std::vector<WakeEvent*>* wake_events) { for (size_t i = start; i < end; ++i) { wake_events->push_back( MakeWakeEvent(i % 2 == 0 ? WakeEvent_WakeEventType::WakeEvent_WakeEventType_ACQUIRED diff --git a/system/common/os_utils.cc b/system/common/os_utils.cc index a4bf8ea314..cdd645bf6f 100644 --- a/system/common/os_utils.cc +++ b/system/common/os_utils.cc @@ -14,14 +14,13 @@ * limitations under the License. */ +#include "common/os_utils.h" + #ifdef __ANDROID__ #include <private/android_filesystem_config.h> #include <unistd.h> #endif -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - bool is_bluetooth_uid() { #ifdef __ANDROID__ return getuid() == AID_BLUETOOTH; diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc index d6a0ea32ec..f875cd6aa6 100644 --- a/system/common/test/thread_performance_test.cc +++ b/system/common/test/thread_performance_test.cc @@ -31,9 +31,6 @@ #include "osi/include/fixed_queue.h" #include "osi/include/thread.h" -// TODO(b/369381361) Enfore -Wmissing-prototypes -#pragma GCC diagnostic ignored "-Wmissing-prototypes" - using bluetooth::common::MessageLoopThread; using namespace bluetooth; @@ -42,7 +39,7 @@ using namespace bluetooth; static int g_counter = 0; static std::unique_ptr<std::promise<void>> g_counter_promise = nullptr; -void callback_batch(fixed_queue_t* queue, void* /* data */) { +static void callback_batch(fixed_queue_t* queue, void* /* data */) { if (queue != nullptr) { fixed_queue_dequeue(queue); } diff --git a/system/gd/Android.bp b/system/gd/Android.bp index 1ed068af68..a57b83073d 100644 --- a/system/gd/Android.bp +++ b/system/gd/Android.bp @@ -37,44 +37,10 @@ cc_defaults { header_libs: ["jni_headers"], } -soong_config_module_type { - name: "mgmt_cc_defaults", - module_type: "cc_defaults", - config_namespace: "mgmt", - variables: ["vertical"], - properties: ["srcs"], -} - -soong_config_string_variable { - name: "vertical", - values: [ - "android_default", - "android_desktop", - ], -} - -mgmt_cc_defaults { - name: "mgmt_defaults", - soong_config_variables: { - vertical: { - android_desktop: { - srcs: [":BluetoothOsSources_mgmt_linux"], - }, - android_default: { - srcs: [":BluetoothOsSources_mgmt"], - }, - conditions_default: { - srcs: [":BluetoothOsSources_mgmt"], - }, - }, - }, -} - cc_defaults { name: "libbluetooth_gd_defaults", defaults: [ "gd_defaults", - "mgmt_defaults", ], host_supported: true, target: { @@ -127,6 +93,7 @@ cc_defaults { ], static_libs: [ "libexpresslog", + "libperfetto_client_experimental", "libstatslog_express", "libtextclassifier_hash_static", ], @@ -148,6 +115,7 @@ cc_defaults { "hal/snoop_logger.cc", "hal/snoop_logger_socket.cc", "hal/snoop_logger_socket_thread.cc", + "hal/snoop_logger_tracing.cc", "hal/syscall_wrapper_impl.cc", "hci/acl_manager.cc", "hci/acl_manager/acl_connection.cc", @@ -375,6 +343,7 @@ cc_test { "android.hardware.bluetooth@1.1", "android.system.suspend-V1-ndk", "android.system.suspend.control-V1-ndk", + "libperfetto_client_experimental", "libstatslog_bt", ], shared_libs: [ @@ -566,6 +535,7 @@ cc_defaults { cflags: [ "-DFUZZ_TARGET", "-DUSE_FAKE_TIMERS", + "-Wno-missing-prototypes", ], target: { android: { @@ -579,6 +549,9 @@ cc_defaults { "libstatslog_bt", "libutils", ], + static_libs: [ + "libperfetto_client_experimental", + ], }, }, } 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/hci_hal_android.cc b/system/gd/hal/hci_hal_android.cc index 51bc789cc8..20d9e29e3d 100644 --- a/system/gd/hal/hci_hal_android.cc +++ b/system/gd/hal/hci_hal_android.cc @@ -14,7 +14,9 @@ * limitations under the License. */ +#include <android_bluetooth_sysprop.h> #include <bluetooth/log.h> +#include <com_android_bluetooth_flags.h> #include <future> #include <mutex> @@ -25,7 +27,6 @@ #include "hal/hci_hal.h" #include "hal/link_clocker.h" #include "hal/snoop_logger.h" -#include "os/mgmt.h" namespace bluetooth::hal { @@ -159,7 +160,10 @@ public: } uint16_t getMsftOpcode() override { - return os::Management::getInstance().getVendorSpecificCode(MGMT_VS_OPCODE_MSFT); + if (com::android::bluetooth::flags::le_scan_msft_support()) { + return android::sysprop::bluetooth::Hci::msft_vendor_opcode().value_or(0); + } + return 0; } protected: diff --git a/system/gd/hal/ranging_hal_android.cc b/system/gd/hal/ranging_hal_android.cc index 1a82eb2062..033ed789f0 100644 --- a/system/gd/hal/ranging_hal_android.cc +++ b/system/gd/hal/ranging_hal_android.cc @@ -402,9 +402,8 @@ public: procedure_data.remote_subevent_data_, hci::CsRole::INITIATOR); channel_sounding_procedure_data.reflectorSubeventResultData = get_subevent_result_data(procedure_data.local_subevent_data_, hci::CsRole::REFLECTOR); - - session_it->second->GetSession()->writeProcedureData(channel_sounding_procedure_data); } + session_it->second->GetSession()->writeProcedureData(channel_sounding_procedure_data); } static std::vector<SubeventResultData> get_subevent_result_data( diff --git a/system/gd/hal/snoop_logger.cc b/system/gd/hal/snoop_logger.cc index 326ec3e82e..53f5509a0b 100644 --- a/system/gd/hal/snoop_logger.cc +++ b/system/gd/hal/snoop_logger.cc @@ -35,6 +35,9 @@ #include "common/circular_buffer.h" #include "common/strings.h" #include "hal/snoop_logger_common.h" +#ifdef __ANDROID__ +#include "hal/snoop_logger_tracing.h" +#endif // __ANDROID__ #include "hci/hci_packets.h" #include "os/files.h" #include "os/parameter_provider.h" @@ -1156,15 +1159,15 @@ void SnoopLogger::Capture(const HciPacket& immutable_packet, Direction direction HciPacket& packet = mutable_packet; ////////////////////////////////////////////////////////////////////////// - #ifdef __ANDROID__ + uint64_t timestamp_us = std::chrono::duration_cast<std::chrono::microseconds>( + std::chrono::system_clock::now().time_since_epoch()) + .count(); +#ifdef __ANDROID__ if (com::android::bluetooth::flags::snoop_logger_tracing()) { - LogTracePoint(packet, direction, type); + LogTracePoint(timestamp_us, packet, direction, type); } #endif // __ANDROID__ - uint64_t timestamp_us = std::chrono::duration_cast<std::chrono::microseconds>( - std::chrono::system_clock::now().time_since_epoch()) - .count(); std::bitset<32> flags = 0; switch (type) { case PacketType::CMD: @@ -1302,19 +1305,28 @@ 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; + } } } + +#ifdef __ANDROID__ + SnoopLoggerTracing::InitializePerfetto(); +#endif // __ANDROID__ + alarm_ = std::make_unique<os::RepeatingAlarm>(GetHandler()); alarm_->Schedule(common::Bind(&delete_old_btsnooz_files, snooz_log_path_, snooz_log_life_time_), snooz_log_delete_alarm_interval_); @@ -1427,7 +1439,8 @@ const ModuleFactory SnoopLogger::Factory = ModuleFactory([]() { }); #ifdef __ANDROID__ -void SnoopLogger::LogTracePoint(const HciPacket& packet, Direction direction, PacketType type) { +void SnoopLogger::LogTracePoint(uint64_t timestamp_us, const HciPacket& packet, Direction direction, + PacketType type) { switch (type) { case PacketType::EVT: { uint8_t evt_code = packet[0]; @@ -1473,6 +1486,8 @@ void SnoopLogger::LogTracePoint(const HciPacket& packet, Direction direction, Pa ATRACE_INSTANT_FOR_TRACK(LOG_TAG, message.c_str()); } break; } + + SnoopLoggerTracing::TracePacket(timestamp_us, packet, direction, type); } #endif // __ANDROID__ diff --git a/system/gd/hal/snoop_logger.h b/system/gd/hal/snoop_logger.h index fbf9696a53..c1546d6ed4 100644 --- a/system/gd/hal/snoop_logger.h +++ b/system/gd/hal/snoop_logger.h @@ -29,6 +29,7 @@ #include "hal/snoop_logger_socket_interface.h" #include "hal/snoop_logger_socket_thread.h" #include "hal/syscall_wrapper_impl.h" +#include "hci/hci_packets.h" #include "module.h" #include "os/repeating_alarm.h" @@ -320,7 +321,8 @@ protected: std::unique_ptr<SnoopLoggerSocketThread> snoop_logger_socket_thread_; #ifdef __ANDROID__ - void LogTracePoint(const HciPacket& packet, Direction direction, PacketType type); + void LogTracePoint(uint64_t timestamp_us, const HciPacket& packet, Direction direction, + PacketType type); #endif // __ANDROID__ private: 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/hal/snoop_logger_tracing.cc b/system/gd/hal/snoop_logger_tracing.cc new file mode 100644 index 0000000000..bb676136de --- /dev/null +++ b/system/gd/hal/snoop_logger_tracing.cc @@ -0,0 +1,207 @@ +/* + * 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. + */ + +#ifdef __ANDROID__ +#include "hal/snoop_logger_tracing.h" + +#include <bluetooth/log.h> +#include <perfetto/trace/android/bluetooth_trace.pbzero.h> +#include <perfetto/tracing.h> + +#include "hal/snoop_logger.h" +#include "hci/hci_packets.h" + +PERFETTO_DEFINE_DATA_SOURCE_STATIC_MEMBERS(bluetooth::hal::SnoopLoggerTracing); + +using perfetto::protos::pbzero::BluetoothTracePacketType; + +namespace bluetooth { +namespace hal { +namespace { + +// The Perfetto trace flush interval in microseconds. +constexpr uint64_t TRACE_FLUSH_INTERVAL_MICROS = 100000; + +static bool SkipTracePoint(const HciPacket& packet, SnoopLogger::PacketType type) { + if (type == SnoopLogger::PacketType::EVT) { + uint8_t evt_code = packet[0]; + + // Below set of commands does not provide further insight into bluetooth + // behavior. Skip these to save bluetooth tracing from becoming too large. + return evt_code == static_cast<uint8_t>(hci::EventCode::NUMBER_OF_COMPLETED_PACKETS) || + evt_code == static_cast<uint8_t>(hci::EventCode::COMMAND_COMPLETE) || + evt_code == static_cast<uint8_t>(hci::EventCode::COMMAND_STATUS); + } + + return false; +} +} // namespace + +BundleKey::BundleKey(const HciPacket& packet, SnoopLogger::Direction direction, + SnoopLogger::PacketType type) + : packet_type(type), direction(direction) { + switch (type) { + case SnoopLogger::PacketType::EVT: { + event_code = packet[0]; + + if (event_code == static_cast<uint8_t>(hci::EventCode::LE_META_EVENT) || + event_code == static_cast<uint8_t>(hci::EventCode::VENDOR_SPECIFIC)) { + subevent_code = packet[2]; + } + } break; + case SnoopLogger::PacketType::CMD: { + op_code = packet[0] | (packet[1] << 8); + } break; + case SnoopLogger::PacketType::ACL: + case SnoopLogger::PacketType::ISO: + case SnoopLogger::PacketType::SCO: { + handle = (packet[0] | (packet[1] << 8)) & 0x0fff; + } break; + } +} + +#define AGG_FIELDS(x) \ + (x).packet_type, (x).direction, (x).event_code, (x).subevent_code, (x).op_code, (x).handle + +bool BundleKey::operator==(const BundleKey& b) const { + return std::tie(AGG_FIELDS(*this)) == std::tie(AGG_FIELDS(b)); +} + +template <typename T, typename... Rest> +void HashCombine(std::size_t& seed, const T& val, const Rest&... rest) { + seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2); + (HashCombine(seed, rest), ...); +} + +std::size_t BundleHash::operator()(const BundleKey& a) const { + std::size_t seed = 0; + HashCombine(seed, AGG_FIELDS(a)); + return seed; +} + +#undef AGG_FIELDS + +void SnoopLoggerTracing::InitializePerfetto() { + perfetto::TracingInitArgs args; + args.backends |= perfetto::kSystemBackend; + + perfetto::Tracing::Initialize(args); + perfetto::DataSourceDescriptor dsd; + dsd.set_name("android.bluetooth_tracing"); + SnoopLoggerTracing::Register(dsd); +} + +BluetoothTracePacketType SnoopLoggerTracing::HciToTracePacketType( + SnoopLogger::PacketType hci_packet_type, SnoopLogger::Direction direction) { + BluetoothTracePacketType trace_packet_type; + switch (hci_packet_type) { + case SnoopLogger::PacketType::CMD: { + trace_packet_type = BluetoothTracePacketType::HCI_CMD; + } break; + case SnoopLogger::PacketType::EVT: { + trace_packet_type = BluetoothTracePacketType::HCI_EVT; + } break; + case SnoopLogger::PacketType::ACL: { + if (direction == SnoopLogger::INCOMING) { + trace_packet_type = BluetoothTracePacketType::HCI_ACL_RX; + } else { + trace_packet_type = BluetoothTracePacketType::HCI_ACL_TX; + } + } break; + case SnoopLogger::PacketType::ISO: { + if (direction == SnoopLogger::INCOMING) { + trace_packet_type = BluetoothTracePacketType::HCI_ISO_RX; + } else { + trace_packet_type = BluetoothTracePacketType::HCI_ISO_TX; + } + } break; + case SnoopLogger::PacketType::SCO: { + if (direction == SnoopLogger::INCOMING) { + trace_packet_type = BluetoothTracePacketType::HCI_SCO_RX; + } else { + trace_packet_type = BluetoothTracePacketType::HCI_SCO_TX; + } + } break; + } + return trace_packet_type; +} + +void SnoopLoggerTracing::TracePacket(uint64_t timestamp_us, const HciPacket& packet, + SnoopLogger::Direction direction, + SnoopLogger::PacketType type) { + if (SkipTracePoint(packet, type)) { + return; + } + + SnoopLoggerTracing::Trace([&](SnoopLoggerTracing::TraceContext ctx) { + perfetto::LockedHandle<SnoopLoggerTracing> handle = ctx.GetDataSourceLocked(); + if (handle.valid()) { + handle->Record(ctx, timestamp_us, packet, direction, type); + } + }); +} + +void SnoopLoggerTracing::Record(TraceContext& ctx, uint64_t timestamp_us, const HciPacket& packet, + SnoopLogger::Direction direction, SnoopLogger::PacketType type) { + BundleKey key(packet, direction, type); + + BundleDetails& bundle = bttrace_bundles_[key]; + bundle.count++; + bundle.total_length += packet.size(); + bundle.start_ts = std::min(bundle.start_ts, timestamp_us); + bundle.end_ts = std::max(bundle.end_ts, timestamp_us); + + if (last_flush_us_ + TRACE_FLUSH_INTERVAL_MICROS < timestamp_us) { + for (const auto& [key, details] : bttrace_bundles_) { + Write(ctx, key, details); + } + + bttrace_bundles_.clear(); + last_flush_us_ = timestamp_us; + } +} + +void SnoopLoggerTracing::Write(TraceContext& ctx, const BundleKey& key, + const BundleDetails& details) { + auto trace_pkt = ctx.NewTracePacket(); + trace_pkt->set_timestamp(perfetto::base::GetBootTimeNs().count()); + auto* bt_event = trace_pkt->set_bluetooth_trace_event(); + bt_event->set_packet_type(HciToTracePacketType(key.packet_type, key.direction)); + bt_event->set_count(details.count); + bt_event->set_length(details.total_length); + bt_event->set_duration((details.end_ts - details.start_ts) / 1000); + if (key.op_code.has_value()) { + bt_event->set_op_code(*key.op_code); + } + if (key.event_code.has_value()) { + bt_event->set_event_code(*key.event_code); + } + if (key.subevent_code.has_value()) { + bt_event->set_subevent_code(*key.subevent_code); + } + if (key.handle.has_value()) { + bt_event->set_connection_handle(*key.handle); + } +} + +void SnoopLoggerTracing::OnSetup(const SetupArgs&) {} +void SnoopLoggerTracing::OnStart(const StartArgs&) {} +void SnoopLoggerTracing::OnStop(const StopArgs&) {} +void SnoopLoggerTracing::OnFlush(const FlushArgs&) {} + +} // namespace hal +} // namespace bluetooth +#endif // __ANDROID__ diff --git a/system/gd/hal/snoop_logger_tracing.h b/system/gd/hal/snoop_logger_tracing.h new file mode 100644 index 0000000000..234ac2f123 --- /dev/null +++ b/system/gd/hal/snoop_logger_tracing.h @@ -0,0 +1,87 @@ +/* + * 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 +#ifdef __ANDROID__ + +#include <perfetto/trace/android/bluetooth_trace.pbzero.h> +#include <perfetto/tracing.h> + +#include "hal/snoop_logger.h" + +namespace bluetooth { +namespace hal { + +// BundleKey is used to group packets into bundles organized by direction, type, +// and eventual op_code or event_code +struct BundleKey { + explicit BundleKey(const HciPacket& packet, SnoopLogger::Direction direction, + SnoopLogger::PacketType type); + + SnoopLogger::PacketType packet_type; + SnoopLogger::Direction direction; + std::optional<uint16_t> op_code; + std::optional<uint8_t> event_code; + std::optional<uint8_t> subevent_code; + std::optional<uint16_t> handle; + + bool operator==(const BundleKey& b) const; +}; + +// BundleHash is used to hash BundleKeys. +struct BundleHash { + std::size_t operator()(const BundleKey& a) const; +}; + +// BundleDetails contains information about a bundle. +struct BundleDetails { + uint32_t count = 0; + uint32_t total_length = 0; + uint64_t start_ts = std::numeric_limits<uint64_t>::max(); + uint64_t end_ts = std::numeric_limits<uint64_t>::min(); +}; + +class SnoopLoggerTracing : public perfetto::DataSource<SnoopLoggerTracing> { +public: + static void InitializePerfetto(); + static void TracePacket(uint64_t timestamp_us, const HciPacket& packet, + SnoopLogger::Direction direction, SnoopLogger::PacketType type); + + void OnSetup(const SetupArgs&) override; + void OnStart(const StartArgs&) override; + void OnStop(const StopArgs&) override; + void OnFlush(const FlushArgs&) override; + +private: + static perfetto::protos::pbzero::BluetoothTracePacketType HciToTracePacketType( + SnoopLogger::PacketType hci_packet_type, SnoopLogger::Direction direction); + + // Records the packet into the internal buffers. + void Record(TraceContext& ctx, uint64_t timestamp_us, const HciPacket& packet, + SnoopLogger::Direction direction, SnoopLogger::PacketType type); + + // Writes all pending data from the internal buffer as a new trace packet. + void Write(TraceContext& ctx, const BundleKey& key, const BundleDetails& details); + + uint64_t last_flush_us_ = 0; + std::unordered_map<BundleKey, BundleDetails, BundleHash> bttrace_bundles_; +}; +} // namespace hal +} // namespace bluetooth + +PERFETTO_DECLARE_DATA_SOURCE_STATIC_MEMBERS(bluetooth::hal::SnoopLoggerTracing); + +#endif // __ANDROID__ 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/acl_manager/le_impl.h b/system/gd/hci/acl_manager/le_impl.h index 95e3db16ca..505aca6cb1 100644 --- a/system/gd/hci/acl_manager/le_impl.h +++ b/system/gd/hci/acl_manager/le_impl.h @@ -1110,6 +1110,9 @@ public: } else { remove_device_from_accept_list(address_with_type); } + // Temporary mapping the error code to PAGE_TIMEOUT + log_le_connection_completion(address_with_type.GetAddress(), ErrorCode::PAGE_TIMEOUT, + true /* is locally initiated */); le_client_handler_->Post(common::BindOnce( &LeConnectionCallbacks::OnLeConnectFail, common::Unretained(le_client_callbacks_), address_with_type, ErrorCode::CONNECTION_ACCEPT_TIMEOUT)); diff --git a/system/gd/hci/acl_manager_mock.h b/system/gd/hci/acl_manager_mock.h index b02a50c382..330b82bdac 100644 --- a/system/gd/hci/acl_manager_mock.h +++ b/system/gd/hci/acl_manager_mock.h @@ -75,6 +75,7 @@ public: MOCK_METHOD(void, CreateLeConnection, (AddressWithType address_with_type, bool is_direct), (override)); MOCK_METHOD(void, CancelConnect, (Address address), (override)); + MOCK_METHOD(void, CancelLeConnect, (AddressWithType address_with_type), (override)); MOCK_METHOD(void, SetPrivacyPolicyForInitiatorAddress, (LeAddressManager::AddressPolicy address_policy, AddressWithType fixed_address, std::chrono::milliseconds minimum_rotation_time, 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/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc index d4d87efa10..885f0b3bf1 100644 --- a/system/gd/hci/distance_measurement_manager.cc +++ b/system/gd/hci/distance_measurement_manager.cc @@ -2175,7 +2175,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { } log::verbose("step_data: {}", tone_data_view.ToString()); procedure_data.measured_freq_offset.push_back(tone_data_view.measured_freq_offset_); - if (is_hal_v2()) { + if (is_hal_v2() && local_subevent_data) { local_subevent_data->step_data_.emplace_back(step_channel, mode, hal::Mode0Data(tone_data_view)); } @@ -2188,7 +2188,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback { continue; } log::verbose("step_data: {}", tone_data_view.ToString()); - if (is_hal_v2()) { + if (is_hal_v2() && local_subevent_data) { local_subevent_data->step_data_.emplace_back(step_channel, mode, hal::Mode0Data(tone_data_view)); } 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/metrics/bluetooth_event.cc b/system/gd/metrics/bluetooth_event.cc index df8387fb7d..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 { @@ -31,53 +29,59 @@ using android::bluetooth::State; using hci::ErrorCode; State MapErrorCodeToState(ErrorCode reason) { - // TODO - map the error codes to the state enum variants. switch (reason) { case ErrorCode::SUCCESS: return State::SUCCESS; - // Timeout related errors + case ErrorCode::UNKNOWN_HCI_COMMAND: + return State::UNKNOWN_HCI_COMMAND; + case ErrorCode::UNKNOWN_CONNECTION: + return State::NO_CONNECTION; + case ErrorCode::HARDWARE_FAILURE: + return State::HARDWARE_FAILURE; case ErrorCode::PAGE_TIMEOUT: return State::PAGE_TIMEOUT; - case ErrorCode::CONNECTION_TIMEOUT: - return State::CONNECTION_TIMEOUT; - case ErrorCode::CONNECTION_ACCEPT_TIMEOUT: - return State::CONNECTION_ACCEPT_TIMEOUT; - case ErrorCode::TRANSACTION_RESPONSE_TIMEOUT: - return State::TRANSACTION_RESPONSE_TIMEOUT; case ErrorCode::AUTHENTICATION_FAILURE: return State::AUTH_FAILURE; - case ErrorCode::REMOTE_USER_TERMINATED_CONNECTION: - case ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES: - case ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF: - return State::REMOTE_USER_TERMINATED_CONNECTION; - case ErrorCode::CONNECTION_ALREADY_EXISTS: - return State::ALREADY_CONNECTED; - case ErrorCode::REPEATED_ATTEMPTS: - return State::REPEATED_ATTEMPTS; case ErrorCode::PIN_OR_KEY_MISSING: return State::KEY_MISSING; - case ErrorCode::PAIRING_NOT_ALLOWED: - return State::PAIRING_NOT_ALLOWED; - case ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES: - return State::RESOURCES_EXCEEDED; - case ErrorCode::HARDWARE_FAILURE: - return State::HARDWARE_FAILURE; case ErrorCode::MEMORY_CAPACITY_EXCEEDED: return State::MEMORY_CAPACITY_EXCEEDED; + case ErrorCode::CONNECTION_TIMEOUT: + return State::CONNECTION_TIMEOUT; case ErrorCode::CONNECTION_LIMIT_EXCEEDED: return State::CONNECTION_LIMIT_EXCEEDED; case ErrorCode::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED: return State::SYNCHRONOUS_CONNECTION_LIMIT_EXCEEDED; + case ErrorCode::CONNECTION_ALREADY_EXISTS: + return State::ALREADY_CONNECTED; + case ErrorCode::COMMAND_DISALLOWED: + return State::COMMAND_DISALLOWED; + case ErrorCode::CONNECTION_REJECTED_LIMITED_RESOURCES: + return State::RESOURCES_EXCEEDED; case ErrorCode::CONNECTION_REJECTED_SECURITY_REASONS: return State::CONNECTION_REJECTED_SECURITY_REASONS; case ErrorCode::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR: return State::CONNECTION_REJECTED_UNACCEPTABLE_BD_ADDR; + case ErrorCode::CONNECTION_ACCEPT_TIMEOUT: + return State::CONNECTION_ACCEPT_TIMEOUT; case ErrorCode::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE: return State::UNSUPPORTED_FEATURE_OR_PARAMETER_VALUE; case ErrorCode::INVALID_HCI_COMMAND_PARAMETERS: return State::INVALID_HCI_COMMAND_PARAMETERS; + case ErrorCode::REMOTE_USER_TERMINATED_CONNECTION: + return State::REMOTE_USER_TERMINATED_CONNECTION; + case ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES: + return State::REMOTE_DEVICE_TERMINATED_CONNECTION_LOW_RESOURCES; + case ErrorCode::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF: + return State::REMOTE_DEVICE_TERMINATED_CONNECTION_POWER_OFF; case ErrorCode::CONNECTION_TERMINATED_BY_LOCAL_HOST: return State::CONNECTION_TERMINATED_BY_LOCAL_HOST; + case ErrorCode::REPEATED_ATTEMPTS: + return State::REPEATED_ATTEMPTS; + case ErrorCode::PAIRING_NOT_ALLOWED: + return State::PAIRING_NOT_ALLOWED; + case ErrorCode::UNKNOWN_LMP_PDU: + return State::UNKNOWN_LMP_PDU; case ErrorCode::UNSUPPORTED_REMOTE_OR_LMP_FEATURE: return State::UNSUPPORTED_REMOTE_OR_LMP_FEATURE; case ErrorCode::SCO_OFFSET_REJECTED: @@ -94,6 +98,8 @@ State MapErrorCodeToState(ErrorCode reason) { return State::UNSUPPORTED_LMP_OR_LL_PARAMETER; case ErrorCode::ROLE_CHANGE_NOT_ALLOWED: return State::ROLE_CHANGE_NOT_ALLOWED; + case ErrorCode::TRANSACTION_RESPONSE_TIMEOUT: + return State::TRANSACTION_RESPONSE_TIMEOUT; case ErrorCode::LINK_LAYER_COLLISION: return State::LINK_LAYER_COLLISION; case ErrorCode::LMP_PDU_NOT_ALLOWED: @@ -161,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; @@ -252,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; @@ -309,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/Android.bp b/system/gd/os/Android.bp deleted file mode 100644 index 92e8533a00..0000000000 --- a/system/gd/os/Android.bp +++ /dev/null @@ -1,22 +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"], -} - -filegroup { - name: "BluetoothOsSources_mgmt", - srcs: [ - "mgmt_stub.cc", - ], -} - -filegroup { - name: "BluetoothOsSources_mgmt_linux", - srcs: [ - "linux_generic/mgmt.cc", - ], -} diff --git a/system/gd/os/android/metrics.cc b/system/gd/os/android/metrics.cc index 1a899062cd..ddb9d826f1 100644 --- a/system/gd/os/android/metrics.cc +++ b/system/gd/os/android/metrics.cc @@ -30,6 +30,7 @@ #include "common/strings.h" #include "hardware/bt_av.h" #include "hci/hci_packets.h" +#include "main/shim/helpers.h" namespace std { template <> @@ -51,6 +52,20 @@ template <> struct formatter<android::bluetooth::EventType> : enum_formatter<android::bluetooth::EventType> {}; template <> struct formatter<android::bluetooth::State> : enum_formatter<android::bluetooth::State> {}; +template <> +struct formatter<android::bluetooth::rfcomm::PortResult> + : enum_formatter<android::bluetooth::rfcomm::PortResult> {}; +template <> +struct formatter<android::bluetooth::rfcomm::RfcommPortState> + : enum_formatter<android::bluetooth::rfcomm::RfcommPortState> {}; +template <> +struct formatter<android::bluetooth::rfcomm::RfcommPortEvent> + : enum_formatter<android::bluetooth::rfcomm::RfcommPortEvent> {}; +template <> +struct formatter<android::bluetooth::rfcomm::SocketConnectionSecurity> + : enum_formatter<android::bluetooth::rfcomm::SocketConnectionSecurity> {}; +template <> +struct formatter<android::bluetooth::BtaStatus> : enum_formatter<android::bluetooth::BtaStatus> {}; } // namespace std namespace bluetooth { @@ -478,5 +493,28 @@ void LogMetricBluetoothEvent(const Address& address, android::bluetooth::EventTy } } +void LogMetricRfcommConnectionAtClose(const Address& address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, + android::bluetooth::BtaStatus sdp_status, bool is_server, + bool sdp_initiated, int32_t sdp_duration_ms) { + int metric_id = 0; + if (address.IsEmpty()) { + log::warn("Failed to upload - Address is empty"); + return; + } + metric_id = MetricIdManager::GetInstance().AllocateId(address); + int ret = stats_write(BLUETOOTH_RFCOMM_CONNECTION_REPORTED_AT_CLOSE, close_reason, security, + last_event, previous_state, open_duration_ms, uid, metric_id, sdp_status, + is_server, sdp_initiated, sdp_duration_ms); + if (ret < 0) { + log::warn("Failed to log RFCOMM Connection metric for uid {}, close reason {}", uid, + close_reason); + } +} + } // namespace os } // namespace bluetooth diff --git a/system/gd/os/chromeos/metrics.cc b/system/gd/os/chromeos/metrics.cc index c5b33a4fce..70258d335a 100644 --- a/system/gd/os/chromeos/metrics.cc +++ b/system/gd/os/chromeos/metrics.cc @@ -203,5 +203,15 @@ void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_op void LogMetricBluetoothEvent(const Address& address, android::bluetooth::EventType event_type, android::bluetooth::State state) {} + +void LogMetricRfcommConnectionAtClose( + const Address& /* raw_address */, android::bluetooth::rfcomm::PortResult /* close_reason */, + android::bluetooth::rfcomm::SocketConnectionSecurity /* security */, + android::bluetooth::rfcomm::RfcommPortEvent /* last_event */, + android::bluetooth::rfcomm::RfcommPortState /* previous_state */, + int32_t /* open_duration_ms */, int32_t /* uid */, + android::bluetooth::BtaStatus /* sdp_status */, bool /* is_server */, + bool /* sdp_initiated */, int32_t /* sdp_duration_ms */) {} + } // namespace os } // namespace bluetooth diff --git a/system/gd/os/host/metrics.cc b/system/gd/os/host/metrics.cc index a019033348..61734e6a81 100644 --- a/system/gd/os/host/metrics.cc +++ b/system/gd/os/host/metrics.cc @@ -124,5 +124,15 @@ void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_op void LogMetricBluetoothEvent(const Address& /* address */, android::bluetooth::EventType /* event type */, android::bluetooth::State /* state */) {} + +void LogMetricRfcommConnectionAtClose( + const Address& /* raw_address */, android::bluetooth::rfcomm::PortResult /* close_reason */, + android::bluetooth::rfcomm::SocketConnectionSecurity /* security */, + android::bluetooth::rfcomm::RfcommPortEvent /* last_event */, + android::bluetooth::rfcomm::RfcommPortState /* previous_state */, + int32_t /* open_duration_ms */, int32_t /* uid */, + android::bluetooth::BtaStatus /* sdp_status */, bool /* is_server */, + bool /* sdp_initiated */, int32_t /* sdp_duration_ms */) {} + } // namespace os } // namespace bluetooth diff --git a/system/gd/os/linux/metrics.cc b/system/gd/os/linux/metrics.cc index c5e38493da..45fca1f4ee 100644 --- a/system/gd/os/linux/metrics.cc +++ b/system/gd/os/linux/metrics.cc @@ -108,6 +108,15 @@ void LogMetricBluetoothCodePathCounterMetrics(int32_t key, int64_t count) {} void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions /* session_options */) {} +void LogMetricRfcommConnectionAtClose(const Address& raw_address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, + android::bluetooth::BtaStatus sdp_status, bool is_server, + bool sdp_initiated, int32_t sdp_duration_ms) {} + void LogMetricBluetoothEvent(const Address& address, android::bluetooth::EventType event_type, android::bluetooth::State state) {} } // namespace os 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/os/metrics.h b/system/gd/os/metrics.h index 7d89483754..9f372b25af 100644 --- a/system/gd/os/metrics.h +++ b/system/gd/os/metrics.h @@ -21,10 +21,12 @@ #include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h> #include <frameworks/proto_logging/stats/enums/bluetooth/hci/enums.pb.h> #include <frameworks/proto_logging/stats/enums/bluetooth/le/enums.pb.h> +#include <frameworks/proto_logging/stats/enums/bluetooth/rfcomm/enums.pb.h> #include <vector> #include "hci/address.h" +#include "types/raw_address.h" namespace bluetooth { @@ -346,6 +348,31 @@ void LogMetricBluetoothLEConnection(os::LEConnectionSessionOptions session_optio */ void LogMetricBluetoothEvent(const hci::Address& address, android::bluetooth::EventType event_type, android::bluetooth::State state); + +/** + * Logs an RFCOMM connection when an RFCOMM port closes + * + * @param address address of the peer device + * @param close_reason reason that the port was closed + * @param security security level of the connection + * @param last_event event processed prior to "CLOSED" + * @param previous_state state prior to "CLOSED" + * @param open_duration_ms that the socket was opened, 0 if connection failed + * @param uid UID of the app that called connect + * @param sdp_status status code for sdp + * @param is_server true if device is server + * @param sdp_initiated true if sdp started for thie connection + * @param sdp_duration_ms duration of sdp, 0 if it didn't happen + */ +void LogMetricRfcommConnectionAtClose(const hci::Address& address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, + android::bluetooth::BtaStatus sdp_status, bool is_server, + bool sdp_initiated, int32_t sdp_duration_ms); + } // namespace os // } // namespace bluetooth diff --git a/system/gd/rust/linux/stack/src/battery_service.rs b/system/gd/rust/linux/stack/src/battery_service.rs index 013b941260..a05b739dd9 100644 --- a/system/gd/rust/linux/stack/src/battery_service.rs +++ b/system/gd/rust/linux/stack/src/battery_service.rs @@ -3,12 +3,11 @@ use crate::battery_provider_manager::{ BatteryProviderManager, IBatteryProviderCallback, IBatteryProviderManager, }; use crate::bluetooth_gatt::{ - BluetoothGatt, BluetoothGattService, IBluetoothGatt, IBluetoothGattCallback, + BluetoothGatt, BluetoothGattCharacteristic, BluetoothGattService, IBluetoothGatt, + IBluetoothGattCallback, }; use crate::callbacks::Callbacks; -use crate::Message; -use crate::RPCProxy; -use crate::{uuid, APIMessage, BluetoothAPI}; +use crate::{uuid, APIMessage, BluetoothAPI, Message, RPCProxy}; use bt_topshim::btif::{BtTransport, DisplayAddress, RawAddress, Uuid}; use bt_topshim::profiles::gatt::{GattStatus, LePhy}; use log::{debug, info}; @@ -170,8 +169,9 @@ impl BatteryService { self.drop_device(addr); return; } - let handle = match self.get_battery_level_handle(addr, services) { - Ok(battery_level_handle) => battery_level_handle, + + let battery_level_char = match self.get_battery_level_char(addr, services) { + Ok(battery_level_char) => battery_level_char, Err(status) => { if let Some(BatteryServiceStatus::BatteryServiceNotSupported) = status { self.callbacks.for_all_callbacks(|callback| { @@ -182,7 +182,7 @@ impl BatteryService { }); } info!( - "BAS: Failed to get handle from {}: status={:?}", + "BAS: Failed to get battery level char from {}: status={:?}", DisplayAddress(&addr), status ); @@ -190,7 +190,7 @@ impl BatteryService { return; } }; - info!("BAS: Found handle from {}", DisplayAddress(&addr)); + info!("BAS: Found battery level char from {}", DisplayAddress(&addr)); let client_id = match self.client_id { Some(id) => id, None => { @@ -198,8 +198,44 @@ impl BatteryService { return; } }; + + let handle = battery_level_char.instance_id; self.handles.insert(addr, handle); + + // Try to register the battery level characteristic notification if the + // remote server supports the CCCD. + let cccd_uuid = Uuid::from_string(uuid::CCCD_UUID).unwrap(); + match battery_level_char + .descriptors + .iter() + .find(|descriptor| descriptor.uuid == cccd_uuid) + { + Some(battery_level_char_cccd) => { + debug!( + "BAS: Found CCCD in battery level char from {}", + DisplayAddress(&addr) + ); + + // Configure the char to send notification. + let cccd_value = vec![1, 0]; + self.gatt.lock().unwrap().write_descriptor( + client_id, + addr, + battery_level_char_cccd.instance_id, + 0, // authentication none + cccd_value, + ); + } + None => { + debug!( + "BAS: Device {} has no BatteryLevel characteristic CCCD", + DisplayAddress(&addr) + ); + } + }; + self.gatt.lock().unwrap().register_for_notification(client_id, addr, handle, true); + if self.battery_sets.get(&addr).is_none() { self.gatt.lock().unwrap().read_characteristic(client_id, addr, handle, 0); } @@ -239,6 +275,7 @@ impl BatteryService { let level: Vec<_> = value.iter().cloned().chain(iter::repeat(0_u8)).take(4).collect(); let level = u32::from_le_bytes(level.try_into().unwrap()); debug!("BAS received battery level for {}: {}", DisplayAddress(remote_address), level); + let battery_set = self.battery_sets.entry(*remote_address).or_insert_with(|| { BatterySet::new( *remote_address, @@ -247,6 +284,11 @@ impl BatteryService { vec![Battery { percentage: level, variant: "".to_string() }], ) }); + + // or_insert_with does not update the value in the hash map if the key already exists. + // Update the battery level if the battery set already exists. + battery_set.batteries[0].percentage = level; + self.battery_provider_manager .lock() .unwrap() @@ -288,11 +330,11 @@ impl BatteryService { } } - fn get_battery_level_handle( + fn get_battery_level_char( &mut self, remote_address: RawAddress, services: Vec<BluetoothGattService>, - ) -> Result<i32, Option<BatteryServiceStatus>> { + ) -> Result<BluetoothGattCharacteristic, Option<BatteryServiceStatus>> { let (bas_uuid, battery_level_uuid) = match (Uuid::from_string(uuid::BAS), Uuid::from_string(CHARACTERISTIC_BATTERY_LEVEL)) { (Some(bas_uuid), Some(battery_level_uuid)) => (bas_uuid, battery_level_uuid), @@ -305,21 +347,20 @@ impl BatteryService { Some(bas) => bas, None => return Err(Some(BatteryServiceStatus::BatteryServiceNotSupported)), }; - let battery_level = match bas + match bas .characteristics .iter() .find(|characteristic| characteristic.uuid == battery_level_uuid) { - Some(battery_level) => battery_level, + Some(battery_level) => Ok(battery_level.clone()), None => { debug!( "Device {} has no BatteryLevel characteristic", DisplayAddress(&remote_address) ); - return Err(None); + Err(None) } - }; - Ok(battery_level.instance_id) + } } /// Perform an explicit read on all devices BAS knows about. diff --git a/system/gd/rust/linux/stack/src/uuid.rs b/system/gd/rust/linux/stack/src/uuid.rs index b7401a7e76..259c16e0df 100644 --- a/system/gd/rust/linux/stack/src/uuid.rs +++ b/system/gd/rust/linux/stack/src/uuid.rs @@ -40,6 +40,9 @@ pub const MEDIA_CONTROL: &str = "00001848-0000-1000-8000-00805F9B34FB"; pub const COORDINATED_SET: &str = "00001846-0000-1000-8000-00805F9B34FB"; pub const BASE_UUID: &str = "00000000-0000-1000-8000-00805F9B34FB"; +// List of descriptor uuids +pub const CCCD_UUID: &str = "00002902-0000-1000-8000-00805f9b34fb"; + /// List of profiles that with known uuids. /// Append new profiles to the end of the enum. Do not insert it in the middle. #[derive(Clone, Debug, Hash, PartialEq, PartialOrd, Eq, Ord, FromPrimitive, ToPrimitive, Copy)] diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h index 94c3762596..b3bda8ee85 100644 --- a/system/include/hardware/bt_le_audio.h +++ b/system/include/hardware/bt_le_audio.h @@ -78,6 +78,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 +175,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; diff --git a/system/main/Android.bp b/system/main/Android.bp index 4ada9e0cf7..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", @@ -218,6 +217,7 @@ cc_test { static_libs: [ "android.system.suspend-V1-ndk", "android.system.suspend.control-V1-ndk", + "libperfetto_client_experimental", ], shared_libs: [ "libstatssocket", 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/acl_api.cc b/system/main/shim/acl_api.cc index 1ad552e069..56e63e1977 100644 --- a/system/main/shim/acl_api.cc +++ b/system/main/shim/acl_api.cc @@ -60,19 +60,6 @@ void bluetooth::shim::ACL_CancelClassicConnection(const RawAddress& raw_address) Stack::GetInstance()->GetAcl()->CancelClassicConnection(address); } -void bluetooth::shim::ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, - bool is_direct) { - BTM_LogHistory(kBtmLogTag, legacy_address_with_type, "Allow connection from", "Le"); - bluetooth::shim::GetAclManager()->CreateLeConnection( - ToAddressWithTypeFromLegacy(legacy_address_with_type), is_direct); -} - -void bluetooth::shim::ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type) { - BTM_LogHistory(kBtmLogTag, legacy_address_with_type, "Ignore connection from", "Le"); - bluetooth::shim::GetAclManager()->CancelLeConnect( - ToAddressWithTypeFromLegacy(legacy_address_with_type)); -} - void bluetooth::shim::ACL_WriteData(uint16_t handle, BT_HDR* p_buf) { std::unique_ptr<bluetooth::packet::RawBuilder> packet = MakeUniquePacket(p_buf->data + p_buf->offset + HCI_DATA_PREAMBLE_SIZE, @@ -128,10 +115,6 @@ void bluetooth::shim::ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STAT void bluetooth::shim::ACL_Shutdown() { Stack::GetInstance()->GetAcl()->Shutdown(); } -void bluetooth::shim::ACL_IgnoreAllLeConnections() { - return Stack::GetInstance()->GetAcl()->ClearFilterAcceptList(); -} - void bluetooth::shim::ACL_ReadConnectionAddress(uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, bool ota_address) { std::promise<bluetooth::hci::AddressWithType> promise; diff --git a/system/main/shim/acl_api.h b/system/main/shim/acl_api.h index a07c42cbb8..6b28988ca6 100644 --- a/system/main/shim/acl_api.h +++ b/system/main/shim/acl_api.h @@ -29,15 +29,12 @@ namespace shim { void ACL_CreateClassicConnection(const RawAddress& raw_address); void ACL_CancelClassicConnection(const RawAddress& raw_address); -void ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct); -void ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type); void ACL_Disconnect(uint16_t handle, bool is_classic, tHCI_STATUS reason, std::string comment); void ACL_WriteData(uint16_t handle, BT_HDR* p_buf); void ACL_Flush(uint16_t handle); void ACL_ConfigureLePrivacy(bool is_le_privacy_enabled); void ACL_Shutdown(); -void ACL_IgnoreAllLeConnections(); void ACL_ReadConnectionAddress(uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE* p_addr_type, bool ota_address); 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 65491b2468..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 { @@ -182,6 +184,31 @@ void LogMetricLeConnectionLifecycle(hci::Address address, bool is_connect, bool } } +void LogMetricLeConnectionCompletion(hci::Address address, hci::ErrorCode reason, + bool is_locally_initiated) { + bluetooth::metrics::LogLeAclCompletionEvent(address, reason, is_locally_initiated); +} + +void LogMetricRfcommConnectionAtClose(const RawAddress& raw_address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, + android::bluetooth::BtaStatus sdp_status, bool is_server, + bool sdp_initiated, int32_t sdp_duration_ms) { + Address address = bluetooth::ToGdAddress(raw_address); + bluetooth::os::LogMetricRfcommConnectionAtClose(address, close_reason, security, last_event, + previous_state, open_duration_ms, uid, sdp_status, + is_server, sdp_initiated, sdp_duration_ms); +} + +void LogMetricLeConnectionRejected(hci::Address address) { + bluetooth::os::LogMetricBluetoothEvent(address, + android::bluetooth::EventType::LE_CONNECTION_REJECTED, + android::bluetooth::State::ATTEMPT_IN_PROGRESS); +} + bool CountCounterMetrics(int32_t key, int64_t count) { auto counter_metrics = GetCounterMetrics(); if (counter_metrics == nullptr) { @@ -190,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 c0165b04b6..43d89e5469 100644 --- a/system/main/shim/metrics_api.h +++ b/system/main/shim/metrics_api.h @@ -281,7 +281,78 @@ void LogMetricLeDeviceInAcceptList(hci::Address address, bool is_connect); */ void LogMetricLeConnectionLifecycle(hci::Address address, bool is_connect, bool is_direct); +/** + * Logs LE Connection Events + * @param address Address of the device + * @param reason the reason/status of the connection event + * @param is_locally_initiated the direction in which the connection request was + * sent + */ +void LogMetricLeConnectionCompletion(hci::Address address, hci::ErrorCode reason, + bool is_locally_initiated); +/** + * Logs an RFCOMM connection when an RFCOMM port closes + * + * @param address address of peer device + * @param close_reason reason that the port was closed + * @param security security level of the connection + * @param second_previous_state two states prior to "CLOSED" + * @param previous_state state prior to "CLOSED" + * @param duration_ms that the socket was opened, 0 if connection failed + * @param uid UID of the app that called connect + */ +void LogMetricRfcommConnectionAtClose(const RawAddress& address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, + android::bluetooth::BtaStatus sdp_status, bool is_server, + bool sdp_initiated, int32_t sdp_duration_ms); +/*Log LE Connection Rejected Event + * @param address Address of the device + */ +void LogMetricLeConnectionRejected(hci::Address address); + bool CountCounterMetrics(int32_t key, int64_t count); +/** + * Logs the AG version in a HFP session + * @param address of a device + * @param version AG HFP version + */ +void LogMetricHfpAgVersion(hci::Address address, uint16_t version); + +/** + * Logs the HF version in a HFP session + * @param address of a device + * @param version HF HFP Version + */ +void LogMetricHfpHfVersion(hci::Address address, uint16_t version); + +/** + * Logs a RFCOMM channel failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommChannelFail(hci::Address address); + +/** + * Logs a RFCOMM collision failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommCollisionFail(hci::Address address); + +/** + * Logs a RFCOMM AG open failure in a HFP session + * @param address of a device + */ +void LogMetricHfpRfcommAgOpenFail(hci::Address address); + +/** + * Logs a SLC failure in a HFP Session + * @param address of a device + */ +void LogMetricHfpSlcFail(hci::Address address); + } // namespace shim } // namespace bluetooth diff --git a/system/pdl/BUILD.gn b/system/pdl/BUILD.gn index bf8885a5ea..c79976fdd7 100644 --- a/system/pdl/BUILD.gn +++ b/system/pdl/BUILD.gn @@ -15,6 +15,15 @@ import("//bt/system/gd/packet/parser/packetgen.gni") +source_set("BluetoothHciPacketSources") { + sources = [ + "hci/address.cc", + "hci/class_of_device.cc", + ] + + include_dirs = [ "//bt/system/gd" ] +} + packetgen_headers("BluetoothGeneratedPackets_h") { sources = [ "hci/hci_packets.pdl", diff --git a/system/rust/src/core/ffi.rs b/system/rust/src/core/ffi.rs index 506bfd0bad..c67e8b5514 100644 --- a/system/rust/src/core/ffi.rs +++ b/system/rust/src/core/ffi.rs @@ -15,7 +15,7 @@ // TODO(b/290018030): Remove this and add proper safety comments. #![allow(clippy::undocumented_unsafe_blocks)] -use crate::core::{start, stop}; +use crate::core::{set_disabled_in_test, start, stop}; use cxx::{type_id, ExternType}; pub use inner::*; @@ -83,5 +83,7 @@ mod inner { ); fn stop(); + + fn set_disabled_in_test(); } } diff --git a/system/rust/src/core/ffi/module.cc b/system/rust/src/core/ffi/module.cc index edd2b13b58..deaeb16cb6 100644 --- a/system/rust/src/core/ffi/module.cc +++ b/system/rust/src/core/ffi/module.cc @@ -60,6 +60,7 @@ future_t* Start() { bluetooth::log::error( "GATT profile not started, so we cannot start the Rust loop - this " "happens only in tests."); + bluetooth::rust_shim::set_disabled_in_test(); bluetooth::rust_shim::FutureReady(*fut); return fut; } diff --git a/system/rust/src/core/mod.rs b/system/rust/src/core/mod.rs index ebcd65c353..51b913ec2b 100644 --- a/system/rust/src/core/mod.rs +++ b/system/rust/src/core/mod.rs @@ -27,3 +27,7 @@ fn start( fn stop() { RustModuleRunner::stop(); } + +fn set_disabled_in_test() { + RustModuleRunner::set_disabled_in_test(); +} diff --git a/system/rust/src/lib.rs b/system/rust/src/lib.rs index f88e635911..d68e3624d4 100644 --- a/system/rust/src/lib.rs +++ b/system/rust/src/lib.rs @@ -40,7 +40,11 @@ enum RustModuleRunner { NotRunning, /// Main event loop is running and messages can be processed. Use [`RustModuleRunner::send`] to /// queue a callback to be sent. - Running { thread: JoinHandle<()>, tx: mpsc::UnboundedSender<BoxedMainThreadCallback> }, + Running { + thread: JoinHandle<()>, + tx: mpsc::UnboundedSender<BoxedMainThreadCallback>, + }, + DisabledInTest, } /// The ModuleViews lets us access all publicly accessible Rust modules from @@ -96,6 +100,15 @@ impl RustModuleRunner { // Wait for the thread to terminate. let _ = thread.join(); } + Self::DisabledInTest => {} + } + } + + pub fn set_disabled_in_test() { + let mut runner = GLOBAL_MODULE_RUNNER.lock().unwrap(); + match &*runner { + RustModuleRunner::NotRunning => *runner = Self::DisabledInTest, + _ => warn!("Unexpected state {:?}", &*runner), } } @@ -151,8 +164,8 @@ impl RustModuleRunner { #[allow(dead_code)] fn send(&self, f: BoxedMainThreadCallback) -> Result<(), (String, BoxedMainThreadCallback)> { match self { - Self::NotRunning => Err(("Not running".to_string(), f)), Self::Running { tx, .. } => tx.send(f).map_err(|e| ("Failed to send".to_string(), e.0)), + _ => Err((format!("Bad state {self:?}"), f)), } } } diff --git a/system/stack/Android.bp b/system/stack/Android.bp index b7ae03bb4b..fe027336d5 100644 --- a/system/stack/Android.bp +++ b/system/stack/Android.bp @@ -294,6 +294,7 @@ cc_library_static { "rfcomm/port_rfc.cc", "rfcomm/port_utils.cc", "rfcomm/rfc_l2cap_if.cc", + "rfcomm/rfc_metrics.cc", "rfcomm/rfc_mx_fsm.cc", "rfcomm/rfc_port_fsm.cc", "rfcomm/rfc_port_if.cc", @@ -467,7 +468,6 @@ cc_fuzz { ":TestMockDevice", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackArbiter", @@ -519,7 +519,6 @@ cc_fuzz { ":TestMockDevice", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackArbiter", @@ -826,6 +825,7 @@ cc_test { "android.hardware.bluetooth@1.0", "android.hardware.bluetooth@1.1", "libexpresslog", + "libperfetto_client_experimental", "libstatslog_express", "libtextclassifier_hash_static", ], @@ -868,6 +868,7 @@ cc_test { ":TestMockStackBtm", ":TestMockStackL2capInterface", ":TestMockStackMetrics", + ":TestMockStackRfcommMetrics", "rfcomm/port_api.cc", "rfcomm/port_rfc.cc", "rfcomm/port_utils.cc", @@ -919,6 +920,9 @@ cc_test { shared_libs: [ "libstatssocket", ], + static_libs: [ + "libperfetto_client_experimental", + ], }, }, sanitize: { @@ -1055,28 +1059,61 @@ cc_test { ], srcs: [ ":TestCommonMainHandler", - ":TestMockStackBtmInterface", + ":TestCommonMockFunctions", + ":TestMockMainShim", + ":TestMockMainShimEntry", + ":TestMockStackBtm", + ":TestMockStackMetrics", "connection_manager/connection_manager.cc", - "test/common/mock_btm_api_layer.cc", "test/connection_manager_test.cc", ], shared_libs: [ + "libaconfig_storage_read_api_cc", + "libbinder", + "libbinder_ndk", + "libcrypto", "libcutils", + "server_configurable_flags", ], static_libs: [ + "bluetooth_flags_c_lib_for_test", "libbase", "libbluetooth-types", + "libbluetooth_core_rs_bridge", + "libbluetooth_crypto_toolbox", "libbluetooth_gd", "libbluetooth_log", "libbt-common", + "libbt-platform-protos-lite", "libchrome", + "libcom.android.sysprop.bluetooth.wrapped", "libevent", "libgmock", "liblog", + "libosi", + "libstatslog_bt", ], sanitize: { cfi: false, }, + target: { + android: { + shared_libs: [ + "libcutils", + "libhidlbase", + "libstatssocket", + "libutils", + ], + static_libs: [ + "android.hardware.bluetooth@1.0", + "android.hardware.bluetooth@1.1", + "android.system.suspend-V1-ndk", + "android.system.suspend.control-V1-ndk", + "libperfetto_client_experimental", + "libstatslog_bt", + ], + }, + }, header_libs: ["libbluetooth_headers"], } @@ -1102,7 +1139,6 @@ cc_test { srcs: [ ":TestCommonMockFunctions", ":TestMockMainShim", - ":TestMockRustFfi", ":TestMockStackArbiter", ":TestMockStackBtm", ":TestMockStackConnMgr", @@ -1437,7 +1473,6 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockMainShim", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackConnMgr", ":TestMockStackL2cap", @@ -1652,10 +1687,8 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockLegacyHciInterface", - ":TestMockMainBte", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtu", ":TestMockStackConnMgr", ":TestMockStackGap", @@ -1747,6 +1780,9 @@ cc_test { shared_libs: [ "libstatssocket", ], + static_libs: [ + "libperfetto_client_experimental", + ], }, }, sanitize: { @@ -1904,7 +1940,6 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", ":TestMockStackAcl", @@ -1982,10 +2017,8 @@ cc_test { ":TestMockBta", ":TestMockBtif", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockSrvcDis", ":TestMockStackAcl", ":TestMockStackBtm", @@ -2086,7 +2119,6 @@ cc_test { ":TestMockBtif", ":TestMockHci", ":TestMockJni", - ":TestMockLegacyHciCommands", ":TestMockMainShim", ":TestMockMainShimEntry", ":TestMockStackAcl", @@ -2141,6 +2173,9 @@ cc_test { "libPlatformProperties", "libstatssocket", ], + static_libs: [ + "libperfetto_client_experimental", + ], }, }, sanitize: { @@ -2182,11 +2217,9 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockHci", - ":TestMockLegacyHciCommands", ":TestMockLegacyHciInterface", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackBtu", ":TestMockStackConnMgr", @@ -2280,10 +2313,8 @@ cc_test { ":TestMockBtif", ":TestMockDevice", ":TestMockLegacyHciInterface", - ":TestMockMainBte", ":TestMockMainShim", ":TestMockMainShimEntry", - ":TestMockRustFfi", ":TestMockStackBtm", ":TestMockStackBtu", ":TestMockStackGap", @@ -2338,6 +2369,13 @@ cc_test { undefined: true, }, }, + target: { + android: { + static_libs: [ + "libperfetto_client_experimental", + ], + }, + }, header_libs: ["libbluetooth_headers"], } diff --git a/system/stack/BUILD.gn b/system/stack/BUILD.gn index ab902f7b5e..d078d1bc14 100644 --- a/system/stack/BUILD.gn +++ b/system/stack/BUILD.gn @@ -157,6 +157,7 @@ source_set("stack") { "rfcomm/port_rfc.cc", "rfcomm/port_utils.cc", "rfcomm/rfc_l2cap_if.cc", + "rfcomm/rfc_metrics.cc", "rfcomm/rfc_mx_fsm.cc", "rfcomm/rfc_port_fsm.cc", "rfcomm/rfc_port_if.cc", 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/avdt/avdt_api.cc b/system/stack/avdt/avdt_api.cc index adad0da41d..9c4a6e8e9b 100644 --- a/system/stack/avdt/avdt_api.cc +++ b/system/stack/avdt/avdt_api.cc @@ -87,6 +87,15 @@ void avdt_scb_transport_channel_timer_timeout(void* data) { avdt_scb_event(p_scb, avdt_event, NULL); } +void avdt_init_delay_report_timer_timeout(void* data) { + log::verbose("Schedule AVDT Open"); + tAVDT_EVT_HDR single; + AvdtpScb* p_scb = (AvdtpScb*)data; + single.seid = p_scb->peer_seid; + tAVDT_SCB_EVT avdt_scb_evt; + avdt_scb_evt.msg.single = single; + avdt_scb_event(p_scb, AVDT_SCB_API_OPEN_REQ_EVT, &avdt_scb_evt); +} /******************************************************************************* * * Function AVDT_Register diff --git a/system/stack/avdt/avdt_int.h b/system/stack/avdt/avdt_int.h index 7f3275930b..73ff0c9103 100644 --- a/system/stack/avdt/avdt_int.h +++ b/system/stack/avdt/avdt_int.h @@ -88,6 +88,9 @@ enum tTRANSPORT_CHANNEL_TYPE : uint8_t { /* scb transport channel disconnect timeout value (in milliseconds) */ #define AVDT_SCB_TC_DISC_TIMEOUT_MS (10 * 1000) +/* timer to monitor initial AVDT delay report as INT */ +#define AVDT_INIT_DELAY_REPORT_TIMEOUT_MS (2 * 1000) + /* maximum number of command retransmissions */ #ifndef AVDT_RET_MAX #define AVDT_RET_MAX 1 @@ -485,6 +488,9 @@ public: alarm_free(transport_channel_timer); transport_channel_timer = nullptr; + alarm_free(init_delay_report_timer); + init_delay_report_timer = nullptr; + p_pkt = nullptr; p_ccb = nullptr; media_seq = 0; @@ -510,6 +516,7 @@ public: AvdtpSepConfig curr_cfg; // Current configuration AvdtpSepConfig req_cfg; // Requested configuration alarm_t* transport_channel_timer; // Transport channel connect timer + alarm_t* init_delay_report_timer; // Timer to monitor initial AVDT delay report as INT BT_HDR* p_pkt; // Packet waiting to be sent AvdtpCcb* p_ccb; // CCB associated with this SCB uint16_t media_seq; // Media packet sequence number @@ -954,6 +961,7 @@ void avdt_ccb_idle_ccb_timer_timeout(void* data); void avdt_ccb_ret_ccb_timer_timeout(void* data); void avdt_ccb_rsp_ccb_timer_timeout(void* data); void avdt_scb_transport_channel_timer_timeout(void* data); +void avdt_init_delay_report_timer_timeout(void* data); /***************************************************************************** * macros diff --git a/system/stack/avdt/avdt_scb.cc b/system/stack/avdt/avdt_scb.cc index 6f4eefa173..1e1d7ae53e 100644 --- a/system/stack/avdt/avdt_scb.cc +++ b/system/stack/avdt/avdt_scb.cc @@ -866,6 +866,7 @@ void AvdtpScb::Allocate(AvdtpCcb* p_avdtp_ccb, const AvdtpStreamConfig& avdtp_st p_ccb = p_avdtp_ccb; stream_config = avdtp_stream_config; transport_channel_timer = alarm_new("avdtp_scb.transport_channel_timer"); + init_delay_report_timer = alarm_new("avdtp_scb.init_delay_report_timer"); allocated = true; } diff --git a/system/stack/avdt/avdt_scb_act.cc b/system/stack/avdt/avdt_scb_act.cc index e09cde8eeb..7dbb7cbdad 100644 --- a/system/stack/avdt/avdt_scb_act.cc +++ b/system/stack/avdt/avdt_scb_act.cc @@ -679,11 +679,18 @@ void avdt_scb_hdl_setconfig_rsp(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { // Delay reporting is sent before open request (i.e., in configured state). avdt_scb_snd_snk_delay_rpt_req(p_scb, p_data); - /* initiate open */ - single.seid = p_scb->peer_seid; - tAVDT_SCB_EVT avdt_scb_evt; - avdt_scb_evt.msg.single = single; - avdt_scb_event(p_scb, AVDT_SCB_API_OPEN_REQ_EVT, &avdt_scb_evt); + if (com::android::bluetooth::flags::avdt_wait_for_initial_delay_report_as_initiator() && + (p_scb->curr_cfg.psc_mask & AVDT_PSC_DELAY_RPT)) { + log::verbose("set alarm init_delay_report_timer"); + alarm_set_on_mloop(p_scb->init_delay_report_timer, AVDT_INIT_DELAY_REPORT_TIMEOUT_MS, + avdt_init_delay_report_timer_timeout, p_scb); + } else { + /* initiate open */ + single.seid = p_scb->peer_seid; + tAVDT_SCB_EVT avdt_scb_evt; + avdt_scb_evt.msg.single = single; + avdt_scb_event(p_scb, AVDT_SCB_API_OPEN_REQ_EVT, &avdt_scb_evt); + } } } @@ -835,11 +842,38 @@ void avdt_scb_hdl_delay_rpt_cmd(AvdtpScb* p_scb, tAVDT_SCB_EVT* p_data) { avdt_scb_to_hdl(p_scb), p_scb->p_ccb ? p_scb->p_ccb->peer_addr : RawAddress::kEmpty, AVDT_DELAY_REPORT_EVT, (tAVDT_CTRL*)&p_data->msg.hdr, p_scb->stream_config.scb_index); - if (p_scb->p_ccb) { - avdt_msg_send_rsp(p_scb->p_ccb, AVDT_SIG_DELAY_RPT, &p_data->msg); - } else { + if (!p_scb->p_ccb) { avdt_scb_rej_not_in_use(p_scb, p_data); + return; + } + + avdt_msg_send_rsp(p_scb->p_ccb, AVDT_SIG_DELAY_RPT, &p_data->msg); + + if (!com::android::bluetooth::flags::avdt_wait_for_initial_delay_report_as_initiator()) { + return; } + + if (!alarm_is_scheduled(p_scb->init_delay_report_timer)) { + log::verbose("init_delay_report_timer alarm not scheduled"); + return; + } + + if (!(p_scb->curr_cfg.psc_mask & AVDT_PSC_DELAY_RPT)) { + log::verbose("delay report not supported"); + return; + } + + if (p_scb->state != AVDT_SCB_CONF_ST) { + log::verbose("not initial delay report"); + return; + } + + alarm_cancel(p_scb->init_delay_report_timer); + + log::verbose("initiate open after receiving initial delay report"); + tAVDT_EVT_HDR single = {.seid = p_scb->peer_seid}; + tAVDT_SCB_EVT avdt_scb_evt = {.msg = {.single = single}}; + avdt_scb_event(p_scb, AVDT_SCB_API_OPEN_REQ_EVT, &avdt_scb_evt); } /******************************************************************************* diff --git a/system/stack/connection_manager/connection_manager.cc b/system/stack/connection_manager/connection_manager.cc index 801088ee18..3b13c63adc 100644 --- a/system/stack/connection_manager/connection_manager.cc +++ b/system/stack/connection_manager/connection_manager.cc @@ -27,10 +27,13 @@ #include <memory> #include <set> +#include "gd/hci/acl_manager.h" #include "gd/hci/controller_interface.h" #include "main/shim/acl_api.h" #include "main/shim/entry.h" +#include "main/shim/helpers.h" #include "main/shim/le_scanning_manager.h" +#include "main/shim/metrics_api.h" #include "osi/include/alarm.h" #include "stack/btm/btm_dev.h" #include "stack/include/advertise_data_parser.h" @@ -45,7 +48,8 @@ using namespace bluetooth; -constexpr char kBtmLogTag[] = "TA"; +constexpr char kBtmLogTagACL[] = "ACL"; +constexpr char kBtmLogTagTA[] = "TA"; struct closure_data { base::OnceClosure user_task; @@ -73,6 +77,21 @@ static void alarm_set_closure(const base::Location& posted_from, alarm_t* alarm, using unique_alarm_ptr = std::unique_ptr<alarm_t, decltype(&alarm_free)>; +namespace { +static void ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type, + bool is_direct) { + BTM_LogHistory(kBtmLogTagACL, legacy_address_with_type, "Allow connection from", "Le"); + bluetooth::shim::GetAclManager()->CreateLeConnection( + bluetooth::ToAddressWithTypeFromLegacy(legacy_address_with_type), is_direct); +} + +static void ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& legacy_address_with_type) { + BTM_LogHistory(kBtmLogTagACL, legacy_address_with_type, "Ignore connection from", "Le"); + bluetooth::shim::GetAclManager()->CancelLeConnect( + bluetooth::ToAddressWithTypeFromLegacy(legacy_address_with_type)); +} +} // namespace + namespace connection_manager { struct tAPPS_CONNECTING { @@ -205,7 +224,7 @@ static void target_announcement_observe_results_cb(tBTM_INQ_RESULTS* p_inq, cons return; } - BTM_LogHistory(kBtmLogTag, addr, "Found TA from"); + BTM_LogHistory(kBtmLogTagTA, addr, "Found TA from"); /* Take fist app_id and use it for direct_connect */ auto app_id = *(it->second.doing_targeted_announcements_conn.begin()); @@ -216,7 +235,7 @@ static void target_announcement_observe_results_cb(tBTM_INQ_RESULTS* p_inq, cons static void target_announcements_filtering_set(bool enable) { log::debug("enable {}", enable); - BTM_LogHistory(kBtmLogTag, RawAddress::kEmpty, (enable ? "Start filtering" : "Stop filtering")); + BTM_LogHistory(kBtmLogTagTA, RawAddress::kEmpty, (enable ? "Start filtering" : "Stop filtering")); /* Safe to call as if there is no support for filtering, this call will be * ignored. */ @@ -258,13 +277,13 @@ bool background_connect_targeted_announcement_add(tAPP_ID app_id, const RawAddre } if (disable_accept_list) { - bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); + ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); bgconn_dev[address].is_in_accept_list = false; } bgconn_dev[address].doing_targeted_announcements_conn.insert(app_id); if (bgconn_dev[address].doing_targeted_announcements_conn.size() == 1) { - BTM_LogHistory(kBtmLogTag, address, "Allow connection from"); + BTM_LogHistory(kBtmLogTagTA, address, "Allow connection from"); } if (num_of_targeted_announcements_users() == 1) { @@ -310,7 +329,8 @@ bool background_connect_add(uint8_t app_id, const RawAddress& address) { return false; } - bluetooth::shim::ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), false); + ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), false); + bgconn_dev[address].is_in_accept_list = true; } } @@ -330,7 +350,7 @@ bool remove_unconditional(const RawAddress& address) { log::info("address {} is not found", address); } - bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); + ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); return count > 0; } @@ -358,7 +378,7 @@ bool background_connect_remove(uint8_t app_id, const RawAddress& address) { } if (removed_from_ta && it->second.doing_targeted_announcements_conn.size() == 0) { - BTM_LogHistory(kBtmLogTag, address, "Ignore connection from"); + BTM_LogHistory(kBtmLogTagTA, address, "Ignore connection from"); } if (is_anyone_connecting(it)) { @@ -371,7 +391,7 @@ bool background_connect_remove(uint8_t app_id, const RawAddress& address) { /* Keep using filtering */ log::debug("Keep using target announcement filtering"); } else if (!it->second.doing_bg_conn.empty()) { - bluetooth::shim::ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), false); + ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), false); bgconn_dev[address].is_in_accept_list = true; } } @@ -382,7 +402,7 @@ bool background_connect_remove(uint8_t app_id, const RawAddress& address) { // no more apps interested - remove from accept list and delete record if (accept_list_enabled) { - bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); + ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); return true; } @@ -418,7 +438,7 @@ void on_app_deregistered(uint8_t app_id) { continue; } - bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(it->first)); + ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(it->first)); it = bgconn_dev.erase(it); } } @@ -450,7 +470,7 @@ void reset(bool after_reset) { bgconn_dev.clear(); if (!after_reset) { target_announcements_filtering_set(false); - bluetooth::shim::ACL_IgnoreAllLeConnections(); + bluetooth::shim::GetAclManager()->ClearFilterAcceptList(); } } @@ -504,6 +524,7 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address, tBLE_ADDR_TYP // app already trying to connect to this particular device if (info.doing_direct_conn.count(app_id)) { log::info("attempt from app_id=0x{:x} to {} already in progress", app_id, address_with_type); + bluetooth::shim::LogMetricLeConnectionRejected(bluetooth::ToGdAddress(address)); return false; } @@ -530,12 +551,12 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address, tBLE_ADDR_TYP return false; } - bluetooth::shim::ACL_AcceptLeConnectionFrom(address_with_type, true /* is_direct */); + ACL_AcceptLeConnectionFrom(address_with_type, true /* is_direct */); bgconn_dev[address].is_in_accept_list = true; } else { // if already in accept list, we should just bump parameters up for direct // connection. There is no API for that yet, so use API that's adding to accept list. - bluetooth::shim::ACL_AcceptLeConnectionFrom(address_with_type, true /* is_direct */); + ACL_AcceptLeConnectionFrom(address_with_type, true /* is_direct */); } // Setup a timer @@ -576,14 +597,13 @@ bool direct_connect_remove(uint8_t app_id, const RawAddress& address, bool conne /* In such case we need to add device back to allow list because, when connection timeout * out, the lower layer removes device from the allow list. */ - bluetooth::shim::ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), - false /* is_direct */); + ACL_AcceptLeConnectionFrom(BTM_Sec_GetAddressWithType(address), false /* is_direct */); } return true; } // no more apps interested - remove from acceptlist - bluetooth::shim::ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); + ACL_IgnoreLeConnectionFrom(BTM_Sec_GetAddressWithType(address)); if (!is_targeted_announcement_enabled) { bgconn_dev.erase(it); 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/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/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/test/headless/config.cc b/system/stack/include/rfc_metrics.h index 7a3aab62a0..66d73ec8d8 100644 --- a/system/test/headless/config.cc +++ b/system/stack/include/rfc_metrics.h @@ -1,5 +1,5 @@ /* - * Copyright 2023 The Android Open Source Project + * Copyright 2024 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,19 +14,8 @@ * limitations under the License. */ -#define LOG_TAG "bt_config" +#pragma once -#include "gd/hal/snoop_logger.h" -#include "test/headless/log.h" +#include "stack/rfcomm/port_int.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 - } -}; +void port_collect_attempt_metrics(tPORT* p_port); diff --git a/system/stack/include/stack_metrics_logging.h b/system/stack/include/stack_metrics_logging.h index dda02a0d1d..9a0a80baa4 100644 --- a/system/stack/include/stack_metrics_logging.h +++ b/system/stack/include/stack_metrics_logging.h @@ -64,3 +64,6 @@ void log_le_connection_status(bluetooth::hci::Address address, bool is_connect, void log_le_device_in_accept_list(bluetooth::hci::Address address, bool is_add); void log_le_connection_lifecycle(bluetooth::hci::Address address, bool is_connect, bool is_direct); + +void log_le_connection_completion(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated); diff --git a/system/stack/l2cap/l2c_ble_conn_params.cc b/system/stack/l2cap/l2c_ble_conn_params.cc index 47c19f3a3c..49eeb06155 100644 --- a/system/stack/l2cap/l2c_ble_conn_params.cc +++ b/system/stack/l2cap/l2c_ble_conn_params.cc @@ -431,10 +431,15 @@ void l2cble_use_preferred_conn_params(const RawAddress& bda) { p_lcb->conn_update_mask &= ~L2C_BLE_AGGRESSIVE_INITIAL_PARAM; } - acl_ble_connection_parameters_request(p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, - p_dev_rec->conn_params.max_conn_int, - p_dev_rec->conn_params.peripheral_latency, - p_dev_rec->conn_params.supervision_tout, 0, 0); + if (com::android::bluetooth::flags::prevent_concurrent_conn_param_updates()) { + p_lcb->conn_update_mask |= L2C_BLE_NEW_CONN_PARAM; + l2cble_start_conn_update(p_lcb); + } else { + acl_ble_connection_parameters_request(p_lcb->Handle(), p_dev_rec->conn_params.min_conn_int, + p_dev_rec->conn_params.max_conn_int, + p_dev_rec->conn_params.peripheral_latency, + p_dev_rec->conn_params.supervision_tout, 0, 0); + } } } diff --git a/system/stack/l2cap/l2c_link.cc b/system/stack/l2cap/l2c_link.cc index 426a12a2ba..082e055afe 100644 --- a/system/stack/l2cap/l2c_link.cc +++ b/system/stack/l2cap/l2c_link.cc @@ -284,113 +284,109 @@ static void l2c_link_iot_store_disc_reason(RawAddress& bda, uint8_t reason) { * ******************************************************************************/ bool l2c_link_hci_disc_comp(uint16_t handle, tHCI_REASON reason) { - tL2C_CCB* p_ccb; - bool status = true; + tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); + if (p_lcb == nullptr) { + log::error("No LCB found for handle:0x{:04x}", handle); + + p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING); + if (p_lcb != nullptr) { + log::info("Resuming pending ACL request {}", p_lcb->remote_bd_addr); + l2cu_create_conn_br_edr(p_lcb); + } + return false; + } + bool lcb_is_free = true; + l2c_link_iot_store_disc_reason(p_lcb->remote_bd_addr, reason); + p_lcb->SetDisconnectReason(reason); - /* If we don't have one, maybe an SCO link. Send to MM */ - tL2C_LCB* p_lcb = l2cu_find_lcb_by_handle(handle); - if (!p_lcb) { - status = false; - } else { - l2c_link_iot_store_disc_reason(p_lcb->remote_bd_addr, reason); + /* Just in case app decides to try again in the callback context */ + p_lcb->link_state = LST_DISCONNECTING; - p_lcb->SetDisconnectReason(reason); + /* Check for BLE and handle that differently */ + if (p_lcb->transport == BT_TRANSPORT_LE) { + btm_ble_decrement_link_topology_mask(p_lcb->LinkRole()); + } - /* Just in case app decides to try again in the callback context */ - p_lcb->link_state = LST_DISCONNECTING; + /* Link is disconnected. For all channels, send the event through their FSMs. The CCBs should + * remove themselves from the LCB */ + for (tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) { + tL2C_CCB* pn = p_ccb->p_next_ccb; - /* Check for BLE and handle that differently */ - if (p_lcb->transport == BT_TRANSPORT_LE) { - btm_ble_decrement_link_topology_mask(p_lcb->LinkRole()); + /* Keep connect pending control block (if exists). + * Possible race condition when a reconnect occurs on the channel during a disconnect of link. + * This ccb will be automatically retried after link disconnect arrives */ + if (p_ccb != p_lcb->p_pending_ccb) { + l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, &reason); } - /* Link is disconnected. For all channels, send the event through */ - /* their FSMs. The CCBs should remove themselves from the LCB */ - for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb;) { - tL2C_CCB* pn = p_ccb->p_next_ccb; + p_ccb = pn; + } - /* Keep connect pending control block (if exists) - * Possible Race condition when a reconnect occurs - * on the channel during a disconnect of link. This - * ccb will be automatically retried after link disconnect - * arrives - */ - if (p_ccb != p_lcb->p_pending_ccb) { - l2c_csm_execute(p_ccb, L2CEVT_LP_DISCONNECT_IND, &reason); - } - p_ccb = pn; - } + if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { + /* Tell SCO management to drop any SCOs on this ACL */ + btm_sco_acl_removed(&p_lcb->remote_bd_addr); + } - if (p_lcb->transport == BT_TRANSPORT_BR_EDR) { - /* Tell SCO management to drop any SCOs on this ACL */ - btm_sco_acl_removed(&p_lcb->remote_bd_addr); + /* If waiting for disconnect and reconnect is pending start the reconnect now race condition where + * layer above issued connect request on link that was disconnecting */ + if (p_lcb->ccb_queue.p_first_ccb != nullptr || p_lcb->p_pending_ccb) { + log::debug("l2c_link_hci_disc_comp: Restarting pending ACL request"); + /* Release any held buffers */ + while (!list_is_empty(p_lcb->link_xmit_data_q)) { + BT_HDR* p_buf = static_cast<BT_HDR*>(list_front(p_lcb->link_xmit_data_q)); + list_remove(p_lcb->link_xmit_data_q, p_buf); + osi_free(p_buf); } - - /* If waiting for disconnect and reconnect is pending start the reconnect - now - race condition where layer above issued connect request on link that was - disconnecting + /* for LE link, always drop and re-open to ensure to get LE remote feature */ - if (p_lcb->ccb_queue.p_first_ccb != NULL || p_lcb->p_pending_ccb) { - log::debug("l2c_link_hci_disc_comp: Restarting pending ACL request"); - /* Release any held buffers */ - while (!list_is_empty(p_lcb->link_xmit_data_q)) { - BT_HDR* p_buf = static_cast<BT_HDR*>(list_front(p_lcb->link_xmit_data_q)); - list_remove(p_lcb->link_xmit_data_q, p_buf); - osi_free(p_buf); - } - /* for LE link, always drop and re-open to ensure to get LE remote feature - */ - if (p_lcb->transport == BT_TRANSPORT_LE) { - btm_acl_removed(handle); - if (com::android::bluetooth::flags::invalidate_hci_handle_on_acl_removal()) { - p_lcb->InvalidateHandle(); - } - } else { - /* If we are going to re-use the LCB without dropping it, release all - fixed channels - here */ - int xx; - for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { - if (p_lcb->p_fixed_ccbs[xx] && p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) { - l2cu_release_ccb(p_lcb->p_fixed_ccbs[xx]); - - p_lcb->p_fixed_ccbs[xx] = NULL; - (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, - p_lcb->remote_bd_addr, false, - p_lcb->DisconnectReason(), p_lcb->transport); - } - } - /* Cleanup connection state to avoid race conditions because - * l2cu_release_lcb won't be invoked to cleanup */ - btm_acl_removed(p_lcb->Handle()); + if (p_lcb->transport == BT_TRANSPORT_LE) { + btm_acl_removed(handle); + if (com::android::bluetooth::flags::invalidate_hci_handle_on_acl_removal()) { p_lcb->InvalidateHandle(); } - if (p_lcb->transport == BT_TRANSPORT_LE) { - if (l2cu_create_conn_le(p_lcb)) { - lcb_is_free = false; /* still using this lcb */ + } else { + /* If we are going to re-use the LCB without dropping it, release all + fixed channels + here */ + int xx; + for (xx = 0; xx < L2CAP_NUM_FIXED_CHNLS; xx++) { + if (p_lcb->p_fixed_ccbs[xx] && p_lcb->p_fixed_ccbs[xx] != p_lcb->p_pending_ccb) { + l2cu_release_ccb(p_lcb->p_fixed_ccbs[xx]); + p_lcb->p_fixed_ccbs[xx] = nullptr; + (*l2cb.fixed_reg[xx].pL2CA_FixedConn_Cb)(xx + L2CAP_FIRST_FIXED_CHNL, + p_lcb->remote_bd_addr, false, + p_lcb->DisconnectReason(), p_lcb->transport); } - } else { - l2cu_create_conn_br_edr(p_lcb); + } + /* Cleanup connection state to avoid race conditions because + * l2cu_release_lcb won't be invoked to cleanup */ + btm_acl_removed(p_lcb->Handle()); + p_lcb->InvalidateHandle(); + } + if (p_lcb->transport == BT_TRANSPORT_LE) { + if (l2cu_create_conn_le(p_lcb)) { lcb_is_free = false; /* still using this lcb */ } + } else { + l2cu_create_conn_br_edr(p_lcb); + lcb_is_free = false; /* still using this lcb */ } + } + p_lcb->p_pending_ccb = nullptr; - p_lcb->p_pending_ccb = NULL; + /* Release the LCB */ + if (lcb_is_free) { + l2cu_release_lcb(p_lcb); - /* Release the LCB */ - if (lcb_is_free) { - l2cu_release_lcb(p_lcb); + /* Now that we have a free acl connection, see if any lcbs are pending */ + p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING); + if (p_lcb != nullptr) { + log::info("Resuming pending ACL request {}", p_lcb->remote_bd_addr); + l2cu_create_conn_br_edr(p_lcb); } } - /* Now that we have a free acl connection, see if any lcbs are pending */ - if (lcb_is_free && ((p_lcb = l2cu_find_lcb_by_state(LST_CONNECT_HOLDING)) != NULL)) { - /* we found one-- create a connection */ - l2cu_create_conn_br_edr(p_lcb); - } - - return status; + return true; } /******************************************************************************* diff --git a/system/stack/metrics/stack_metrics_logging.cc b/system/stack/metrics/stack_metrics_logging.cc index ffe7a43488..398a72ce33 100644 --- a/system/stack/metrics/stack_metrics_logging.cc +++ b/system/stack/metrics/stack_metrics_logging.cc @@ -94,3 +94,8 @@ void log_le_device_in_accept_list(bluetooth::hci::Address address, bool is_add) void log_le_connection_lifecycle(bluetooth::hci::Address address, bool is_connect, bool is_direct) { bluetooth::shim::LogMetricLeConnectionLifecycle(address, is_connect, is_direct); } + +void log_le_connection_completion(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated) { + bluetooth::shim::LogMetricLeConnectionCompletion(address, reason, is_locally_initiated); +} 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 4dc7590d96..860fdf0450 100644 --- a/system/stack/rfcomm/port_rfc.cc +++ b/system/stack/rfcomm/port_rfc.cc @@ -40,6 +40,7 @@ #include "osi/include/mutex.h" #include "stack/include/bt_hdr.h" #include "stack/include/bt_uuid16.h" +#include "stack/include/rfc_metrics.h" #include "stack/include/stack_metrics_logging.h" #include "stack/l2cap/l2c_int.h" #include "stack/rfcomm/port_int.h" @@ -452,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; @@ -499,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 @@ -636,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); + } + } + } } /******************************************************************************* @@ -673,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); + } + } + } } /******************************************************************************* @@ -1051,6 +1091,7 @@ void port_rfc_closed(tPORT* p_port, uint8_t res) { rfc_set_state(RFC_STATE_CLOSED, p_port); p_port->rfc.sm_cb.close_reason = static_cast<tPORT_RESULT>(res); + port_collect_attempt_metrics(p_port); log::info( "RFCOMM connection closed, port_handle={}, state={}, reason={}[{}], " "UUID=0x{:x}, bd_addr={}, is_server={}", diff --git a/system/stack/rfcomm/rfc_metrics.cc b/system/stack/rfcomm/rfc_metrics.cc new file mode 100644 index 0000000000..13f6ad2bdd --- /dev/null +++ b/system/stack/rfcomm/rfc_metrics.cc @@ -0,0 +1,176 @@ +/* + * Copyright 2024 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 "rfc_metrics" + +#include "../include/rfc_metrics.h" + +#include <bluetooth/log.h> +#include <frameworks/proto_logging/stats/enums/bluetooth/rfcomm/enums.pb.h> + +#include "bta/include/bta_jv_api.h" +#include "common/time_util.h" +#include "main/shim/metrics_api.h" +#include "stack/btm/security_device_record.h" +#include "stack/include/btm_sec_api_types.h" +#include "stack/include/port_api.h" +#include "stack/rfcomm/port_int.h" +#include "stack/rfcomm/rfc_event.h" +#include "stack/rfcomm/rfc_state.h" +#include "types/raw_address.h" + +using namespace bluetooth; + +using namespace android::bluetooth; +using namespace android::bluetooth::rfcomm; + +static SocketConnectionSecurity toSecurity(uint16_t sec_mask); +static PortResult toPortResult(tPORT_RESULT result); +static RfcommPortState toPortState(tRFC_PORT_STATE state); +static RfcommPortEvent toPortEvent(tRFC_PORT_EVENT event); + +void port_collect_attempt_metrics(tPORT* p_port) { + bool is_server = p_port->is_server; + bool sdp_initiated = (p_port->sdp_duration_ms > 0); + // If we're calling this metrics function, SDP completed with no problems + BtaStatus sdp_status = sdp_initiated ? BTA_STATUS_SUCCESS : BTA_STATUS_UNKNOWN; + RfcommPortSm sm_cb = p_port->rfc.sm_cb; + log::assert_that(sm_cb.state == RFC_STATE_CLOSED, "Assert failed: Port not closed"); + uint64_t open_duration_ms = (sm_cb.close_timestamp - sm_cb.open_timestamp) / 1000; + + shim::LogMetricRfcommConnectionAtClose( + p_port->bd_addr, toPortResult(sm_cb.close_reason), toSecurity(p_port->sec_mask), + toPortEvent(sm_cb.last_event), toPortState(sm_cb.state_prior), + static_cast<int32_t>(open_duration_ms), static_cast<int32_t>(p_port->app_uid), sdp_status, + is_server, sdp_initiated, static_cast<int32_t>(p_port->sdp_duration_ms)); +} + +static SocketConnectionSecurity toSecurity(uint16_t sec_mask) { + if (((sec_mask & BTM_SEC_IN_FLAGS) == (BTM_SEC_IN_AUTHENTICATE | BTM_SEC_IN_ENCRYPT)) || + ((sec_mask & BTM_SEC_OUT_FLAGS) == (BTM_SEC_OUT_AUTHENTICATE | BTM_SEC_OUT_ENCRYPT))) { + return SocketConnectionSecurity::SOCKET_SECURITY_SECURE; + } else if (((sec_mask & BTM_SEC_IN_FLAGS) == (BTM_SEC_NONE)) || + ((sec_mask & BTM_SEC_OUT_FLAGS) == (BTM_SEC_NONE))) { + return SocketConnectionSecurity::SOCKET_SECURITY_INSECURE; + } + + return SocketConnectionSecurity::SOCKET_SECURITY_UNKNOWN; +} + +static PortResult toPortResult(tPORT_RESULT result) { + switch (result) { + case PORT_SUCCESS: + return PortResult::PORT_RESULT_SUCCESS; + case PORT_UNKNOWN_ERROR: + return PortResult::PORT_RESULT_UNKNOWN_ERROR; + case PORT_ALREADY_OPENED: + return PortResult::PORT_RESULT_ALREADY_OPENED; + case PORT_CMD_PENDING: + return PortResult::PORT_RESULT_CMD_PENDING; + case PORT_APP_NOT_REGISTERED: + return PortResult::PORT_RESULT_APP_NOT_REGISTERED; + case PORT_NO_MEM: + return PortResult::PORT_RESULT_NO_MEM; + case PORT_NO_RESOURCES: + return PortResult::PORT_RESULT_NO_RESOURCES; + case PORT_BAD_BD_ADDR: + return PortResult::PORT_RESULT_BAD_BD_ADDR; + case PORT_BAD_HANDLE: + return PortResult::PORT_RESULT_BAD_HANDLE; + case PORT_NOT_OPENED: + return PortResult::PORT_RESULT_NOT_OPENED; + case PORT_LINE_ERR: + return PortResult::PORT_RESULT_LINE_ERR; + case PORT_START_FAILED: + return PortResult::PORT_RESULT_START_FAILED; + case PORT_PAR_NEG_FAILED: + return PortResult::PORT_RESULT_PAR_NEG_FAILED; + case PORT_PORT_NEG_FAILED: + return PortResult::PORT_RESULT_PORT_NEG_FAILED; + case PORT_SEC_FAILED: + return PortResult::PORT_RESULT_SEC_FAILED; + case PORT_PEER_CONNECTION_FAILED: + return PortResult::PORT_RESULT_PEER_CONNECTION_FAILED; + case PORT_PEER_FAILED: + return PortResult::PORT_RESULT_PEER_FAILED; + case PORT_PEER_TIMEOUT: + return PortResult::PORT_RESULT_PEER_TIMEOUT; + case PORT_CLOSED: + return PortResult::PORT_RESULT_CLOSED; + case PORT_TX_FULL: + return PortResult::PORT_RESULT_TX_FULL; + case PORT_LOCAL_CLOSED: + return PortResult::PORT_RESULT_LOCAL_CLOSED; + case PORT_LOCAL_TIMEOUT: + return PortResult::PORT_RESULT_LOCAL_TIMEOUT; + case PORT_TX_QUEUE_DISABLED: + return PortResult::PORT_RESULT_TX_QUEUE_DISABLED; + case PORT_PAGE_TIMEOUT: + return PortResult::PORT_RESULT_PAGE_TIMEOUT; + case PORT_INVALID_SCN: + return PortResult::PORT_RESULT_INVALID_SCN; + case PORT_ERR_MAX: + return PortResult::PORT_RESULT_ERR_MAX; + } + return PortResult::PORT_RESULT_UNDEFINED; +} + +static RfcommPortState toPortState(tRFC_PORT_STATE state) { + switch (state) { + case RFC_STATE_SABME_WAIT_UA: + return RfcommPortState::PORT_STATE_SABME_WAIT_UA; + case RFC_STATE_ORIG_WAIT_SEC_CHECK: + return RfcommPortState::PORT_STATE_ORIG_WAIT_SEC_CHECK; + case RFC_STATE_TERM_WAIT_SEC_CHECK: + return RfcommPortState::PORT_STATE_TERM_WAIT_SEC_CHECK; + case RFC_STATE_OPENED: + return RfcommPortState::PORT_STATE_OPENED; + case RFC_STATE_DISC_WAIT_UA: + return RfcommPortState::PORT_STATE_DISC_WAIT_UA; + case RFC_STATE_CLOSED: + return RfcommPortState::PORT_STATE_CLOSED; + } + return RfcommPortState::PORT_STATE_UNKNOWN; +} + +static RfcommPortEvent toPortEvent(tRFC_PORT_EVENT event) { + switch (event) { + case RFC_PORT_EVENT_SABME: + return RfcommPortEvent::PORT_EVENT_SABME; + case RFC_PORT_EVENT_UA: + return RfcommPortEvent::PORT_EVENT_UA; + case RFC_PORT_EVENT_DM: + return RfcommPortEvent::PORT_EVENT_DM; + case RFC_PORT_EVENT_DISC: + return RfcommPortEvent::PORT_EVENT_DISC; + case RFC_PORT_EVENT_UIH: + return RfcommPortEvent::PORT_EVENT_UIH; + case RFC_PORT_EVENT_TIMEOUT: + return RfcommPortEvent::PORT_EVENT_TIMEOUT; + case RFC_PORT_EVENT_OPEN: + return RfcommPortEvent::PORT_EVENT_OPEN; + case RFC_PORT_EVENT_ESTABLISH_RSP: + return RfcommPortEvent::PORT_EVENT_ESTABLISH_RSP; + case RFC_PORT_EVENT_CLOSE: + return RfcommPortEvent::PORT_EVENT_CLOSE; + case RFC_PORT_EVENT_CLEAR: + return RfcommPortEvent::PORT_EVENT_CLEAR; + case RFC_PORT_EVENT_DATA: + return RfcommPortEvent::PORT_EVENT_DATA; + case RFC_PORT_EVENT_SEC_COMPLETE: + return RfcommPortEvent::PORT_EVENT_SEC_COMPLETE; + } + return RfcommPortEvent::PORT_EVENT_UNKNOWN; +} diff --git a/system/stack/test/btm/stack_btm_dm_inq_db_test.cc b/system/stack/test/btm/stack_btm_dm_inq_db_test.cc deleted file mode 100644 index 7fc971a5c3..0000000000 --- a/system/stack/test/btm/stack_btm_dm_inq_db_test.cc +++ /dev/null @@ -1,221 +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 <gtest/gtest.h> -#include <stdlib.h> - -#include <deque> -#include <mutex> -#include <queue> - -#include "stack/btm/btm_int_types.h" -#include "stack/btm/neighbor_inquiry.h" -#include "stack/include/btm_inq.h" -#include "stack/include/inq_hci_link_interface.h" -#include "test/common/mock_functions.h" -#include "test/fake/fake_looper.h" -#include "test/fake/fake_osi.h" -#include "test/fake/fake_thread.h" -#include "test/mock/mock_osi_allocator.h" -#include "test/mock/mock_osi_thread.h" - -extern tBTM_CB btm_cb; - -namespace { -constexpr size_t kNumberOfThreads = 8; -constexpr size_t kEntriesPerThread = static_cast<size_t>(BTM_INQ_DB_SIZE) / kNumberOfThreads; - -constexpr RawAddress* kClearAllEntries = nullptr; -} // namespace - -namespace bluetooth { -namespace legacy { -namespace testing { -void btm_clr_inq_db(const RawAddress* p_bda); -uint16_t btm_get_num_bd_entries(); -} // namespace testing -} // namespace legacy -} // namespace bluetooth - -class BtmDmInqDbWithMockTest : public testing::Test { -protected: - void SetUp() override { - reset_mock_function_count_map(); - fake_osi_ = std::make_unique<test::fake::FakeOsi>(); - test::mock::osi_thread::thread_new.body = [](const char* name) -> thread_t* { - thread_t* thread = new thread_t; - thread->name_ = std::string(name); - thread_start_arg_t start_arg; - start_arg.thread = thread; - pthread_create(&thread->pthread_, nullptr, run_message_loop, &start_arg); - // Wait for thread to start up with semaphore before continuing - start_arg.start_sem.wait(); - return thread; - }; - test::mock::osi_thread::thread_post.body = [](thread_t* thread, thread_func func, - void* context) -> bool { - if (!thread->is_running()) { - return false; - } - { - std::lock_guard<std::mutex> lock(thread->work_queue_semaphore.mutex_); - thread->work_queue.push(std::make_pair(func, context)); - } - thread->work_queue_semaphore.notify(); - return true; - }; - test::mock::osi_thread::thread_free.body = [](thread_t* thread) { - thread->quiesce(); - pthread_join(thread->pthread_, nullptr); - thread->work_queue = {}; - delete thread; - }; - } - - void TearDown() override { - test::mock::osi_thread::thread_free = {}; - test::mock::osi_thread::thread_post = {}; - test::mock::osi_thread::thread_new = {}; - } - std::unique_ptr<test::fake::FakeOsi> fake_osi_; -}; - -class BtmDmInqDbTest : public BtmDmInqDbWithMockTest { -protected: - void SetUp() override { - BtmDmInqDbWithMockTest::SetUp(); - bluetooth::legacy::testing::btm_clr_inq_db(kClearAllEntries); - btm_init_inq_result_flt(); - } - - void TearDown() override { - btm_clr_inq_result_flt(); - bluetooth::legacy::testing::btm_clr_inq_db(kClearAllEntries); - BtmDmInqDbWithMockTest::TearDown(); - } -}; - -class BtmDmInqDbThreadedTest : public BtmDmInqDbTest { -protected: - void SetUp() override { BtmDmInqDbTest::SetUp(); } - - void TearDown() override { BtmDmInqDbTest::TearDown(); } - - void setup_thread() { - for (size_t i = 0; i < kNumberOfThreads; i++) { - std::string name = std::format("thread:{}", i); - threads[i] = thread_new(name.c_str()); - } - } - - void teardown_thread() { - for (size_t i = 0; i < kNumberOfThreads; i++) { - thread_free(threads[i]); - } - } - - thread_t* threads[kNumberOfThreads]; -}; - -struct context_t { - std::deque<tINQ_DB_ENT*> inq_db_queue[kNumberOfThreads]; -}; - -struct entry_data_t { - int thread_id; - std::deque<tINQ_DB_ENT*>* inq_db_queue; -}; - -RawAddress RawAddressMaker(int thread_id, int subid) { - RawAddress bd_addr = {}; - // tODO Use const std::array<uint8_t, kLength> array) - bd_addr.address[0] = 0x0a; - bd_addr.address[1] = 0x0b; - bd_addr.address[2] = 0x0c; - bd_addr.address[3] = 0x0d; - bd_addr.address[4] = (uint8_t)thread_id; - bd_addr.address[5] = (uint8_t)subid; - return bd_addr; -} - -void allocate_db_entry(void* context) { - entry_data_t* data = static_cast<entry_data_t*>(context); - RawAddress p_bda = RawAddressMaker(data->thread_id, (int)data->inq_db_queue->size()); - tINQ_DB_ENT* ent = btm_inq_db_new(p_bda); - data->inq_db_queue->push_back(ent); -} - -TEST_F(BtmDmInqDbThreadedTest, btm_inq_db_new) { - this->setup_thread(); - - context_t context = {}; - - for (size_t j = 0; j < kEntriesPerThread; j++) { - for (size_t i = 0; i < kNumberOfThreads; i++) { - data_t* data = static_cast<data_t*>(calloc(sizeof(data_t), 1)); - data->thread_id = i; - data->inq_db_queue = &context.inq_db_queue[i]; - ASSERT_TRUE(thread_post(threads[i], allocate_db_entry, static_cast<void*>(data))); - } - } - - this->teardown_thread(); - - int failed = 0; - for (size_t i = 0; i < kNumberOfThreads; i++) { - ASSERT_EQ(kEntriesPerThread, context.inq_db_queue[i].size()); - for (const auto& it : context.inq_db_queue[i]) { - RawAddress exp = it->inq_info.results.remote_bd_addr; - exp.address[4] = i; - if (exp != it->inq_info.results.remote_bd_addr) { - EXPECT_EQ(exp, it->inq_info.results.remote_bd_addr); - failed++; - } - } - } - ASSERT_EQ(0, failed); -} - -struct address_data_t { - int thread_id; - int offset; -}; - -void check_address(void* context) { - address_data_t* data = static_cast<address_data_t*>(context); - RawAddress p_bda = RawAddressMaker(data->thread_id, data->offset); - // Make sure it's new - ASSERT_FALSE(btm_inq_find_bdaddr(p_bda)); -} - -TEST_F(BtmDmInqDbThreadedTest, btm_inq_find_bdaddr) { - this->setup_thread(); - context_t context = {}; - - for (size_t j = 0; j < kEntriesPerThread; j++) { - for (size_t i = 0; i < kNumberOfThreads; i++) { - address_data_t* data = static_cast<address_data_t*>(calloc(sizeof(address_data_t), 1)); - data->thread_id = i; - data->offset = (int)j; - ASSERT_TRUE(thread_post(threads[i], check_address, static_cast<void*>(data))); - } - } - - this->teardown_thread(); - - ASSERT_EQ((uint16_t)(kNumberOfThreads * kEntriesPerThread), - bluetooth::legacy::testing::btm_get_num_bd_entries()); -} diff --git a/system/stack/test/connection_manager_test.cc b/system/stack/test/connection_manager_test.cc index c5cbcc059b..1a06158ca0 100644 --- a/system/stack/test/connection_manager_test.cc +++ b/system/stack/test/connection_manager_test.cc @@ -4,12 +4,14 @@ #include <base/functional/bind.h> #include <base/functional/callback.h> #include <base/location.h> +#include <bluetooth/log.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <memory> -#include "gd/hci/controller_interface_mock.h" +#include "gd/hci/acl_manager_mock.h" +#include "gd/hci/controller_mock.h" #include "main/shim/acl_api.h" #include "main/shim/entry.h" #include "main/shim/le_scanning_manager.h" @@ -22,35 +24,27 @@ #include "stack/include/btm_ble_api.h" #include "stack/include/btm_log_history.h" #include "stack/l2cap/internal/l2c_api.h" +#include "test/mock/mock_main_shim_entry.h" using testing::_; using testing::DoAll; +using testing::Eq; using testing::Mock; using testing::Return; using testing::SaveArg; -using connection_manager::tAPP_ID; +using bluetooth::hci::AddressWithType; -namespace { -// convenience mock, for verifying acceptlist operations on lower layer are -// actually scheduled -class AcceptlistMock { -public: - MOCK_METHOD2(AcceptlistAdd, bool(const RawAddress&, bool is_direct)); - MOCK_METHOD1(AcceptlistRemove, void(const RawAddress&)); - MOCK_METHOD0(AcceptlistClear, void()); - MOCK_METHOD2(OnConnectionTimedOut, void(uint8_t, const RawAddress&)); - - /* Not really accept list related, btui still BTM - just for testing put it - * here. */ - MOCK_METHOD2(EnableTargetedAnnouncements, void(bool, tBTM_INQ_RESULTS_CB*)); -}; +using connection_manager::tAPP_ID; +namespace test = bluetooth::hci::testing; -std::unique_ptr<AcceptlistMock> localAcceptlistMock; -} // namespace +const RawAddress address1{{0x01, 0x01, 0x01, 0x01, 0x01, 0x07}}; +const RawAddress address2{{0x22, 0x22, 0x02, 0x22, 0x33, 0x22}}; -RawAddress address1{{0x01, 0x01, 0x01, 0x01, 0x01, 0x01}}; -RawAddress address2{{0x22, 0x22, 0x02, 0x22, 0x33, 0x22}}; +const AddressWithType address1_hci{{0x07, 0x01, 0x01, 0x01, 0x01, 0x01}, + bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; +const AddressWithType address2_hci{{0x22, 0x33, 0x22, 0x02, 0x22, 0x22}, + bluetooth::hci::AddressType::PUBLIC_DEVICE_ADDRESS}; constexpr tAPP_ID CLIENT1 = 1; constexpr tAPP_ID CLIENT2 = 2; @@ -59,54 +53,28 @@ constexpr tAPP_ID CLIENT10 = 10; std::string get_client_name(uint8_t /* gatt_if */) { return ""; } -const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { - return tBLE_BD_ADDR{.type = BLE_ADDR_PUBLIC, .bda = bd_addr}; -} - -tBTM_SEC_DEV_REC* btm_find_dev(const RawAddress& /* bd_addr */) { return nullptr; } - -namespace bluetooth { -namespace shim { - -void ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& address, bool is_direct) { - localAcceptlistMock->AcceptlistAdd(address.bda, is_direct); -} -void ACL_IgnoreLeConnectionFrom(const tBLE_BD_ADDR& address) { - return localAcceptlistMock->AcceptlistRemove(address.bda); -} - -void ACL_IgnoreAllLeConnections() { return localAcceptlistMock->AcceptlistClear(); } - -testing::NiceMock<bluetooth::hci::testing::MockControllerInterface> controller; - -hci::ControllerInterface* GetController() { - ON_CALL(controller, GetLeFilterAcceptListSize).WillByDefault(Return(128)); - return &controller; -} +class MockConnTimeout { +public: + MOCK_METHOD2(OnConnectionTimedOut, void(uint8_t, const RawAddress&)); +}; -} // namespace shim -} // namespace bluetooth +std::unique_ptr<MockConnTimeout> localConnTimeoutMock; -void BTM_BleTargetAnnouncementObserve(bool enable, tBTM_INQ_RESULTS_CB* p_results_cb) { - localAcceptlistMock->EnableTargetedAnnouncements(enable, p_results_cb); +namespace connection_manager { +void on_connection_timed_out(uint8_t app_id, const RawAddress& address) { + localConnTimeoutMock->OnConnectionTimedOut(app_id, address); } - -void BTM_LogHistory(const std::string& /*tag*/, const RawAddress& /*bd_addr*/, - const std::string& /*msg*/) {} - -namespace bluetooth { -namespace shim { -void set_target_announcements_filter(bool /*enable*/) {} -} // namespace shim -} // namespace bluetooth - -bool L2CA_ConnectFixedChnl(uint16_t /*fixed_cid*/, const RawAddress& /*bd_addr*/) { return false; } -uint16_t BTM_GetHCIConnHandle(RawAddress const&, tBT_TRANSPORT) { return 0xFFFF; } +} // namespace connection_manager namespace connection_manager { class BleConnectionManager : public testing::Test { void SetUp() override { - localAcceptlistMock = std::make_unique<AcceptlistMock>(); + localConnTimeoutMock = std::make_unique<MockConnTimeout>(); + /* extern */ test::mock_acl_manager_ = new bluetooth::hci::testing::MockAclManager(); + /* extern */ test::mock_controller_ = + new testing::NiceMock<bluetooth::hci::testing::MockControllerInterface>(); + ON_CALL(*test::mock_controller_, GetLeFilterAcceptListSize()).WillByDefault(Return(16)); + auto alarm_mock = AlarmMock::Get(); ON_CALL(*alarm_mock, AlarmNew(_)).WillByDefault(testing::Invoke([](const char* /*name*/) { // We must return something from alarm_new in tests, if we just return @@ -124,44 +92,43 @@ class BleConnectionManager : public testing::Test { void TearDown() override { connection_manager::reset(true); AlarmMock::Reset(); - localAcceptlistMock.reset(); + delete test::mock_controller_; + delete test::mock_acl_manager_; + localConnTimeoutMock.reset(); } }; -void on_connection_timed_out(uint8_t app_id, const RawAddress& address) { - localAcceptlistMock->OnConnectionTimedOut(app_id, address); -} - /** Verify that app can add a device to acceptlist, it is returned as interested * app, and then can remove the device later. */ TEST_F(BleConnectionManager, test_background_connection_add_remove) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).WillOnce(Return(true)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); std::set<tAPP_ID> apps = get_apps_connecting_to(address1); EXPECT_EQ(apps.size(), 1UL); EXPECT_EQ(apps.count(CLIENT1), 1UL); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(_, _)).Times(0); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(_, _)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(address1_hci)).Times(1); EXPECT_TRUE(background_connect_remove(CLIENT1, address1)); EXPECT_EQ(get_apps_connecting_to(address1).size(), 0UL); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify that multiple clients adding same device multiple times, result in * device being added to whtie list only once, also, that device is removed only * after last client removes it. */ TEST_F(BleConnectionManager, test_background_connection_multiple_clients) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).WillOnce(Return(true)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); + EXPECT_TRUE(background_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_add(CLIENT2, address1)); @@ -169,9 +136,9 @@ TEST_F(BleConnectionManager, test_background_connection_multiple_clients) { EXPECT_EQ(get_apps_connecting_to(address1).size(), 3UL); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(_, _)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(_, _)).Times(0); // removing from nonexisting client, should fail EXPECT_FALSE(background_connect_remove(CLIENT10, address1)); @@ -181,20 +148,21 @@ TEST_F(BleConnectionManager, test_background_connection_multiple_clients) { EXPECT_FALSE(background_connect_remove(CLIENT1, address1)); EXPECT_TRUE(background_connect_remove(CLIENT2, address1)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(address1_hci)).Times(1); EXPECT_TRUE(background_connect_remove(CLIENT3, address1)); EXPECT_EQ(get_apps_connecting_to(address1).size(), 0UL); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify adding/removing device to direct connection. */ TEST_F(BleConnectionManager, test_direct_connection_client) { // Direct connect attempt: use faster scan parameters, add to acceptlist, // start 30 timeout - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, true)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); @@ -205,9 +173,9 @@ TEST_F(BleConnectionManager, test_direct_connection_client) { // Client that don't do direct connection should fail attempt to stop it EXPECT_FALSE(direct_connect_remove(CLIENT2, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); // Removal should lower the connection parameters, and free the alarm. @@ -215,13 +183,13 @@ TEST_F(BleConnectionManager, test_direct_connection_client) { // acceptlist is in use, i.e. next connection attempt EXPECT_TRUE(direct_connect_remove(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify direct connection timeout does remove device from acceptlist, and * lower the connection scan parameters */ TEST_F(BleConnectionManager, test_direct_connect_timeout) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, true)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); alarm_callback_t alarm_callback = nullptr; void* alarm_data = nullptr; @@ -233,34 +201,36 @@ TEST_F(BleConnectionManager, test_direct_connect_timeout) { // Start direct connect attempt... EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); - EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT1, address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(1); + EXPECT_CALL(*localConnTimeoutMock, OnConnectionTimedOut(CLIENT1, address1)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); // simulate timeout seconds passed, alarm executing alarm_callback(alarm_data); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify that we properly handle successfull direct connection */ TEST_F(BleConnectionManager, test_direct_connection_success) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, true)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); // Start direct connect attempt... EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(address1_hci)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); // simulate event from lower layers - connections was established // successfully. on_connection_complete(address1); + + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify that we properly handle application unregistration */ @@ -272,35 +242,38 @@ TEST_F(BleConnectionManager, test_app_unregister) { * - unregistration of Client2 should trigger address2 removal */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, true)).Times(1); EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address2, false)).WillOnce(Return(true)); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); + + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address2_hci, false)).Times(1); EXPECT_TRUE(background_connect_add(CLIENT1, address2)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address2, true)).WillOnce(Return(true)); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); + + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address2_hci, true)).Times(1); EXPECT_TRUE(direct_connect_add(CLIENT2, address2)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(address1_hci)).Times(1); on_app_deregistered(CLIENT1); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(address2)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(address2_hci)).Times(1); on_app_deregistered(CLIENT2); - - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } /** Verify adding device to both direct connection and background connection. */ TEST_F(BleConnectionManager, test_direct_and_background_connect) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, true)).WillOnce(Return(true)); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, true)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_CALL(*AlarmMock::Get(), AlarmNew(_)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)).Times(1); // add device as both direct and background connection EXPECT_TRUE(direct_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); // not removing from acceptlist yet, as the background connection is still @@ -308,65 +281,65 @@ TEST_F(BleConnectionManager, test_direct_and_background_connect) { EXPECT_TRUE(direct_connect_remove(CLIENT1, address1)); // remove from acceptlist, because no more interest in device. - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(1); EXPECT_TRUE(background_connect_remove(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } TEST_F(BleConnectionManager, test_target_announement_connect) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT1, address1)); } TEST_F(BleConnectionManager, test_add_targeted_announement_when_allow_list_used) { /* Accept adding to allow list */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).WillOnce(Return(true)); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); /* This shall be called when registering announcements */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(1); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT2, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } TEST_F(BleConnectionManager, test_add_background_connect_when_targeted_announcement_are_enabled) { /* Accept adding to allow list */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(0); /* This shall be called when registering announcements */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT2, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } TEST_F(BleConnectionManager, test_re_add_background_connect_to_allow_list) { - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).Times(0); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_TRUE(background_connect_targeted_announcement_add(CLIENT2, address1)); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); /* Now remove app using targeted announcement and expect device * to be added to white list */ /* Accept adding to allow list */ - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).WillOnce(Return(true)); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); EXPECT_TRUE(background_connect_remove(CLIENT2, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(1); EXPECT_TRUE(background_connect_remove(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } TEST_F(BleConnectionManager, test_re_add_to_allow_list_after_timeout_with_multiple_clients) { @@ -374,15 +347,12 @@ TEST_F(BleConnectionManager, test_re_add_to_allow_list_after_timeout_with_multip alarm_callback_t alarm_callback = nullptr; void* alarm_data = nullptr; - /* Accept adding to allow list */ - ON_CALL(*localAcceptlistMock, AcceptlistAdd(address1, _)).WillByDefault(Return(true)); - - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).Times(1); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); EXPECT_TRUE(background_connect_add(CLIENT1, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); EXPECT_CALL(*AlarmMock::Get(), AlarmSetOnMloop(_, _, _, _)) .Times(1) @@ -390,16 +360,16 @@ TEST_F(BleConnectionManager, test_re_add_to_allow_list_after_timeout_with_multip // Start direct connect attempt... EXPECT_TRUE(direct_connect_add(CLIENT2, address1)); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); // simulate timeout seconds passed, alarm executing - EXPECT_CALL(*localAcceptlistMock, OnConnectionTimedOut(CLIENT2, address1)).Times(1); - EXPECT_CALL(*localAcceptlistMock, AcceptlistRemove(_)).Times(0); - EXPECT_CALL(*localAcceptlistMock, AcceptlistAdd(address1, false)).Times(1); + EXPECT_CALL(*localConnTimeoutMock, OnConnectionTimedOut(CLIENT2, address1)).Times(1); + EXPECT_CALL(*test::mock_acl_manager_, CancelLeConnect(_)).Times(0); + EXPECT_CALL(*test::mock_acl_manager_, CreateLeConnection(address1_hci, false)).Times(1); EXPECT_CALL(*AlarmMock::Get(), AlarmFree(_)).Times(1); alarm_callback(alarm_data); - Mock::VerifyAndClearExpectations(localAcceptlistMock.get()); + Mock::VerifyAndClearExpectations(test::mock_acl_manager_); } } // namespace connection_manager diff --git a/system/stack/test/fuzzers/Android.bp b/system/stack/test/fuzzers/Android.bp index 30ad5a5092..91bc857f8f 100644 --- a/system/stack/test/fuzzers/Android.bp +++ b/system/stack/test/fuzzers/Android.bp @@ -89,4 +89,11 @@ cc_defaults { "libutils", "server_configurable_flags", ], + target: { + android: { + static_libs: [ + "libperfetto_client_experimental", + ], + }, + }, } 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 c965355dcc..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", @@ -142,6 +137,13 @@ filegroup { } filegroup { + name: "TestMockBtaRfcMetrics", + srcs: [ + "mock/mock_bta_rfc_metrics.cc", + ], +} + +filegroup { name: "TestMockBtaScn", srcs: [ "mock/mock_bta_scn.cc", @@ -189,6 +191,7 @@ filegroup { ":TestMockBtaLeAudioHalVerifier", ":TestMockBtaPan", ":TestMockBtaRas", + ":TestMockBtaRfcMetrics", ":TestMockBtaSdp", ":TestMockBtaSys", ":TestMockBtaVc", @@ -290,6 +293,13 @@ filegroup { } filegroup { + name: "TestMockStackRfcommMetrics", + srcs: [ + "mock/mock_stack_rfcomm_metrics.cc", + ], +} + +filegroup { name: "TestMockStackRnr", srcs: [ "mock/mock_stack_rnr_interface.cc", @@ -339,13 +349,6 @@ filegroup { } filegroup { - name: "TestMockLegacyHciCommands", - srcs: [ - "mock/mock_hcic_*.cc", - ], -} - -filegroup { name: "TestMockMainShimEntry", srcs: [ "mock/mock_main_shim_entry.cc", @@ -482,13 +485,6 @@ filegroup { } filegroup { - name: "TestMockStackEatt", - srcs: [ - "mock/mock_stack_eatt*.cc", - ], -} - -filegroup { name: "TestMockStackGatt", srcs: [ "mock/mock_stack_gatt*.cc", @@ -496,13 +492,6 @@ filegroup { } filegroup { - name: "TestMockRustFfi", - srcs: [ - "mock/mock_rust_ffi_connection*.cc", - ], -} - -filegroup { name: "TestMockStackBtu", srcs: [ "mock/mock_stack_btu*.cc", @@ -510,13 +499,6 @@ filegroup { } filegroup { - name: "TestMockMainBte", - srcs: [ - "mock/mock_main_bte*.cc", - ], -} - -filegroup { name: "TestMockBtu", srcs: [ "mock/mock_btu_*cc", diff --git a/system/test/headless/Android.bp b/system/test/headless/Android.bp index 09a08f8fec..7b1b487154 100644 --- a/system/test/headless/Android.bp +++ b/system/test/headless/Android.bp @@ -145,6 +145,7 @@ cc_binary { "android.hardware.bluetooth@1.1", "android.system.suspend.control-V1-ndk", "libexpresslog", + "libperfetto_client_experimental", "libstatslog_express", "libtextclassifier_hash_static", ], 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_rfc_metrics.cc b/system/test/mock/mock_bta_rfc_metrics.cc new file mode 100644 index 0000000000..9c1c0cced2 --- /dev/null +++ b/system/test/mock/mock_bta_rfc_metrics.cc @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#include "bta/include/bta_jv_api.h" +#include "bta/include/bta_rfcomm_metrics.h" +#include "test/common/mock_functions.h" +#include "types/raw_address.h" + +void bta_collect_rfc_metrics_after_sdp_fail(tBTA_JV_STATUS /* sdp_status */, RawAddress /* addr */, + int /* app_uid */, int /* security */, + bool /* is_server */, uint64_t /* sdp_duration */) { + inc_func_call_count(__func__); +} + +void bta_collect_rfc_metrics_after_port_fail(tPORT_RESULT /* port_result */, + bool /* sdp_initiated */, + tBTA_JV_STATUS /* sdp_status */, RawAddress /* addr */, + int /* app_uid */, int /* security */, + bool /* is_server */, uint64_t /* sdp_duration_ms */) { + inc_func_call_count(__func__); +} diff --git a/system/test/mock/mock_main_shim_acl_api.cc b/system/test/mock/mock_main_shim_acl_api.cc index f8d1f18fe2..3d257f1a5a 100644 --- a/system/test/mock/mock_main_shim_acl_api.cc +++ b/system/test/mock/mock_main_shim_acl_api.cc @@ -35,14 +35,6 @@ void bluetooth::shim::ACL_CreateClassicConnection(const RawAddress& /* raw_addre void bluetooth::shim::ACL_CancelClassicConnection(const RawAddress& /* raw_address */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_AcceptLeConnectionFrom(const tBLE_BD_ADDR& /* legacy_address_with_type */, - bool /* is_direct */) { - inc_func_call_count(__func__); -} -void bluetooth::shim::ACL_IgnoreLeConnectionFrom( - const tBLE_BD_ADDR& /* legacy_address_with_type */) { - inc_func_call_count(__func__); -} void bluetooth::shim::ACL_ConfigureLePrivacy(bool /* is_le_privacy_enabled */) { inc_func_call_count(__func__); } @@ -54,7 +46,6 @@ void bluetooth::shim::ACL_Disconnect(uint16_t /* handle */, bool /* is_classic * tHCI_STATUS /* reason */, std::string /* comment */) { inc_func_call_count(__func__); } -void bluetooth::shim::ACL_IgnoreAllLeConnections() { inc_func_call_count(__func__); } void bluetooth::shim::ACL_ReadConnectionAddress(uint16_t /* handle */, RawAddress& /* conn_addr */, tBLE_ADDR_TYPE* /* p_addr_type */, bool /* ota_address */) { diff --git a/system/test/mock/mock_main_shim_acl_api.h b/system/test/mock/mock_main_shim_acl_api.h index 782bf4ae55..ab891673e3 100644 --- a/system/test/mock/mock_main_shim_acl_api.h +++ b/system/test/mock/mock_main_shim_acl_api.h @@ -42,19 +42,6 @@ namespace test { namespace mock { namespace main_shim_acl_api { -// Shared state between mocked functions and tests -// Name: ACL_AcceptLeConnectionFrom -// Params: const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct -// Return: bool -struct ACL_AcceptLeConnectionFrom { - std::function<void(const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct)> body{ - [](const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) {}}; - void operator()(const tBLE_BD_ADDR& legacy_address_with_type, bool is_direct) { - body(legacy_address_with_type, is_direct); - } -}; -extern struct ACL_AcceptLeConnectionFrom ACL_AcceptLeConnectionFrom; - // Name: ACL_AddToAddressResolution // Params: const tBLE_BD_ADDR& legacy_address_with_type, const Octet16& // peer_irk, const Octet16& local_irk Return: void @@ -157,25 +144,6 @@ struct ACL_Disconnect { }; extern struct ACL_Disconnect ACL_Disconnect; -// Name: ACL_IgnoreAllLeConnections -// Params: -// Return: void -struct ACL_IgnoreAllLeConnections { - std::function<void()> body{[]() {}}; - void operator()() { body(); } -}; -extern struct ACL_IgnoreAllLeConnections ACL_IgnoreAllLeConnections; - -// Name: ACL_IgnoreLeConnectionFrom -// Params: const tBLE_BD_ADDR& legacy_address_with_type -// Return: void -struct ACL_IgnoreLeConnectionFrom { - std::function<void(const tBLE_BD_ADDR& legacy_address_with_type)> body{ - [](const tBLE_BD_ADDR& legacy_address_with_type) {}}; - void operator()(const tBLE_BD_ADDR& legacy_address_with_type) { body(legacy_address_with_type); } -}; -extern struct ACL_IgnoreLeConnectionFrom ACL_IgnoreLeConnectionFrom; - // Name: ACL_ReadConnectionAddress // Params: uint16_t handle, RawAddress& conn_addr, tBLE_ADDR_TYPE*, bool // p_addr_type Return: void diff --git a/system/test/mock/mock_main_shim_metrics_api.cc b/system/test/mock/mock_main_shim_metrics_api.cc index 841cd759a9..259fa2dcfb 100644 --- a/system/test/mock/mock_main_shim_metrics_api.cc +++ b/system/test/mock/mock_main_shim_metrics_api.cc @@ -58,6 +58,15 @@ struct LogMetricManufacturerInfo LogMetricManufacturerInfo; struct LogMetricLeConnectionStatus LogMetricLeConnectionStatus; struct LogMetricLeDeviceInAcceptList LogMetricLeDeviceInAcceptList; 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 @@ -207,4 +216,59 @@ void bluetooth::shim::LogMetricLeConnectionLifecycle(bluetooth::hci::Address add inc_func_call_count(__func__); test::mock::main_shim_metrics_api::LogMetricLeConnectionLifecycle(address, is_connect, is_direct); } +void bluetooth::shim::LogMetricLeConnectionCompletion(bluetooth::hci::Address address, + bluetooth::hci::ErrorCode reason, + bool is_locally_initiated) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricLeConnectionCompletion(address, reason, + is_locally_initiated); +} +void bluetooth::shim::LogMetricRfcommConnectionAtClose( + const RawAddress& raw_address, android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, int32_t open_duration_ms, + int32_t uid, android::bluetooth::BtaStatus sdp_status, bool is_server, bool sdp_initiated, + int32_t sdp_duration_ms) { + inc_func_call_count(__func__); + test::mock::main_shim_metrics_api::LogMetricRfcommConnectionAtClose( + raw_address, close_reason, security, last_event, previous_state, open_duration_ms, uid, + sdp_status, is_server, sdp_initiated, sdp_duration_ms); +} + +void bluetooth::shim::LogMetricLeConnectionRejected(bluetooth::hci::Address address) { + inc_func_call_count(__func__); + 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 f5f177b5f4..8a245bbe37 100644 --- a/system/test/mock/mock_main_shim_metrics_api.h +++ b/system/test/mock/mock_main_shim_metrics_api.h @@ -351,6 +351,129 @@ struct LogMetricLeConnectionLifecycle { }; extern struct LogMetricLeConnectionLifecycle LogMetricLeConnectionLifecycle; +// Name: LogMetricLeConnectionCompletion +// Params: bluetooth::hci::Address, hci::ErrorCode reason, bool +// is_locally_initiated +// Returns: void +struct LogMetricLeConnectionCompletion { + std::function<void(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated)> + body{[](bluetooth::hci::Address /* address */, bluetooth::hci::ErrorCode /* reason */, + bool /* is_locally_initiated */) {}}; + void operator()(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated) { + body(address, reason, is_locally_initiated); + } +}; +extern struct LogMetricLeConnectionCompletion LogMetricLeConnectionCompletion; + +// Name: LogMetricRfcommConnectionAtClose +// Params: const RawAddress& raw_address, android::bluetooth::rfcomm::PortResult close_reason, +// android::bluetooth::rfcomm::SocketConnectionSecurity security, +// android::bluetooth::rfcomm::RfcommPortEvent last_event, +// android::bluetooth::rfcomm::RfcommPortState previous_state, int32_t open_duration_ms, +// int32_t uid, android::bluetooth::BtaStatus sdp_status, bool is_server, +// bool sdp_initiated, int32_t sdp_duration_ms +// Returns: void +struct LogMetricRfcommConnectionAtClose { + std::function<void( + const RawAddress& raw_address, android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, int32_t open_duration_ms, + int32_t uid, android::bluetooth::BtaStatus sdp_status, bool is_server, bool sdp_initiated, + int32_t sdp_duration_ms)> + body{[](const RawAddress& /* raw_address */, + android::bluetooth::rfcomm::PortResult /* close_reason */, + android::bluetooth::rfcomm::SocketConnectionSecurity /* security */, + android::bluetooth::rfcomm::RfcommPortEvent /* last_event */, + android::bluetooth::rfcomm::RfcommPortState /* previous_state */, + int32_t /* open_duration_ms */, int32_t /* uid */, + android::bluetooth::BtaStatus /* sdp_status */, bool /* is_server */, + bool /* sdp_initiated */, int32_t /* sdp_duration_ms */) {}}; + void operator()(const RawAddress& raw_address, + android::bluetooth::rfcomm::PortResult close_reason, + android::bluetooth::rfcomm::SocketConnectionSecurity security, + android::bluetooth::rfcomm::RfcommPortEvent last_event, + android::bluetooth::rfcomm::RfcommPortState previous_state, + int32_t open_duration_ms, int32_t uid, android::bluetooth::BtaStatus sdp_status, + bool is_server, bool sdp_initiated, int32_t sdp_duration_ms) { + body(raw_address, close_reason, security, last_event, previous_state, open_duration_ms, uid, + sdp_status, is_server, sdp_initiated, sdp_duration_ms); + } +}; +extern struct LogMetricRfcommConnectionAtClose LogMetricRfcommConnectionAtClose; + +// Name: LogMetricLeConnectionRejected +// Params: bluetooth::hci::Address +// Returns: void +struct LogMetricLeConnectionRejected { + std::function<void(bluetooth::hci::Address address)> body{ + [](bluetooth::hci::Address /* address */) {}}; + 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_btm_dev.cc b/system/test/mock/mock_stack_btm_dev.cc index 1dc2da8646..60f88b0d6e 100644 --- a/system/test/mock/mock_stack_btm_dev.cc +++ b/system/test/mock/mock_stack_btm_dev.cc @@ -111,9 +111,9 @@ bool maybe_resolve_address(RawAddress* bda, tBLE_ADDR_TYPE* bda_type) { inc_func_call_count(__func__); return test::mock::stack_btm_dev::maybe_resolve_address(bda, bda_type); } -const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& /* bd_addr */) { +const tBLE_BD_ADDR BTM_Sec_GetAddressWithType(const RawAddress& bd_addr) { inc_func_call_count(__func__); - return {}; + return tBLE_BD_ADDR{.type = BLE_ADDR_PUBLIC, .bda = bd_addr}; } void DumpsysRecord(int /* fd */) { 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 f2336668e1..751fcc3794 100644 --- a/system/test/mock/mock_stack_metrics_logging.cc +++ b/system/test/mock/mock_stack_metrics_logging.cc @@ -55,6 +55,14 @@ struct log_mmc_transcode_rtt_stats log_mmc_transcode_rtt_stats; struct log_le_connection_status log_le_connection_status; 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 @@ -152,4 +160,46 @@ void log_le_connection_lifecycle(bluetooth::hci::Address address, bool is_connec inc_func_call_count(__func__); test::mock::stack_metrics_logging::log_le_connection_lifecycle(address, is_connect, is_direct); } + +void log_le_connection_completion(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated) { + inc_func_call_count(__func__); + test::mock::stack_metrics_logging::log_le_connection_completion(address, reason, + is_locally_initiated); +} + +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 413cbea629..d807c1f761 100644 --- a/system/test/mock/mock_stack_metrics_logging.h +++ b/system/test/mock/mock_stack_metrics_logging.h @@ -234,6 +234,71 @@ struct log_le_connection_lifecycle { }; extern struct log_le_device_in_accept_list log_le_device_in_accept_list; +// Name: log_le_connection_completion +struct log_le_connection_completion { + std::function<void(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated)> + body{[](bluetooth::hci::Address /* address */, bluetooth::hci::ErrorCode /* reason */, + bool /* is locally initiated */) {}}; + void operator()(bluetooth::hci::Address address, bluetooth::hci::ErrorCode reason, + bool is_locally_initiated) { + body(address, reason, is_locally_initiated); + } +}; +extern struct log_le_connection_completion log_le_connection_completion; + +// Name: log_le_connection_rejected +struct log_le_connection_rejected { + std::function<void(bluetooth::hci::Address)> body{[](bluetooth::hci::Address /* address */) {}}; + void operator()(bluetooth::hci::Address address) { body(address); } +}; + +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 diff --git a/system/test/mock/mock_stack_rfcomm_metrics.cc b/system/test/mock/mock_stack_rfcomm_metrics.cc new file mode 100644 index 0000000000..f44af222b1 --- /dev/null +++ b/system/test/mock/mock_stack_rfcomm_metrics.cc @@ -0,0 +1,21 @@ +/* + * 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. + */ + +#include "rfc_metrics.h" +#include "stack/rfcomm/port_int.h" +#include "test/common/mock_functions.h" + +void port_collect_attempt_metrics(tPORT* /* p_port */) { inc_func_call_count(__func__); } diff --git a/system/test/suite/Android.bp b/system/test/suite/Android.bp index ac4a5e3b24..b916f691d5 100644 --- a/system/test/suite/Android.bp +++ b/system/test/suite/Android.bp @@ -148,6 +148,7 @@ cc_test { "android.hardware.bluetooth@1.1", "android.hardware.common-V2-ndk", "android.hardware.common.fmq-V1-ndk", + "libperfetto_client_experimental", ], }, host: {}, |