summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Android.bp2
-rw-r--r--TEST_MAPPING6
-rw-r--r--android/ChannelSoundingTestApp/app/src/main/java/com/android/bluetooth/channelsoundingtestapp/BleConnectionViewModel.java12
-rw-r--r--android/app/Android.bp38
-rw-r--r--android/app/aidl/android/bluetooth/IBluetooth.aidl3
-rw-r--r--android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl2
-rw-r--r--android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl2
-rw-r--r--android/app/jni/com_android_bluetooth_avrcp_target.cpp7
-rw-r--r--android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp7
-rw-r--r--android/app/jni/com_android_bluetooth_gatt.cpp137
-rw-r--r--android/app/jni/com_android_bluetooth_le_audio.cpp52
-rw-r--r--android/app/lib-lint-baseline.xml489
-rw-r--r--android/app/src/com/android/bluetooth/BluetoothMethodProxy.java2
-rw-r--r--android/app/src/com/android/bluetooth/ObexAppParameters.java10
-rw-r--r--android/app/src/com/android/bluetooth/ObexServerSockets.java6
-rw-r--r--android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java4
-rw-r--r--android/app/src/com/android/bluetooth/a2dp/A2dpService.java41
-rw-r--r--android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java24
-rw-r--r--android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java8
-rw-r--r--android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java4
-rw-r--r--android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java16
-rw-r--r--android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java2
-rw-r--r--android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java7
-rw-r--r--android/app/src/com/android/bluetooth/avrcp/helpers/AvrcpVersion.java4
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java43
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java2
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java13
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java34
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java14
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java2
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java2
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java4
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java2
-rw-r--r--android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java12
-rw-r--r--android/app/src/com/android/bluetooth/bas/BatteryService.java25
-rw-r--r--android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java36
-rw-r--r--android/app/src/com/android/bluetooth/bass_client/BaseData.java16
-rw-r--r--android/app/src/com/android/bluetooth/bass_client/BassClientService.java55
-rw-r--r--android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java74
-rw-r--r--android/app/src/com/android/bluetooth/bass_client/BassUtils.java9
-rw-r--r--android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java17
-rw-r--r--android/app/src/com/android/bluetooth/btservice/AdapterProperties.java61
-rw-r--r--android/app/src/com/android/bluetooth/btservice/AdapterService.java308
-rw-r--r--android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java4
-rw-r--r--android/app/src/com/android/bluetooth/btservice/BondStateMachine.java27
-rw-r--r--android/app/src/com/android/bluetooth/btservice/DataMigration.java4
-rw-r--r--android/app/src/com/android/bluetooth/btservice/MetricsLogger.java6
-rw-r--r--android/app/src/com/android/bluetooth/btservice/PhonePolicy.java10
-rw-r--r--android/app/src/com/android/bluetooth/btservice/RemoteDevices.java50
-rw-r--r--android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java9
-rw-r--r--android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java10
-rw-r--r--android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java207
-rw-r--r--android/app/src/com/android/bluetooth/btservice/storage/Metadata.java16
-rw-r--r--android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java24
-rw-r--r--android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java40
-rw-r--r--android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java33
-rw-r--r--android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java51
-rw-r--r--android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java38
-rw-r--r--android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java2
-rw-r--r--android/app/src/com/android/bluetooth/gatt/ContextMap.java6
-rw-r--r--android/app/src/com/android/bluetooth/gatt/DistanceMeasurementBinder.kt53
-rw-r--r--android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java167
-rw-r--r--android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java39
-rw-r--r--android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java2
-rw-r--r--android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java5
-rw-r--r--android/app/src/com/android/bluetooth/gatt/GattService.java39
-rw-r--r--android/app/src/com/android/bluetooth/hap/HapClientBinder.java13
-rw-r--r--android/app/src/com/android/bluetooth/hap/HapClientService.java22
-rw-r--r--android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java17
-rw-r--r--android/app/src/com/android/bluetooth/hfp/AtPhonebook.java2
-rw-r--r--android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java95
-rw-r--r--android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java5
-rw-r--r--android/app/src/com/android/bluetooth/hfp/HeadsetService.java91
-rw-r--r--android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java50
-rw-r--r--android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java15
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java64
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java72
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java2
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java9
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java4
-rw-r--r--android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java10
-rw-r--r--android/app/src/com/android/bluetooth/hid/HidDeviceService.java22
-rw-r--r--android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java15
-rw-r--r--android/app/src/com/android/bluetooth/hid/HidHostService.java83
-rw-r--r--android/app/src/com/android/bluetooth/le_audio/LeAudioService.java134
-rw-r--r--android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java55
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/BatchScanThrottler.java (renamed from android/app/src/com/com/android/bluetooth/le_scan/BatchScanThrottler.java)6
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java172
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScanClient.java98
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScanController.java282
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java75
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScanManager.java509
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java4
-rw-r--r--android/app/src/com/android/bluetooth/le_scan/ScannerMap.java14
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java2
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java14
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapContent.java58
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java2
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java8
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java101
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapService.java18
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java6
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java8
-rw-r--r--android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java6
-rw-r--r--android/app/src/com/android/bluetooth/map/SmsMmsContacts.java4
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/MapClientService.java42
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/MasClient.java2
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java41
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java12
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/MnsService.java9
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java7
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/obex/RequestPushMessage.java2
-rw-r--r--android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java8
-rw-r--r--android/app/src/com/android/bluetooth/mcp/McpService.java5
-rw-r--r--android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java8
-rw-r--r--android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java4
-rw-r--r--android/app/src/com/android/bluetooth/notification/NotificationHelperService.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivity.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java4
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java33
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java4
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java22
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppService.java8
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java4
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/BluetoothShare.java2
-rw-r--r--android/app/src/com/android/bluetooth/opp/Constants.java38
-rw-r--r--android/app/src/com/android/bluetooth/pan/PanNativeInterface.java16
-rw-r--r--android/app/src/com/android/bluetooth/pan/PanService.java45
-rw-r--r--android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java18
-rw-r--r--android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java59
-rw-r--r--android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java9
-rw-r--r--android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java6
-rw-r--r--android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java34
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/PbapClientAccountManager.java2
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java7
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java33
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java40
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java42
-rw-r--r--android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java26
-rw-r--r--android/app/src/com/android/bluetooth/sap/SapMessage.java2
-rw-r--r--android/app/src/com/android/bluetooth/sap/SapRilReceiver.java4
-rw-r--r--android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java4
-rw-r--r--android/app/src/com/android/bluetooth/sap/SapServer.java16
-rw-r--r--android/app/src/com/android/bluetooth/sap/SapService.java26
-rw-r--r--android/app/src/com/android/bluetooth/tbs/TbsGatt.java14
-rw-r--r--android/app/src/com/android/bluetooth/tbs/TbsService.java5
-rw-r--r--android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java235
-rw-r--r--android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java2
-rw-r--r--android/app/src/com/android/bluetooth/vc/VolumeControlService.java6
-rw-r--r--android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java15
-rw-r--r--android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java505
-rw-r--r--android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java2
-rw-r--r--android/app/tests/unit/Android.bp1
-rw-r--r--android/app/tests/unit/AndroidTest.xml2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/TestUtils.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java7
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java89
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java10
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java16
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/audio_util/MediaPlayerListTest.java10
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/audio_util/MetadataTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcp/AvrcpBipObexServerTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java29
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java5
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java10
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java24
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java213
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java35
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java20
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java18
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java29
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java33
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java36
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java37
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java161
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientStateMachineTest.java68
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java14
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java12
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java101
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java66
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java12
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java17
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java11
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java72
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json357
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementBinderTest.java18
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java10
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceBinderTest.java5
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/gatt/GattServiceTest.java9
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java24
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java5
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hearingaid/HearingAidNativeInterfaceTest.java9
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/AtPhonebookTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java22
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java105
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java245
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java126
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java9
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java82
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java11
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java54
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java114
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioStateMachineTest.java41
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorMergedPatternListTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/PeriodicScanManagerTest.java7
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanControllerTest.java65
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanFilterQueueTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java116
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/le_scan/ScannerMapTest.java9
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java7
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java50
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java21
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java75
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexServerSessionTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppTransferTest.java140
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java47
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java6
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java96
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientAccountManagerTest.java2
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java18
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java82
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java17
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java207
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java6
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java6
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverHidlTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java4
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java14
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java19
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java8
-rw-r--r--android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java6
-rw-r--r--android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java26
-rw-r--r--android/pandora/server/src/A2dp.kt16
-rw-r--r--android/pandora/server/src/A2dpSink.kt25
-rw-r--r--android/pandora/server/src/Asha.kt27
-rw-r--r--android/pandora/server/src/GattInstance.kt54
-rw-r--r--android/pandora/server/src/Hap.kt5
-rw-r--r--android/pandora/server/src/Hfp.kt14
-rw-r--r--android/pandora/server/src/HfpHandsfree.kt36
-rw-r--r--android/pandora/server/src/Host.kt7
-rw-r--r--android/pandora/server/src/LeAudio.kt11
-rw-r--r--android/pandora/server/src/Pan.kt9
-rw-r--r--android/pandora/server/src/Vcp.kt8
-rw-r--r--android/pandora/test/Android.bp12
-rw-r--r--android/pandora/test/a2dp_test.py4
-rw-r--r--flags/bta_dm.aconfig10
-rw-r--r--flags/gap.aconfig4
-rw-r--r--flags/pairing.aconfig10
-rw-r--r--flags/rfcomm.aconfig12
-rw-r--r--framework/java/android/bluetooth/BluetoothA2dp.java49
-rw-r--r--framework/java/android/bluetooth/BluetoothA2dpSink.java42
-rw-r--r--framework/java/android/bluetooth/BluetoothAdapter.java19
-rw-r--r--framework/java/android/bluetooth/BluetoothAvrcpController.java8
-rw-r--r--framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java11
-rw-r--r--framework/java/android/bluetooth/BluetoothDevice.java32
-rw-r--r--framework/java/android/bluetooth/BluetoothGatt.java9
-rw-r--r--framework/java/android/bluetooth/BluetoothGattServer.java6
-rw-r--r--framework/java/android/bluetooth/BluetoothHapClient.java19
-rw-r--r--framework/java/android/bluetooth/BluetoothHeadset.java46
-rw-r--r--framework/java/android/bluetooth/BluetoothHeadsetClient.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothHearingAid.java41
-rw-r--r--framework/java/android/bluetooth/BluetoothHidDevice.java14
-rw-r--r--framework/java/android/bluetooth/BluetoothHidHost.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothLeAudio.java33
-rw-r--r--framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java11
-rw-r--r--framework/java/android/bluetooth/BluetoothManager.java9
-rw-r--r--framework/java/android/bluetooth/BluetoothMap.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothMapClient.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothPan.java15
-rw-r--r--framework/java/android/bluetooth/BluetoothPbap.java19
-rw-r--r--framework/java/android/bluetooth/BluetoothPbapClient.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothSap.java16
-rw-r--r--framework/java/android/bluetooth/BluetoothSocket.java2
-rw-r--r--framework/java/android/bluetooth/BluetoothUtils.java8
-rw-r--r--framework/java/android/bluetooth/BluetoothVolumeControl.java11
-rw-r--r--framework/java/android/bluetooth/le/BluetoothLeScanner.java65
-rw-r--r--framework/tests/bumble/Android.bp6
-rw-r--r--framework/tests/bumble/AndroidManifest.xml1
-rw-r--r--framework/tests/bumble/AndroidTest.xml2
-rw-r--r--framework/tests/bumble/doc/guide.md4
-rw-r--r--framework/tests/bumble/doc/overview.md4
-rw-r--r--framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java18
-rw-r--r--framework/tests/bumble/src/android/bluetooth/DckGattTest.kt34
-rw-r--r--framework/tests/bumble/src/android/bluetooth/DckTestRule.kt17
-rw-r--r--framework/tests/bumble/src/android/bluetooth/GattClientTest.java17
-rw-r--r--framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java10
-rw-r--r--framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java10
-rw-r--r--framework/tests/bumble/src/android/bluetooth/RfcommTest.kt98
-rw-r--r--framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java22
-rw-r--r--framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java15
-rw-r--r--framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java42
-rw-r--r--framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java2
-rw-r--r--framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java10
-rw-r--r--framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt450
-rw-r--r--framework/tests/unit/src/android/bluetooth/BluetoothCodecStatusTest.java70
-rw-r--r--offload/hal/Android.bp16
-rw-r--r--offload/hal/include/hal/ffi.h111
-rw-r--r--offload/hal/service.rs18
-rw-r--r--system/Android.bp34
-rw-r--r--system/TEST_MAPPING5
-rw-r--r--system/audio/asrc/asrc_resampler.cc4
-rw-r--r--system/audio/asrc/asrc_resampler_test.cc1
-rw-r--r--system/audio_hal_interface/Android.bp2
-rw-r--r--system/audio_hal_interface/aidl/le_audio_software_aidl.cc5
-rw-r--r--system/audio_hal_interface/aidl/le_audio_utils.cc6
-rw-r--r--system/audio_hal_interface/aidl/le_audio_utils_unittest.cc4
-rw-r--r--system/audio_hal_interface/fuzzer/Android.bp3
-rw-r--r--system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp2
-rw-r--r--system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp2
-rw-r--r--system/audio_hal_interface/hidl/client_interface_hidl.cc1
-rw-r--r--system/audio_hal_interface/le_audio_software.cc24
-rw-r--r--system/bta/Android.bp100
-rw-r--r--system/bta/ag/bta_ag_sco.cc10
-rw-r--r--system/bta/csis/csis_client.cc6
-rw-r--r--system/bta/csis/csis_client_test.cc6
-rw-r--r--system/bta/dm/bta_dm_disc.cc53
-rw-r--r--system/bta/dm/bta_dm_disc_int.h7
-rw-r--r--system/bta/gmap/gmap_client_test.cc3
-rw-r--r--system/bta/has/has_client.cc2
-rw-r--r--system/bta/has/has_client_test.cc10
-rw-r--r--system/bta/hearing_aid/hearing_aid.cc2
-rw-r--r--system/bta/hearing_aid/hearing_aid_audio_source.cc2
-rw-r--r--system/bta/hh/bta_hh_le.cc4
-rw-r--r--system/bta/include/bta_le_audio_api.h7
-rw-r--r--system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc6
-rw-r--r--system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc8
-rw-r--r--system/bta/le_audio/audio_set_scenarios.json20
-rw-r--r--system/bta/le_audio/broadcaster/broadcaster_test.cc16
-rw-r--r--system/bta/le_audio/broadcaster/state_machine.cc27
-rw-r--r--system/bta/le_audio/broadcaster/state_machine_test.cc56
-rw-r--r--system/bta/le_audio/client.cc245
-rw-r--r--system/bta/le_audio/client_linux.cc4
-rw-r--r--system/bta/le_audio/codec_manager.cc5
-rw-r--r--system/bta/le_audio/codec_manager_test.cc14
-rw-r--r--system/bta/le_audio/device_groups.cc105
-rw-r--r--system/bta/le_audio/device_groups.h79
-rw-r--r--system/bta/le_audio/devices.cc61
-rw-r--r--system/bta/le_audio/devices.h9
-rw-r--r--system/bta/le_audio/devices_test.cc434
-rw-r--r--system/bta/le_audio/le_audio_client_test.cc368
-rw-r--r--system/bta/le_audio/le_audio_types.h34
-rw-r--r--system/bta/le_audio/le_audio_utils.cc2
-rw-r--r--system/bta/le_audio/mock_state_machine.h4
-rw-r--r--system/bta/le_audio/state_machine.cc232
-rw-r--r--system/bta/le_audio/state_machine.h4
-rw-r--r--system/bta/le_audio/state_machine_test.cc777
-rw-r--r--system/bta/le_audio/storage_helper.cc47
-rw-r--r--system/bta/test/bta_ag_sco_test.cc2
-rw-r--r--system/bta/test/bta_ag_test.cc10
-rw-r--r--system/bta/test/bta_gatt_client_test.cc60
-rw-r--r--system/bta/test/common/btif_storage_mock.cc11
-rw-r--r--system/bta/test/common/btif_storage_mock.h9
-rw-r--r--system/bta/test/common/btm_api_mock.cc9
-rw-r--r--system/bta/test/common/btm_api_mock.h9
-rw-r--r--system/bta/vc/devices_test.cc11
-rw-r--r--system/bta/vc/vc.cc2
-rw-r--r--system/bta/vc/vc_test.cc10
-rw-r--r--system/btcore/Android.bp24
-rw-r--r--system/btcore/src/osi_module.cc7
-rw-r--r--system/btcore/test/device_class_test.cc6
-rw-r--r--system/btif/Android.bp114
-rw-r--r--system/btif/include/bluetooth.h (renamed from system/osi/include/thread_scheduler.h)9
-rw-r--r--system/btif/include/btif_api.h11
-rw-r--r--system/btif/include/btif_profile_storage.h7
-rw-r--r--system/btif/include/btif_storage.h7
-rw-r--r--system/btif/src/bluetooth.cc23
-rw-r--r--system/btif/src/btif_a2dp_sink.cc45
-rw-r--r--system/btif/src/btif_a2dp_source.cc33
-rw-r--r--system/btif/src/btif_dm.cc141
-rw-r--r--system/btif/src/btif_hf_client.cc98
-rw-r--r--system/btif/src/btif_jni_task.cc2
-rw-r--r--system/btif/src/btif_le_audio.cc8
-rw-r--r--system/btif/src/btif_profile_storage.cc24
-rw-r--r--system/btif/src/stack_manager.cc19
-rw-r--r--system/btif/test/btif_keystore_test.cc63
-rw-r--r--system/btif/test/btif_rc_test.cc2
-rw-r--r--system/common/benchmark/thread_performance_benchmark.cc8
-rw-r--r--system/common/message_loop_thread.cc18
-rw-r--r--system/common/message_loop_thread.h15
-rw-r--r--system/common/message_loop_thread_unittest.cc36
-rw-r--r--system/common/repeating_timer.cc14
-rw-r--r--system/common/repeating_timer.h4
-rw-r--r--system/common/repeating_timer_unittest.cc14
-rw-r--r--system/common/test/thread_performance_test.cc6
-rw-r--r--system/device/fuzzer/Android.bp3
-rw-r--r--system/device/fuzzer/btdevice_esco_fuzzer.cpp3
-rw-r--r--system/device/src/interop.cc5
-rw-r--r--system/gd/hal/hci_hal_android.cc8
-rw-r--r--system/gd/hal/hci_hal_host.cc8
-rw-r--r--system/gd/hal/hci_hal_host_rootcanal.cc5
-rw-r--r--system/gd/hal/snoop_logger.cc75
-rw-r--r--system/gd/hal/snoop_logger.h20
-rw-r--r--system/gd/hal/snoop_logger_socket_thread.cc2
-rw-r--r--system/gd/hal/snoop_logger_socket_thread.h2
-rw-r--r--system/gd/hal/snoop_logger_test.cc691
-rw-r--r--system/gd/hal/socket_hal_android.cc5
-rw-r--r--system/gd/hci/BUILD.gn2
-rw-r--r--system/gd/hci/acl_manager.cc4
-rw-r--r--system/gd/hci/acl_manager.h1
-rw-r--r--system/gd/hci/acl_manager/le_impl.h39
-rw-r--r--system/gd/hci/address.cc132
-rw-r--r--system/gd/hci/class_of_device.cc130
-rw-r--r--system/gd/hci/distance_measurement_manager.cc115
-rw-r--r--system/gd/hci/msft.cc26
-rw-r--r--system/gd/rust/linux/client/src/callbacks.rs4
-rw-r--r--system/gd/rust/linux/client/src/dbus_iface.rs4
-rw-r--r--system/gd/rust/linux/mgmt/src/config_util.rs4
-rw-r--r--system/gd/rust/linux/service/src/iface_bluetooth_media.rs4
-rw-r--r--system/gd/rust/linux/stack/src/bluetooth_media.rs8
-rw-r--r--system/gd/rust/topshim/Android.bp166
-rw-r--r--system/gd/rust/topshim/le_audio/le_audio_shim.cc31
-rw-r--r--system/gd/rust/topshim/src/profiles/le_audio.rs14
-rw-r--r--system/include/hardware/bt_le_audio.h10
-rw-r--r--system/main/Android.bp1
-rw-r--r--system/main/shim/BUILD.gn2
-rw-r--r--system/main/shim/acl.cc3
-rw-r--r--system/main/shim/acl.h3
-rw-r--r--system/main/shim/entry.cc2
-rw-r--r--system/main/shim/hci_layer.cc13
-rw-r--r--system/main/shim/stack.cc13
-rw-r--r--system/main/shim/stack.h5
-rw-r--r--system/main/test/main_shim_test.cc57
-rw-r--r--system/osi/Android.bp3
-rw-r--r--system/osi/BUILD.gn2
-rw-r--r--system/osi/include/properties.h1
-rw-r--r--system/osi/include/ringbuffer.h62
-rw-r--r--system/osi/src/alarm.cc2
-rw-r--r--system/osi/src/list.cc5
-rw-r--r--system/osi/src/ringbuffer.cc131
-rw-r--r--system/osi/src/stack_power_telemetry.cc5
-rw-r--r--system/osi/src/thread_scheduler.cc36
-rw-r--r--system/osi/test/alarm_test.cc4
-rw-r--r--system/osi/test/future_test.cc2
-rw-r--r--system/osi/test/fuzzers/ringbuffer/Android.bp25
-rw-r--r--system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc160
-rw-r--r--system/osi/test/internal/semaphore_test.cc2
-rw-r--r--system/osi/test/ringbuffer_test.cc139
-rw-r--r--system/packet/tests/fuzzers/reject_packet_fuzzer.cc3
-rw-r--r--system/pdl/BUILD.gn9
-rw-r--r--system/pdl/hci/Android.bp15
-rw-r--r--system/pdl/security/Android.bp15
-rw-r--r--system/profile/avrcp/Android.bp3
-rw-r--r--system/profile/avrcp/connection_handler.cc5
-rw-r--r--system/profile/avrcp/device.cc14
-rw-r--r--system/profile/avrcp/tests/avrcp_connection_handler_test.cc4
-rw-r--r--system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc3
-rw-r--r--system/profile/avrcp/tests/avrcp_device_test.cc6
-rw-r--r--system/stack/Android.bp225
-rw-r--r--system/stack/avdt/avdt_int.h1
-rw-r--r--system/stack/btm/btm_ble.cc6
-rw-r--r--system/stack/btm/btm_ble_adv_filter.cc6
-rw-r--r--system/stack/btm/btm_ble_sec.cc8
-rw-r--r--system/stack/btm/btm_dev.cc10
-rw-r--r--system/stack/btm/btm_sec.cc17
-rw-r--r--system/stack/btm/btm_sec.h2
-rw-r--r--system/stack/btm/btm_sec_cb.cc39
-rw-r--r--system/stack/btm/btm_sec_cb.h4
-rw-r--r--system/stack/btm/btm_security_client_interface.cc2
-rw-r--r--system/stack/btm/security_device_record.h3
-rw-r--r--system/stack/btu/btu_hcif.cc15
-rw-r--r--system/stack/btu/main_thread.cc4
-rw-r--r--system/stack/connection_manager/connection_manager.cc9
-rw-r--r--system/stack/eatt/eatt_impl.h2
-rw-r--r--system/stack/gatt/gatt_auth.cc4
-rw-r--r--system/stack/gatt/gatt_utils.cc2
-rw-r--r--system/stack/hcic/hciblecmds.cc41
-rw-r--r--system/stack/hcic/hcicmds.cc4
-rw-r--r--system/stack/hid/hidh_conn.cc16
-rw-r--r--system/stack/include/btm_ble_sec_api.h15
-rw-r--r--system/stack/include/btu_hcif.h4
-rw-r--r--system/stack/include/security_client_callbacks.h2
-rw-r--r--system/stack/l2cap/l2c_int.h1
-rw-r--r--system/stack/mmc/daemon/service.cc6
-rw-r--r--system/stack/sdp/sdp_api.cc2
-rw-r--r--system/stack/test/common/mock_btm_api_layer.cc4
-rw-r--r--system/stack/test/common/mock_btm_api_layer.h4
-rw-r--r--system/stack/test/eatt/eatt_test.cc4
-rw-r--r--system/stack/test/fuzzers/Android.bp50
-rw-r--r--system/stack/test/fuzzers/a2dp/Android.bp17
-rw-r--r--system/stack/test/fuzzers/a2dp/codec/Android.bp45
-rw-r--r--system/stack/test/fuzzers/avrc/Android.bp17
-rw-r--r--system/stack/test/fuzzers/sdp/Android.bp17
-rw-r--r--system/test/Android.bp47
-rw-r--r--system/test/common/jni_thread.cc9
-rw-r--r--system/test/common/main_handler.cc9
-rw-r--r--system/test/common/stack_config.cc52
-rw-r--r--system/test/common/sync_main_handler.cc5
-rw-r--r--system/test/fake/fake_looper.cc5
-rw-r--r--system/test/headless/Android.bp3
-rw-r--r--system/test/headless/android_namespace.cc19
-rw-r--r--system/test/headless/config.cc32
-rw-r--r--system/test/headless/headless.cc81
-rw-r--r--system/test/headless/log.cc5
-rw-r--r--system/test/headless/messenger.cc5
-rw-r--r--system/test/headless/read/name.cc5
-rw-r--r--system/test/headless/util.cc5
-rw-r--r--system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc3
-rw-r--r--system/test/mock/mock_bluetooth_interface.cc4
-rw-r--r--system/test/mock/mock_bta_ag_api.cc4
-rw-r--r--system/test/mock/mock_bta_ag_sco.cc9
-rw-r--r--system/test/mock/mock_bta_ag_sco.h12
-rw-r--r--system/test/mock/mock_bta_ar.cc4
-rw-r--r--system/test/mock/mock_bta_av_ci.cc4
-rw-r--r--system/test/mock/mock_bta_dm_act.cc16
-rw-r--r--system/test/mock/mock_bta_dm_act.h24
-rw-r--r--system/test/mock/mock_bta_dm_api.cc13
-rw-r--r--system/test/mock/mock_bta_dm_api.h21
-rw-r--r--system/test/mock/mock_bta_dm_main.cc4
-rw-r--r--system/test/mock/mock_bta_gattc_api.cc4
-rw-r--r--system/test/mock/mock_bta_gatts_api.cc3
-rw-r--r--system/test/mock/mock_bta_hh_utils.cc9
-rw-r--r--system/test/mock/mock_bta_hh_utils.h11
-rw-r--r--system/test/mock/mock_bta_leaudio.cc5
-rw-r--r--system/test/mock/mock_bta_pan_api.cc3
-rw-r--r--system/test/mock/mock_bta_sdp_api.cc8
-rw-r--r--system/test/mock/mock_bta_sdp_api.h9
-rw-r--r--system/test/mock/mock_bta_sys_conn.cc5
-rw-r--r--system/test/mock/mock_bta_sys_main.cc3
-rw-r--r--system/test/mock/mock_btif_av.cc3
-rw-r--r--system/test/mock/mock_btif_bluetooth.cc39
-rw-r--r--system/test/mock/mock_btif_bluetooth.h64
-rw-r--r--system/test/mock/mock_btif_bqr.cc41
-rw-r--r--system/test/mock/mock_btif_bta_pan_co_rx.cc4
-rw-r--r--system/test/mock/mock_btif_co_bta_av_co.cc5
-rw-r--r--system/test/mock/mock_btif_co_bta_dm_co.cc8
-rw-r--r--system/test/mock/mock_btif_co_bta_hh_co.cc3
-rw-r--r--system/test/mock/mock_btif_config.cc4
-rw-r--r--system/test/mock/mock_btif_core.cc4
-rw-r--r--system/test/mock/mock_btif_dm.cc16
-rw-r--r--system/test/mock/mock_btif_hf.cc4
-rw-r--r--system/test/mock/mock_btif_profile_storage.cc22
-rw-r--r--system/test/mock/mock_btif_profile_storage.h31
-rw-r--r--system/test/mock/mock_btif_sock_l2cap.cc4
-rw-r--r--system/test/mock/mock_btif_sock_rfc.cc23
-rw-r--r--system/test/mock/mock_btif_sock_rfc.h40
-rw-r--r--system/test/mock/mock_btif_stack_manager.cc4
-rw-r--r--system/test/mock/mock_btif_storage.cc32
-rw-r--r--system/test/mock/mock_btif_storage.h53
-rw-r--r--system/test/mock/mock_btif_util.cc60
-rw-r--r--system/test/mock/mock_btif_util.h112
-rw-r--r--system/test/mock/mock_device_esco_parameters.cc13
-rw-r--r--system/test/mock/mock_device_esco_parameters.h6
-rw-r--r--system/test/mock/mock_device_interop.cc10
-rw-r--r--system/test/mock/mock_device_interop.h11
-rw-r--r--system/test/mock/mock_device_iot_config.cc4
-rw-r--r--system/test/mock/mock_jni_thread.cc8
-rw-r--r--system/test/mock/mock_main_shim_acl.cc5
-rw-r--r--system/test/mock/mock_main_shim_acl_interface.cc7
-rw-r--r--system/test/mock/mock_main_shim_hci_layer.cc22
-rw-r--r--system/test/mock/mock_main_shim_hci_layer.h33
-rw-r--r--system/test/mock/mock_main_shim_stack.cc45
-rw-r--r--system/test/mock/mock_osi_future.cc8
-rw-r--r--system/test/mock/mock_osi_future.h11
-rw-r--r--system/test/mock/mock_osi_list.cc8
-rw-r--r--system/test/mock/mock_osi_list.h15
-rw-r--r--system/test/mock/mock_osi_mutex.cc4
-rw-r--r--system/test/mock/mock_osi_properties.cc4
-rw-r--r--system/test/mock/mock_osi_properties.h3
-rw-r--r--system/test/mock/mock_osi_ringbuffer.cc84
-rw-r--r--system/test/mock/mock_osi_ringbuffer.h139
-rw-r--r--system/test/mock/mock_osi_socket.cc4
-rw-r--r--system/test/mock/mock_osi_thread_scheduler.cc55
-rw-r--r--system/test/mock/mock_osi_thread_scheduler.h62
-rw-r--r--system/test/mock/mock_osi_wakelock.cc4
-rw-r--r--system/test/mock/mock_stack_a2dp_sbc.cc4
-rw-r--r--system/test/mock/mock_stack_avrc_apt.cc4
-rw-r--r--system/test/mock/mock_stack_avrc_utils.cc5
-rw-r--r--system/test/mock/mock_stack_btm_ble.cc26
-rw-r--r--system/test/mock/mock_stack_btm_ble.h40
-rw-r--r--system/test/mock/mock_stack_btm_ble_addr.cc6
-rw-r--r--system/test/mock/mock_stack_btm_ble_gap.cc11
-rw-r--r--system/test/mock/mock_stack_btm_ble_privacy.cc15
-rw-r--r--system/test/mock/mock_stack_btm_ble_privacy.h17
-rw-r--r--system/test/mock/mock_stack_btm_dev.cc7
-rw-r--r--system/test/mock/mock_stack_btm_devctl.cc6
-rw-r--r--system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc4
-rw-r--r--system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc4
-rw-r--r--system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc4
-rw-r--r--system/test/mock/mock_stack_btm_inq.cc11
-rw-r--r--system/test/mock/mock_stack_btm_inq.h9
-rw-r--r--system/test/mock/mock_stack_btm_interface.cc8
-rw-r--r--system/test/mock/mock_stack_btm_main.cc5
-rw-r--r--system/test/mock/mock_stack_btm_sco.cc5
-rw-r--r--system/test/mock/mock_stack_btm_sec.cc26
-rw-r--r--system/test/mock/mock_stack_btm_sec.h21
-rw-r--r--system/test/mock/mock_stack_btu_hcif.cc5
-rw-r--r--system/test/mock/mock_stack_hcic_hciblecmds.cc10
-rw-r--r--system/test/mock/mock_stack_hcic_hciblecmds.h13
-rw-r--r--system/test/mock/mock_stack_l2cap_api.cc5
-rw-r--r--system/test/mock/mock_stack_l2cap_ble.cc5
-rw-r--r--system/test/mock/mock_stack_l2cap_main.cc5
-rw-r--r--system/test/mock/mock_stack_l2cap_utils.cc14
-rw-r--r--system/test/mock/mock_stack_metrics_logging.cc56
-rw-r--r--system/test/mock/mock_stack_metrics_logging.h52
-rw-r--r--system/test/mock/mock_stack_security_client_interface.cc7
-rw-r--r--system/test/mock/mock_stack_security_client_interface.h2
-rw-r--r--system/test/mock/mock_udrv_ulinux_uipc.cc12
-rw-r--r--system/test/stub/osi.cc37
-rw-r--r--system/test/suite/Android.bp3
-rw-r--r--system/udrv/ulinux/uipc.cc11
-rw-r--r--tools/rootcanal/Android.bp5
627 files changed, 9210 insertions, 10975 deletions
diff --git a/Android.bp b/Android.bp
index 93d31a7b63..d0d7a7db40 100644
--- a/Android.bp
+++ b/Android.bp
@@ -137,6 +137,7 @@ java_defaults {
"-Xep:EqualsHashCode:ERROR",
"-Xep:EqualsIncompatibleType:ERROR",
"-Xep:FallThrough:ERROR",
+ "-Xep:FieldCanBeStatic:ERROR",
"-Xep:Finalize:ERROR",
"-Xep:ForEachIterable:ERROR",
"-Xep:FutureReturnValueIgnored:ERROR",
@@ -173,6 +174,7 @@ java_defaults {
"-Xep:ReferenceEquality:ERROR",
"-Xep:ReturnAtTheEndOfVoidFunction:ERROR",
"-Xep:ReturnFromVoid:ERROR",
+ "-Xep:SelfAssertion:ERROR",
"-Xep:StaticAssignmentInConstructor:ERROR",
"-Xep:StaticGuardedByInstance:ERROR",
"-Xep:StringCaseLocaleUsage:ERROR",
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 34772b59b0..b1cc9a7594 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -97,9 +97,6 @@
"name": "bluetooth_test_common"
},
{
- "name": "bluetooth_test_gd_unit"
- },
- {
"name": "bluetooth_test_with_timerfd"
},
{
@@ -332,9 +329,6 @@
"name": "bluetooth_test_common"
},
{
- "name": "bluetooth_test_gd_unit"
- },
- {
"name": "bluetooth_test_with_timerfd"
},
{
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 b7e4929cbb..686d97ff12 100644
--- a/android/app/Android.bp
+++ b/android/app/Android.bp
@@ -113,7 +113,6 @@ cc_library_shared {
"libbt-audio-asrc",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -121,12 +120,10 @@ cc_library_shared {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
"libchrome",
"libcutils",
"libevent",
@@ -165,41 +162,6 @@ cc_library_shared {
min_sdk_version: "Tiramisu",
}
-cc_library {
- name: "libbluetooth-core",
- defaults: ["fluoride_defaults"],
- header_libs: [
- "jni_headers",
- "libbluetooth_headers",
- ],
- static_libs: [
- "lib-bt-packets",
- "lib-bt-packets-base",
- "libbt-bta-core",
- "libbt-common",
- "libbt-hci",
- "libbt-stack-core",
- "libbtcore",
- "libbtdevice",
- "libbte",
- "libbtif-core",
- "libosi",
-
- "libbluetooth-types",
- ],
- cflags: [
- // we export all classes, so change default visibility,
- // instead of having EXPORT_SYMBOL on each class
- "-fvisibility=default",
- ],
- sanitize: {
- scs: true,
- },
- apex_available: ["com.android.bt"],
- host_supported: true,
- min_sdk_version: "Tiramisu",
-}
-
android_library {
name: "BluetoothLib",
defaults: ["bluetooth_framework_errorprone_rules"],
diff --git a/android/app/aidl/android/bluetooth/IBluetooth.aidl b/android/app/aidl/android/bluetooth/IBluetooth.aidl
index 9ab583b042..b9cf6bca14 100644
--- a/android/app/aidl/android/bluetooth/IBluetooth.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetooth.aidl
@@ -350,4 +350,7 @@ interface IBluetooth
@JavaPassthrough(annotation="@android.annotation.RequiresNoPermission")
IBinder getDistanceMeasurement();
+
+ @JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
+ int getKeyMissingCount(in BluetoothDevice device, in AttributionSource source);
}
diff --git a/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl
index 49a5cd6650..3b3292cd16 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothHeadset.aidl
@@ -69,8 +69,6 @@ interface IBluetoothHeadset {
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
boolean stopScoUsingVirtualVoiceCall(in AttributionSource attributionSource);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE})")
- void phoneStateChanged(int numActive, int numHeld, int callState, String number, int type, String name, in AttributionSource attributionSource);
- @JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.MODIFY_PHONE_STATE})")
boolean setActiveDevice(in BluetoothDevice device, in AttributionSource attributionSource);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
BluetoothDevice getActiveDevice(in AttributionSource attributionSource);
diff --git a/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl b/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
index 05f647d4a9..ce2397ff33 100644
--- a/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
+++ b/android/app/aidl/android/bluetooth/IBluetoothSocketManager.aidl
@@ -30,7 +30,7 @@ interface IBluetoothSocketManager
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
@nullable ParcelFileDescriptor connectSocket(in BluetoothDevice device, int type, in @nullable ParcelUuid uuid, int port, int flag);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
- @nullable ParcelFileDescriptor connectSocketwithOffload(in BluetoothDevice device, int type, in @nullable ParcelUuid uuid, int port, int flag, int dataPath, in String socketName, long hubId, long endpointId, int maximumPacketSize);
+ @nullable ParcelFileDescriptor connectSocketWithOffload(in BluetoothDevice device, int type, in @nullable ParcelUuid uuid, int port, int flag, int dataPath, in String socketName, long hubId, long endpointId, int maximumPacketSize);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(android.Manifest.permission.BLUETOOTH_CONNECT)")
@nullable ParcelFileDescriptor createSocketChannel(int type, in @nullable String serviceName, in @nullable ParcelUuid uuid, int port, int flag);
@JavaPassthrough(annotation="@android.annotation.RequiresPermission(allOf={android.Manifest.permission.BLUETOOTH_CONNECT,android.Manifest.permission.BLUETOOTH_PRIVILEGED})")
diff --git a/android/app/jni/com_android_bluetooth_avrcp_target.cpp b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
index 35208d9eb5..a2bd48e4a7 100644
--- a/android/app/jni/com_android_bluetooth_avrcp_target.cpp
+++ b/android/app/jni/com_android_bluetooth_avrcp_target.cpp
@@ -37,9 +37,6 @@
#include "hardware/bluetooth.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using bluetooth::avrcp::Attribute;
using bluetooth::avrcp::AttributeEntry;
using bluetooth::avrcp::FolderInfo;
@@ -321,7 +318,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) {
sServiceInterface = nullptr;
}
-jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) {
+static jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) {
log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
@@ -341,7 +338,7 @@ jboolean connectDeviceNative(JNIEnv* env, jobject /* object */, jstring address)
return sServiceInterface->ConnectDevice(bdaddr) == true ? JNI_TRUE : JNI_FALSE;
}
-jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) {
+static jboolean disconnectDeviceNative(JNIEnv* env, jobject /* object */, jstring address) {
log::debug("");
std::unique_lock<std::shared_timed_mutex> interface_lock(interface_mutex);
if (mServiceCallbacks == nullptr) {
diff --git a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
index 47db682622..78db0b3a10 100644
--- a/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
+++ b/android/app/jni/com_android_bluetooth_btservice_AdapterService.cpp
@@ -43,9 +43,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::Uuid;
extern bt_interface_t bluetoothInterface;
@@ -1025,7 +1022,7 @@ static bt_os_callouts_t sBluetoothOsCallouts = {
release_wake_lock_callout,
};
-int hal_util_load_bt_library(const bt_interface_t** interface) {
+static int hal_util_load_bt_library(const bt_interface_t** interface) {
*interface = &bluetoothInterface;
return 0;
}
@@ -2279,7 +2276,7 @@ static jboolean restoreFilterAcceptListNative(JNIEnv* /* env */, jobject /* obj
return (ret == BT_STATUS_SUCCESS) ? JNI_TRUE : JNI_FALSE;
}
-int register_com_android_bluetooth_btservice_AdapterService(JNIEnv* env) {
+static int register_com_android_bluetooth_btservice_AdapterService(JNIEnv* env) {
const JNINativeMethod methods[] = {
{"initNative", "(ZZIZ)Z", reinterpret_cast<void*>(initNative)},
{"cleanupNative", "()V", reinterpret_cast<void*>(cleanupNative)},
diff --git a/android/app/jni/com_android_bluetooth_gatt.cpp b/android/app/jni/com_android_bluetooth_gatt.cpp
index 357e23f5d0..85ba34bf9d 100644
--- a/android/app/jni/com_android_bluetooth_gatt.cpp
+++ b/android/app/jni/com_android_bluetooth_gatt.cpp
@@ -54,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;
#define UUID_PARAMS(uuid) uuid_lsb(uuid), uuid_msb(uuid)
@@ -248,7 +245,7 @@ static std::shared_mutex callbacks_mutex;
* BTA client callbacks
*/
-void btgattc_register_app_cb(int status, int clientIf, const Uuid& app_uuid) {
+static void btgattc_register_app_cb(int status, int clientIf, const Uuid& app_uuid) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -258,7 +255,7 @@ void btgattc_register_app_cb(int status, int clientIf, const Uuid& app_uuid) {
UUID_PARAMS(app_uuid));
}
-void btgattc_open_cb(int conn_id, int status, int clientIf, const RawAddress& bda) {
+static void btgattc_open_cb(int conn_id, int status, int clientIf, const RawAddress& bda) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -270,7 +267,7 @@ void btgattc_open_cb(int conn_id, int status, int clientIf, const RawAddress& bd
address.get());
}
-void btgattc_close_cb(int conn_id, int status, int clientIf, const RawAddress& bda) {
+static void btgattc_close_cb(int conn_id, int status, int clientIf, const RawAddress& bda) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -282,7 +279,7 @@ void btgattc_close_cb(int conn_id, int status, int clientIf, const RawAddress& b
address.get());
}
-void btgattc_search_complete_cb(int conn_id, int status) {
+static void btgattc_search_complete_cb(int conn_id, int status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -292,8 +289,8 @@ void btgattc_search_complete_cb(int conn_id, int status) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSearchCompleted, conn_id, status);
}
-void btgattc_register_for_notification_cb(int conn_id, int registered, int status,
- uint16_t handle) {
+static void btgattc_register_for_notification_cb(int conn_id, int registered, int status,
+ uint16_t handle) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -304,7 +301,7 @@ void btgattc_register_for_notification_cb(int conn_id, int registered, int statu
registered, handle);
}
-void btgattc_notify_cb(int conn_id, const btgatt_notify_params_t& p_data) {
+static void btgattc_notify_cb(int conn_id, const btgatt_notify_params_t& p_data) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -320,7 +317,8 @@ void btgattc_notify_cb(int conn_id, const btgatt_notify_params_t& p_data) {
p_data.handle, p_data.is_notify, jb.get());
}
-void btgattc_read_characteristic_cb(int conn_id, int status, const btgatt_read_params_t& p_data) {
+static void btgattc_read_characteristic_cb(int conn_id, int status,
+ const btgatt_read_params_t& p_data) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -341,8 +339,8 @@ void btgattc_read_characteristic_cb(int conn_id, int status, const btgatt_read_p
p_data.handle, jb.get());
}
-void btgattc_write_characteristic_cb(int conn_id, int status, uint16_t handle, uint16_t len,
- const uint8_t* value) {
+static void btgattc_write_characteristic_cb(int conn_id, int status, uint16_t handle, uint16_t len,
+ const uint8_t* value) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -356,7 +354,7 @@ void btgattc_write_characteristic_cb(int conn_id, int status, uint16_t handle, u
jb.get());
}
-void btgattc_execute_write_cb(int conn_id, int status) {
+static void btgattc_execute_write_cb(int conn_id, int status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -366,7 +364,8 @@ void btgattc_execute_write_cb(int conn_id, int status) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onExecuteCompleted, conn_id, status);
}
-void btgattc_read_descriptor_cb(int conn_id, int status, const btgatt_read_params_t& p_data) {
+static void btgattc_read_descriptor_cb(int conn_id, int status,
+ const btgatt_read_params_t& p_data) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -385,8 +384,8 @@ void btgattc_read_descriptor_cb(int conn_id, int status, const btgatt_read_param
p_data.handle, jb.get());
}
-void btgattc_write_descriptor_cb(int conn_id, int status, uint16_t handle, uint16_t len,
- const uint8_t* value) {
+static void btgattc_write_descriptor_cb(int conn_id, int status, uint16_t handle, uint16_t len,
+ const uint8_t* value) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -400,7 +399,7 @@ void btgattc_write_descriptor_cb(int conn_id, int status, uint16_t handle, uint1
jb.get());
}
-void btgattc_remote_rssi_cb(int client_if, const RawAddress& bda, int rssi, int status) {
+static void btgattc_remote_rssi_cb(int client_if, const RawAddress& bda, int rssi, int status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -413,7 +412,7 @@ void btgattc_remote_rssi_cb(int client_if, const RawAddress& bda, int rssi, int
rssi, status);
}
-void btgattc_configure_mtu_cb(int conn_id, int status, int mtu) {
+static void btgattc_configure_mtu_cb(int conn_id, int status, int mtu) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -422,7 +421,7 @@ void btgattc_configure_mtu_cb(int conn_id, int status, int mtu) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onConfigureMTU, conn_id, status, mtu);
}
-void btgattc_congestion_cb(int conn_id, bool congested) {
+static void btgattc_congestion_cb(int conn_id, bool congested) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -431,7 +430,8 @@ void btgattc_congestion_cb(int conn_id, bool congested) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onClientCongestion, conn_id, congested);
}
-void fillGattDbElementArray(JNIEnv* env, jobject* array, const btgatt_db_element_t* db, int count) {
+static void fillGattDbElementArray(JNIEnv* env, jobject* array, const btgatt_db_element_t* db,
+ int count) {
// Because JNI uses a different class loader in the callback context, we
// cannot simply get the class.
// As a workaround, we have to make sure we obtain an object of the class
@@ -494,7 +494,7 @@ void fillGattDbElementArray(JNIEnv* env, jobject* array, const btgatt_db_element
}
}
-void btgattc_get_gatt_db_cb(int conn_id, const btgatt_db_element_t* db, int count) {
+static void btgattc_get_gatt_db_cb(int conn_id, const btgatt_db_element_t* db, int count) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -513,7 +513,7 @@ void btgattc_get_gatt_db_cb(int conn_id, const btgatt_db_element_t* db, int coun
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onGetGattDb, conn_id, array.get());
}
-void btgattc_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) {
+static void btgattc_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -524,8 +524,8 @@ void btgattc_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t
status);
}
-void btgattc_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, uint16_t timeout,
- uint8_t status) {
+static void btgattc_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency,
+ uint16_t timeout, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -536,7 +536,7 @@ void btgattc_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, u
timeout, status);
}
-void btgattc_service_changed_cb(int conn_id) {
+static void btgattc_service_changed_cb(int conn_id) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -546,8 +546,8 @@ void btgattc_service_changed_cb(int conn_id) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServiceChanged, conn_id);
}
-void btgattc_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency,
- uint16_t cont_num, uint16_t timeout, uint8_t status) {
+static void btgattc_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency,
+ uint16_t cont_num, uint16_t timeout, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -586,11 +586,11 @@ static const btgatt_client_callbacks_t sGattClientCallbacks = {
* BTA server callbacks
*/
-void btgatts_register_app_cb(int status, int server_if, const Uuid& uuid) {
+static 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());
+ log::error("Rust module isn't started! only_start_scan_during_ble_on={}",
+ com::android::bluetooth::flags::only_start_scan_during_ble_on());
}
bluetooth::gatt::open_server(server_if);
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
@@ -602,7 +602,8 @@ void btgatts_register_app_cb(int status, int server_if, const Uuid& uuid) {
UUID_PARAMS(uuid));
}
-void btgatts_connection_cb(int conn_id, int server_if, int connected, const RawAddress& bda) {
+static void btgatts_connection_cb(int conn_id, int server_if, int connected,
+ const RawAddress& bda) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -614,8 +615,8 @@ void btgatts_connection_cb(int conn_id, int server_if, int connected, const RawA
conn_id, server_if);
}
-void btgatts_service_added_cb(int status, int server_if, const btgatt_db_element_t* service,
- size_t service_count) {
+static void btgatts_service_added_cb(int status, int server_if, const btgatt_db_element_t* service,
+ size_t service_count) {
// mirror the database in rust, now that it's created.
if (status == 0x00 /* SUCCESS */) {
auto service_records = rust::Vec<bluetooth::gatt::GattRecord>();
@@ -647,7 +648,7 @@ void btgatts_service_added_cb(int status, int server_if, const btgatt_db_element
array.get());
}
-void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) {
+static void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) {
bluetooth::gatt::remove_service(server_if, srvc_handle);
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
@@ -659,7 +660,7 @@ void btgatts_service_stopped_cb(int status, int server_if, int srvc_handle) {
srvc_handle);
}
-void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) {
+static void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) {
bluetooth::gatt::remove_service(server_if, srvc_handle);
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
@@ -671,8 +672,8 @@ void btgatts_service_deleted_cb(int status, int server_if, int srvc_handle) {
srvc_handle);
}
-void btgatts_request_read_characteristic_cb(int conn_id, int trans_id, const RawAddress& bda,
- int attr_handle, int offset, bool is_long) {
+static void btgatts_request_read_characteristic_cb(int conn_id, int trans_id, const RawAddress& bda,
+ int attr_handle, int offset, bool is_long) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -684,8 +685,8 @@ void btgatts_request_read_characteristic_cb(int conn_id, int trans_id, const Raw
conn_id, trans_id, attr_handle, offset, is_long);
}
-void btgatts_request_read_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda,
- int attr_handle, int offset, bool is_long) {
+static void btgatts_request_read_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda,
+ int attr_handle, int offset, bool is_long) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -697,9 +698,10 @@ void btgatts_request_read_descriptor_cb(int conn_id, int trans_id, const RawAddr
trans_id, attr_handle, offset, is_long);
}
-void btgatts_request_write_characteristic_cb(int conn_id, int trans_id, const RawAddress& bda,
- int attr_handle, int offset, bool need_rsp,
- bool is_prep, const uint8_t* value, size_t length) {
+static void btgatts_request_write_characteristic_cb(int conn_id, int trans_id,
+ const RawAddress& bda, int attr_handle,
+ int offset, bool need_rsp, bool is_prep,
+ const uint8_t* value, size_t length) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -716,9 +718,9 @@ void btgatts_request_write_characteristic_cb(int conn_id, int trans_id, const Ra
val.get());
}
-void btgatts_request_write_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda,
- int attr_handle, int offset, bool need_rsp, bool is_prep,
- const uint8_t* value, size_t length) {
+static void btgatts_request_write_descriptor_cb(int conn_id, int trans_id, const RawAddress& bda,
+ int attr_handle, int offset, bool need_rsp,
+ bool is_prep, const uint8_t* value, size_t length) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -735,8 +737,8 @@ void btgatts_request_write_descriptor_cb(int conn_id, int trans_id, const RawAdd
val.get());
}
-void btgatts_request_exec_write_cb(int conn_id, int trans_id, const RawAddress& bda,
- int exec_write) {
+static void btgatts_request_exec_write_cb(int conn_id, int trans_id, const RawAddress& bda,
+ int exec_write) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -748,7 +750,7 @@ void btgatts_request_exec_write_cb(int conn_id, int trans_id, const RawAddress&
trans_id, exec_write);
}
-void btgatts_response_confirmation_cb(int status, int handle) {
+static void btgatts_response_confirmation_cb(int status, int handle) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -757,7 +759,7 @@ void btgatts_response_confirmation_cb(int status, int handle) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onResponseSendCompleted, status, handle);
}
-void btgatts_indication_sent_cb(int conn_id, int status) {
+static void btgatts_indication_sent_cb(int conn_id, int status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -766,7 +768,7 @@ void btgatts_indication_sent_cb(int conn_id, int status) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onNotificationSent, conn_id, status);
}
-void btgatts_congestion_cb(int conn_id, bool congested) {
+static void btgatts_congestion_cb(int conn_id, bool congested) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -775,7 +777,7 @@ void btgatts_congestion_cb(int conn_id, bool congested) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerCongestion, conn_id, congested);
}
-void btgatts_mtu_changed_cb(int conn_id, int mtu) {
+static void btgatts_mtu_changed_cb(int conn_id, int mtu) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -784,7 +786,7 @@ void btgatts_mtu_changed_cb(int conn_id, int mtu) {
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onServerMtuChanged, conn_id, mtu);
}
-void btgatts_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) {
+static void btgatts_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -795,8 +797,8 @@ void btgatts_phy_updated_cb(int conn_id, uint8_t tx_phy, uint8_t rx_phy, uint8_t
status);
}
-void btgatts_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, uint16_t timeout,
- uint8_t status) {
+static void btgatts_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency,
+ uint16_t timeout, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -807,8 +809,8 @@ void btgatts_conn_updated_cb(int conn_id, uint16_t interval, uint16_t latency, u
timeout, status);
}
-void btgatts_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency,
- uint16_t cont_num, uint16_t timeout, uint8_t status) {
+static void btgatts_subrate_change_cb(int conn_id, uint16_t subrate_factor, uint16_t latency,
+ uint16_t cont_num, uint16_t timeout, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mCallbacksObj) {
@@ -1231,7 +1233,7 @@ static void initializeNative(JNIEnv* env, jobject object) {
return;
}
- if (com::android::bluetooth::flags::scan_manager_refactor()) {
+ if (com::android::bluetooth::flags::only_start_scan_during_ble_on()) {
log::info("Starting rust module");
btIf->start_rust_module();
}
@@ -1250,7 +1252,7 @@ static void cleanupNative(JNIEnv* env, jobject /* object */) {
return;
}
- if (com::android::bluetooth::flags::scan_manager_refactor()) {
+ if (com::android::bluetooth::flags::only_start_scan_during_ble_on()) {
log::info("Stopping rust module");
btIf->stop_rust_module();
}
@@ -1294,7 +1296,7 @@ static void gattClientUnregisterAppNative(JNIEnv* /* env */, jobject /* object *
sGattIf->client->unregister_client(clientIf);
}
-void btgattc_register_scanner_cb(const Uuid& app_uuid, uint8_t scannerId, uint8_t status) {
+static void btgattc_register_scanner_cb(const Uuid& app_uuid, uint8_t scannerId, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1542,7 +1544,8 @@ static void gattSetScanParametersNative(JNIEnv* /* env */, jobject /* object */,
scan_window_unit_coded, scan_phy);
}
-void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action, uint8_t status) {
+static void scan_filter_param_cb(uint8_t client_if, uint8_t avbl_space, uint8_t action,
+ uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1794,7 +1797,7 @@ static void gattClientScanFilterClearNative(JNIEnv* /* env */, jobject /* object
sScanner->ScanFilterClear(filt_index, base::Bind(&scan_filter_cfg_cb, client_if));
}
-void scan_enable_cb(uint8_t client_if, uint8_t action, uint8_t status) {
+static void scan_enable_cb(uint8_t client_if, uint8_t action, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1812,7 +1815,7 @@ static void gattClientScanFilterEnableNative(JNIEnv* /* env */, jobject /* objec
sScanner->ScanFilterEnable(enable, base::Bind(&scan_enable_cb, client_if));
}
-void msft_monitor_add_cb(int filter_index, uint8_t monitor_handle, uint8_t status) {
+static void msft_monitor_add_cb(int filter_index, uint8_t monitor_handle, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1822,7 +1825,7 @@ void msft_monitor_add_cb(int filter_index, uint8_t monitor_handle, uint8_t statu
monitor_handle, status);
}
-void msft_monitor_remove_cb(int filter_index, uint8_t status) {
+static void msft_monitor_remove_cb(int filter_index, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1832,7 +1835,7 @@ void msft_monitor_remove_cb(int filter_index, uint8_t status) {
status);
}
-void msft_monitor_enable_cb(uint8_t status) {
+static void msft_monitor_enable_cb(uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -1981,7 +1984,7 @@ static int gattSubrateRequestNative(JNIEnv* env, jobject /* object */, jint /* c
return 0; // BluetoothStatusCodes.SUCCESS
}
-void batchscan_cfg_storage_cb(uint8_t client_if, uint8_t status) {
+static void batchscan_cfg_storage_cb(uint8_t client_if, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
@@ -2003,7 +2006,7 @@ static void gattClientConfigBatchScanStorageNative(JNIEnv* /* env */, jobject /*
base::Bind(&batchscan_cfg_storage_cb, client_if));
}
-void batchscan_enable_cb(uint8_t client_if, uint8_t status) {
+static void batchscan_enable_cb(uint8_t client_if, uint8_t status) {
std::shared_lock<std::shared_mutex> lock(callbacks_mutex);
CallbackEnv sCallbackEnv(__func__);
if (!sCallbackEnv.valid() || !mScanCallbacksObj) {
diff --git a/android/app/jni/com_android_bluetooth_le_audio.cpp b/android/app/jni/com_android_bluetooth_le_audio.cpp
index 3b0411135c..99b61e5272 100644
--- a/android/app/jni/com_android_bluetooth_le_audio.cpp
+++ b/android/app/jni/com_android_bluetooth_le_audio.cpp
@@ -40,9 +40,6 @@
#include "hardware/bt_le_audio.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using bluetooth::le_audio::BroadcastId;
using bluetooth::le_audio::BroadcastState;
using bluetooth::le_audio::btle_audio_bits_per_sample_index_t;
@@ -132,7 +129,7 @@ static std::shared_timed_mutex callbacks_mutex;
static jclass class_LeAudioNativeInterface;
-jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig) {
+static jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig) {
log::info(
"ct: {}, codec_priority: {}, sample_rate: {}, bits_per_sample: {}, "
"channel_count: {}, frame_duration: {}, octets_per_frame: {}",
@@ -149,8 +146,8 @@ jobject prepareCodecConfigObj(JNIEnv* env, btle_audio_codec_config_t codecConfig
return codecConfigObj;
}
-jobjectArray prepareArrayOfCodecConfigs(JNIEnv* env,
- std::vector<btle_audio_codec_config_t> codecConfigs) {
+static jobjectArray prepareArrayOfCodecConfigs(
+ JNIEnv* env, std::vector<btle_audio_codec_config_t> codecConfigs) {
jsize i = 0;
jobjectArray CodecConfigArray = env->NewObjectArray(
(jsize)codecConfigs.size(), android_bluetooth_BluetoothLeAudioCodecConfig.clazz, nullptr);
@@ -235,8 +232,10 @@ public:
(jint)group_id, (jint)node_status);
}
- void OnAudioConf(uint8_t direction, int group_id, uint32_t sink_audio_location,
- uint32_t source_audio_location, uint16_t avail_cont) override {
+ void OnAudioConf(uint8_t direction, int group_id,
+ std::optional<std::bitset<32>> sink_audio_location,
+ std::optional<std::bitset<32>> source_audio_location,
+ uint16_t avail_cont) override {
log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
@@ -245,13 +244,15 @@ public:
return;
}
+ jint jni_sink_audio_location = sink_audio_location ? sink_audio_location->to_ulong() : -1;
+ jint jni_source_audio_location = source_audio_location ? source_audio_location->to_ulong() : -1;
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onAudioConf, (jint)direction, (jint)group_id,
- (jint)sink_audio_location, (jint)source_audio_location,
+ jni_sink_audio_location, jni_source_audio_location,
(jint)avail_cont);
}
void OnSinkAudioLocationAvailable(const RawAddress& bd_addr,
- uint32_t sink_audio_location) override {
+ std::optional<std::bitset<32>> sink_audio_location) override {
log::info("");
std::shared_lock<std::shared_timed_mutex> lock(callbacks_mutex);
@@ -268,8 +269,9 @@ public:
}
sCallbackEnv->SetByteArrayRegion(addr.get(), 0, sizeof(RawAddress), (jbyte*)&bd_addr);
+ jint jni_sink_audio_location = sink_audio_location ? sink_audio_location->to_ulong() : -1;
sCallbackEnv->CallVoidMethod(mCallbacksObj, method_onSinkAudioLocationAvailable, addr.get(),
- (jint)sink_audio_location);
+ jni_sink_audio_location);
}
void OnAudioLocalCodecCapabilities(
@@ -397,8 +399,8 @@ public:
static LeAudioClientCallbacksImpl sLeAudioClientCallbacks;
-std::vector<btle_audio_codec_config_t> prepareCodecPreferences(JNIEnv* env, jobject /* object */,
- jobjectArray codecConfigArray) {
+static std::vector<btle_audio_codec_config_t> prepareCodecPreferences(
+ JNIEnv* env, jobject /* object */, jobjectArray codecConfigArray) {
std::vector<btle_audio_codec_config_t> codec_preferences;
int numConfigs = env->GetArrayLength(codecConfigArray);
@@ -758,7 +760,7 @@ static std::shared_timed_mutex sBroadcasterCallbacksMutex;
#define VEC_UINT8_TO_UINT16(vec) (((vec).data()[1] << 8) + ((vec).data()[0]))
-size_t RawPacketSize(const std::map<uint8_t, std::vector<uint8_t>>& values) {
+static size_t RawPacketSize(const std::map<uint8_t, std::vector<uint8_t>>& values) {
size_t bytes = 0;
for (auto const& value : values) {
bytes += (/* ltv_len + ltv_type */ 2 + value.second.size());
@@ -766,8 +768,8 @@ size_t RawPacketSize(const std::map<uint8_t, std::vector<uint8_t>>& values) {
return bytes;
}
-jbyteArray prepareRawLtvArray(JNIEnv* env,
- const std::map<uint8_t, std::vector<uint8_t>>& metadata) {
+static jbyteArray prepareRawLtvArray(JNIEnv* env,
+ const std::map<uint8_t, std::vector<uint8_t>>& metadata) {
auto raw_meta_size = RawPacketSize(metadata);
jbyteArray raw_metadata = env->NewByteArray(raw_meta_size);
@@ -834,7 +836,7 @@ static jint getOctetsPerFrameOrDefault(const std::map<uint8_t, std::vector<uint8
return VEC_UINT8_TO_UINT16(vec);
}
-jobject prepareLeAudioCodecConfigMetadataObject(
+static jobject prepareLeAudioCodecConfigMetadataObject(
JNIEnv* env, const std::map<uint8_t, std::vector<uint8_t>>& metadata) {
jlong audio_location = getAudioLocationOrDefault(metadata, -1);
jint sampling_frequency = getSamplingFrequencyOrDefault(metadata, 0);
@@ -854,7 +856,7 @@ jobject prepareLeAudioCodecConfigMetadataObject(
return obj;
}
-jobject prepareLeBroadcastChannelObject(
+static jobject prepareLeBroadcastChannelObject(
JNIEnv* env, const bluetooth::le_audio::BasicAudioAnnouncementBisConfig& bis_config) {
ScopedLocalRef<jobject> meta_object(
env, prepareLeAudioCodecConfigMetadataObject(env, bis_config.codec_specific_params));
@@ -870,7 +872,7 @@ jobject prepareLeBroadcastChannelObject(
return obj;
}
-jobject prepareLeAudioContentMetadataObject(
+static jobject prepareLeAudioContentMetadataObject(
JNIEnv* env, const std::map<uint8_t, std::vector<uint8_t>>& metadata) {
jstring program_info_str = nullptr;
if (metadata.count(bluetooth::le_audio::kLeAudioMetadataTypeProgramInfo)) {
@@ -922,7 +924,7 @@ jobject prepareLeAudioContentMetadataObject(
return obj;
}
-jobject prepareLeBroadcastChannelListObject(
+static jobject prepareLeBroadcastChannelListObject(
JNIEnv* env,
const std::vector<bluetooth::le_audio::BasicAudioAnnouncementBisConfig>& bis_configs) {
jobject array = env->NewObject(java_util_ArrayList.clazz, java_util_ArrayList.constructor);
@@ -943,7 +945,7 @@ jobject prepareLeBroadcastChannelListObject(
return array;
}
-jobject prepareLeBroadcastSubgroupObject(
+static jobject prepareLeBroadcastSubgroupObject(
JNIEnv* env, const bluetooth::le_audio::BasicAudioAnnouncementSubgroup& subgroup) {
// Serialize codec ID
jlong jlong_codec_id = subgroup.codec_config.codec_id |
@@ -979,7 +981,7 @@ jobject prepareLeBroadcastSubgroupObject(
channel_list_obj.get());
}
-jobject prepareLeBroadcastSubgroupListObject(
+static jobject prepareLeBroadcastSubgroupListObject(
JNIEnv* env,
const std::vector<bluetooth::le_audio::BasicAudioAnnouncementSubgroup>& subgroup_configs) {
jobject array = env->NewObject(java_util_ArrayList.clazz, java_util_ArrayList.constructor);
@@ -1000,7 +1002,7 @@ jobject prepareLeBroadcastSubgroupListObject(
return array;
}
-jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, int addr_type) {
+static jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, int addr_type) {
// The address string has to be uppercase or the BluetoothDevice constructor
// will treat it as invalid.
auto addr_str = addr.ToString();
@@ -1018,7 +1020,7 @@ jobject prepareBluetoothDeviceObject(JNIEnv* env, const RawAddress& addr, int ad
(jint)addr_type);
}
-jobject prepareBluetoothLeBroadcastMetadataObject(
+static jobject prepareBluetoothLeBroadcastMetadataObject(
JNIEnv* env, const bluetooth::le_audio::BroadcastMetadata& broadcast_metadata) {
ScopedLocalRef<jobject> device_obj(
env,
@@ -1313,7 +1315,7 @@ static void BroadcasterCleanupNative(JNIEnv* env, jobject /* object */) {
}
}
-std::vector<std::vector<uint8_t>> convertToDataVectors(JNIEnv* env, jobjectArray dataArray) {
+static std::vector<std::vector<uint8_t>> convertToDataVectors(JNIEnv* env, jobjectArray dataArray) {
jsize arraySize = env->GetArrayLength(dataArray);
std::vector<std::vector<uint8_t>> res(arraySize);
diff --git a/android/app/lib-lint-baseline.xml b/android/app/lib-lint-baseline.xml
index 0af37b746f..c2a527c3fc 100644
--- a/android/app/lib-lint-baseline.xml
+++ b/android/app/lib-lint-baseline.xml
@@ -129,7 +129,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1229"
+ line="1228"
column="35"/>
</issue>
@@ -140,7 +140,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1240"
+ line="1239"
column="35"/>
</issue>
@@ -151,7 +151,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1251"
+ line="1250"
column="35"/>
</issue>
@@ -162,7 +162,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1262"
+ line="1261"
column="35"/>
</issue>
@@ -173,7 +173,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1277"
+ line="1276"
column="35"/>
</issue>
@@ -184,7 +184,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1288"
+ line="1287"
column="35"/>
</issue>
@@ -195,7 +195,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1295"
+ line="1294"
column="35"/>
</issue>
@@ -206,7 +206,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1306"
+ line="1305"
column="35"/>
</issue>
@@ -217,7 +217,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1511"
+ line="1510"
column="35"/>
</issue>
@@ -228,7 +228,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1522"
+ line="1521"
column="35"/>
</issue>
@@ -239,7 +239,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1759"
+ line="1758"
column="35"/>
</issue>
@@ -250,7 +250,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java"
- line="1770"
+ line="1769"
column="35"/>
</issue>
@@ -305,7 +305,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java"
- line="82"
+ line="81"
column="35"/>
</issue>
@@ -426,7 +426,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="824"
+ line="807"
column="9"/>
</issue>
@@ -437,7 +437,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="824"
+ line="807"
column="9"/>
</issue>
@@ -448,7 +448,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="824"
+ line="807"
column="9"/>
</issue>
@@ -459,7 +459,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="824"
+ line="807"
column="9"/>
</issue>
@@ -470,7 +470,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapbMessage.java"
- line="922"
+ line="921"
column="9"/>
</issue>
@@ -492,7 +492,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java"
- line="554"
+ line="555"
column="13"/>
</issue>
@@ -569,7 +569,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java"
- line="801"
+ line="802"
column="33"/>
</issue>
@@ -580,7 +580,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java"
- line="809"
+ line="810"
column="26"/>
</issue>
@@ -591,7 +591,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java"
- line="822"
+ line="823"
column="33"/>
</issue>
@@ -602,7 +602,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java"
- line="842"
+ line="843"
column="26"/>
</issue>
@@ -613,7 +613,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/a2dp/A2dpService.java"
- line="917"
+ line="918"
column="45"/>
</issue>
@@ -624,7 +624,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="1155"
+ line="1149"
column="20"/>
</issue>
@@ -635,7 +635,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="1160"
+ line="1154"
column="20"/>
</issue>
@@ -646,7 +646,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="2004"
+ line="1996"
column="43"/>
</issue>
@@ -657,7 +657,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="2009"
+ line="2001"
column="45"/>
</issue>
@@ -668,7 +668,7 @@
errorLine2=" ~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="2013"
+ line="2005"
column="34"/>
</issue>
@@ -679,7 +679,7 @@
errorLine2=" ~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="2245"
+ line="2237"
column="33"/>
</issue>
@@ -690,7 +690,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="7279"
+ line="7293"
column="28"/>
</issue>
@@ -701,7 +701,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="7281"
+ line="7295"
column="28"/>
</issue>
@@ -1020,7 +1020,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java"
- line="1262"
+ line="1261"
column="49"/>
</issue>
@@ -1031,7 +1031,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java"
- line="103"
+ line="104"
column="49"/>
</issue>
@@ -1042,7 +1042,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListing.java"
- line="152"
+ line="153"
column="45"/>
</issue>
@@ -1053,7 +1053,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapMessageListingElement.java"
- line="277"
+ line="276"
column="41"/>
</issue>
@@ -1075,7 +1075,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java"
- line="646"
+ line="656"
column="28"/>
</issue>
@@ -1086,7 +1086,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java"
- line="683"
+ line="693"
column="28"/>
</issue>
@@ -1097,7 +1097,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java"
- line="713"
+ line="723"
column="28"/>
</issue>
@@ -1108,7 +1108,7 @@
errorLine2=" ~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java"
- line="859"
+ line="855"
column="63"/>
</issue>
@@ -1130,7 +1130,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java"
- line="106"
+ line="105"
column="26"/>
</issue>
@@ -1141,7 +1141,7 @@
errorLine2=" ~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java"
- line="176"
+ line="177"
column="26"/>
</issue>
@@ -1412,12 +1412,12 @@
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" mHandler = new Handler(headsetService.getStateMachinesThreadLooper());"
- errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
+ errorLine1=" mHandler = new Handler(headsetService.getStateMachinesThreadLooper());"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetPhoneState.java"
- line="86"
- column="51"/>
+ line="91"
+ column="47"/>
</issue>
<issue
@@ -1427,7 +1427,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="272"
+ line="273"
column="38"/>
</issue>
@@ -1438,7 +1438,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="274"
+ line="275"
column="42"/>
</issue>
@@ -1449,7 +1449,7 @@
errorLine2=" ~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="287"
+ line="288"
column="26"/>
</issue>
@@ -1460,7 +1460,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="440"
+ line="436"
column="42"/>
</issue>
@@ -1471,7 +1471,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="512"
+ line="508"
column="30"/>
</issue>
@@ -1482,7 +1482,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="906"
+ line="866"
column="48"/>
</issue>
@@ -1493,7 +1493,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="954"
+ line="914"
column="48"/>
</issue>
@@ -1504,29 +1504,18 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="974"
+ line="934"
column="34"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" devices.add(stateMachine.getDevice());"
- errorLine2=" ~~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="975"
- column="46"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
errorLine1=" return stateMachine.getConnectionState();"
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1022"
+ line="982"
column="33"/>
</issue>
@@ -1537,7 +1526,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1136"
+ line="1096"
column="38"/>
</issue>
@@ -1548,7 +1537,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1138"
+ line="1098"
column="42"/>
</issue>
@@ -1559,7 +1548,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1154"
+ line="1114"
column="48"/>
</issue>
@@ -1570,7 +1559,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1228"
+ line="1188"
column="48"/>
</issue>
@@ -1581,7 +1570,7 @@
errorLine2=" ~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1283"
+ line="1243"
column="26"/>
</issue>
@@ -1592,7 +1581,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1419"
+ line="1379"
column="30"/>
</issue>
@@ -1603,7 +1592,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1462"
+ line="1422"
column="35"/>
</issue>
@@ -1611,21 +1600,10 @@
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
errorLine1=" if (mSystemInterface.isInCall() || mSystemInterface.isRinging()) {"
- errorLine2=" ~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1473"
- column="34"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
- errorLine1=" if (mSystemInterface.isInCall() || mSystemInterface.isRinging()) {"
errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1473"
+ line="1433"
column="65"/>
</issue>
@@ -1636,7 +1614,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1491"
+ line="1451"
column="38"/>
</issue>
@@ -1647,7 +1625,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1530"
+ line="1490"
column="42"/>
</issue>
@@ -1658,29 +1636,18 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1589"
+ line="1549"
column="30"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" devices.add(stateMachine.getDevice());"
- errorLine2=" ~~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1614"
- column="46"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
errorLine1=" if (mSystemInterface.getVoiceRecognitionWakeLock().isHeld()) {"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1824"
+ line="1784"
column="38"/>
</issue>
@@ -1691,7 +1658,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1826"
+ line="1786"
column="42"/>
</issue>
@@ -1702,7 +1669,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1908"
+ line="1868"
column="35"/>
</issue>
@@ -1713,7 +1680,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1921"
+ line="1881"
column="35"/>
</issue>
@@ -1724,7 +1691,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1922"
+ line="1882"
column="34"/>
</issue>
@@ -1735,7 +1702,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1949"
+ line="1909"
column="38"/>
</issue>
@@ -1746,7 +1713,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1951"
+ line="1911"
column="42"/>
</issue>
@@ -1757,140 +1724,151 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="1972"
+ line="1932"
column="35"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" int connectionState = stateMachine.getConnectionState();"
- errorLine2=" ~~~~~~~~~~~~~~~~~~">
+ errorLine1=" boolean isCallIdleBefore = mSystemInterface.isCallIdle();"
+ errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2119"
- column="48"/>
+ line="1984"
+ column="65"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" if (mVoiceRecognitionStarted || mVirtualCallStarted || !mSystemInterface.isCallIdle()) {"
- errorLine2=" ~~~~~~~~~~">
+ errorLine1=" mSystemInterface.getHeadsetPhoneState().setNumActiveCall(numActive);"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2267"
- column="86"/>
+ line="1985"
+ column="38"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" + mSystemInterface.isCallIdle());"
- errorLine2=" ~~~~~~~~~~">
+ errorLine1=" mSystemInterface.getHeadsetPhoneState().setNumHeldCall(numHeld);"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2275"
- column="52"/>
+ line="1986"
+ column="38"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" return mSystemInterface.isInCall()"
- errorLine2=" ~~~~~~~~">
+ errorLine1=" mSystemInterface.getHeadsetPhoneState().setCallState(callState);"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2303"
- column="33"/>
+ line="1987"
+ column="38"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" || (mSystemInterface.isRinging() &amp;&amp; isInbandRingingEnabled());"
- errorLine2=" ~~~~~~~~~">
+ errorLine1=" &amp;&amp; !mSystemInterface.isCallIdle()"
+ errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2304"
- column="38"/>
+ line="1991"
+ column="50"/>
</issue>
<issue
id="VisibleForTests"
- message="This method should only be accessed from tests or within package private scope"
- errorLine1=" if (a2dpService != null &amp;&amp; a2dpService.okToConnect(device, true)) {"
- errorLine2=" ~~~~~~~~~~~">
+ message="This method should only be accessed from tests or within private scope"
+ errorLine1=" &amp;&amp; mSystemInterface.isCallIdle()"
+ errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2534"
- column="56"/>
+ line="2009"
+ column="49"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" + mSystemInterface.isInCall()"
- errorLine2=" ~~~~~~~~">
+ errorLine1=" int connectionState = stateMachine.getConnectionState();"
+ errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2599"
+ line="2078"
column="48"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" + mSystemInterface.isRinging()"
- errorLine2=" ~~~~~~~~~">
+ errorLine1=" if (mVoiceRecognitionStarted || mVirtualCallStarted || !mSystemInterface.isCallIdle()) {"
+ errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2603"
- column="48"/>
+ line="2226"
+ column="86"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" ProfileService.println(sb, &quot;Telecom.isInCall(): &quot; + mSystemInterface.isInCall());"
- errorLine2=" ~~~~~~~~">
+ errorLine1=" + mSystemInterface.isCallIdle());"
+ errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2681"
- column="82"/>
+ line="2234"
+ column="52"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" ProfileService.println(sb, &quot;Telecom.isRinging(): &quot; + mSystemInterface.isRinging());"
- errorLine2=" ~~~~~~~~~">
+ errorLine1=" || (mSystemInterface.isRinging() &amp;&amp; isInbandRingingEnabled());"
+ errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2682"
- column="83"/>
+ line="2263"
+ column="38"/>
+ </issue>
+
+ <issue
+ id="VisibleForTests"
+ message="This method should only be accessed from tests or within package private scope"
+ errorLine1=" if (a2dpService != null &amp;&amp; a2dpService.okToConnect(device, true)) {"
+ errorLine2=" ~~~~~~~~~~~">
+ <location
+ file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
+ line="2493"
+ column="56"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" sb, &quot;==== StateMachine for &quot; + stateMachine.getDevice() + &quot; ====&quot;);"
- errorLine2=" ~~~~~~~~~">
+ errorLine1=" + mSystemInterface.isRinging()"
+ errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2685"
- column="69"/>
+ line="2562"
+ column="48"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" boolean result = mNativeInterface.enableSwb(swbCodec, enable, device);"
- errorLine2=" ~~~~~~~~~">
+ errorLine1=" ProfileService.println(sb, &quot;Telecom.isRinging(): &quot; + mSystemInterface.isRinging());"
+ errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetService.java"
- line="2694"
- column="43"/>
+ line="2641"
+ column="83"/>
</issue>
<issue
@@ -1900,7 +1878,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="210"
+ line="208"
column="34"/>
</issue>
@@ -1911,7 +1889,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="214"
+ line="212"
column="30"/>
</issue>
@@ -1922,7 +1900,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="349"
+ line="347"
column="29"/>
</issue>
@@ -1933,7 +1911,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="374"
+ line="372"
column="29"/>
</issue>
@@ -1944,7 +1922,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="529"
+ line="527"
column="39"/>
</issue>
@@ -1955,7 +1933,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="590"
+ line="588"
column="43"/>
</issue>
@@ -1966,7 +1944,7 @@
errorLine2=" ~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="665"
+ line="663"
column="47"/>
</issue>
@@ -1977,7 +1955,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="847"
+ line="845"
column="46"/>
</issue>
@@ -1988,7 +1966,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="851"
+ line="849"
column="46"/>
</issue>
@@ -1999,7 +1977,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1023"
+ line="1021"
column="47"/>
</issue>
@@ -2010,7 +1988,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1039"
+ line="1037"
column="47"/>
</issue>
@@ -2021,7 +1999,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1049"
+ line="1047"
column="43"/>
</issue>
@@ -2032,7 +2010,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1062"
+ line="1060"
column="38"/>
</issue>
@@ -2043,7 +2021,7 @@
errorLine2=" ~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1075"
+ line="1073"
column="42"/>
</issue>
@@ -2054,7 +2032,7 @@
errorLine2=" ~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1083"
+ line="1081"
column="38"/>
</issue>
@@ -2065,7 +2043,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1095"
+ line="1093"
column="42"/>
</issue>
@@ -2076,7 +2054,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1115"
+ line="1113"
column="46"/>
</issue>
@@ -2087,7 +2065,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1149"
+ line="1147"
column="46"/>
</issue>
@@ -2098,18 +2076,7 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1152"
- column="46"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
- errorLine1=" mSystemInterface.sendDtmf(event.valueInt, event.device);"
- errorLine2=" ~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1161"
+ line="1150"
column="46"/>
</issue>
@@ -2120,18 +2087,18 @@
errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1255"
+ line="1253"
column="34"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" mSystemInterface.queryPhoneState();"
+ errorLine1=" mSystemInterface.queryPhoneState(mHeadsetService);"
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1276"
+ line="1274"
column="34"/>
</issue>
@@ -2142,7 +2109,7 @@
errorLine2=" ~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1309"
+ line="1307"
column="47"/>
</issue>
@@ -2153,7 +2120,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1336"
+ line="1334"
column="53"/>
</issue>
@@ -2164,7 +2131,7 @@
errorLine2=" ~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1347"
+ line="1345"
column="43"/>
</issue>
@@ -2175,7 +2142,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1379"
+ line="1377"
column="47"/>
</issue>
@@ -2186,7 +2153,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1395"
+ line="1393"
column="47"/>
</issue>
@@ -2197,7 +2164,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1583"
+ line="1581"
column="47"/>
</issue>
@@ -2208,7 +2175,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1613"
+ line="1611"
column="46"/>
</issue>
@@ -2219,7 +2186,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1926"
+ line="1923"
column="30"/>
</issue>
@@ -2230,7 +2197,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1933"
+ line="1930"
column="34"/>
</issue>
@@ -2241,7 +2208,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1941"
+ line="1938"
column="34"/>
</issue>
@@ -2252,7 +2219,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1948"
+ line="1945"
column="34"/>
</issue>
@@ -2263,7 +2230,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1960"
+ line="1957"
column="30"/>
</issue>
@@ -2274,7 +2241,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1969"
+ line="1966"
column="34"/>
</issue>
@@ -2285,7 +2252,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1973"
+ line="1970"
column="34"/>
</issue>
@@ -2296,7 +2263,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1975"
+ line="1972"
column="34"/>
</issue>
@@ -2307,7 +2274,7 @@
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="1978"
+ line="1975"
column="30"/>
</issue>
@@ -2318,7 +2285,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2108"
+ line="2103"
column="63"/>
</issue>
@@ -2329,7 +2296,7 @@
errorLine2=" ~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2146"
+ line="2141"
column="26"/>
</issue>
@@ -2340,7 +2307,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2413"
+ line="2406"
column="26"/>
</issue>
@@ -2351,7 +2318,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2474"
+ line="2467"
column="26"/>
</issue>
@@ -2362,7 +2329,7 @@
errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2592"
+ line="2584"
column="30"/>
</issue>
@@ -2373,29 +2340,18 @@
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2593"
+ line="2585"
column="30"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" } else if (mSystemInterface.isInCall()) {"
- errorLine2=" ~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2594"
- column="37"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
errorLine1=" mSystemInterface.hangupCall(device);"
errorLine2=" ~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2601"
+ line="2593"
column="34"/>
</issue>
@@ -2406,7 +2362,7 @@
errorLine2=" ~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2604"
+ line="2596"
column="35"/>
</issue>
@@ -2417,7 +2373,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2731"
+ line="2723"
column="26"/>
</issue>
@@ -2428,7 +2384,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java"
- line="2731"
+ line="2723"
column="49"/>
</issue>
@@ -2439,7 +2395,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java"
- line="623"
+ line="624"
column="51"/>
</issue>
@@ -2450,7 +2406,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java"
- line="66"
+ line="67"
column="12"/>
</issue>
@@ -2461,7 +2417,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java"
- line="67"
+ line="68"
column="16"/>
</issue>
@@ -2472,7 +2428,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioObjectsFactory.java"
- line="68"
+ line="69"
column="17"/>
</issue>
@@ -2483,7 +2439,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="196"
+ line="204"
column="5"/>
</issue>
@@ -2494,51 +2450,18 @@
errorLine2=" ~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="540"
+ line="593"
column="29"/>
</issue>
<issue
id="VisibleForTests"
message="This method should only be accessed from tests or within private scope"
- errorLine1=" LeAudioTmapGattServer.TMAP_ROLE_FLAG_CG | LeAudioTmapGattServer.TMAP_ROLE_FLAG_UMS;"
- errorLine2=" ~~~~~~~~~~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="633"
- column="39"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
- errorLine1=" LeAudioTmapGattServer.TMAP_ROLE_FLAG_CG | LeAudioTmapGattServer.TMAP_ROLE_FLAG_UMS;"
- errorLine2=" ~~~~~~~~~~~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="633"
- column="81"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
- errorLine1=" mTmapRoleMask |= LeAudioTmapGattServer.TMAP_ROLE_FLAG_BMS;"
- errorLine2=" ~~~~~~~~~~~~~~~~~~">
- <location
- file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="646"
- column="52"/>
- </issue>
-
- <issue
- id="VisibleForTests"
- message="This method should only be accessed from tests or within private scope"
errorLine1=" mTmapGattServer.stop();"
errorLine2=" ~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="706"
+ line="683"
column="29"/>
</issue>
@@ -2549,7 +2472,7 @@
errorLine2=" ~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="2808"
+ line="2775"
column="52"/>
</issue>
@@ -2560,7 +2483,7 @@
errorLine2=" ~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="3541"
+ line="3516"
column="52"/>
</issue>
@@ -2571,7 +2494,7 @@
errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java"
- line="4790"
+ line="4765"
column="29"/>
</issue>
@@ -2670,7 +2593,7 @@
errorLine2=" ~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hfpclient/VendorCommandResponseProcessor.java"
- line="104"
+ line="103"
column="31"/>
</issue>
@@ -2758,7 +2681,7 @@
errorLine2=" ~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="429"
+ line="467"
column="35"/>
</issue>
@@ -2769,7 +2692,7 @@
errorLine2=" ~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java"
- line="216"
+ line="201"
column="27"/>
</issue>
@@ -2780,7 +2703,7 @@
errorLine2=" ~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java"
- line="575"
+ line="574"
column="35"/>
</issue>
@@ -2802,7 +2725,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="6560"
+ line="6561"
column="17"/>
</issue>
@@ -2813,7 +2736,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="235"
+ line="273"
column="13"/>
</issue>
@@ -2824,7 +2747,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/map/BluetoothMapService.java"
- line="418"
+ line="456"
column="25"/>
</issue>
@@ -2835,7 +2758,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java"
- line="177"
+ line="162"
column="13"/>
</issue>
@@ -2846,7 +2769,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java"
- line="325"
+ line="310"
column="13"/>
</issue>
@@ -2857,7 +2780,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java"
- line="559"
+ line="558"
column="25"/>
</issue>
@@ -2901,7 +2824,7 @@
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java"
- line="627"
+ line="628"
column="5"/>
</issue>
@@ -2912,7 +2835,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/btservice/AdapterService.java"
- line="759"
+ line="755"
column="9"/>
</issue>
@@ -2989,7 +2912,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java"
- line="229"
+ line="230"
column="13"/>
</issue>
@@ -3000,7 +2923,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java"
- line="370"
+ line="365"
column="13"/>
</issue>
@@ -3022,7 +2945,7 @@
errorLine2=" ^">
<location
file="packages/modules/Bluetooth/android/app/src/com/android/bluetooth/hid/HidHostService.java"
- line="348"
+ line="335"
column="13"/>
</issue>
diff --git a/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java b/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java
index c87481853a..4ddecc3113 100644
--- a/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java
+++ b/android/app/src/com/android/bluetooth/BluetoothMethodProxy.java
@@ -290,7 +290,7 @@ public class BluetoothMethodProxy {
return handlerThread.getLooper();
}
- /** Peoziws {@link MediaSessionManager#getActiveSessions} */
+ /** Proxies {@link MediaSessionManager#getActiveSessions} */
public @NonNull List<MediaController> mediaSessionManagerGetActiveSessions(
MediaSessionManager manager) {
return manager.getActiveSessions(null);
diff --git a/android/app/src/com/android/bluetooth/ObexAppParameters.java b/android/app/src/com/android/bluetooth/ObexAppParameters.java
index 80a3645cda..bb5942497d 100644
--- a/android/app/src/com/android/bluetooth/ObexAppParameters.java
+++ b/android/app/src/com/android/bluetooth/ObexAppParameters.java
@@ -18,7 +18,6 @@ package com.android.bluetooth;
import com.android.obex.HeaderSet;
-import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
@@ -58,14 +57,7 @@ public final class ObexAppParameters {
}
public static ObexAppParameters fromHeaderSet(HeaderSet headerset) {
- try {
- byte[] raw = (byte[]) headerset.getHeader(HeaderSet.APPLICATION_PARAMETER);
- return new ObexAppParameters(raw);
- } catch (IOException e) {
- // won't happen
- }
-
- return null;
+ return new ObexAppParameters((byte[]) headerset.getHeader(HeaderSet.APPLICATION_PARAMETER));
}
public byte[] getHeader() {
diff --git a/android/app/src/com/android/bluetooth/ObexServerSockets.java b/android/app/src/com/android/bluetooth/ObexServerSockets.java
index afa2f8b646..712049d561 100644
--- a/android/app/src/com/android/bluetooth/ObexServerSockets.java
+++ b/android/app/src/com/android/bluetooth/ObexServerSockets.java
@@ -106,7 +106,7 @@ public class ObexServerSockets {
*
* @param validator a reference to the {@link IObexConnectionHandler} object to call to validate
* an incoming connection.
- * @param isSecure boolean flag to determine whether socket would be secured or inseucure.
+ * @param isSecure boolean flag to determine whether socket would be secured or insecure.
* @return a reference to a {@link ObexServerSockets} object instance.
* <p>TODO: Make public when it becomes possible to determine that the listen-call failed
* due to channel-in-use.
@@ -338,7 +338,7 @@ public class ObexServerSockets {
Log.i(TAG, "RemoteDevice is invalid - creating ObexRejectServer.");
BluetoothObexTransport obexTrans =
new BluetoothObexTransport(connSocket);
- // Create and detach a selfdestructing ServerSession to respond to any
+ // Create and detach a self destructing ServerSession to respond to any
// incoming OBEX signals.
new ServerSession(
obexTrans,
@@ -384,7 +384,7 @@ public class ObexServerSockets {
// If called from another thread, interrupt the thread
if (!Thread.currentThread().equals(this)) {
// TODO: Will this interrupt the thread if it is blocked in synchronized?
- // Else: change to use InterruptableLock
+ // Else: change to use InterruptibleLock
Log.d(TAG, "shutdown called from another thread - interrupt().");
interrupt();
}
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
index 31549ea3fd..bb94277c5a 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpCodecConfig.java
@@ -103,7 +103,7 @@ class A2dpCodecConfig {
}
// Check whether the codecConfig would change current codec config.
- int prioritizedCodecType = getPrioitizedCodecType(newCodecConfig, selectableCodecs);
+ int prioritizedCodecType = getPrioritizedCodecType(newCodecConfig, selectableCodecs);
BluetoothCodecConfig currentCodecConfig = codecStatus.getCodecConfig();
if (prioritizedCodecType == currentCodecConfig.getCodecType()
&& (prioritizedCodecType != newCodecConfig.getCodecType()
@@ -168,7 +168,7 @@ class A2dpCodecConfig {
}
// Get the codec type of the highest priority of selectableCodecs and codecConfig.
- private static int getPrioitizedCodecType(
+ private static int getPrioritizedCodecType(
BluetoothCodecConfig codecConfig, List<BluetoothCodecConfig> selectableCodecs) {
BluetoothCodecConfig prioritizedCodecConfig = codecConfig;
for (BluetoothCodecConfig config : selectableCodecs) {
diff --git a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
index 13b21b6e0f..e739c24c99 100644
--- a/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
+++ b/android/app/src/com/android/bluetooth/a2dp/A2dpService.java
@@ -18,8 +18,13 @@ package com.android.bluetooth.a2dp;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static com.android.bluetooth.Utils.checkCallerTargetSdk;
@@ -219,7 +224,7 @@ public class A2dpService extends ProfileService {
public boolean connect(BluetoothDevice device) {
Log.d(TAG, "connect(): " + device);
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN");
return false;
}
@@ -235,9 +240,7 @@ public class A2dpService extends ProfileService {
List<BluetoothDevice> sinks =
getDevicesMatchingConnectionStates(
new int[] {
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_DISCONNECTING
+ STATE_CONNECTED, STATE_CONNECTING, STATE_DISCONNECTING
});
for (BluetoothDevice sink : sinks) {
if (sink.equals(device)) {
@@ -306,8 +309,8 @@ public class A2dpService extends ProfileService {
synchronized (mStateMachines) {
for (A2dpStateMachine sm : mStateMachines.values()) {
switch (sm.getConnectionState()) {
- case BluetoothProfile.STATE_CONNECTING:
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTING:
+ case STATE_CONNECTED:
if (Objects.equals(device, sm.getDevice())) {
return true; // Already connected or accounted for
}
@@ -356,8 +359,8 @@ public class A2dpService extends ProfileService {
return false;
}
}
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
if (!isOutgoingRequest) {
HeadsetService headsetService = HeadsetService.getHeadsetService();
if (headsetService != null && headsetService.okToAcceptConnection(device, true)) {
@@ -391,7 +394,7 @@ public class A2dpService extends ProfileService {
mAdapterService.getRemoteUuids(device), BluetoothUuid.A2DP_SINK)) {
continue;
}
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
A2dpStateMachine sm = mStateMachines.get(device);
if (sm != null) {
connectionState = sm.getConnectionState();
@@ -427,7 +430,7 @@ public class A2dpService extends ProfileService {
synchronized (mStateMachines) {
A2dpStateMachine sm = mStateMachines.get(device);
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -532,7 +535,7 @@ public class A2dpService extends ProfileService {
+ "no state machine");
return false;
}
- if (sm.getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
+ if (sm.getConnectionState() != STATE_CONNECTED) {
Log.e(
TAG,
"setActiveDevice("
@@ -629,9 +632,9 @@ public class A2dpService extends ProfileService {
device, BluetoothProfile.A2DP, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -1181,7 +1184,7 @@ 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;
}
@@ -1303,17 +1306,17 @@ public class A2dpService extends ProfileService {
if ((device == null) || (fromState == toState)) {
return;
}
- if (toState == BluetoothProfile.STATE_CONNECTED) {
+ if (toState == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.A2DP);
}
// Set the active device if only one connected device is supported and it was connected
- if (toState == BluetoothProfile.STATE_CONNECTED && (mMaxConnectedAudioDevices == 1)) {
+ if (toState == STATE_CONNECTED && (mMaxConnectedAudioDevices == 1)) {
setActiveDevice(device);
}
// When disconnected, ActiveDeviceManager will call setActiveDevice(null)
// Check if the device is disconnected - if unbond, remove the state machine
- if (toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (toState == STATE_DISCONNECTED) {
if (mAdapterService.getBondState(device) == BluetoothDevice.BOND_NONE) {
if (mFactory.getAvrcpTargetService() != null) {
mFactory.getAvrcpTargetService().removeStoredVolumeForDevice(device);
@@ -1437,7 +1440,7 @@ public class A2dpService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
A2dpService service = getServiceAndEnforceConnect(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -1484,7 +1487,7 @@ public class A2dpService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
A2dpService service = getServiceAndEnforceConnect(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
diff --git a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
index 7ad03639a7..10b9249bad 100644
--- a/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
+++ b/android/app/src/com/android/bluetooth/a2dpsink/A2dpSinkService.java
@@ -17,6 +17,11 @@ package com.android.bluetooth.a2dpsink;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
@@ -249,7 +254,7 @@ public class A2dpSinkService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
A2dpSinkService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
}
@@ -271,7 +276,7 @@ public class A2dpSinkService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
A2dpSinkService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
@@ -314,7 +319,7 @@ public class A2dpSinkService extends ProfileService {
if (device == null) {
throw new IllegalArgumentException("Null device");
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.w(TAG, "Connection not allowed: <" + device + "> is CONNECTION_POLICY_FORBIDDEN");
return false;
}
@@ -354,8 +359,7 @@ public class A2dpSinkService extends ProfileService {
return false;
}
int connectionState = stateMachine.getState();
- if (connectionState == BluetoothProfile.STATE_DISCONNECTED
- || connectionState == BluetoothProfile.STATE_DISCONNECTING) {
+ if (connectionState == STATE_DISCONNECTED || connectionState == STATE_DISCONNECTING) {
return false;
}
// upon completion of disconnect, the state machine will remove itself from the available
@@ -437,14 +441,12 @@ public class A2dpSinkService extends ProfileService {
* BluetoothProfile#STATE_DISCONNECTING} if this profile is being disconnected
*/
public int getConnectionState(BluetoothDevice device) {
- if (device == null) return BluetoothProfile.STATE_DISCONNECTED;
+ if (device == null) return STATE_DISCONNECTED;
A2dpSinkStateMachine stateMachine;
synchronized (mDeviceStateMap) {
stateMachine = mDeviceStateMap.get(device);
}
- return (stateMachine == null)
- ? BluetoothProfile.STATE_DISCONNECTED
- : stateMachine.getState();
+ return (stateMachine == null) ? STATE_DISCONNECTED : stateMachine.getState();
}
/**
@@ -468,9 +470,9 @@ public class A2dpSinkService extends ProfileService {
device, BluetoothProfile.A2DP_SINK, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
diff --git a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
index 248fd20c14..26f37f8267 100644
--- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
+++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerList.java
@@ -450,7 +450,7 @@ public class MediaPlayerList {
info.browsable = true;
ret.add(info);
}
- Log.i(TAG, "getMediaPlayerList: number of mediaplayers: " + mMediaPlayers.size());
+ Log.i(TAG, "getMediaPlayerList: number of mediaPlayers: " + mMediaPlayers.size());
// Also list non-browsable players, they can be selected if controller supports it.
for (MediaPlayerWrapper mediaPlayer : mMediaPlayers.values()) {
// Skip player if already added as browsable
@@ -473,7 +473,7 @@ public class MediaPlayerList {
info.name = BLUETOOTH_PLAYER_NAME;
info.browsable = true;
if (mBrowsablePlayers.size() == 0) {
- // Set Bluetooth Player as non-browable if there is not browsable player exist.
+ // Set Bluetooth Player as non-browsable if there is not browsable player exist.
info.browsable = false;
}
ret.add(info);
@@ -1235,7 +1235,7 @@ public class MediaPlayerList {
/** For testing purposes only, sets the {@link #mAudioPlaybackIsActive} flag. */
@VisibleForTesting
- void injectAudioPlaybacActive(boolean isActive) {
+ void injectAudioPlaybackActive(boolean isActive) {
mAudioPlaybackIsActive = isActive;
updateMediaForAudioPlayback();
}
@@ -1339,7 +1339,7 @@ public class MediaPlayerList {
* MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY}, the session change shall be ignored as this
* flag is used only by Telecom to handle wired headsets key events.
*
- * <p>It can happen that {@code token} is null, in such case wecan still check if we have a
+ * <p>It can happen that {@code token} is null, in such case we can still check if we have a
* {@link MediaController} corresponding to {@code packageName} and set it as active.
*/
@VisibleForTesting
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 36a9ee9793..079319d07f 100644
--- a/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java
+++ b/android/app/src/com/android/bluetooth/audio_util/MediaPlayerWrapper.java
@@ -396,7 +396,7 @@ public class MediaPlayerWrapper {
Log.e(TAG, "Timeout while waiting for metadata to sync for " + mPackageName);
Log.e(TAG, " └ Current Metadata: " + Util.toMetadata(mContext, getMetadata()));
- Log.e(TAG, " └ Current Playstate: " + getPlaybackState());
+ Log.e(TAG, " └ Current PlaybackState: " + getPlaybackState());
List<Metadata> current_queue = Util.toMetadataList(mContext, getQueue());
for (int i = 0; i < current_queue.size(); i++) {
Log.e(TAG, " └ QueueItem(" + i + "): " + current_queue.get(i));
@@ -574,7 +574,7 @@ public class MediaPlayerWrapper {
}
/**
- * Checks wheter the core information of two PlaybackStates match. This function allows a
+ * Checks whether the core information of two PlaybackStates match. This function allows a
* certain amount of deviation between the position fields of the PlaybackStates. This is to
* prevent matches from failing when updates happen in quick succession.
*
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
index 3ab495fdb0..9df35f9388 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpBipObexServer.java
@@ -88,17 +88,11 @@ public class AvrcpBipObexServer extends ServerRequestHandler {
@Override
public int onConnect(final HeaderSet request, HeaderSet reply) {
debug("onConnect");
- try {
- byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
- debug("onConnect - uuid=" + Arrays.toString(uuid));
- if (!Arrays.equals(uuid, BLUETOOTH_UUID_AVRCP_COVER_ART)) {
- warn("onConnect - uuid didn't match. Not Acceptable");
- return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
- }
- // ...
- } catch (IOException e) {
- warn("onConnect - Something bad happened");
- return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+ byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
+ debug("onConnect - uuid=" + Arrays.toString(uuid));
+ if (!Arrays.equals(uuid, BLUETOOTH_UUID_AVRCP_COVER_ART)) {
+ warn("onConnect - uuid didn't match. Not Acceptable");
+ return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
}
reply.setHeader(HeaderSet.WHO, BLUETOOTH_UUID_AVRCP_COVER_ART);
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
index 232bdfa56a..1a015287f4 100644
--- a/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
+++ b/android/app/src/com/android/bluetooth/avrcp/AvrcpCoverArtService.java
@@ -88,7 +88,7 @@ public class AvrcpCoverArtService {
/**
* Stop the AVRCP Cover Art Service.
*
- * <p>Tear down existing connections, remove ourselved from the SDP record.
+ * <p>Tear down existing connections, remove ourselves from the SDP record.
*/
public boolean stop() {
debug("Stopping service");
diff --git a/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java b/android/app/src/com/android/bluetooth/avrcp/AvrcpTargetService.java
index 559578dc71..29e6e6676b 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;
@@ -144,7 +145,7 @@ public class AvrcpTargetService extends ProfileService {
mMediaPlayerList.init(new ListCallback());
}
- if (!mAvrcpVersion.isAtleastVersion(AvrcpVersion.AVRCP_VERSION_1_6)) {
+ if (!mAvrcpVersion.isAtLeastVersion(AvrcpVersion.AVRCP_VERSION_1_6)) {
Log.e(TAG, "Please use AVRCP version 1.6 to enable cover art");
mAvrcpCoverArtService = null;
} else {
@@ -341,7 +342,7 @@ public class AvrcpTargetService extends ProfileService {
*/
public void handleA2dpConnectionStateChanged(BluetoothDevice device, int newState) {
if (device == null) return;
- if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (newState == STATE_DISCONNECTED) {
// If there is no connection, disconnectDevice() will do nothing
if (mNativeInterface.disconnectDevice(device)) {
Log.d(TAG, "request to disconnect device " + device);
diff --git a/android/app/src/com/android/bluetooth/avrcp/helpers/AvrcpVersion.java b/android/app/src/com/android/bluetooth/avrcp/helpers/AvrcpVersion.java
index c475db1ef1..fa8d28d120 100644
--- a/android/app/src/com/android/bluetooth/avrcp/helpers/AvrcpVersion.java
+++ b/android/app/src/com/android/bluetooth/avrcp/helpers/AvrcpVersion.java
@@ -38,7 +38,7 @@ final class AvrcpVersion {
public int minor;
public static AvrcpVersion getCurrentSystemPropertiesValue() {
- // Make sure this default version agrees with AVRC_GetProfileVersion
+ // Make sure this default version agrees with AVRCP_GetProfileVersion
String defaultVersion =
Flags.avrcp16Default() ? AVRCP_VERSION_1_6_STRING : AVRCP_VERSION_1_5_STRING;
@@ -58,7 +58,7 @@ final class AvrcpVersion {
}
}
- public boolean isAtleastVersion(AvrcpVersion version) {
+ public boolean isAtLeastVersion(AvrcpVersion version) {
if (version == null) return true;
if (major < version.major) return false;
if (major > version.major) return true;
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
index 1407b9292f..dd5f3bb067 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClient.java
@@ -16,9 +16,14 @@
package com.android.bluetooth.avrcpcontroller;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+import static android.bluetooth.BluetoothProfile.getConnectionStateName;
+
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.HandlerThread;
@@ -79,7 +84,7 @@ public class AvrcpBipClient {
private final BluetoothDevice mDevice;
private final int mPsm;
- private int mState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mState = STATE_DISCONNECTED;
private BluetoothSocket mSocket;
private BluetoothObexTransport mTransport;
@@ -185,7 +190,7 @@ public class AvrcpBipClient {
* @return True if connected, False otherwise
*/
public boolean isConnected() {
- return getState() == BluetoothProfile.STATE_CONNECTED;
+ return getState() == STATE_CONNECTED;
}
/**
@@ -247,7 +252,7 @@ public class AvrcpBipClient {
}
try {
- setConnectionState(BluetoothProfile.STATE_CONNECTING);
+ setConnectionState(STATE_CONNECTING);
mSocket = mDevice.createL2capSocket(mPsm);
mSocket.connect();
@@ -261,7 +266,7 @@ public class AvrcpBipClient {
headerSet = mSession.connect(headerSet);
int responseCode = headerSet.getResponseCode();
if (responseCode == ResponseCodes.OBEX_HTTP_OK) {
- setConnectionState(BluetoothProfile.STATE_CONNECTED);
+ setConnectionState(STATE_CONNECTED);
debug("Connection established");
} else {
error("Error connecting, code: " + responseCode);
@@ -278,7 +283,7 @@ public class AvrcpBipClient {
if (mSession == null) return;
try {
- setConnectionState(BluetoothProfile.STATE_DISCONNECTING);
+ setConnectionState(STATE_DISCONNECTING);
mSession.disconnect(null);
debug("Disconnected from OBEX session");
} catch (IOException e) {
@@ -288,7 +293,7 @@ public class AvrcpBipClient {
}
try {
- setConnectionState(BluetoothProfile.STATE_CONNECTING);
+ setConnectionState(STATE_CONNECTING);
HeaderSet headerSet = new HeaderSet();
headerSet.setHeader(HeaderSet.TARGET, BLUETOOTH_UUID_AVRCP_COVER_ART);
@@ -296,7 +301,7 @@ public class AvrcpBipClient {
headerSet = mSession.connect(headerSet);
int responseCode = headerSet.getResponseCode();
if (responseCode == ResponseCodes.OBEX_HTTP_OK) {
- setConnectionState(BluetoothProfile.STATE_CONNECTED);
+ setConnectionState(STATE_CONNECTED);
debug("Reconnection established");
} else {
error("Error reconnecting, code: " + responseCode);
@@ -319,7 +324,7 @@ public class AvrcpBipClient {
*/
private synchronized void disconnect() {
if (mSession != null) {
- setConnectionState(BluetoothProfile.STATE_DISCONNECTING);
+ setConnectionState(STATE_DISCONNECTING);
try {
mSession.disconnect(null);
@@ -341,7 +346,7 @@ public class AvrcpBipClient {
mTransport = null;
mSocket = null;
}
- setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
+ setConnectionState(STATE_DISCONNECTED);
}
private void executeRequest(BipRequest request) {
@@ -423,28 +428,12 @@ public class AvrcpBipClient {
}
}
- @VisibleForTesting
- String getStateName() {
- int state = getState();
- switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED:
- return "Disconnected";
- case BluetoothProfile.STATE_CONNECTING:
- return "Connecting";
- case BluetoothProfile.STATE_CONNECTED:
- return "Connected";
- case BluetoothProfile.STATE_DISCONNECTING:
- return "Disconnecting";
- }
- return "Unknown";
- }
-
@Override
public String toString() {
return "<AvrcpBipClient"
+ (" device=" + mDevice)
+ (" psm=" + mPsm)
- + (" state=" + getStateName())
+ + (" state=" + getConnectionStateName(getState()))
+ ">";
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
index b01dbc3ec0..0b29c00f3e 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerNativeInterface.java
@@ -232,7 +232,7 @@ public class AvrcpControllerNativeInterface {
+ (" uid=" + uid)
+ (" type=" + type)
+ (" name=" + name)
- + (" attrids=" + Arrays.toString(attrIds))
+ + (" attrIds=" + Arrays.toString(attrIds))
+ (" attrVals=" + Arrays.toString(attrVals)));
return new AvrcpItem.Builder()
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
index 318ce4ba4c..12344bd56d 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerService.java
@@ -17,6 +17,9 @@
package com.android.bluetooth.avrcpcontroller;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -24,7 +27,6 @@ import android.annotation.RequiresPermission;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothAvrcpPlayerSettings;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothAvrcpController;
import android.content.AttributionSource;
import android.content.Intent;
@@ -422,7 +424,7 @@ public class AvrcpControllerService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
AvrcpControllerService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
}
@@ -705,8 +707,7 @@ public class AvrcpControllerService extends ProfileService {
return false;
}
int connectionState = stateMachine.getState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
stateMachine.disconnect();
@@ -790,9 +791,7 @@ public class AvrcpControllerService extends ProfileService {
synchronized int getConnectionState(BluetoothDevice device) {
AvrcpControllerStateMachine stateMachine = mDeviceStateMap.get(device);
- return (stateMachine == null)
- ? BluetoothProfile.STATE_DISCONNECTED
- : stateMachine.getState();
+ return (stateMachine == null) ? STATE_DISCONNECTED : stateMachine.getState();
}
@Override
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
index 8d8690a4bb..a7475476b4 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachine.java
@@ -17,6 +17,10 @@
package com.android.bluetooth.avrcpcontroller;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
@@ -126,7 +130,7 @@ class AvrcpControllerStateMachine extends StateMachine {
protected final Disconnecting mDisconnecting;
protected int mCoverArtPsm;
- protected int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED;
+ protected int mMostRecentState = STATE_DISCONNECTED;
private boolean mShouldSendPlayOnFocusRecovery = false;
private boolean mRemoteControlConnected = false;
@@ -256,9 +260,7 @@ class AvrcpControllerStateMachine extends StateMachine {
ProfileService.println(sb, "Control: " + mRemoteControlConnected);
ProfileService.println(sb, "Browsing: " + mBrowsingConnected);
ProfileService.println(
- sb,
- "Cover Art: "
- + (mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED));
+ sb, "Cover Art: " + (mCoverArtManager.getState(mDevice) == STATE_CONNECTED));
ProfileService.println(sb, "Addressed Player ID: " + mAddressedPlayerId);
ProfileService.println(sb, "Browsed Player ID: " + mBrowseTree.getCurrentBrowsedPlayer());
@@ -321,7 +323,7 @@ class AvrcpControllerStateMachine extends StateMachine {
// Called from "connected" state, which assumes either control or browse is connected
if (mCoverArtManager != null
&& mCoverArtPsm != 0
- && mCoverArtManager.getState(mDevice) != BluetoothProfile.STATE_CONNECTED) {
+ && mCoverArtManager.getState(mDevice) != STATE_CONNECTED) {
debug("Attempting to connect to AVRCP BIP, psm: " + mCoverArtPsm);
mCoverArtManager.connect(mDevice, /* psm */ mCoverArtPsm);
}
@@ -330,7 +332,7 @@ class AvrcpControllerStateMachine extends StateMachine {
synchronized void refreshCoverArt() {
if (mCoverArtManager != null
&& mCoverArtPsm != 0
- && mCoverArtManager.getState(mDevice) == BluetoothProfile.STATE_CONNECTED) {
+ && mCoverArtManager.getState(mDevice) == STATE_CONNECTED) {
debug("Attempting to refresh AVRCP BIP OBEX session, psm: " + mCoverArtPsm);
mCoverArtManager.refreshSession(mDevice);
}
@@ -415,10 +417,10 @@ class AvrcpControllerStateMachine extends StateMachine {
@Override
public void enter() {
debug("Disconnected: Entered");
- if (mMostRecentState != BluetoothProfile.STATE_DISCONNECTED) {
+ if (mMostRecentState != STATE_DISCONNECTED) {
sendMessage(CLEANUP);
}
- broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED);
+ broadcastConnectionStateChanged(STATE_DISCONNECTED);
}
@Override
@@ -448,7 +450,7 @@ class AvrcpControllerStateMachine extends StateMachine {
@Override
public void enter() {
debug("Connecting: Enter Connecting");
- broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTING);
+ broadcastConnectionStateChanged(STATE_CONNECTING);
transitionTo(mConnected);
}
}
@@ -458,8 +460,8 @@ class AvrcpControllerStateMachine extends StateMachine {
@Override
public void enter() {
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTING) {
- broadcastConnectionStateChanged(BluetoothProfile.STATE_CONNECTED);
+ if (mMostRecentState == STATE_CONNECTING) {
+ broadcastConnectionStateChanged(STATE_CONNECTED);
mService.getBrowseTree().mRootNode.addChild(mBrowseTree.mRootNode);
BluetoothMediaBrowserService.onBrowseNodeChanged(
mService.getBrowseTree().mRootNode);
@@ -686,7 +688,7 @@ class AvrcpControllerStateMachine extends StateMachine {
mAddressedPlayer = mAvailablePlayerList.get(mAddressedPlayerId);
// Fetch metadata including the now playing list. The specification claims that
- // the player feature bit only incidates if the player *natively* supports a now
+ // the player feature bit only indicates if the player *natively* supports a now
// playing list. However, now playing is mandatory if browsing is supported,
// even if the player doesn't support it. A list of one item can be returned
// instead.
@@ -813,7 +815,7 @@ class AvrcpControllerStateMachine extends StateMachine {
(byte) 1,
new byte[] {PlayerApplicationSettings.REPEAT_STATUS},
new byte[] {
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.REPEAT_STATUS, repeatMode)
});
}
@@ -824,7 +826,7 @@ class AvrcpControllerStateMachine extends StateMachine {
(byte) 1,
new byte[] {PlayerApplicationSettings.SHUFFLE_STATUS},
new byte[] {
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.SHUFFLE_STATUS, shuffleMode)
});
}
@@ -1192,7 +1194,7 @@ class AvrcpControllerStateMachine extends StateMachine {
onBrowsingDisconnected();
mService.getBrowseTree().mRootNode.removeChild(mBrowseTree.mRootNode);
BluetoothMediaBrowserService.onBrowseNodeChanged(mService.getBrowseTree().mRootNode);
- broadcastConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING);
+ broadcastConnectionStateChanged(STATE_DISCONNECTING);
transitionTo(mDisconnected);
}
}
@@ -1403,7 +1405,7 @@ class AvrcpControllerStateMachine extends StateMachine {
if (mMostRecentState == currentState) {
return;
}
- if (currentState == BluetoothProfile.STATE_CONNECTED) {
+ if (currentState == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(
BluetoothMetricsProto.ProfileId.AVRCP_CONTROLLER);
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtManager.java
index eac5f2644b..9fb548a2bb 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;
@@ -86,7 +88,7 @@ public class AvrcpCoverArtManager {
}
/**
- * A thread-safe collection of BIP connection specific imformation meant to be cleared each time
+ * A thread-safe collection of BIP connection specific information meant to be cleared each time
* a client disconnects from the Target's BIP OBEX server.
*
* <p>Currently contains the mapping of image handles seen to assigned UUIDs.
@@ -215,11 +217,11 @@ public class AvrcpCoverArtManager {
* Get the client connection state for a particular device's BIP Client
*
* @param device The Bluetooth device you want connection status for
- * @return Connection status, based on BluetoothProfile.STATE_* constants
+ * @return Connection status, based on STATE_* constants
*/
public int getState(BluetoothDevice device) {
AvrcpBipClient client = getClient(device);
- if (client == null) return BluetoothProfile.STATE_DISCONNECTED;
+ if (client == null) return STATE_DISCONNECTED;
return client.getState();
}
@@ -403,14 +405,14 @@ public class AvrcpCoverArtManager {
@Override
public void onConnectionStateChanged(int oldState, int newState) {
debug(mDevice + ": " + oldState + " -> " + newState);
- if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (newState == STATE_CONNECTED) {
// Ensure the handle map is cleared since old ones are invalid on a new connection
clearHandleUuids(mDevice);
// Once we're connected fetch the current metadata again in case the target has an
// image handle they can now give us. Only do this if we don't already have one.
mService.getCurrentMetadataIfNoCoverArt(mDevice);
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ } else if (newState == STATE_DISCONNECTED) {
AvrcpBipClient client = getClient(mDevice);
boolean shouldReconnect = (client != null);
disconnect(mDevice);
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
index a188eb5494..7dcc1eb949 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorage.java
@@ -82,7 +82,7 @@ public class AvrcpCoverArtStorage {
public Uri addImage(BluetoothDevice device, String imageUuid, Bitmap image) {
debug("Storing image '" + imageUuid + "' from device " + device);
if (device == null || imageUuid == null || "".equals(imageUuid) || image == null) {
- debug("Cannot store image. Improper aruguments");
+ debug("Cannot store image. Improper arguments");
return null;
}
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
index ac7133da61..6c68eb33d5 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/AvrcpPlayer.java
@@ -269,7 +269,7 @@ class AvrcpPlayer {
/**
* Set the device that this Player came from
*
- * @param device The BleutoothDevice representing the remote device
+ * @param device The BluetoothDevice representing the remote device
* @return This object, so you can continue building
*/
public Builder setDevice(BluetoothDevice device) {
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
index 4a27b1582c..2dd97d22e3 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettings.java
@@ -26,7 +26,7 @@ import com.android.internal.annotations.VisibleForTesting;
import java.util.ArrayList;
/*
- * Contains information Player Application Setting extended from BluetootAvrcpPlayerSettings
+ * Contains information Player Application Setting extended from BluetoothAvrcpPlayerSettings
*/
class PlayerApplicationSettings {
private static final String TAG = PlayerApplicationSettings.class.getSimpleName();
@@ -144,7 +144,7 @@ class PlayerApplicationSettings {
}
// Convert an AVRCP Setting/Value pair into the native equivalent value;
- static byte mapAvrcpPlayerSettingstoBTattribVal(int mSetting, int mSettingVal) {
+ static byte mapAvrcpPlayerSettingsToBTattribVal(int mSetting, int mSettingVal) {
if (mSetting == REPEAT_STATUS) {
switch (mSettingVal) {
case PlaybackStateCompat.REPEAT_MODE_NONE:
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 504f9e92c6..6777f0fae7 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptor.java
@@ -132,7 +132,7 @@ public class BipImageDescriptor {
/**
* Set the max file size of the image for the descriptor you're building
*
- * @param size The maxe image size in bytes
+ * @param size The max image size in bytes
* @return This object so you can continue building
*/
public Builder setMaxFileSize(int size) {
diff --git a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
index 88fca6aa1a..743db63ef4 100644
--- a/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
+++ b/android/app/src/com/android/bluetooth/avrcpcontroller/bip/BipRequest.java
@@ -64,10 +64,10 @@ abstract class BipRequest {
public abstract void execute(ClientSession session) throws IOException;
/**
- * A generica GET operation, providing overridable hooks to read response headers and content.
+ * A generic GET operation, providing overridable hooks to read response headers and content.
*/
protected void executeGet(ClientSession session) throws IOException {
- debug("Exeucting GET");
+ debug("Executing GET");
setOperation(null);
try {
ClientOperation operation = (ClientOperation) session.get(mHeaderSet);
@@ -82,15 +82,15 @@ abstract class BipRequest {
mResponseCode = operation.getResponseCode();
} catch (IOException e) {
mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
- error("GET threw an exeception: " + e);
+ error("GET threw an exception: " + e);
throw e;
}
debug("GET final response code is '" + mResponseCode + "'");
}
- /** A generica PUT operation, providing overridable hooks to read response headers. */
+ /** A generic PUT operation, providing overridable hooks to read response headers. */
protected void executePut(ClientSession session, byte[] body) throws IOException {
- debug("Exeucting PUT");
+ debug("Executing PUT");
setOperation(null);
mHeaderSet.setHeader(HeaderSet.LENGTH, Long.valueOf(body.length));
try {
@@ -104,7 +104,7 @@ abstract class BipRequest {
mResponseCode = operation.getResponseCode();
} catch (IOException e) {
mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
- error("PUT threw an exeception: " + e);
+ error("PUT threw an exception: " + e);
throw e;
}
debug("PUT final response code is '" + mResponseCode + "'");
diff --git a/android/app/src/com/android/bluetooth/bas/BatteryService.java b/android/app/src/com/android/bluetooth/bas/BatteryService.java
index 23cda4bd5c..ac5eaab2f9 100644
--- a/android/app/src/com/android/bluetooth/bas/BatteryService.java
+++ b/android/app/src/com/android/bluetooth/bas/BatteryService.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.bas;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static java.util.Objects.requireNonNull;
import android.bluetooth.BluetoothDevice;
@@ -136,7 +141,7 @@ public class BatteryService extends ProfileService {
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.w(TAG, "Cannot connect to " + device + " : policy forbidden");
return false;
}
@@ -164,7 +169,7 @@ public class BatteryService extends ProfileService {
*/
public boolean connectIfPossible(BluetoothDevice device) {
if (device == null
- || getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
+ || getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN
|| !Utils.arrayContains(
mAdapterService.getRemoteUuids(device), BluetoothUuid.BATTERY)) {
return false;
@@ -215,8 +220,8 @@ public class BatteryService extends ProfileService {
if (bondState != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "canConnect: return false, bondState=" + bondState);
return false;
- } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "canConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -239,7 +244,7 @@ public class BatteryService extends ProfileService {
}
// Check if the device is disconnected - if unbonded, remove the state machine
- if (toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (toState == STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
Log.d(TAG, device + " is unbonded. Remove state machine");
@@ -259,7 +264,7 @@ public class BatteryService extends ProfileService {
}
synchronized (mStateMachines) {
for (BluetoothDevice device : bondedDevices) {
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
BatteryStateMachine sm = mStateMachines.get(device);
if (sm != null) {
connectionState = sm.getConnectionState();
@@ -296,7 +301,7 @@ public class BatteryService extends ProfileService {
synchronized (mStateMachines) {
BatteryStateMachine sm = mStateMachines.get(device);
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -320,9 +325,9 @@ public class BatteryService extends ProfileService {
Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(
device, BluetoothProfile.BATTERY, connectionPolicy);
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -370,7 +375,7 @@ public class BatteryService extends ProfileService {
if (sm == null) {
return;
}
- if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (sm.getConnectionState() != STATE_DISCONNECTED) {
return;
}
removeStateMachine(device);
diff --git a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
index 3b1fa511e1..abd223648d 100644
--- a/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
+++ b/android/app/src/com/android/bluetooth/bas/BatteryStateMachine.java
@@ -20,6 +20,10 @@ import static android.bluetooth.BluetoothDevice.BATTERY_LEVEL_UNKNOWN;
import static android.bluetooth.BluetoothDevice.PHY_LE_1M_MASK;
import static android.bluetooth.BluetoothDevice.PHY_LE_2M_MASK;
import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.bluetooth.BluetoothProfile.getConnectionStateName;
import static java.util.Objects.requireNonNull;
@@ -71,7 +75,7 @@ public class BatteryStateMachine extends StateMachine {
private Connecting mConnecting;
private Connected mConnected;
private Disconnecting mDisconnecting;
- private int mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mLastConnectionState = STATE_DISCONNECTED;
private final BatteryService mService;
@@ -119,7 +123,7 @@ public class BatteryStateMachine extends StateMachine {
}
synchronized boolean isConnected() {
- return mLastConnectionState == BluetoothProfile.STATE_CONNECTED;
+ return mLastConnectionState == STATE_CONNECTED;
}
private static String messageWhatToString(int what) {
@@ -236,11 +240,11 @@ public class BatteryStateMachine extends StateMachine {
mBluetoothGatt = null;
}
- if (mLastConnectionState != BluetoothProfile.STATE_DISCONNECTED) {
+ if (mLastConnectionState != STATE_DISCONNECTED) {
// Don't broadcast during startup
- dispatchConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTED);
+ dispatchConnectionStateChanged(STATE_DISCONNECTED);
}
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ mLastConnectionState = STATE_DISCONNECTED;
}
@Override
@@ -286,8 +290,8 @@ public class BatteryStateMachine extends StateMachine {
@Override
public void enter() {
log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what));
- dispatchConnectionStateChanged(BluetoothProfile.STATE_CONNECTING);
- mLastConnectionState = BluetoothProfile.STATE_CONNECTING;
+ dispatchConnectionStateChanged(STATE_CONNECTING);
+ mLastConnectionState = STATE_CONNECTING;
}
@Override
@@ -318,11 +322,11 @@ public class BatteryStateMachine extends StateMachine {
// in Connecting state
private void processConnectionEvent(int state) {
switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED -> {
+ case STATE_DISCONNECTED -> {
Log.w(TAG, "Device disconnected: " + mDevice);
transitionTo(mDisconnected);
}
- case BluetoothProfile.STATE_CONNECTED -> transitionTo(mConnected);
+ case STATE_CONNECTED -> transitionTo(mConnected);
default -> Log.e(TAG, "Incorrect state: " + state);
}
}
@@ -337,8 +341,8 @@ public class BatteryStateMachine extends StateMachine {
public void enter() {
log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(MESSAGE_CONNECT_TIMEOUT, CONNECT_TIMEOUT.toMillis());
- dispatchConnectionStateChanged(BluetoothProfile.STATE_DISCONNECTING);
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING;
+ dispatchConnectionStateChanged(STATE_DISCONNECTING);
+ mLastConnectionState = STATE_DISCONNECTING;
}
@Override
@@ -370,11 +374,11 @@ public class BatteryStateMachine extends StateMachine {
// in Disconnecting state
private void processConnectionEvent(int state) {
switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED -> {
+ case STATE_DISCONNECTED -> {
Log.i(TAG, "Disconnected: " + mDevice);
transitionTo(mDisconnected);
}
- case BluetoothProfile.STATE_CONNECTED -> {
+ case STATE_CONNECTED -> {
// TODO: Check if connect while disconnecting is okay. It is related to
// MESSAGE_CONNECT_TIMEOUT as well.
@@ -397,8 +401,8 @@ public class BatteryStateMachine extends StateMachine {
@Override
public void enter() {
log(TAG, "Enter (" + mDevice + "): " + messageWhatToString(getCurrentMessage().what));
- dispatchConnectionStateChanged(BluetoothProfile.STATE_CONNECTED);
- mLastConnectionState = BluetoothProfile.STATE_CONNECTED;
+ dispatchConnectionStateChanged(STATE_CONNECTED);
+ mLastConnectionState = STATE_CONNECTED;
discoverServicesGatt();
}
@@ -434,7 +438,7 @@ public class BatteryStateMachine extends StateMachine {
// in Connected state
private void processConnectionEvent(int state) {
switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED -> {
+ case STATE_DISCONNECTED -> {
Log.i(TAG, "Disconnected from " + mDevice);
transitionTo(mDisconnected);
}
diff --git a/android/app/src/com/android/bluetooth/bass_client/BaseData.java b/android/app/src/com/android/bluetooth/bass_client/BaseData.java
index 948abff89c..ee768d5a2d 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BaseData.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BaseData.java
@@ -33,7 +33,7 @@ class BaseData {
private static final int METADATA_LEVEL1 = 1;
private static final int METADATA_LEVEL2 = 2;
private static final int METADATA_LEVEL3 = 3;
- private static final int METADATA_PRESENTATIONDELAY_LENGTH = 3;
+ private static final int METADATA_PRESENTATION_DELAY_LENGTH = 3;
private static final int METADATA_CODEC_LENGTH = 5;
private static final int CODEC_CONFIGURATION_SAMPLE_RATE_TYPE = 0x01;
private static final int CODEC_CONFIGURATION_FRAME_DURATION_TYPE = 0x02;
@@ -125,7 +125,7 @@ class BaseData {
static BaseData parseBaseData(byte[] serviceData) {
if (serviceData == null) {
Log.e(TAG, "Invalid service data for BaseData construction");
- throw new IllegalArgumentException("Basedata: serviceData is null");
+ throw new IllegalArgumentException("BaseData: serviceData is null");
}
BaseInformation levelOne = new BaseInformation();
List<BaseInformation> levelTwo = new ArrayList<>();
@@ -137,7 +137,7 @@ class BaseData {
levelOne.level = METADATA_LEVEL1;
int offset = 0;
System.arraycopy(serviceData, offset, levelOne.presentationDelay, 0, 3);
- offset += METADATA_PRESENTATIONDELAY_LENGTH;
+ offset += METADATA_PRESENTATION_DELAY_LENGTH;
levelOne.numSubGroups = serviceData[offset++];
levelOne.print();
log("levelOne subgroups" + levelOne.numSubGroups);
@@ -174,7 +174,7 @@ class BaseData {
offset = pair2.second;
}
}
- consolidateBaseofLevelTwo(levelTwo, levelThree);
+ consolidateBaseOfLevelTwo(levelTwo, levelThree);
return new BaseData(levelOne, levelTwo, levelThree, numOfBISIndices);
}
@@ -269,19 +269,19 @@ class BaseData {
return new Pair<BaseInformation, Integer>(node, offset);
}
- static void consolidateBaseofLevelTwo(
+ static void consolidateBaseOfLevelTwo(
List<BaseInformation> levelTwo, List<BaseInformation> levelThree) {
int startIdx = 0;
int children = 0;
for (int i = 0; i < levelTwo.size(); i++) {
startIdx = startIdx + children;
children = children + levelTwo.get(i).numSubGroups;
- consolidateBaseofLevelThree(
+ consolidateBaseOfLevelThree(
levelTwo, levelThree, i, startIdx, levelTwo.get(i).numSubGroups);
}
}
- static void consolidateBaseofLevelThree(
+ static void consolidateBaseOfLevelThree(
List<BaseInformation> levelTwo,
List<BaseInformation> levelThree,
int parentSubgroup,
@@ -308,7 +308,7 @@ class BaseData {
return mLevelThree;
}
- public byte getNumberOfSubgroupsofBIG() {
+ public byte getNumberOfSubGroupsOfBIG() {
byte ret = 0;
if (mLevelOne != null) {
ret = mLevelOne.numSubGroups;
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 ab811c2589..f68340b53d 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassClientService.java
@@ -19,7 +19,11 @@ package com.android.bluetooth.bass_client;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID;
import static com.android.bluetooth.flags.Flags.leaudioBassScanWithInternalScanController;
@@ -719,13 +723,13 @@ public class BassClientService extends ProfileService {
}
}
- void updateBase(int syncHandlemap, BaseData base) {
+ void updateBase(int syncHandleMap, BaseData base) {
log("updateBase : mSyncHandleToBaseDataMap>>");
- mSyncHandleToBaseDataMap.put(syncHandlemap, base);
+ mSyncHandleToBaseDataMap.put(syncHandleMap, base);
}
- BaseData getBase(int syncHandlemap) {
- BaseData base = mSyncHandleToBaseDataMap.get(syncHandlemap);
+ BaseData getBase(int syncHandleMap) {
+ BaseData base = mSyncHandleToBaseDataMap.get(syncHandleMap);
log("getBase returns " + base);
return base;
}
@@ -1479,7 +1483,7 @@ public class BassClientService extends ProfileService {
&& (devices.contains(device))) {
Log.i(
TAG,
- "connectionStateChanged: reconnected previousely synced device: "
+ "connectionStateChanged: reconnected previously synced device: "
+ device);
mHandler.removeCallbacks(mDialingOutTimeoutEvent);
mDialingOutTimeoutEvent = null;
@@ -1614,7 +1618,7 @@ public class BassClientService extends ProfileService {
+ BluetoothProfile.getConnectionStateName(toState));
// Check if the device is disconnected - if unbond, remove the state machine
- if (toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (toState == STATE_DISCONNECTED) {
mPendingGroupOp.remove(device);
mPausedBroadcastSinks.remove(device);
synchronized (mSinksWaitingForPast) {
@@ -1674,7 +1678,7 @@ public class BassClientService extends ProfileService {
if (sm == null) {
return;
}
- if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (sm.getConnectionState() != STATE_DISCONNECTED) {
Log.i(TAG, "Disconnecting device because it was unbonded.");
disconnect(device);
return;
@@ -1695,7 +1699,7 @@ public class BassClientService extends ProfileService {
Log.e(TAG, "connect: device is null");
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "connect: connection policy set to forbidden");
return false;
}
@@ -1712,7 +1716,7 @@ public class BassClientService extends ProfileService {
}
/**
- * Disconnects Bassclient profile for the passed in device
+ * Disconnects BassClient profile for the passed in device
*
* @param device is the device with which we want to disconnected the BAss client profile
* @return true if Bass client profile successfully disconnected, false otherwise
@@ -1757,8 +1761,8 @@ public class BassClientService extends ProfileService {
if (bondState != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "okToConnect: return false, bondState=" + bondState);
return false;
- } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -1777,7 +1781,7 @@ public class BassClientService extends ProfileService {
BassClientStateMachine sm = getOrCreateStateMachine(sink);
if (sm == null) {
log("getConnectionState returns STATE_DISC");
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -1804,7 +1808,7 @@ public class BassClientService extends ProfileService {
if (!Utils.arrayContains(featureUuids, BluetoothUuid.BASS)) {
continue;
}
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
BassClientStateMachine sm = getOrCreateStateMachine(device);
if (sm != null) {
connectionState = sm.getConnectionState();
@@ -1854,10 +1858,9 @@ public class BassClientService extends ProfileService {
boolean setSuccessfully =
mDatabaseManager.setProfileConnectionPolicy(
device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT, connectionPolicy);
- if (setSuccessfully && connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (setSuccessfully && connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (setSuccessfully
- && connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (setSuccessfully && connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return setSuccessfully;
@@ -2023,7 +2026,7 @@ public class BassClientService extends ProfileService {
log("Broadcasts to sync on start: " + broadcastsToSync);
- // Add broadcsts to sync queue
+ // Add broadcasts to sync queue
for (int broadcastId : broadcastsToSync) {
addSelectSourceRequest(broadcastId, /* hasPriority */ true);
}
@@ -2252,7 +2255,7 @@ public class BassClientService extends ProfileService {
}
}
- /** Internal periodc Advertising manager callback */
+ /** Internal periodic Advertising manager callback */
final class PACallback extends PeriodicAdvertisingCallback {
@Override
public void onSyncEstablished(
@@ -2899,11 +2902,11 @@ public class BassClientService extends ProfileService {
cancelActiveSync(syncHandle);
} else {
Boolean canceledActiveSync = false;
- int broadcstIdToLostMonitoring = BassConstants.INVALID_BROADCAST_ID;
+ int broadcastIdToLostMonitoring = BassConstants.INVALID_BROADCAST_ID;
for (int syncHandle : activeSyncedSrc) {
if (!isAnyReceiverSyncedToBroadcast(getBroadcastIdForSyncHandle(syncHandle))) {
canceledActiveSync = true;
- broadcstIdToLostMonitoring = getBroadcastIdForSyncHandle(syncHandle);
+ broadcastIdToLostMonitoring = getBroadcastIdForSyncHandle(syncHandle);
cancelActiveSync(syncHandle);
break;
}
@@ -2911,11 +2914,11 @@ public class BassClientService extends ProfileService {
if (!canceledActiveSync) {
int syncHandle = activeSyncedSrc.get(0);
// removing the 1st synced source before proceeding to add new
- broadcstIdToLostMonitoring = getBroadcastIdForSyncHandle(syncHandle);
+ broadcastIdToLostMonitoring = getBroadcastIdForSyncHandle(syncHandle);
cancelActiveSync(syncHandle);
}
mTimeoutHandler.start(
- broadcstIdToLostMonitoring, MESSAGE_SYNC_LOST_TIMEOUT, sSyncLostTimeout);
+ broadcastIdToLostMonitoring, MESSAGE_SYNC_LOST_TIMEOUT, sSyncLostTimeout);
}
}
@@ -4864,7 +4867,7 @@ public class BassClientService extends ProfileService {
/* Dump first connected state machines */
for (Map.Entry<BluetoothDevice, BassClientStateMachine> entry : mStateMachines.entrySet()) {
BassClientStateMachine sm = entry.getValue();
- if (sm.getConnectionState() == BluetoothProfile.STATE_CONNECTED) {
+ if (sm.getConnectionState() == STATE_CONNECTED) {
sm.dump(sb);
sb.append("\n\n");
}
@@ -4873,7 +4876,7 @@ public class BassClientService extends ProfileService {
/* Dump at least all other than connected state machines */
for (Map.Entry<BluetoothDevice, BassClientStateMachine> entry : mStateMachines.entrySet()) {
BassClientStateMachine sm = entry.getValue();
- if (sm.getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
+ if (sm.getConnectionState() != STATE_CONNECTED) {
sm.dump(sb);
}
}
@@ -4943,7 +4946,7 @@ public class BassClientService extends ProfileService {
BassClientService service = getServiceAndEnforceConnect(source);
if (service == null) {
Log.e(TAG, "Service is null");
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(sink);
}
@@ -4985,7 +4988,7 @@ public class BassClientService extends ProfileService {
BassClientService service = getServiceAndEnforceConnect(source);
if (service == null) {
Log.e(TAG, "Service is null");
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
return service.getConnectionPolicy(device);
}
diff --git a/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java b/android/app/src/com/android/bluetooth/bass_client/BassClientStateMachine.java
index 24af973437..d5d532940a 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;
@@ -60,6 +63,8 @@ import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
+import com.google.common.primitives.Bytes;
+
import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -295,11 +300,11 @@ class BassClientStateMachine extends StateMachine {
return null;
}
- BassClientStateMachine BassclientSm =
+ BassClientStateMachine bassClientSm =
new BassClientStateMachine(
device, svc, adapterService, looper, BassConstants.CONNECT_TIMEOUT_MS);
- BassclientSm.start();
- return BassclientSm;
+ bassClientSm.start();
+ return bassClientSm;
}
static void destroy(BassClientStateMachine stateMachine) {
@@ -759,7 +764,7 @@ class BassClientStateMachine extends StateMachine {
BassConstants.BCAST_RCVR_STATE_SRC_ADDR_SIZE);
byte sourceAddressType =
receiverState[BassConstants.BCAST_RCVR_STATE_SRC_ADDR_TYPE_IDX];
- BassUtils.reverse(sourceAddress);
+ Bytes.reverse(sourceAddress);
String address = Utils.getAddressStringFromByte(sourceAddress);
BluetoothDevice device =
BluetoothAdapter.getDefaultAdapter()
@@ -980,7 +985,7 @@ class BassClientStateMachine extends StateMachine {
BassConstants.BCAST_RCVR_STATE_SRC_ADDR_SIZE);
byte sourceAddressType =
receiverState[BassConstants.BCAST_RCVR_STATE_SRC_ADDR_TYPE_IDX];
- BassUtils.reverse(sourceAddress);
+ Bytes.reverse(sourceAddress);
String address = Utils.getAddressStringFromByte(sourceAddress);
BluetoothDevice device =
BluetoothAdapter.getDefaultAdapter()
@@ -1113,12 +1118,11 @@ 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);
+ Log.w(TAG, "BassClient Connected from Disconnected state: " + mDevice);
if (mService.okToConnect(mDevice)) {
- log("Bassclient Connected to: " + mDevice);
+ log("BassClient Connected to: " + mDevice);
if (mBluetoothGatt != null) {
log(
"Attempting to start service discovery:"
@@ -1127,15 +1131,15 @@ class BassClientStateMachine extends StateMachine {
}
} else if (mBluetoothGatt != null) {
// Reject the connection
- Log.w(TAG, "Bassclient Connect request rejected: " + mDevice);
+ Log.w(TAG, "BassClient Connect request rejected: " + mDevice);
mBluetoothGatt.disconnect();
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.");
}
@@ -1266,7 +1270,7 @@ class BassClientStateMachine extends StateMachine {
}
}
- /** Internal periodc Advertising manager callback */
+ /** Internal periodic Advertising manager callback */
private final class PACallback extends PeriodicAdvertisingCallback {
@Override
public void onSyncTransferred(BluetoothDevice device, int status) {
@@ -1389,9 +1393,8 @@ class BassClientStateMachine extends StateMachine {
if (mLastConnectionState == -1) {
log("no Broadcast of initial profile state ");
} else {
- broadcastConnectionState(
- mDevice, mLastConnectionState, BluetoothProfile.STATE_DISCONNECTED);
- if (mLastConnectionState != BluetoothProfile.STATE_DISCONNECTED) {
+ broadcastConnectionState(mDevice, mLastConnectionState, STATE_DISCONNECTED);
+ if (mLastConnectionState != STATE_DISCONNECTED) {
// Reconnect in background if not disallowed by the service
if (mService.okToConnect(mDevice) && mAllowReconnect) {
connectGatt(/*autoConnect*/ true);
@@ -1407,7 +1410,7 @@ class BassClientStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ mLastConnectionState = STATE_DISCONNECTED;
}
@Override
@@ -1448,7 +1451,7 @@ class BassClientStateMachine extends StateMachine {
case CONNECTION_STATE_CHANGED:
int state = (int) message.obj;
Log.w(TAG, "connection state changed:" + state);
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
log("remote/wl connection");
transitionTo(mConnected);
} else {
@@ -1473,8 +1476,7 @@ class BassClientStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(CONNECT_TIMEOUT, mDevice, mConnectTimeoutMs);
- broadcastConnectionState(
- mDevice, mLastConnectionState, BluetoothProfile.STATE_CONNECTING);
+ broadcastConnectionState(mDevice, mLastConnectionState, STATE_CONNECTING);
}
@Override
@@ -1484,7 +1486,7 @@ class BassClientStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTING;
+ mLastConnectionState = STATE_CONNECTING;
removeMessages(CONNECT_TIMEOUT);
}
@@ -1511,7 +1513,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);
@@ -1565,7 +1567,7 @@ class BassClientStateMachine extends StateMachine {
// Advertiser_Address
byte[] bcastSourceAddr = Utils.getBytesFromAddress(advSource.getAddress());
- BassUtils.reverse(bcastSourceAddr);
+ Bytes.reverse(bcastSourceAddr);
stream.write(bcastSourceAddr, 0, 6);
// Advertising_SID
@@ -1765,9 +1767,8 @@ class BassClientStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
removeDeferredMessages(CONNECT);
- if (mLastConnectionState != BluetoothProfile.STATE_CONNECTED) {
- broadcastConnectionState(
- mDevice, mLastConnectionState, BluetoothProfile.STATE_CONNECTED);
+ if (mLastConnectionState != STATE_CONNECTED) {
+ broadcastConnectionState(mDevice, mLastConnectionState, STATE_CONNECTED);
}
}
@@ -1778,7 +1779,7 @@ class BassClientStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTED;
+ mLastConnectionState = STATE_CONNECTED;
}
private void writeBassControlPoint(byte[] value) {
@@ -1818,7 +1819,7 @@ class BassClientStateMachine extends StateMachine {
case CONNECTION_STATE_CHANGED:
int state = (int) message.obj;
Log.w(TAG, "Connected:connection state changed:" + state);
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
Log.w(TAG, "device is already connected to Bass" + mDevice);
} else {
Log.w(TAG, "unexpected disconnected from " + mDevice);
@@ -2167,7 +2168,7 @@ class BassClientStateMachine extends StateMachine {
case CONNECTION_STATE_CHANGED:
int state = (int) message.obj;
Log.w(TAG, "ConnectedProcessing: connection state changed:" + state);
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
Log.w(TAG, "should never happen from this state");
} else {
Log.w(TAG, "Unexpected disconnection " + mDevice);
@@ -2217,7 +2218,7 @@ class BassClientStateMachine extends StateMachine {
cancelPendingSourceOperation(broadcastId);
break;
default:
- log("CONNECTEDPROCESSING: not handled message:" + message.what);
+ log("ConnectedProcessing: not handled message:" + message.what);
return NOT_HANDLED;
}
return HANDLED;
@@ -2226,8 +2227,7 @@ class BassClientStateMachine extends StateMachine {
void broadcastConnectionState(BluetoothDevice device, int fromState, int toState) {
log("broadcastConnectionState " + device + ": " + fromState + "->" + toState);
- if (fromState == BluetoothProfile.STATE_CONNECTED
- && toState == BluetoothProfile.STATE_CONNECTED) {
+ if (fromState == STATE_CONNECTED && toState == STATE_CONNECTED) {
log("CONNECTED->CONNECTED: Ignore");
return;
}
@@ -2254,15 +2254,15 @@ class BassClientStateMachine extends StateMachine {
}
switch (currentState) {
case "Disconnected":
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
case "Connecting":
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
case "Connected":
case "ConnectedProcessing":
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
default:
Log.e(TAG, "Bad currentState: " + currentState);
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
diff --git a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
index a5dca87a68..69d61ce234 100644
--- a/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
+++ b/android/app/src/com/android/bluetooth/bass_client/BassUtils.java
@@ -147,13 +147,4 @@ class BassUtils {
static void printByteArray(byte[] array) {
log("Entire byte Array as string: " + Arrays.toString(array));
}
-
- static void reverse(byte[] address) {
- int len = address.length;
- for (int i = 0; i < len / 2; ++i) {
- byte b = address[i];
- address[i] = address[len - 1 - i];
- address[len - 1 - i] = b;
- }
- }
}
diff --git a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
index bdf0db4d47..95c6661be4 100644
--- a/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/ActiveDeviceManager.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.btservice;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.bluetooth.BluetoothAdapter;
@@ -180,7 +183,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
*/
public void profileConnectionStateChanged(
int profile, BluetoothDevice device, int fromState, int toState) {
- if (toState == BluetoothProfile.STATE_CONNECTED) {
+ if (toState == STATE_CONNECTED) {
switch (profile) {
case BluetoothProfile.A2DP:
mHandler.post(() -> handleA2dpConnected(device));
@@ -198,7 +201,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
mHandler.post(() -> handleHapConnected(device));
break;
}
- } else if (fromState == BluetoothProfile.STATE_CONNECTED) {
+ } else if (fromState == STATE_CONNECTED) {
switch (profile) {
case BluetoothProfile.A2DP:
mHandler.post(() -> handleA2dpDisconnected(device));
@@ -291,7 +294,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
}
// Activate A2DP if audio mode is normal or HFP is not supported or enabled.
if (mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET)
- != BluetoothProfile.CONNECTION_POLICY_ALLOWED
+ != CONNECTION_POLICY_ALLOWED
|| mAudioManager.getMode() == AudioManager.MODE_NORMAL) {
boolean a2dpMadeActive = setA2dpActiveDevice(device);
if (a2dpMadeActive && !Utils.isDualModeAudioEnabled()) {
@@ -361,7 +364,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
}
// Activate HFP if audio mode is not normal or A2DP is not supported or enabled.
if (mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP)
- != BluetoothProfile.CONNECTION_POLICY_ALLOWED
+ != CONNECTION_POLICY_ALLOWED
|| mAudioManager.getMode() != AudioManager.MODE_NORMAL) {
if (Utils.isWatch(mAdapterService, device)) {
Log.i(TAG, "Do not set hfp active for watch device " + device);
@@ -682,7 +685,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
if (!Objects.equals(mHfpActiveDevice, device)
&& mHfpConnectedDevices.contains(device)
&& mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ == CONNECTION_POLICY_ALLOWED) {
mClassicDeviceToBeActivated = device;
setHfpActiveDevice(device);
mHandler.postDelayed(
@@ -753,7 +756,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
if (!Objects.equals(mA2dpActiveDevice, device)
&& mA2dpConnectedDevices.contains(device)
&& mDbManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ == CONNECTION_POLICY_ALLOWED) {
mClassicDeviceToBeActivated = device;
setA2dpActiveDevice(device);
mHandler.postDelayed(
@@ -1365,7 +1368,7 @@ public class ActiveDeviceManager implements AdapterService.BluetoothStateCallbac
return false;
}
- if (leAudioService.getAllBroadcastMetadata().isEmpty()) {
+ if (!leAudioService.isBroadcastStarted()) {
Log.d(TAG, "isBroadcastingAudio: false - getAllBroadcastMetadata is empty");
return false;
}
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
index 963ff62337..8166412b0a 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterProperties.java
@@ -19,6 +19,10 @@ package com.android.bluetooth.btservice;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import android.annotation.NonNull;
import android.app.BroadcastOptions;
@@ -597,7 +601,7 @@ class AdapterProperties {
if (p != null) {
return p.first;
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
@@ -668,37 +672,36 @@ class AdapterProperties {
}
private static boolean validateProfileConnectionState(int state) {
- return (state == BluetoothProfile.STATE_DISCONNECTED
- || state == BluetoothProfile.STATE_CONNECTING
- || state == BluetoothProfile.STATE_CONNECTED
- || state == BluetoothProfile.STATE_DISCONNECTING);
+ return (state == STATE_DISCONNECTED
+ || state == STATE_CONNECTING
+ || state == STATE_CONNECTED
+ || state == STATE_DISCONNECTING);
}
private static int convertToAdapterState(int state) {
switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED:
+ case STATE_DISCONNECTED:
return BluetoothAdapter.STATE_DISCONNECTED;
- case BluetoothProfile.STATE_DISCONNECTING:
+ case STATE_DISCONNECTING:
return BluetoothAdapter.STATE_DISCONNECTING;
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTED:
return BluetoothAdapter.STATE_CONNECTED;
- case BluetoothProfile.STATE_CONNECTING:
+ case STATE_CONNECTING:
return BluetoothAdapter.STATE_CONNECTING;
}
- Log.e(TAG, "convertToAdapterState, unknow state " + state);
+ Log.e(TAG, "convertToAdapterState, unknown state " + state);
return -1;
}
private static boolean isNormalStateTransition(int prevState, int nextState) {
switch (prevState) {
- case BluetoothProfile.STATE_DISCONNECTED:
- return nextState == BluetoothProfile.STATE_CONNECTING;
- case BluetoothProfile.STATE_CONNECTED:
- return nextState == BluetoothProfile.STATE_DISCONNECTING;
- case BluetoothProfile.STATE_DISCONNECTING:
- case BluetoothProfile.STATE_CONNECTING:
- return (nextState == BluetoothProfile.STATE_DISCONNECTED)
- || (nextState == BluetoothProfile.STATE_CONNECTED);
+ case STATE_DISCONNECTED:
+ return nextState == STATE_CONNECTING;
+ case STATE_CONNECTED:
+ return nextState == STATE_DISCONNECTING;
+ case STATE_DISCONNECTING:
+ case STATE_CONNECTING:
+ return (nextState == STATE_DISCONNECTED) || (nextState == STATE_CONNECTED);
default:
return false;
}
@@ -706,7 +709,7 @@ class AdapterProperties {
private boolean updateCountersAndCheckForConnectionStateChange(int state, int prevState) {
switch (prevState) {
- case BluetoothProfile.STATE_CONNECTING:
+ case STATE_CONNECTING:
if (mProfilesConnecting > 0) {
mProfilesConnecting--;
} else {
@@ -716,7 +719,7 @@ class AdapterProperties {
}
break;
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTED:
if (mProfilesConnected > 0) {
mProfilesConnected--;
} else {
@@ -726,7 +729,7 @@ class AdapterProperties {
}
break;
- case BluetoothProfile.STATE_DISCONNECTING:
+ case STATE_DISCONNECTING:
if (mProfilesDisconnecting > 0) {
mProfilesDisconnecting--;
} else {
@@ -738,19 +741,19 @@ class AdapterProperties {
}
switch (state) {
- case BluetoothProfile.STATE_CONNECTING:
+ case STATE_CONNECTING:
mProfilesConnecting++;
return (mProfilesConnected == 0 && mProfilesConnecting == 1);
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTED:
mProfilesConnected++;
return (mProfilesConnected == 1);
- case BluetoothProfile.STATE_DISCONNECTING:
+ case STATE_DISCONNECTING:
mProfilesDisconnecting++;
return (mProfilesConnected == 0 && mProfilesDisconnecting == 1);
- case BluetoothProfile.STATE_DISCONNECTED:
+ case STATE_DISCONNECTED:
return (mProfilesConnected == 0 && mProfilesConnecting == 0);
default:
@@ -785,17 +788,15 @@ class AdapterProperties {
if (newState == currHashState) {
numDev++;
- } else if (newState == BluetoothProfile.STATE_CONNECTED
- || (newState == BluetoothProfile.STATE_CONNECTING
- && currHashState != BluetoothProfile.STATE_CONNECTED)) {
+ } else if (newState == STATE_CONNECTED
+ || (newState == STATE_CONNECTING && currHashState != STATE_CONNECTED)) {
numDev = 1;
} else if (numDev == 1 && oldState == currHashState) {
update = true;
} else if (numDev > 1 && oldState == currHashState) {
numDev--;
- if (currHashState == BluetoothProfile.STATE_CONNECTED
- || currHashState == BluetoothProfile.STATE_CONNECTING) {
+ if (currHashState == STATE_CONNECTED || currHashState == STATE_CONNECTING) {
newHashState = currHashState;
}
} else {
diff --git a/android/app/src/com/android/bluetooth/btservice/AdapterService.java b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
index e180e8ba87..3d61a63928 100644
--- a/android/app/src/com/android/bluetooth/btservice/AdapterService.java
+++ b/android/app/src/com/android/bluetooth/btservice/AdapterService.java
@@ -28,6 +28,12 @@ import static android.bluetooth.BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERA
import static android.bluetooth.BluetoothAdapter.SCAN_MODE_NONE;
import static android.bluetooth.BluetoothDevice.BATTERY_LEVEL_UNKNOWN;
import static android.bluetooth.BluetoothDevice.TRANSPORT_AUTO;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothProfile.getProfileName;
import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
@@ -555,7 +561,7 @@ public class AdapterService extends Service {
// TODO(b/228875190): GATT is assumed supported. GATT starting triggers hardware
// initialization. Configuring a device without GATT causes start up failures.
if (GattService.class.getSimpleName().equals(profile.getName())
- && !Flags.scanManagerRefactor()) {
+ && !Flags.onlyStartScanDuringBleOn()) {
mNativeInterface.enable();
} else if (mRegisteredProfiles.size() == Config.getSupportedProfiles().length
&& mRegisteredProfiles.size() == mRunningProfiles.size()) {
@@ -580,7 +586,7 @@ public class AdapterService extends Service {
}
mRunningProfiles.remove(profile);
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
if (mRunningProfiles.size() == 0) {
mAdapterStateMachine.sendMessage(AdapterState.BREDR_STOPPED);
}
@@ -640,7 +646,7 @@ public class AdapterService extends Service {
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
- // OnCreate must perform the minimum of infaillible and mandatory initialization
+ // OnCreate must perform the minimum of infallible and mandatory initialization
mRemoteDevices = new RemoteDevices(this, mLooper);
mAdapterProperties = new AdapterProperties(this, mRemoteDevices, mLooper);
mAdapterStateMachine = new AdapterState(this, mLooper);
@@ -988,7 +994,7 @@ public class AdapterService extends Service {
TAG,
"GATT is configured off but the stack assumes it to be enabled. Start anyway.");
}
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
startScanController();
} else {
startGattProfileService();
@@ -996,7 +1002,7 @@ public class AdapterService extends Service {
}
void bringDownBle() {
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
stopScanController();
} else {
stopGattProfileService();
@@ -1017,7 +1023,7 @@ public class AdapterService extends Service {
void startProfileServices() {
Log.d(TAG, "startCoreServices()");
int[] supportedProfileServices = Config.getSupportedProfiles();
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
// Scanning is always supported, started separately, and is not a profile service.
// This will check other profile services.
if (supportedProfileServices.length == 0) {
@@ -1050,7 +1056,7 @@ public class AdapterService extends Service {
setScanMode(SCAN_MODE_NONE, "StopProfileServices");
int[] supportedProfileServices = Config.getSupportedProfiles();
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
// Scanning is always supported, started separately, and is not a profile service.
// This will check other profile services.
if (supportedProfileServices.length == 0) {
@@ -1570,10 +1576,10 @@ public class AdapterService extends Service {
mStartedProfiles.put(profileId, profileService);
addProfile(profileService);
profileService.setAvailable(true);
- // With `Flags.scanManagerRefactor()` GattService initialization is pushed back to
+ // With `Flags.onlyStartScanDuringBleOn()` GattService initialization is pushed back to
// `ON` state instead of `BLE_ON`. Here we ensure mGattService is set prior
// to other Profiles using it.
- if (profileId == BluetoothProfile.GATT && Flags.scanManagerRefactor()) {
+ if (profileId == BluetoothProfile.GATT && Flags.onlyStartScanDuringBleOn()) {
mGattService = GattService.getGattService();
}
onProfileServiceStateChanged(profileService, BluetoothAdapter.STATE_ON);
@@ -1598,7 +1604,7 @@ public class AdapterService extends Service {
private void setAllProfileServiceStates(int[] profileIds, int state) {
for (int profileId : profileIds) {
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
// TODO(b/228875190): GATT is assumed supported and treated differently as part of
// the "BLE ON" state, despite GATT not being BLE specific.
if (profileId == BluetoothProfile.GATT) {
@@ -1729,17 +1735,16 @@ public class AdapterService extends Service {
remoteDeviceUuids, HidHostService.ANDROID_HEADTRACKER_UUID);
}
if (profile == BluetoothProfile.HID_DEVICE) {
- return mHidDeviceService.getConnectionState(device)
- == BluetoothProfile.STATE_DISCONNECTED;
+ return mHidDeviceService.getConnectionState(device) == STATE_DISCONNECTED;
}
if (profile == BluetoothProfile.PAN) {
return Utils.arrayContains(remoteDeviceUuids, BluetoothUuid.NAP);
}
if (profile == BluetoothProfile.MAP) {
- return mMapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
+ return mMapService.getConnectionState(device) == STATE_CONNECTED;
}
if (profile == BluetoothProfile.PBAP) {
- return mPbapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
+ return mPbapService.getConnectionState(device) == STATE_CONNECTED;
}
if (profile == BluetoothProfile.MAP_CLIENT) {
return Utils.arrayContains(localDeviceUuids, BluetoothUuid.MNS)
@@ -1787,73 +1792,60 @@ public class AdapterService extends Service {
*/
boolean isAllProfilesUnknown(BluetoothDevice device) {
if (mA2dpService != null
- && mA2dpService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mA2dpService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mA2dpSinkService != null
- && mA2dpSinkService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mA2dpSinkService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mHeadsetService != null
- && mHeadsetService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mHeadsetService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mHeadsetClientService != null
- && mHeadsetClientService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mHeadsetClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mMapClientService != null
- && mMapClientService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mMapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mHidHostService != null
- && mHidHostService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mHidHostService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mPanService != null
- && mPanService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mPanService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mPbapClientService != null
- && mPbapClientService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mPbapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mHearingAidService != null
- && mHearingAidService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mHearingAidService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mHapClientService != null
- && mHapClientService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mHapClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mVolumeControlService != null
- && mVolumeControlService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mVolumeControlService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mCsipSetCoordinatorService != null
&& mCsipSetCoordinatorService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mLeAudioService != null
- && mLeAudioService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mLeAudioService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
if (mBassClientService != null
- && mBassClientService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ && mBassClientService.getConnectionPolicy(device) != CONNECTION_POLICY_UNKNOWN) {
return false;
}
return true;
@@ -1870,105 +1862,93 @@ public class AdapterService extends Service {
if (mCsipSetCoordinatorService != null
&& isProfileSupported(device, BluetoothProfile.CSIP_SET_COORDINATOR)
&& mCsipSetCoordinatorService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Coordinated Set Profile");
mCsipSetCoordinatorService.connect(device);
}
if (mA2dpService != null
&& isProfileSupported(device, BluetoothProfile.A2DP)
- && mA2dpService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mA2dpService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting A2dp");
mA2dpService.connect(device);
}
if (mA2dpSinkService != null
&& isProfileSupported(device, BluetoothProfile.A2DP_SINK)
- && mA2dpSinkService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mA2dpSinkService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting A2dp Sink");
mA2dpSinkService.connect(device);
}
if (mHeadsetService != null
&& isProfileSupported(device, BluetoothProfile.HEADSET)
- && mHeadsetService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mHeadsetService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Headset Profile");
mHeadsetService.connect(device);
}
if (mHeadsetClientService != null
&& isProfileSupported(device, BluetoothProfile.HEADSET_CLIENT)
&& mHeadsetClientService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting HFP");
mHeadsetClientService.connect(device);
}
if (mMapClientService != null
&& isProfileSupported(device, BluetoothProfile.MAP_CLIENT)
- && mMapClientService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mMapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting MAP");
mMapClientService.connect(device);
}
if (mHidHostService != null
&& isProfileSupported(device, BluetoothProfile.HID_HOST)
- && mHidHostService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mHidHostService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Hid Host Profile");
mHidHostService.connect(device);
}
if (mPanService != null
&& isProfileSupported(device, BluetoothProfile.PAN)
- && mPanService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mPanService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Pan Profile");
mPanService.connect(device);
}
if (mPbapClientService != null
&& isProfileSupported(device, BluetoothProfile.PBAP_CLIENT)
- && mPbapClientService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mPbapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Pbap");
mPbapClientService.connect(device);
}
if (mHearingAidService != null
&& isProfileSupported(device, BluetoothProfile.HEARING_AID)
- && mHearingAidService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mHearingAidService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Hearing Aid Profile");
mHearingAidService.connect(device);
}
if (mHapClientService != null
&& isProfileSupported(device, BluetoothProfile.HAP_CLIENT)
- && mHapClientService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mHapClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting HAS Profile");
mHapClientService.connect(device);
}
if (mVolumeControlService != null
&& isProfileSupported(device, BluetoothProfile.VOLUME_CONTROL)
&& mVolumeControlService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Volume Control Profile");
mVolumeControlService.connect(device);
}
if (mLeAudioService != null
&& isProfileSupported(device, BluetoothProfile.LE_AUDIO)
- && mLeAudioService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mLeAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting LeAudio profile (BAP)");
mLeAudioService.connect(device);
}
if (mBassClientService != null
&& isProfileSupported(device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)
- && mBassClientService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mBassClientService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting LE Broadcast Assistant Profile");
mBassClientService.connect(device);
}
if (mBatteryService != null
&& isProfileSupported(device, BluetoothProfile.BATTERY)
- && mBatteryService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ && mBatteryService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.i(TAG, "connectEnabledProfiles: Connecting Battery Service");
mBatteryService.connect(device);
}
@@ -2646,7 +2626,7 @@ public class AdapterService extends Service {
|| (checkConnect
&& !Utils.checkConnectPermissionForDataDelivery(
service, source, "AdapterService getProfileConnectionState"))) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.mAdapterProperties.getProfileConnectionState(profile);
@@ -4438,6 +4418,27 @@ public class AdapterService extends Service {
AdapterService service = getService();
return service == null ? null : service.getDistanceMeasurement();
}
+
+ @Override
+ public int getKeyMissingCount(BluetoothDevice device, AttributionSource source) {
+ AdapterService service = getService();
+ if (service == null) {
+ return -1;
+ }
+ if (!callerIsSystemOrActiveOrManagedUser(service, TAG, "getKeyMissingCount")) {
+ throw new IllegalStateException(
+ "Caller is not the system or part of the active/managed user");
+ }
+ if (!BluetoothAdapter.checkBluetoothAddress(device.getAddress())) {
+ throw new IllegalArgumentException("device cannot have an invalid address");
+ }
+ if (!Utils.checkConnectPermissionForDataDelivery(
+ service, source, "AdapterService getKeyMissingCount")) {
+ return -1;
+ }
+
+ return service.mDatabaseManager.getKeyMissingCount(device);
+ }
}
/**
@@ -5206,8 +5207,7 @@ public class AdapterService extends Service {
return;
}
- if (mLeAudioService.getConnectionPolicy(device)
- != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (mLeAudioService.getConnectionPolicy(device) != CONNECTION_POLICY_ALLOWED) {
Log.d(
TAG,
"addGattClientToControlAutoActiveMode: "
@@ -5327,7 +5327,7 @@ public class AdapterService extends Service {
if (isAutoActiveModeDisabled && ((getConnectionState(device) & leConnectedState) != 0)) {
for (BluetoothDevice dev : mLeAudioService.getGroupDevices(groupId)) {
/* Need to disconnect all the devices from the group as those might be connected
- * as well especially those which migh keep the connection
+ * as well especially those which might keep the connection
*/
if ((getConnectionState(dev) & leConnectedState) != 0) {
mNativeInterface.disconnectAcl(dev, BluetoothDevice.TRANSPORT_LE);
@@ -5340,7 +5340,7 @@ public class AdapterService extends Service {
* Notify AdapterService about failed GATT connection attempt.
*
* @param clientIf ClientIf which was doing GATT connection attempt
- * @param device Remote device to which connection attpemt failed
+ * @param device Remote device to which connection attempt failed
*/
public void notifyGattClientConnectFailed(int clientIf, BluetoothDevice device) {
if (mLeAudioService != null) {
@@ -5411,7 +5411,7 @@ public class AdapterService extends Service {
}
/**
- * Checks whether the device was recently associated with the comapnion app that called {@link
+ * Checks whether the device was recently associated with the companion app that called {@link
* BluetoothDevice#createBond}. This allows these devices to skip the pairing dialog if their
* pairing variant is {@link BluetoothDevice#PAIRING_VARIANT_CONSENT}.
*
@@ -5479,17 +5479,17 @@ public class AdapterService extends Service {
mA2dpService != null
&& (device == null
|| mA2dpService.getConnectionPolicy(device)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ == CONNECTION_POLICY_ALLOWED);
boolean hfpSupported =
mHeadsetService != null
&& (device == null
|| mHeadsetService.getConnectionPolicy(device)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ == CONNECTION_POLICY_ALLOWED);
boolean leAudioSupported =
mLeAudioService != null
&& (device == null
|| mLeAudioService.getConnectionPolicy(device)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ == CONNECTION_POLICY_ALLOWED);
if (leAudioSupported) {
Log.i(TAG, "setActiveDevice: Setting active Le Audio device " + device);
@@ -5529,7 +5529,7 @@ public class AdapterService extends Service {
if (mHearingAidService != null
&& (device == null
|| mHearingAidService.getConnectionPolicy(device)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ == CONNECTION_POLICY_ALLOWED)) {
Log.i(TAG, "setActiveDevice: Setting active Hearing Aid " + device);
if (device == null) {
mHearingAidService.removeActiveDevice(false);
@@ -5654,7 +5654,7 @@ public class AdapterService extends Service {
return BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED;
}
- // Checks if any profiles are enablde or disabled and if so, only connect enabled profiles
+ // Checks if any profiles are enabled or disabled and if so, only connect enabled profiles
if (!isAllProfilesUnknown(device)) {
return connectEnabledProfiles(device);
}
@@ -5676,48 +5676,44 @@ public class AdapterService extends Service {
if (mA2dpService != null && isProfileSupported(device, BluetoothProfile.A2DP)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting A2dp");
// Set connection policy also connects the profile with CONNECTION_POLICY_ALLOWED
- mA2dpService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mA2dpService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mA2dpSinkService != null && isProfileSupported(device, BluetoothProfile.A2DP_SINK)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting A2dp Sink");
- mA2dpSinkService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mA2dpSinkService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mHeadsetService != null && isProfileSupported(device, BluetoothProfile.HEADSET)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Headset Profile");
- mHeadsetService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mHeadsetService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mHeadsetClientService != null
&& isProfileSupported(device, BluetoothProfile.HEADSET_CLIENT)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting HFP");
- mHeadsetClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mHeadsetClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mMapClientService != null && isProfileSupported(device, BluetoothProfile.MAP_CLIENT)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting MAP");
- mMapClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mMapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mHidHostService != null && isProfileSupported(device, BluetoothProfile.HID_HOST)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Hid Host Profile");
- mHidHostService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mHidHostService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mPanService != null && isProfileSupported(device, BluetoothProfile.PAN)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Pan Profile");
- mPanService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mPanService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mPbapClientService != null
&& isProfileSupported(device, BluetoothProfile.PBAP_CLIENT)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Pbap");
- mPbapClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mPbapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mHearingAidService != null
@@ -5731,46 +5727,41 @@ public class AdapterService extends Service {
+ " Profile");
} else {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Hearing Aid Profile");
- mHearingAidService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mHearingAidService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
}
if (mHapClientService != null && isProfileSupported(device, BluetoothProfile.HAP_CLIENT)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Hearing Access Client Profile");
- mHapClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mHapClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mVolumeControlService != null
&& isProfileSupported(device, BluetoothProfile.VOLUME_CONTROL)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Volume Control Profile");
- mVolumeControlService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mVolumeControlService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mCsipSetCoordinatorService != null
&& isProfileSupported(device, BluetoothProfile.CSIP_SET_COORDINATOR)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Coordinated Set Profile");
- mCsipSetCoordinatorService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mCsipSetCoordinatorService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mLeAudioService != null && isProfileSupported(device, BluetoothProfile.LE_AUDIO)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting LeAudio profile (BAP)");
- mLeAudioService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mLeAudioService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mBassClientService != null
&& isProfileSupported(device, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting LE Broadcast Assistant Profile");
- mBassClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mBassClientService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
if (mBatteryService != null && isProfileSupported(device, BluetoothProfile.BATTERY)) {
Log.i(TAG, "connectAllSupportedProfiles: Connecting Battery Service");
- mBatteryService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mBatteryService.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
numProfilesConnected++;
}
@@ -5793,134 +5784,111 @@ public class AdapterService extends Service {
}
if (mA2dpService != null
- && (mA2dpService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mA2dpService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mA2dpService.getConnectionState(device) == STATE_CONNECTED
+ || mA2dpService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting A2dp");
mA2dpService.disconnect(device);
}
if (mA2dpSinkService != null
- && (mA2dpSinkService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mA2dpSinkService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mA2dpSinkService.getConnectionState(device) == STATE_CONNECTED
+ || mA2dpSinkService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting A2dp Sink");
mA2dpSinkService.disconnect(device);
}
if (mHeadsetService != null
- && (mHeadsetService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mHeadsetService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHeadsetService.getConnectionState(device) == STATE_CONNECTED
+ || mHeadsetService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Headset Profile");
mHeadsetService.disconnect(device);
}
if (mHeadsetClientService != null
- && (mHeadsetClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
- || mHeadsetClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHeadsetClientService.getConnectionState(device) == STATE_CONNECTED
+ || mHeadsetClientService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting HFP");
mHeadsetClientService.disconnect(device);
}
if (mMapClientService != null
- && (mMapClientService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mMapClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mMapClientService.getConnectionState(device) == STATE_CONNECTED
+ || mMapClientService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting MAP Client");
mMapClientService.disconnect(device);
}
if (mMapService != null
- && (mMapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mMapService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mMapService.getConnectionState(device) == STATE_CONNECTED
+ || mMapService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting MAP");
mMapService.disconnect(device);
}
if (mHidDeviceService != null
- && (mHidDeviceService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mHidDeviceService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHidDeviceService.getConnectionState(device) == STATE_CONNECTED
+ || mHidDeviceService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hid Device Profile");
mHidDeviceService.disconnect(device);
}
if (mHidHostService != null
- && (mHidHostService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mHidHostService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHidHostService.getConnectionState(device) == STATE_CONNECTED
+ || mHidHostService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hid Host Profile");
mHidHostService.disconnect(device);
}
if (mPanService != null
- && (mPanService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mPanService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mPanService.getConnectionState(device) == STATE_CONNECTED
+ || mPanService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pan Profile");
mPanService.disconnect(device);
}
if (mPbapClientService != null
- && (mPbapClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
- || mPbapClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mPbapClientService.getConnectionState(device) == STATE_CONNECTED
+ || mPbapClientService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pbap Client");
mPbapClientService.disconnect(device);
}
if (mPbapService != null
- && (mPbapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mPbapService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mPbapService.getConnectionState(device) == STATE_CONNECTED
+ || mPbapService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Pbap Server");
mPbapService.disconnect(device);
}
if (mHearingAidService != null
- && (mHearingAidService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
- || mHearingAidService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHearingAidService.getConnectionState(device) == STATE_CONNECTED
+ || mHearingAidService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hearing Aid Profile");
mHearingAidService.disconnect(device);
}
if (mHapClientService != null
- && (mHapClientService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mHapClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mHapClientService.getConnectionState(device) == STATE_CONNECTED
+ || mHapClientService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Hearing Access Profile Client");
mHapClientService.disconnect(device);
}
if (mVolumeControlService != null
- && (mVolumeControlService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
- || mVolumeControlService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mVolumeControlService.getConnectionState(device) == STATE_CONNECTED
+ || mVolumeControlService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Volume Control Profile");
mVolumeControlService.disconnect(device);
}
if (mSapService != null
- && (mSapService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mSapService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mSapService.getConnectionState(device) == STATE_CONNECTED
+ || mSapService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Sap Profile");
mSapService.disconnect(device);
}
if (mCsipSetCoordinatorService != null
- && (mCsipSetCoordinatorService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
+ && (mCsipSetCoordinatorService.getConnectionState(device) == STATE_CONNECTED
|| mCsipSetCoordinatorService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting Coordinator Set Profile");
mCsipSetCoordinatorService.disconnect(device);
}
if (mLeAudioService != null
- && (mLeAudioService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mLeAudioService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mLeAudioService.getConnectionState(device) == STATE_CONNECTED
+ || mLeAudioService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting LeAudio profile (BAP)");
mLeAudioService.disconnect(device);
}
if (mBassClientService != null
- && (mBassClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTED
- || mBassClientService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mBassClientService.getConnectionState(device) == STATE_CONNECTED
+ || mBassClientService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(
TAG,
"disconnectAllEnabledProfiles: Disconnecting "
@@ -5928,9 +5896,8 @@ public class AdapterService extends Service {
mBassClientService.disconnect(device);
}
if (mBatteryService != null
- && (mBatteryService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED
- || mBatteryService.getConnectionState(device)
- == BluetoothProfile.STATE_CONNECTING)) {
+ && (mBatteryService.getConnectionState(device) == STATE_CONNECTED
+ || mBatteryService.getConnectionState(device) == STATE_CONNECTING)) {
Log.i(TAG, "disconnectAllEnabledProfiles: Disconnecting " + "Battery Service");
mBatteryService.disconnect(device);
}
@@ -6011,7 +5978,7 @@ public class AdapterService extends Service {
case /*HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE*/ 0x25:
case /*HCI_ERR_UNIT_KEY_USED*/ 0x26:
case /*HCI_ERR_PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED*/ 0x29:
- case /*HCI_ERR_INSUFFCIENT_SECURITY*/ 0x2F:
+ case /*HCI_ERR_INSUFFICIENT_SECURITY*/ 0x2F:
case /*HCI_ERR_HOST_BUSY_PAIRING*/ 0x38:
return BluetoothStatusCodes.ERROR_DISCONNECT_REASON_SECURITY;
case /*HCI_ERR_MEMORY_FULL*/ 0x07:
@@ -6360,7 +6327,7 @@ public class AdapterService extends Service {
@Nullable
public ScanController getBluetoothScanController() {
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
return mScanController;
} else {
return mGattService == null ? null : mGattService.getScanController();
@@ -6677,7 +6644,6 @@ public class AdapterService extends Service {
}
/** Update metadata change to registered listeners */
- @VisibleForTesting
public void onMetadataChanged(BluetoothDevice device, int key, byte[] value) {
mHandler.post(() -> onMetadataChangedInternal(device, key, value));
}
@@ -6753,7 +6719,7 @@ public class AdapterService extends Service {
for (ProfileService profile : mRunningProfiles) {
profile.setTestModeEnabled(testModeEnabled);
}
- if (Flags.scanManagerRefactor() && mScanController != null) {
+ if (Flags.onlyStartScanDuringBleOn() && mScanController != null) {
mScanController.setTestModeEnabled(testModeEnabled);
}
mTestModeEnabled = testModeEnabled;
@@ -6797,7 +6763,7 @@ public class AdapterService extends Service {
for (ProfileService profile : mRegisteredProfiles) {
profile.dump(sb);
}
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
ScanController scanController = mScanController;
if (scanController != null) {
scanController.dumpRegisterId(sb);
@@ -6843,7 +6809,7 @@ public class AdapterService extends Service {
for (ProfileService profile : mRegisteredProfiles) {
profile.dumpProto(metricsBuilder);
}
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
ScanController scanController = mScanController;
if (scanController != null) {
scanController.dumpProto(metricsBuilder);
diff --git a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
index 8c9be74c98..c9b1c82473 100644
--- a/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
+++ b/android/app/src/com/android/bluetooth/btservice/BluetoothSocketManagerBinder.java
@@ -96,7 +96,7 @@ class BluetoothSocketManagerBinder extends IBluetoothSocketManager.Stub {
}
@Override
- public ParcelFileDescriptor connectSocketwithOffload(
+ public ParcelFileDescriptor connectSocketWithOffload(
BluetoothDevice device,
int type,
ParcelUuid uuid,
@@ -125,7 +125,7 @@ class BluetoothSocketManagerBinder extends IBluetoothSocketManager.Stub {
Log.i(
TAG,
- "connectSocketwithOffload: device="
+ "connectSocketWithOffload: device="
+ device
+ ", type="
+ type
diff --git a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
index 1411961bee..30be010ae4 100644
--- a/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
+++ b/android/app/src/com/android/bluetooth/btservice/BondStateMachine.java
@@ -17,6 +17,7 @@
package com.android.bluetooth.btservice;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND_RETRY;
import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__FAIL;
@@ -27,7 +28,6 @@ import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothProtoEnums;
import android.bluetooth.OobData;
import android.content.Intent;
@@ -779,39 +779,34 @@ final class BondStateMachine extends StateMachine {
HapClientService hapClientService = HapClientService.getHapClientService();
if (hidService != null) {
- hidService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ hidService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (a2dpService != null) {
- a2dpService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ a2dpService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (headsetService != null) {
- headsetService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ headsetService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (headsetClientService != null) {
- headsetClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ headsetClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (a2dpSinkService != null) {
- a2dpSinkService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ a2dpSinkService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (pbapClientService != null) {
- pbapClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ pbapClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (leAudioService != null) {
- leAudioService.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ leAudioService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (csipSetCoordinatorService != null) {
- csipSetCoordinatorService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ csipSetCoordinatorService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (volumeControlService != null) {
- volumeControlService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ volumeControlService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
if (hapClientService != null) {
- hapClientService.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ hapClientService.setConnectionPolicy(device, CONNECTION_POLICY_UNKNOWN);
}
}
diff --git a/android/app/src/com/android/bluetooth/btservice/DataMigration.java b/android/app/src/com/android/bluetooth/btservice/DataMigration.java
index ec46a85a38..6561f9a4cb 100644
--- a/android/app/src/com/android/bluetooth/btservice/DataMigration.java
+++ b/android/app/src/com/android/bluetooth/btservice/DataMigration.java
@@ -97,7 +97,7 @@ final class DataMigration {
markMigrationStatus(ctx, MIGRATION_STATUS_MISSING_APK);
return MIGRATION_STATUS_MISSING_APK;
}
- if (!incrementeMigrationAttempt(ctx)) {
+ if (!incrementMigrationAttempt(ctx)) {
Log.d(TAG, "Legacy migration skipped: still failing after too many attempt");
markMigrationStatus(ctx, MIGRATION_STATUS_MAX_ATTEMPT);
return MIGRATION_STATUS_MAX_ATTEMPT;
@@ -238,7 +238,7 @@ final class DataMigration {
}
@VisibleForTesting
- static boolean incrementeMigrationAttempt(Context ctx) {
+ static boolean incrementMigrationAttempt(Context ctx) {
SharedPreferences pref = ctx.getSharedPreferences(BLUETOOTH_CONFIG, Context.MODE_PRIVATE);
int currentAttempt = Math.min(pref.getInt(MIGRATION_ATTEMPT_PROPERTY, 0), MAX_ATTEMPT);
pref.edit().putInt(MIGRATION_ATTEMPT_PROPERTY, currentAttempt + 1).apply();
diff --git a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
index ce55d94619..e8a5df5043 100644
--- a/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
+++ b/android/app/src/com/android/bluetooth/btservice/MetricsLogger.java
@@ -15,6 +15,8 @@
*/
package com.android.bluetooth.btservice;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+
import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__BOND;
import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION;
import static com.android.bluetooth.BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__PROFILE_CONNECTION_A2DP;
@@ -344,7 +346,7 @@ public class MetricsLogger {
BluetoothDevice device = connIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
int state = connIntent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
int metricId = mAdapterService.getMetricId(device);
- if (state == BluetoothProfile.STATE_CONNECTING) {
+ if (state == STATE_CONNECTING) {
String deviceName = mRemoteDevices.getName(device);
BluetoothStatsLog.write(
BluetoothStatsLog.BLUETOOTH_DEVICE_NAME_REPORTED, metricId, deviceName);
@@ -627,7 +629,7 @@ public class MetricsLogger {
}
@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
- protected void uploadRestrictedBluetothDeviceName(List<String> wordBreakdownList) {
+ protected void uploadRestrictedBluetoothDeviceName(List<String> wordBreakdownList) {
for (String word : wordBreakdownList) {
BtRestrictedStatsLog.write(RESTRICTED_BLUETOOTH_DEVICE_NAME_REPORTED, word);
}
diff --git a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
index fd18a104ee..048602338f 100644
--- a/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
+++ b/android/app/src/com/android/bluetooth/btservice/PhonePolicy.java
@@ -1008,9 +1008,8 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback {
List<BluetoothDevice> connectedDevices = hapClientService.getConnectedDevices();
if (!connectedDevices.contains(device)
&& (hapClientService.getConnectionPolicy(device)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED)
- && (hapClientService.getConnectionState(device)
- == BluetoothProfile.STATE_DISCONNECTED)) {
+ == CONNECTION_POLICY_ALLOWED)
+ && (hapClientService.getConnectionState(device) == STATE_DISCONNECTED)) {
Log.d(TAG, log + "Retrying HAP connection");
hapClientService.connect(device);
}
@@ -1057,11 +1056,10 @@ public class PhonePolicy implements AdapterService.BluetoothStateCallback {
profileId < BluetoothProfile.MAX_PROFILE_ID;
profileId++) {
if (mAdapterService.getDatabase().getProfileConnectionPolicy(device, profileId)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ == CONNECTION_POLICY_ALLOWED) {
mAdapterService
.getDatabase()
- .setProfileConnectionPolicy(
- device, profileId, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .setProfileConnectionPolicy(device, profileId, CONNECTION_POLICY_FORBIDDEN);
}
}
}
diff --git a/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java b/android/app/src/com/android/bluetooth/btservice/RemoteDevices.java
index f4aaf5715b..cb3331ffce 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;
@@ -998,7 +1000,7 @@ public class RemoteDevices {
* Converts HFP's Battery Charge indicator values of {@code 0 -- 5} to an integer percentage.
*/
@VisibleForTesting
- static int batteryChargeIndicatorToPercentge(int indicator) {
+ static int batteryChargeIndicatorToPercentage(int indicator) {
int percent;
switch (indicator) {
case 5:
@@ -1084,7 +1086,7 @@ public class RemoteDevices {
MetricsLogger.getInstance().getWordBreakdownList(newName);
if (SdkLevel.isAtLeastU()) {
MetricsLogger.getInstance()
- .uploadRestrictedBluetothDeviceName(wordBreakdownList);
+ .uploadRestrictedBluetoothDeviceName(wordBreakdownList);
}
intent = new Intent(BluetoothDevice.ACTION_NAME_CHANGED);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, bdDevice);
@@ -1405,8 +1407,7 @@ public class RemoteDevices {
if (mAdapterService.getConnectionState(device) == 0) {
BatteryService batteryService = BatteryService.getBatteryService();
if (batteryService != null
- && batteryService.getConnectionState(device)
- != BluetoothProfile.STATE_DISCONNECTED
+ && batteryService.getConnectionState(device) != STATE_DISCONNECTED
&& transportLinkType == BluetoothDevice.TRANSPORT_LE) {
batteryService.disconnect(device);
}
@@ -1556,6 +1557,23 @@ public class RemoteDevices {
.addFlags(
Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
| Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
+
+ // Log transition to key missing state, if the key missing count is 0 which indicates
+ // that the device is bonded until now.
+ if (mAdapterService.getDatabase().getKeyMissingCount(bluetoothDevice) == 0) {
+ MetricsLogger.getInstance()
+ .logBluetoothEvent(
+ bluetoothDevice,
+ BluetoothStatsLog
+ .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__TRANSITION,
+ BluetoothStatsLog
+ .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__BOND_BONDED_TO_ACTION_KEY_MISSING,
+ 0);
+ }
+
+ // Bond loss detected, add to the count.
+ mAdapterService.getDatabase().updateKeyMissingCount(bluetoothDevice, true);
+
if (Flags.keyMissingPublic()) {
mAdapterService.sendOrderedBroadcast(
intent,
@@ -1629,6 +1647,22 @@ public class RemoteDevices {
/* Classic link using non-secure connections mode */
algorithm = BluetoothDevice.ENCRYPTION_ALGORITHM_E0;
}
+
+ // Log transition to encryption change state (bonded), if the key missing count is > 0
+ // which indicates that the device is in key missing state.
+ if (mAdapterService.getDatabase().getKeyMissingCount(bluetoothDevice) > 0) {
+ MetricsLogger.getInstance()
+ .logBluetoothEvent(
+ bluetoothDevice,
+ BluetoothStatsLog
+ .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__TRANSITION,
+ BluetoothStatsLog
+ .BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__ACTION_KEY_MISSING_TO_ENCRYPTION_CHANGE,
+ 0);
+
+ // Successful bond detected, reset the count.
+ mAdapterService.getDatabase().updateKeyMissingCount(bluetoothDevice, false);
+ }
}
Intent intent =
@@ -1708,7 +1742,7 @@ public class RemoteDevices {
Log.e(TAG, "onHeadsetConnectionStateChanged() remote device is null");
return;
}
- if (toState == BluetoothProfile.STATE_DISCONNECTED && !hasBatteryService(device)) {
+ if (toState == STATE_DISCONNECTED && !hasBatteryService(device)) {
resetBatteryLevel(device, /* isBas= */ false);
}
}
@@ -1923,7 +1957,7 @@ public class RemoteDevices {
boolean hasBatteryService(BluetoothDevice device) {
BatteryService batteryService = BatteryService.getBatteryService();
return batteryService != null
- && batteryService.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
+ && batteryService.getConnectionState(device) == STATE_CONNECTED;
}
/** Handles headset client connection state change event. */
@@ -1938,7 +1972,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);
}
}
@@ -1955,7 +1989,7 @@ public class RemoteDevices {
return;
}
updateBatteryLevel(
- device, batteryChargeIndicatorToPercentge(batteryLevel), /* isBas= */ false);
+ device, batteryChargeIndicatorToPercentage(batteryLevel), /* isBas= */ false);
}
private static void errorLog(String msg) {
diff --git a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
index bbc8dfc521..4d6c706e06 100644
--- a/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/SilenceDeviceManager.java
@@ -17,6 +17,7 @@
package com.android.bluetooth.btservice;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
@@ -135,13 +136,13 @@ public class SilenceDeviceManager {
int prevState = msg.arg1;
int nextState = msg.arg2;
- if (nextState == BluetoothProfile.STATE_CONNECTED) {
+ if (nextState == STATE_CONNECTED) {
// enter connected state
addConnectedDevice(device, BluetoothProfile.A2DP);
if (!mSilenceDevices.containsKey(device)) {
mSilenceDevices.put(device, false);
}
- } else if (prevState == BluetoothProfile.STATE_CONNECTED) {
+ } else if (prevState == STATE_CONNECTED) {
// exiting from connected state
removeConnectedDevice(device, BluetoothProfile.A2DP);
if (!isBluetoothAudioConnected(device)) {
@@ -156,13 +157,13 @@ public class SilenceDeviceManager {
int prev = msg.arg1;
int next = msg.arg2;
- if (next == BluetoothProfile.STATE_CONNECTED) {
+ if (next == STATE_CONNECTED) {
// enter connected state
addConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET);
if (!mSilenceDevices.containsKey(bluetoothDevice)) {
mSilenceDevices.put(bluetoothDevice, false);
}
- } else if (prev == BluetoothProfile.STATE_CONNECTED) {
+ } else if (prev == STATE_CONNECTED) {
// exiting from connected state
removeConnectedDevice(bluetoothDevice, BluetoothProfile.HEADSET);
if (!isBluetoothAudioConnected(bluetoothDevice)) {
diff --git a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java
index d9fdf936e5..c083c04e01 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/BluetoothDatabaseMigration.java
@@ -16,6 +16,10 @@
package com.android.bluetooth.btservice.storage;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
@@ -187,9 +191,9 @@ public final class BluetoothDatabaseMigration {
final List<Integer> allowedValue =
new ArrayList<>(
Arrays.asList(
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED));
+ CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_FORBIDDEN,
+ CONNECTION_POLICY_ALLOWED));
for (Pair<Integer, String> p : CONNECTION_POLICIES) {
final int policy = cursor.getInt(cursor.getColumnIndexOrThrow(p.second));
if (allowedValue.contains(policy)) {
diff --git a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java
index 7874b066c2..ee8b2d3fc1 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/DatabaseManager.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.btservice.storage;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.getProfileName;
+
import static java.util.Objects.requireNonNull;
import android.bluetooth.BluetoothA2dp;
@@ -68,19 +73,7 @@ public class DatabaseManager {
private static final String TAG =
Utils.TAG_PREFIX_BLUETOOTH + DatabaseManager.class.getSimpleName();
- private final AdapterService mAdapterService;
- private HandlerThread mHandlerThread = null;
- private Handler mHandler = null;
- private final Object mDatabaseLock = new Object();
- private @GuardedBy("mDatabaseLock") MetadataDatabase mDatabase = null;
- private boolean mMigratedFromSettingsGlobal = false;
-
- @VisibleForTesting final Map<String, Metadata> mMetadataCache = new HashMap<>();
- private final Semaphore mSemaphore = new Semaphore(1);
- private static final int METADATA_CHANGED_LOG_MAX_SIZE = 20;
- private final EvictingQueue<String> mMetadataChangedLog;
-
- private static final int LOAD_DATABASE_TIMEOUT = 500; // milliseconds
+ private static final int LOAD_DATABASE_TIMEOUT_MS = 500;
private static final int MSG_LOAD_DATABASE = 0;
private static final int MSG_UPDATE_DATABASE = 1;
private static final int MSG_DELETE_DATABASE = 2;
@@ -106,13 +99,28 @@ public class DatabaseManager {
private static final String LEGACY_HEARING_AID_PRIORITY_PREFIX =
"bluetooth_hearing_aid_priority_";
+ private static final int METADATA_CHANGED_LOG_MAX_SIZE = 20;
+
+ private final BluetoothAdapter mAdapter;
+ private final AdapterService mAdapterService;
+ private HandlerThread mHandlerThread = null;
+ private Handler mHandler = null;
+ private final Object mDatabaseLock = new Object();
+ private @GuardedBy("mDatabaseLock") MetadataDatabase mDatabase = null;
+ private boolean mMigratedFromSettingsGlobal = false;
+
+ @VisibleForTesting final Map<String, Metadata> mMetadataCache = new HashMap<>();
+ private final Semaphore mSemaphore = new Semaphore(1);
+ private final EvictingQueue<String> mMetadataChangedLog;
+
/** Constructor of the DatabaseManager */
public DatabaseManager(AdapterService service) {
+ mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapterService = requireNonNull(service);
mMetadataChangedLog = EvictingQueue.create(METADATA_CHANGED_LOG_MAX_SIZE);
}
- class DatabaseHandler extends Handler {
+ private class DatabaseHandler extends Handler {
DatabaseHandler(Looper looper) {
super(looper);
}
@@ -243,7 +251,6 @@ public class DatabaseManager {
}
/** Set customized metadata to database with requested key */
- @VisibleForTesting
public boolean setCustomMeta(BluetoothDevice device, int key, byte[] newValue) {
if (device == null) {
Log.e(TAG, "setCustomMeta: device is null");
@@ -300,7 +307,6 @@ public class DatabaseManager {
}
/** Set audio policy metadata to database with requested key */
- @VisibleForTesting
public boolean setAudioPolicyMetadata(
BluetoothDevice device, BluetoothSinkAudioPolicy policies) {
if (device == null) {
@@ -325,7 +331,6 @@ public class DatabaseManager {
}
/** Get audio policy metadata from database with requested key */
- @VisibleForTesting
public BluetoothSinkAudioPolicy getAudioPolicyMetadata(BluetoothDevice device) {
if (device == null) {
Log.e(TAG, "getAudioPolicyMetadata: device is null");
@@ -363,9 +368,8 @@ public class DatabaseManager {
* BluetoothProfile#VOLUME_CONTROL}, {@link BluetoothProfile#CSIP_SET_COORDINATOR}, {@link
* BluetoothProfile#LE_AUDIO_BROADCAST_ASSISTANT},
* @param newConnectionPolicy the connectionPolicy to set; one of {@link
- * BluetoothProfile.CONNECTION_POLICY_UNKNOWN}, {@link
- * BluetoothProfile.CONNECTION_POLICY_FORBIDDEN}, {@link
- * BluetoothProfile.CONNECTION_POLICY_ALLOWED}
+ * CONNECTION_POLICY_UNKNOWN}, {@link CONNECTION_POLICY_FORBIDDEN}, {@link
+ * CONNECTION_POLICY_ALLOWED}
*/
public boolean setProfileConnectionPolicy(
BluetoothDevice device, int profile, int newConnectionPolicy) {
@@ -374,9 +378,9 @@ public class DatabaseManager {
return false;
}
- if (newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && newConnectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (newConnectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && newConnectionPolicy != CONNECTION_POLICY_FORBIDDEN
+ && newConnectionPolicy != CONNECTION_POLICY_ALLOWED) {
Log.e(
TAG,
"setProfileConnectionPolicy: invalid connection policy " + newConnectionPolicy);
@@ -387,7 +391,7 @@ public class DatabaseManager {
synchronized (mMetadataCache) {
if (!mMetadataCache.containsKey(address)) {
- if (newConnectionPolicy == BluetoothProfile.CONNECTION_POLICY_UNKNOWN) {
+ if (newConnectionPolicy == CONNECTION_POLICY_UNKNOWN) {
return true;
}
createMetadata(address, false);
@@ -398,7 +402,7 @@ public class DatabaseManager {
Log.v(TAG, "setProfileConnectionPolicy connection policy not changed.");
return true;
}
- String profileStr = BluetoothProfile.getProfileName(profile);
+ String profileStr = getProfileName(profile);
logMetadataChange(
data,
profileStr
@@ -406,7 +410,6 @@ public class DatabaseManager {
+ oldConnectionPolicy
+ " -> "
+ newConnectionPolicy);
-
Log.v(
TAG,
"setProfileConnectionPolicy:"
@@ -434,14 +437,13 @@ public class DatabaseManager {
* BluetoothProfile#VOLUME_CONTROL}, {@link BluetoothProfile#CSIP_SET_COORDINATOR}, {@link
* BluetoothProfile#LE_AUDIO_BROADCAST_ASSISTANT},
* @return the profile connection policy of the device; one of {@link
- * BluetoothProfile.CONNECTION_POLICY_UNKNOWN}, {@link
- * BluetoothProfile.CONNECTION_POLICY_FORBIDDEN}, {@link
- * BluetoothProfile.CONNECTION_POLICY_ALLOWED}
+ * CONNECTION_POLICY_UNKNOWN}, {@link CONNECTION_POLICY_FORBIDDEN}, {@link
+ * CONNECTION_POLICY_ALLOWED}
*/
public int getProfileConnectionPolicy(BluetoothDevice device, int profile) {
if (device == null) {
Log.e(TAG, "getProfileConnectionPolicy: device is null");
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
String address = device.getAddress();
@@ -449,7 +451,7 @@ public class DatabaseManager {
synchronized (mMetadataCache) {
if (!mMetadataCache.containsKey(address)) {
Log.d(TAG, "getProfileConnectionPolicy: device=" + device + " is not in cache");
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
Metadata data = mMetadataCache.get(address);
@@ -459,22 +461,21 @@ public class DatabaseManager {
TAG,
"getProfileConnectionPolicy:"
+ (" device=" + device)
- + (" profile=" + BluetoothProfile.getProfileName(profile))
+ + (" profile=" + getProfileName(profile))
+ (" connectionPolicy=" + connectionPolicy));
return connectionPolicy;
}
}
/**
- * Set the A2DP optional coedc support value
+ * Set the A2DP optional codec support value
*
* @param device {@link BluetoothDevice} wish to set
- * @param newValue the new A2DP optional coedc support value, one of {@link
+ * @param newValue the new A2DP optional codec support value, one of {@link
* BluetoothA2dp#OPTIONAL_CODECS_SUPPORT_UNKNOWN}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_NOT_SUPPORTED}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_SUPPORTED}
*/
- @VisibleForTesting
public void setA2dpSupportsOptionalCodecs(BluetoothDevice device, int newValue) {
if (device == null) {
Log.e(TAG, "setA2dpOptionalCodec: device is null");
@@ -507,15 +508,14 @@ public class DatabaseManager {
}
/**
- * Get the A2DP optional coedc support value
+ * Get the A2DP optional codec support value
*
* @param device {@link BluetoothDevice} wish to get
- * @return the A2DP optional coedc support value, one of {@link
+ * @return the A2DP optional codec support value, one of {@link
* BluetoothA2dp#OPTIONAL_CODECS_SUPPORT_UNKNOWN}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_NOT_SUPPORTED}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_SUPPORTED},
*/
- @VisibleForTesting
@OptionalCodecsSupportStatus
public int getA2dpSupportsOptionalCodecs(BluetoothDevice device) {
if (device == null) {
@@ -537,15 +537,14 @@ public class DatabaseManager {
}
/**
- * Set the A2DP optional coedc enabled value
+ * Set the A2DP optional codec enabled value
*
* @param device {@link BluetoothDevice} wish to set
- * @param newValue the new A2DP optional coedc enabled value, one of {@link
+ * @param newValue the new A2DP optional codec enabled value, one of {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_UNKNOWN}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_DISABLED}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_ENABLED}
*/
- @VisibleForTesting
public void setA2dpOptionalCodecsEnabled(BluetoothDevice device, int newValue) {
if (device == null) {
Log.e(TAG, "setA2dpOptionalCodecEnabled: device is null");
@@ -578,15 +577,14 @@ public class DatabaseManager {
}
/**
- * Get the A2DP optional coedc enabled value
+ * Get the A2DP optional codec enabled value
*
* @param device {@link BluetoothDevice} wish to get
- * @return the A2DP optional coedc enabled value, one of {@link
+ * @return the A2DP optional codec enabled value, one of {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_UNKNOWN}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_DISABLED}, {@link
* BluetoothA2dp#OPTIONAL_CODECS_PREF_ENABLED}
*/
- @VisibleForTesting
@OptionalCodecsPreferenceStatus
public int getA2dpOptionalCodecsEnabled(BluetoothDevice device) {
if (device == null) {
@@ -684,19 +682,12 @@ public class DatabaseManager {
*/
public void setDisconnection(BluetoothDevice device, int profileId) {
if (device == null) {
- Log.e(
- TAG,
- "setDisconnection: device is null, "
- + "profileId: "
- + BluetoothProfile.getProfileName(profileId));
+ Log.e(TAG, "setDisconnection: device is null, profileId: " + getProfileName(profileId));
return;
}
Log.d(
TAG,
- "setDisconnection: device "
- + device
- + "profileId: "
- + BluetoothProfile.getProfileName(profileId));
+ "setDisconnection: device " + device + "profileId: " + getProfileName(profileId));
if (profileId != BluetoothProfile.A2DP && profileId != BluetoothProfile.HEADSET) {
// there is no change on metadata when profile is neither A2DP nor Headset
@@ -710,7 +701,6 @@ public class DatabaseManager {
return;
}
Metadata metadata = mMetadataCache.get(address);
-
if (profileId == BluetoothProfile.A2DP && metadata.is_active_a2dp_device) {
metadata.is_active_a2dp_device = false;
Log.d(
@@ -773,8 +763,7 @@ public class DatabaseManager {
for (Metadata metadata : sortedMetadata) {
try {
mostRecentlyConnectedDevices.add(
- BluetoothAdapter.getDefaultAdapter()
- .getRemoteDevice(metadata.getAddress()));
+ mAdapter.getRemoteDevice(metadata.getAddress()));
} catch (IllegalArgumentException ex) {
Log.d(
TAG,
@@ -827,8 +816,7 @@ public class DatabaseManager {
Metadata metadata = entry.getValue();
if (metadata.is_active_a2dp_device) {
try {
- return BluetoothAdapter.getDefaultAdapter()
- .getRemoteDevice(metadata.getAddress());
+ return mAdapter.getRemoteDevice(metadata.getAddress());
} catch (IllegalArgumentException ex) {
Log.d(
TAG,
@@ -857,8 +845,7 @@ public class DatabaseManager {
}
if (entry != null) {
try {
- return BluetoothAdapter.getDefaultAdapter()
- .getRemoteDevice(entry.getValue().getAddress());
+ return mAdapter.getRemoteDevice(entry.getValue().getAddress());
} catch (IllegalArgumentException ex) {
Log.d(
TAG,
@@ -874,11 +861,10 @@ public class DatabaseManager {
* @return the list of device registered as HFP active
*/
public List<BluetoothDevice> getMostRecentlyActiveHfpDevices() {
- BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
synchronized (mMetadataCache) {
return mMetadataCache.entrySet().stream()
.filter(x -> x.getValue().isActiveHfpDevice)
- .map(x -> adapter.getRemoteDevice(x.getValue().getAddress()))
+ .map(x -> mAdapter.getRemoteDevice(x.getValue().getAddress()))
.collect(Collectors.toList());
}
}
@@ -959,7 +945,7 @@ public class DatabaseManager {
+ "device: "
+ device
+ " to "
- + BluetoothProfile.getProfileName(outputProfile));
+ + getProfileName(outputProfile));
metadata.preferred_output_only_profile = outputProfile;
isPreferenceSet = true;
}
@@ -971,11 +957,10 @@ public class DatabaseManager {
"setPreferredAudioProfiles: Updating DUPLEX audio profile for device: "
+ device
+ " to "
- + BluetoothProfile.getProfileName(duplexProfile));
+ + getProfileName(duplexProfile));
metadata.preferred_duplex_profile = duplexProfile;
isPreferenceSet = true;
}
-
updateDatabase(metadata);
}
@@ -992,7 +977,7 @@ public class DatabaseManager {
+ "device: "
+ firstGroupDevice
+ " to "
- + BluetoothProfile.getProfileName(outputProfile));
+ + getProfileName(outputProfile));
metadata.preferred_output_only_profile = outputProfile;
}
if (duplexProfile != 0) {
@@ -1001,10 +986,9 @@ public class DatabaseManager {
"setPreferredAudioProfiles: Updating duplex audio profile for device: "
+ firstGroupDevice
+ " to "
- + BluetoothProfile.getProfileName(duplexProfile));
+ + getProfileName(duplexProfile));
metadata.preferred_duplex_profile = duplexProfile;
}
-
updateDatabase(metadata);
}
}
@@ -1081,7 +1065,6 @@ public class DatabaseManager {
+ " to: "
+ activeAudioDevicePolicy);
metadata.active_audio_device_policy = activeAudioDevicePolicy;
-
updateDatabase(metadata);
}
return BluetoothStatusCodes.SUCCESS;
@@ -1104,7 +1087,6 @@ public class DatabaseManager {
}
Metadata metadata = mMetadataCache.get(address);
-
return metadata.active_audio_device_policy;
}
}
@@ -1130,7 +1112,6 @@ public class DatabaseManager {
Metadata metadata = mMetadataCache.get(address);
Log.i(TAG, "setMicrophoneForCallEnabled(" + device + ", " + enabled + ")");
metadata.is_preferred_microphone_for_calls = enabled;
-
updateDatabase(metadata);
}
return BluetoothStatusCodes.SUCCESS;
@@ -1154,7 +1135,6 @@ public class DatabaseManager {
}
Metadata metadata = mMetadataCache.get(address);
-
return metadata.is_preferred_microphone_for_calls;
}
}
@@ -1164,7 +1144,6 @@ public class DatabaseManager {
*
* @return {@link Looper} for the handler thread
*/
- @VisibleForTesting
public Looper getHandlerLooper() {
if (mHandlerThread == null) {
return null;
@@ -1265,8 +1244,7 @@ public class DatabaseManager {
&& !Arrays.asList(bondedDevices).stream()
.anyMatch(device -> address.equals(device.getAddress()))) {
List<Integer> list = metadata.getChangedCustomizedMeta();
- BluetoothDevice device =
- BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
+ BluetoothDevice device = mAdapter.getRemoteDevice(address);
for (int key : list) {
mAdapterService.onMetadataChanged(device, key, null);
}
@@ -1319,62 +1297,62 @@ public class DatabaseManager {
Settings.Global.getInt(
contentResolver,
getLegacyA2dpSinkPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int a2dpSinkConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyA2dpSrcPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int hearingaidConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyHearingAidPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int headsetConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyHeadsetPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int headsetClientConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyHeadsetPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int hidHostConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyHidHostPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int mapConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyMapPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int mapClientConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyMapClientPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int panConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyPanPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int pbapConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyPbapClientPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int pbapClientConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacyPbapClientPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int sapConnectionPolicy =
Settings.Global.getInt(
contentResolver,
getLegacySapPriorityKey(device.getAddress()),
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ CONNECTION_POLICY_UNKNOWN);
int a2dpSupportsOptionalCodec =
Settings.Global.getInt(
contentResolver,
@@ -1403,8 +1381,7 @@ public class DatabaseManager {
data.setProfileConnectionPolicy(BluetoothProfile.SAP, sapConnectionPolicy);
data.setProfileConnectionPolicy(
BluetoothProfile.HEARING_AID, hearingaidConnectionPolicy);
- data.setProfileConnectionPolicy(
- BluetoothProfile.LE_AUDIO, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ data.setProfileConnectionPolicy(BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_UNKNOWN);
data.a2dpSupportsOptionalCodecs = a2dpSupportsOptionalCodec;
data.a2dpOptionalCodecsEnabled = a2dpOptionalCodecEnabled;
mMetadataCache.put(address, data);
@@ -1490,7 +1467,7 @@ public class DatabaseManager {
mHandler.sendMessage(message);
try {
// Lock the thread until handler thread finish loading database.
- mSemaphore.tryAcquire(LOAD_DATABASE_TIMEOUT, TimeUnit.MILLISECONDS);
+ mSemaphore.tryAcquire(LOAD_DATABASE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Log.e(TAG, "loadDatabase: semaphore acquire failed");
}
@@ -1588,4 +1565,54 @@ public class DatabaseManager {
writer.println(" " + entry.getValue());
}
}
+
+ /**
+ * Update Key missing count.
+ *
+ * <p>It is used to update the key missing count when a bond loss is detected (increment the
+ * count) or a successful bond is detected (reset the count)
+ *
+ * @param isKeyMissingDetected true if the bond loss is detected, false if the bond is
+ * successfully established.
+ */
+ public void updateKeyMissingCount(BluetoothDevice device, boolean isKeyMissingDetected) {
+ synchronized (mMetadataCache) {
+ String address = device.getAddress();
+
+ if (!mMetadataCache.containsKey(address)) {
+ Log.e(TAG, "device is not bonded");
+ return;
+ }
+
+ Metadata metadata = mMetadataCache.get(address);
+ if (isKeyMissingDetected) {
+ metadata.key_missing_count++;
+ Log.i(TAG, "Bond loss detected, count: " + metadata.key_missing_count);
+ } else {
+ metadata.key_missing_count = 0;
+ Log.i(TAG, "Successful bond detected, reset key missing count");
+ }
+ updateDatabase(metadata);
+ }
+ }
+
+ /**
+ * Get the key missing count.
+ *
+ * @param device the BluetoothDevice to get the key missing count for.
+ * @return the key missing count, or -1 if the device is not bonded.
+ */
+ public int getKeyMissingCount(BluetoothDevice device) {
+ synchronized (mMetadataCache) {
+ String address = device.getAddress();
+
+ if (!mMetadataCache.containsKey(address)) {
+ Log.e(TAG, "device is not bonded");
+ return -1;
+ }
+
+ Metadata metadata = mMetadataCache.get(address);
+ return metadata.key_missing_count;
+ }
+ }
}
diff --git a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java
index 43bd50afb1..2e8aaa625e 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/Metadata.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.btservice.storage;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothA2dp.OptionalCodecsPreferenceStatus;
import android.bluetooth.BluetoothA2dp.OptionalCodecsSupportStatus;
@@ -32,7 +35,6 @@ import java.util.ArrayList;
import java.util.List;
@Entity(tableName = "metadata")
-
public class Metadata {
@PrimaryKey @NonNull private String address;
@@ -74,6 +76,9 @@ public class Metadata {
/** This is used to indicate whether device's microphone prefer to use during calls */
public boolean is_preferred_microphone_for_calls;
+ /** This is used to indicate the number of times the bond has been lost */
+ public int key_missing_count;
+
Metadata(String address) {
this(address, false, false);
}
@@ -93,6 +98,7 @@ public class Metadata {
preferred_duplex_profile = 0;
active_audio_device_policy = BluetoothDevice.ACTIVE_AUDIO_DEVICE_POLICY_DEFAULT;
is_preferred_microphone_for_calls = true;
+ key_missing_count = 0;
}
static final class Builder {
@@ -138,9 +144,9 @@ public class Metadata {
void setProfileConnectionPolicy(int profile, int connectionPolicy) {
// We no longer support BluetoothProfile.PRIORITY_AUTO_CONNECT and are merging it into
- // BluetoothProfile.CONNECTION_POLICY_ALLOWED
- if (connectionPolicy > BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ // CONNECTION_POLICY_ALLOWED
+ if (connectionPolicy > CONNECTION_POLICY_ALLOWED) {
+ connectionPolicy = CONNECTION_POLICY_ALLOWED;
}
switch (profile) {
@@ -247,7 +253,7 @@ public class Metadata {
case BluetoothProfile.BATTERY:
return profileConnectionPolicies.battery_connection_policy;
}
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
void setCustomizedMeta(int key, byte[] value) {
diff --git a/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java b/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java
index 0a9df7f70d..00c52734a8 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/MetadataDatabase.java
@@ -33,7 +33,7 @@ import java.util.List;
/** MetadataDatabase is a Room database stores Bluetooth persistence data */
@Database(
entities = {Metadata.class},
- version = 121)
+ version = 122)
public abstract class MetadataDatabase extends RoomDatabase {
/** The metadata database file name */
public static final String DATABASE_NAME = "bluetooth_db";
@@ -71,6 +71,7 @@ public abstract class MetadataDatabase extends RoomDatabase {
.addMigrations(MIGRATION_118_119)
.addMigrations(MIGRATION_119_120)
.addMigrations(MIGRATION_120_121)
+ .addMigrations(MIGRATION_121_122)
.allowMainThreadQueries()
.build();
}
@@ -694,4 +695,25 @@ public abstract class MetadataDatabase extends RoomDatabase {
}
}
};
+
+ @VisibleForTesting
+ static final Migration MIGRATION_121_122 =
+ new Migration(121, 122) {
+ @Override
+ public void migrate(SupportSQLiteDatabase database) {
+ try {
+ database.execSQL(
+ "ALTER TABLE metadata ADD COLUMN"
+ + " `key_missing_count` INTEGER NOT NULL"
+ + " DEFAULT 0");
+ } catch (SQLException ex) {
+ // Check if user has new schema, but is just missing the version update
+ Cursor cursor = database.query("SELECT * FROM metadata");
+ if (cursor == null
+ || cursor.getColumnIndex("key_missing_count") == -1) {
+ throw ex;
+ }
+ }
+ }
+ };
}
diff --git a/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java b/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java
index 85ec34544b..5fb23b9267 100644
--- a/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java
+++ b/android/app/src/com/android/bluetooth/btservice/storage/ProfilePrioritiesEntity.java
@@ -16,7 +16,7 @@
package com.android.bluetooth.btservice.storage;
-import android.bluetooth.BluetoothProfile;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import androidx.room.Entity;
@@ -44,25 +44,25 @@ class ProfilePrioritiesEntity {
public int battery_connection_policy;
ProfilePrioritiesEntity() {
- a2dp_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- a2dp_sink_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- hfp_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- hfp_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- hid_host_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- pan_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- pbap_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- pbap_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- map_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- sap_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- hearing_aid_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- hap_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- map_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- le_audio_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- volume_control_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- csip_set_coordinator_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- le_call_control_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- bass_client_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
- battery_connection_policy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ a2dp_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ a2dp_sink_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ hfp_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ hfp_client_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ hid_host_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ pan_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ pbap_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ pbap_client_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ map_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ sap_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ hearing_aid_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ hap_client_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ map_client_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ le_audio_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ volume_control_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ csip_set_coordinator_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ le_call_control_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ bass_client_connection_policy = CONNECTION_POLICY_UNKNOWN;
+ battery_connection_policy = CONNECTION_POLICY_UNKNOWN;
}
public String toString() {
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
index 684d08c59d..2b49f467a8 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorService.java
@@ -19,6 +19,11 @@ package com.android.bluetooth.csip;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
import static java.util.Objects.requireNonNullElseGet;
@@ -231,7 +236,7 @@ public class CsipSetCoordinatorService extends ProfileService {
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
return false;
}
final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device);
@@ -306,8 +311,8 @@ public class CsipSetCoordinatorService extends ProfileService {
if (bondState != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "okToConnect: return false, bondState=" + bondState);
return false;
- } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -330,7 +335,7 @@ public class CsipSetCoordinatorService extends ProfileService {
if (!Utils.arrayContains(featureUuids, BluetoothUuid.COORDINATED_SET)) {
continue;
}
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
CsipSetCoordinatorStateMachine sm = mStateMachines.get(device);
if (sm != null) {
connectionState = sm.getConnectionState();
@@ -401,7 +406,7 @@ public class CsipSetCoordinatorService extends ProfileService {
synchronized (mStateMachines) {
CsipSetCoordinatorStateMachine sm = mStateMachines.get(device);
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -425,9 +430,9 @@ public class CsipSetCoordinatorService extends ProfileService {
Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(
device, BluetoothProfile.CSIP_SET_COORDINATOR, connectionPolicy);
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -674,14 +679,14 @@ public class CsipSetCoordinatorService extends ProfileService {
}
for (BluetoothDevice groupDevice : mGroupIdToConnectedDevices.get(groupId)) {
if (mLeAudioService.getConnectionPolicy(groupDevice)
- == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ == CONNECTION_POLICY_FORBIDDEN) {
Log.i(
TAG,
"Setting CSIP connection policy to FORBIDDEN for device "
+ groupDevice
+ " after all group devices bonded because LEA "
+ "connection policy is FORBIDDEN");
- setConnectionPolicy(groupDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ setConnectionPolicy(groupDevice, CONNECTION_POLICY_FORBIDDEN);
}
}
} else {
@@ -914,7 +919,7 @@ public class CsipSetCoordinatorService extends ProfileService {
if (sm == null) {
return;
}
- if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (sm.getConnectionState() != STATE_DISCONNECTED) {
Log.i(TAG, "Disconnecting device because it was unbonded.");
disconnect(device);
return;
@@ -963,13 +968,13 @@ public class CsipSetCoordinatorService extends ProfileService {
}
// Check if the device is disconnected - if unbond, remove the state machine
- if (toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (toState == STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
Log.d(TAG, device + " is unbond. Remove state machine");
removeStateMachine(device);
}
- } else if (toState == BluetoothProfile.STATE_CONNECTED) {
+ } else if (toState == STATE_CONNECTED) {
int groupId = getGroupId(device, BluetoothUuid.CAP);
if (!mGroupIdToConnectedDevices.containsKey(groupId)) {
mGroupIdToConnectedDevices.put(groupId, new HashSet<>());
@@ -1053,7 +1058,7 @@ public class CsipSetCoordinatorService extends ProfileService {
CsipSetCoordinatorService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -1080,7 +1085,7 @@ public class CsipSetCoordinatorService extends ProfileService {
CsipSetCoordinatorService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
return service.getConnectionPolicy(device);
diff --git a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
index 1e72275324..8a9953dbb7 100644
--- a/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
+++ b/android/app/src/com/android/bluetooth/csip/CsipSetCoordinatorStateMachine.java
@@ -18,6 +18,11 @@
package com.android.bluetooth.csip;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+import static android.bluetooth.BluetoothProfile.getConnectionStateName;
import android.bluetooth.BluetoothCsipSetCoordinator;
import android.bluetooth.BluetoothDevice;
@@ -125,7 +130,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
removeDeferredMessages(DISCONNECT);
if (mLastConnectionState != -1) {
- csipConnectionState(BluetoothProfile.STATE_DISCONNECTED, mLastConnectionState);
+ csipConnectionState(STATE_DISCONNECTED, mLastConnectionState);
}
}
@@ -136,7 +141,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ mLastConnectionState = STATE_DISCONNECTED;
}
@Override
@@ -248,7 +253,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs);
- csipConnectionState(BluetoothProfile.STATE_CONNECTING, mLastConnectionState);
+ csipConnectionState(STATE_CONNECTING, mLastConnectionState);
}
@Override
@@ -258,7 +263,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTING;
+ mLastConnectionState = STATE_CONNECTING;
removeMessages(CONNECT_TIMEOUT);
}
@@ -346,7 +351,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs);
- csipConnectionState(BluetoothProfile.STATE_DISCONNECTING, mLastConnectionState);
+ csipConnectionState(STATE_DISCONNECTING, mLastConnectionState);
}
@Override
@@ -356,7 +361,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING;
+ mLastConnectionState = STATE_DISCONNECTING;
removeMessages(CONNECT_TIMEOUT);
}
@@ -463,7 +468,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
removeDeferredMessages(CONNECT);
- csipConnectionState(BluetoothProfile.STATE_CONNECTED, mLastConnectionState);
+ csipConnectionState(STATE_CONNECTED, mLastConnectionState);
}
@Override
@@ -473,7 +478,7 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTED;
+ mLastConnectionState = STATE_CONNECTED;
}
@Override
@@ -545,16 +550,16 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
String currentState = getCurrentState().getName();
switch (currentState) {
case "Disconnected":
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
case "Connecting":
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
case "Connected":
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
case "Disconnecting":
- return BluetoothProfile.STATE_DISCONNECTING;
+ return STATE_DISCONNECTING;
default:
Log.e(TAG, "Bad currentState: " + currentState);
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
@@ -564,9 +569,9 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
"Connection state "
+ mDevice
+ ": "
- + profileStateToString(prevState)
+ + getConnectionStateName(prevState)
+ "->"
- + profileStateToString(newState));
+ + getConnectionStateName(newState));
mService.handleConnectionStateChanged(mDevice, prevState, newState);
Intent intent =
@@ -596,22 +601,6 @@ public class CsipSetCoordinatorStateMachine extends StateMachine {
return Integer.toString(what);
}
- private static String profileStateToString(int state) {
- switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED:
- return "DISCONNECTED";
- case BluetoothProfile.STATE_CONNECTING:
- return "CONNECTING";
- case BluetoothProfile.STATE_CONNECTED:
- return "CONNECTED";
- case BluetoothProfile.STATE_DISCONNECTING:
- return "DISCONNECTING";
- default:
- break;
- }
- return Integer.toString(state);
- }
-
/** Dump the state machine logs */
public void dump(StringBuilder sb) {
ProfileService.println(sb, "mDevice: " + mDevice);
diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java b/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java
index c276e6e017..f61f56cd16 100644
--- a/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java
+++ b/android/app/src/com/android/bluetooth/gatt/AdvertiseHelper.java
@@ -80,18 +80,18 @@ class AdvertiseHelper {
byte[] manufacturerData = data.getManufacturerSpecificData().get(manufacturerId);
int dataLen = 2 + (manufacturerData == null ? 0 : manufacturerData.length);
- byte[] concated = new byte[dataLen];
+ byte[] concatenated = new byte[dataLen];
// First two bytes are manufacturer id in little-endian.
- concated[0] = (byte) (manufacturerId & 0xFF);
- concated[1] = (byte) ((manufacturerId >> 8) & 0xFF);
+ concatenated[0] = (byte) (manufacturerId & 0xFF);
+ concatenated[1] = (byte) ((manufacturerId >> 8) & 0xFF);
if (manufacturerData != null) {
- System.arraycopy(manufacturerData, 0, concated, 2, manufacturerData.length);
+ System.arraycopy(manufacturerData, 0, concatenated, 2, manufacturerData.length);
}
- check_length(MANUFACTURER_SPECIFIC_DATA, concated.length + 1);
- ret.write(concated.length + 1);
+ check_length(MANUFACTURER_SPECIFIC_DATA, concatenated.length + 1);
+ ret.write(concatenated.length + 1);
ret.write(MANUFACTURER_SPECIFIC_DATA);
- ret.write(concated, 0, concated.length);
+ ret.write(concatenated, 0, concatenated.length);
}
if (data.getIncludeTxPowerLevel()) {
@@ -147,29 +147,29 @@ class AdvertiseHelper {
int uuidLen = uuid.length;
int dataLen = uuidLen + (serviceData == null ? 0 : serviceData.length);
- byte[] concated = new byte[dataLen];
+ byte[] concatenated = new byte[dataLen];
- System.arraycopy(uuid, 0, concated, 0, uuidLen);
+ System.arraycopy(uuid, 0, concatenated, 0, uuidLen);
if (serviceData != null) {
- System.arraycopy(serviceData, 0, concated, uuidLen, serviceData.length);
+ System.arraycopy(serviceData, 0, concatenated, uuidLen, serviceData.length);
}
if (uuid.length == BluetoothUuid.UUID_BYTES_16_BIT) {
- check_length(SERVICE_DATA_16_BIT_UUID, concated.length + 1);
- ret.write(concated.length + 1);
+ check_length(SERVICE_DATA_16_BIT_UUID, concatenated.length + 1);
+ ret.write(concatenated.length + 1);
ret.write(SERVICE_DATA_16_BIT_UUID);
- ret.write(concated, 0, concated.length);
+ ret.write(concatenated, 0, concatenated.length);
} else if (uuid.length == BluetoothUuid.UUID_BYTES_32_BIT) {
- check_length(SERVICE_DATA_32_BIT_UUID, concated.length + 1);
- ret.write(concated.length + 1);
+ check_length(SERVICE_DATA_32_BIT_UUID, concatenated.length + 1);
+ ret.write(concatenated.length + 1);
ret.write(SERVICE_DATA_32_BIT_UUID);
- ret.write(concated, 0, concated.length);
+ ret.write(concatenated, 0, concatenated.length);
} else /*if (uuid.length == BluetoothUuid.UUID_BYTES_128_BIT)*/ {
- check_length(SERVICE_DATA_128_BIT_UUID, concated.length + 1);
- ret.write(concated.length + 1);
+ check_length(SERVICE_DATA_128_BIT_UUID, concatenated.length + 1);
+ ret.write(concatenated.length + 1);
ret.write(SERVICE_DATA_128_BIT_UUID);
- ret.write(concated, 0, concated.length);
+ ret.write(concatenated, 0, concatenated.length);
}
}
}
diff --git a/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java b/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java
index 7917915a2b..e3aac31354 100644
--- a/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java
+++ b/android/app/src/com/android/bluetooth/gatt/AdvertiserMap.java
@@ -77,7 +77,7 @@ class AdvertiserMap {
return mAppAdvertiseStats.get(id);
}
- /** update the advertiser ID by the regiseter ID */
+ /** update the advertiser ID by the register ID */
synchronized void setAdvertiserIdByRegId(int regId, int advertiserId) {
AppAdvertiseStats stats = mAppAdvertiseStats.get(regId);
if (stats == null) {
diff --git a/android/app/src/com/android/bluetooth/gatt/ContextMap.java b/android/app/src/com/android/bluetooth/gatt/ContextMap.java
index b725f31b6f..5aa3529982 100644
--- a/android/app/src/com/android/bluetooth/gatt/ContextMap.java
+++ b/android/app/src/com/android/bluetooth/gatt/ContextMap.java
@@ -405,13 +405,13 @@ public class ContextMap<C> {
/** Returns connect device map with addr and appid */
Map<Integer, String> getConnectedMap() {
- Map<Integer, String> connectedmap = new HashMap<Integer, String>();
+ Map<Integer, String> connectedMap = new HashMap<Integer, String>();
synchronized (mConnectionsLock) {
for (Connection conn : mConnections) {
- connectedmap.put(conn.appId, conn.address);
+ connectedMap.put(conn.appId, conn.address);
}
}
- return connectedmap;
+ return connectedMap;
}
/** Logs debug information. */
diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementBinder.kt b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementBinder.kt
index 63c9b21a59..a63b757904 100644
--- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementBinder.kt
+++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementBinder.kt
@@ -69,7 +69,13 @@ class DistanceMeasurementBinder(
): List<DistanceMeasurementMethod> {
val manager: DistanceMeasurementManager =
getManager(source, "getSupportedDistanceMeasurementMethods") ?: return emptyList()
- return manager.getSupportedDistanceMeasurementMethods()
+
+ val result =
+ manager.runOnDistanceMeasurementThreadAndWaitForResult {
+ manager.getSupportedDistanceMeasurementMethods()
+ }
+
+ return result ?: ArrayList()
}
override fun startDistanceMeasurement(
@@ -80,7 +86,10 @@ class DistanceMeasurementBinder(
) {
val manager: DistanceMeasurementManager =
getManager(source, "startDistanceMeasurement") ?: return
- manager.startDistanceMeasurement(uuid.uuid, distanceMeasurementParams, callback)
+
+ manager.postOnDistanceMeasurementThread {
+ manager.startDistanceMeasurement(uuid.uuid, distanceMeasurementParams, callback)
+ }
}
override fun stopDistanceMeasurement(
@@ -105,7 +114,18 @@ class DistanceMeasurementBinder(
return BluetoothStatusCodes.ERROR_MISSING_BLUETOOTH_CONNECT_PERMISSION
}
mContext.enforceCallingOrSelfPermission(Manifest.permission.BLUETOOTH_PRIVILEGED, null)
- return mDistanceMeasurementManager.stopDistanceMeasurement(uuid.uuid, device, method, false)
+
+ val result =
+ mDistanceMeasurementManager.runOnDistanceMeasurementThreadAndWaitForResult {
+ mDistanceMeasurementManager.stopDistanceMeasurement(
+ uuid.uuid,
+ device,
+ method,
+ false,
+ )
+ }
+
+ return result ?: BluetoothStatusCodes.ERROR_UNKNOWN
}
override fun getChannelSoundingMaxSupportedSecurityLevel(
@@ -115,25 +135,38 @@ class DistanceMeasurementBinder(
val manager: DistanceMeasurementManager =
getManager(source, "getChannelSoundingMaxSupportedSecurityLevel")
?: return ChannelSoundingParams.CS_SECURITY_LEVEL_UNKNOWN
- return manager.getChannelSoundingMaxSupportedSecurityLevel(remoteDevice)
+
+ val result =
+ manager.runOnDistanceMeasurementThreadAndWaitForResult {
+ manager.getChannelSoundingMaxSupportedSecurityLevel(remoteDevice)
+ }
+
+ return result ?: ChannelSoundingParams.CS_SECURITY_LEVEL_UNKNOWN
}
override fun getLocalChannelSoundingMaxSupportedSecurityLevel(source: AttributionSource): Int {
val manager: DistanceMeasurementManager =
getManager(source, "getLocalChannelSoundingMaxSupportedSecurityLevel")
?: return ChannelSoundingParams.CS_SECURITY_LEVEL_UNKNOWN
- return manager.getLocalChannelSoundingMaxSupportedSecurityLevel()
+
+ val result =
+ manager.runOnDistanceMeasurementThreadAndWaitForResult {
+ manager.getLocalChannelSoundingMaxSupportedSecurityLevel()
+ }
+
+ return result ?: ChannelSoundingParams.CS_SECURITY_LEVEL_UNKNOWN
}
override fun getChannelSoundingSupportedSecurityLevels(source: AttributionSource): IntArray {
val manager: DistanceMeasurementManager =
getManager(source, "getChannelSoundingSupportedSecurityLevels") ?: return IntArray(0)
- return manager
- .getChannelSoundingSupportedSecurityLevels()
- .stream()
- .mapToInt { i -> i }
- .toArray()
+ val result =
+ manager.runOnDistanceMeasurementThreadAndWaitForResult {
+ manager.getChannelSoundingSupportedSecurityLevels()
+ }
+
+ return result?.stream()?.mapToInt { i -> i }?.toArray() ?: IntArray(0)
}
companion object {
diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
index 04c6f7fff8..7ed4fe72e6 100644
--- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
+++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementManager.java
@@ -26,10 +26,13 @@ import android.bluetooth.le.DistanceMeasurementMethod;
import android.bluetooth.le.DistanceMeasurementParams;
import android.bluetooth.le.DistanceMeasurementResult;
import android.bluetooth.le.IDistanceMeasurementCallback;
+import android.os.Handler;
import android.os.HandlerThread;
+import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
+import com.android.bluetooth.Utils;
import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.flags.Flags;
import com.android.internal.annotations.VisibleForTesting;
@@ -38,20 +41,27 @@ import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
/** Manages distance measurement operations and interacts with Gabeldorsche stack. */
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
public class DistanceMeasurementManager {
private static final String TAG = DistanceMeasurementManager.class.getSimpleName();
+ private static final long RUN_SYNC_WAIT_TIME_MS = 2000L;
+
private static final int RSSI_LOW_FREQUENCY_INTERVAL_MS = 3000;
private static final int RSSI_MEDIUM_FREQUENCY_INTERVAL_MS = 1000;
private static final int RSSI_HIGH_FREQUENCY_INTERVAL_MS = 500;
private static final int CS_LOW_FREQUENCY_INTERVAL_MS = 5000;
- private static final int CS_MEDIUM_FREQUENCY_INTERVAL_MS = 3000;
- private static final int CS_HIGH_FREQUENCY_INTERVAL_MS = 200;
+ private static final int CS_MEDIUM_FREQUENCY_INTERVAL_MS = 200;
+ private static final int CS_HIGH_FREQUENCY_INTERVAL_MS = 100;
+ private static final int THREAD_WAIT_TIMEOUT_MS = 2000;
// sync with system/gd/hic/DistanceMeasurementManager
private static final int INVALID_AZIMUTH_ANGLE_DEGREE = -1;
@@ -59,6 +69,7 @@ public class DistanceMeasurementManager {
private final AdapterService mAdapterService;
private final HandlerThread mHandlerThread;
+ private final Handler mHandler;
private final DistanceMeasurementNativeInterface mDistanceMeasurementNativeInterface;
private final DistanceMeasurementBinder mDistanceMeasurementBinder;
private final ConcurrentHashMap<String, CopyOnWriteArraySet<DistanceMeasurementTracker>>
@@ -70,12 +81,24 @@ public class DistanceMeasurementManager {
private volatile boolean mIsTurnedOff = false;
/** Constructor of {@link DistanceMeasurementManager}. */
- DistanceMeasurementManager(AdapterService adapterService) {
+ DistanceMeasurementManager(AdapterService adapterService, Looper looper) {
mAdapterService = adapterService;
- // Start a HandlerThread that handles distance measurement operations
- mHandlerThread = new HandlerThread("DistanceMeasurementManager");
- mHandlerThread.start();
+ if (Flags.distanceMeasurementThread()) {
+ // TODO(b/391508617): When removing this flag, remove all 'synchronized' and replace
+ // java.util.concurrent data structures with the basic ones.
+ // Also, remove mHandlerThread variable.
+ mHandler = new Handler(looper);
+
+ mHandlerThread = null;
+ } else {
+ // Start a HandlerThread that handles distance measurement operations
+ mHandlerThread = new HandlerThread("DistanceMeasurementManager");
+ mHandlerThread.start();
+
+ mHandler = new Handler(mHandlerThread.getLooper());
+ }
+
mDistanceMeasurementNativeInterface = DistanceMeasurementNativeInterface.getInstance();
mDistanceMeasurementNativeInterface.init(this);
mDistanceMeasurementBinder = new DistanceMeasurementBinder(adapterService, this);
@@ -90,22 +113,27 @@ public class DistanceMeasurementManager {
}
void cleanup() {
- mIsTurnedOff = true;
- mDistanceMeasurementBinder.cleanup();
- mDistanceMeasurementNativeInterface.cleanup();
- Log.d(TAG, "stop all sessions as BT is off");
- for (String addressForCs : mCsTrackers.keySet()) {
- onDistanceMeasurementStopped(
- addressForCs,
- BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED,
- DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING);
- }
- for (String addressForRssi : mRssiTrackers.keySet()) {
- onDistanceMeasurementStopped(
- addressForRssi,
- BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED,
- DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI);
- }
+ forceRunSyncOnDistanceMeasurementThread(
+ () -> {
+ mIsTurnedOff = true;
+ mHandler.removeCallbacksAndMessages(null);
+ mDistanceMeasurementBinder.cleanup();
+ mDistanceMeasurementNativeInterface.cleanup();
+ Log.d(TAG, "stop all sessions as BT is off");
+ for (String addressForCs : mCsTrackers.keySet()) {
+ onDistanceMeasurementStopped(
+ addressForCs,
+ BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED,
+ DistanceMeasurementMethod
+ .DISTANCE_MEASUREMENT_METHOD_CHANNEL_SOUNDING);
+ }
+ for (String addressForRssi : mRssiTrackers.keySet()) {
+ onDistanceMeasurementStopped(
+ addressForRssi,
+ BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED,
+ DistanceMeasurementMethod.DISTANCE_MEASUREMENT_METHOD_RSSI);
+ }
+ });
}
DistanceMeasurementBinder getBinder() {
@@ -130,6 +158,8 @@ public class DistanceMeasurementManager {
void startDistanceMeasurement(
UUID uuid, DistanceMeasurementParams params, IDistanceMeasurementCallback callback) {
+ checkThread();
+
if (mIsTurnedOff) {
Log.d(TAG, "BT is turned off, no new request is allowed.");
invokeStartFail(
@@ -228,6 +258,8 @@ public class DistanceMeasurementManager {
}
int stopDistanceMeasurement(UUID uuid, BluetoothDevice device, int method, boolean timeout) {
+ checkThread();
+
Log.i(
TAG,
"stopDistanceMeasurement device:"
@@ -257,6 +289,8 @@ public class DistanceMeasurementManager {
}
int getChannelSoundingMaxSupportedSecurityLevel(BluetoothDevice remoteDevice) {
+ checkThread();
+
if (mHasChannelSoundingFeature && mAdapterService.isLeChannelSoundingSupported()) {
return ChannelSoundingParams.CS_SECURITY_LEVEL_ONE;
}
@@ -264,6 +298,8 @@ public class DistanceMeasurementManager {
}
int getLocalChannelSoundingMaxSupportedSecurityLevel() {
+ checkThread();
+
if (mHasChannelSoundingFeature && mAdapterService.isLeChannelSoundingSupported()) {
return ChannelSoundingParams.CS_SECURITY_LEVEL_ONE;
}
@@ -271,6 +307,8 @@ public class DistanceMeasurementManager {
}
Set<Integer> getChannelSoundingSupportedSecurityLevels() {
+ checkThread();
+
// TODO(b/378685103): get it from the HAL when level 4 is supported and HAL v2 is available.
if (mHasChannelSoundingFeature && mAdapterService.isLeChannelSoundingSupported()) {
return Set.of(ChannelSoundingParams.CS_SECURITY_LEVEL_ONE);
@@ -386,6 +424,8 @@ public class DistanceMeasurementManager {
}
void onDistanceMeasurementStarted(String address, int method) {
+ checkThread();
+
logd(
"onDistanceMeasurementStarted address:"
+ BluetoothUtils.toAnonymizedAddress(address)
@@ -403,7 +443,7 @@ public class DistanceMeasurementManager {
}
}
- void handleRssiStarted(String address) {
+ private void handleRssiStarted(String address) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
@@ -414,7 +454,7 @@ public class DistanceMeasurementManager {
if (!tracker.mStarted) {
tracker.mStarted = true;
tracker.mCallback.onStarted(tracker.mDevice);
- tracker.startTimer(mHandlerThread.getLooper());
+ tracker.startTimer(mHandler.getLooper());
}
} catch (RemoteException e) {
Log.e(TAG, "Exception: " + e);
@@ -422,7 +462,7 @@ public class DistanceMeasurementManager {
}
}
- void handleCsStarted(String address) {
+ private void handleCsStarted(String address) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mCsTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find CS tracker");
@@ -433,7 +473,7 @@ public class DistanceMeasurementManager {
if (!tracker.mStarted) {
tracker.mStarted = true;
tracker.mCallback.onStarted(tracker.mDevice);
- tracker.startTimer(mHandlerThread.getLooper());
+ tracker.startTimer(mHandler.getLooper());
}
} catch (RemoteException e) {
Log.e(TAG, "Exception: " + e);
@@ -442,6 +482,7 @@ public class DistanceMeasurementManager {
}
void onDistanceMeasurementStopped(String address, int reason, int method) {
+ checkThread();
logd(
"onDistanceMeasurementStopped address:"
+ BluetoothUtils.toAnonymizedAddress(address)
@@ -461,7 +502,7 @@ public class DistanceMeasurementManager {
}
}
- void handleRssiStopped(String address, int reason) {
+ private void handleRssiStopped(String address, int reason) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
@@ -478,7 +519,7 @@ public class DistanceMeasurementManager {
mRssiTrackers.remove(address);
}
- void handleCsStopped(String address, int reason) {
+ private void handleCsStopped(String address, int reason) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mCsTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find CS tracker");
@@ -509,6 +550,7 @@ public class DistanceMeasurementManager {
int detectedAttackLevel,
double velocityMetersPerSecond,
int method) {
+ checkThread();
logd(
"onDistanceMeasurementResult "
+ BluetoothUtils.toAnonymizedAddress(address)
@@ -550,7 +592,7 @@ public class DistanceMeasurementManager {
}
}
- void handleRssiResult(String address, DistanceMeasurementResult result) {
+ private void handleRssiResult(String address, DistanceMeasurementResult result) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mRssiTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find rssi tracker");
@@ -568,7 +610,7 @@ public class DistanceMeasurementManager {
}
}
- void handleCsResult(String address, DistanceMeasurementResult result) {
+ private void handleCsResult(String address, DistanceMeasurementResult result) {
CopyOnWriteArraySet<DistanceMeasurementTracker> set = mCsTrackers.get(address);
if (set == null) {
Log.w(TAG, "Can't find cs tracker");
@@ -586,6 +628,71 @@ public class DistanceMeasurementManager {
}
}
+ interface GetResultTask<T> {
+ T getResult();
+ }
+
+ void postOnDistanceMeasurementThread(Runnable r) {
+ if (Flags.distanceMeasurementThread()) {
+ mHandler.post(r);
+ } else {
+ r.run();
+ }
+ }
+
+ <T> T runOnDistanceMeasurementThreadAndWaitForResult(GetResultTask<T> task) throws Throwable {
+ if (Flags.distanceMeasurementThread() && !mHandler.getLooper().isCurrentThread()) {
+ CompletableFuture<T> result = new CompletableFuture<>();
+ mHandler.post(
+ () -> {
+ try {
+ result.complete(task.getResult());
+ } catch (Exception e) {
+ result.completeExceptionally(e);
+ }
+ });
+
+ try {
+ return result.get(THREAD_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | TimeoutException e) {
+ Log.w(TAG, "Exception happened", e);
+ } catch (ExecutionException e) {
+ // Propagate exception to the caller
+ throw e.getCause();
+ }
+ return null;
+ } else {
+ return task.getResult();
+ }
+ }
+
+ private void forceRunSyncOnDistanceMeasurementThread(Runnable r) {
+ if (!Flags.distanceMeasurementThread()) {
+ r.run();
+ return;
+ }
+
+ final CompletableFuture<Void> future = new CompletableFuture<>();
+ mHandler.postAtFrontOfQueue(
+ () -> {
+ r.run();
+ future.complete(null);
+ });
+ try {
+ future.get(RUN_SYNC_WAIT_TIME_MS, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException | TimeoutException | ExecutionException e) {
+ Log.w(TAG, "Unable to complete sync task: " + e);
+ }
+ }
+
+ private void checkThread() {
+ if (Flags.distanceMeasurementThread()
+ && !mHandler.getLooper().isCurrentThread()
+ && !Utils.isInstrumentationTestMode()) {
+ throw new IllegalStateException("Not on distance measurement thread");
+ }
+ }
+
/** Logs the message in debug ROM. */
private static void logd(String msg) {
Log.d(TAG, msg);
diff --git a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java
index 5992a7b9ce..8d617ecf54 100644
--- a/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/gatt/DistanceMeasurementNativeInterface.java
@@ -89,12 +89,15 @@ public class DistanceMeasurementNativeInterface {
}
void onDistanceMeasurementStarted(String address, int method) {
- mDistanceMeasurementManager.onDistanceMeasurementStarted(address, method);
+ mDistanceMeasurementManager.postOnDistanceMeasurementThread(
+ () -> mDistanceMeasurementManager.onDistanceMeasurementStarted(address, method));
}
void onDistanceMeasurementStopped(String address, int reason, int method) {
- mDistanceMeasurementManager.onDistanceMeasurementStopped(
- address, convertErrorCode(reason), method);
+ mDistanceMeasurementManager.postOnDistanceMeasurementThread(
+ () ->
+ mDistanceMeasurementManager.onDistanceMeasurementStopped(
+ address, convertErrorCode(reason), method));
}
void onDistanceMeasurementResult(
@@ -111,20 +114,22 @@ public class DistanceMeasurementNativeInterface {
int detectedAttackLevel,
double velocityMetersPerSecond,
int method) {
- mDistanceMeasurementManager.onDistanceMeasurementResult(
- address,
- centimeter,
- errorCentimeter,
- azimuthAngle,
- errorAzimuthAngle,
- altitudeAngle,
- errorAltitudeAngle,
- elapsedRealtimeNanos,
- confidenceLevel,
- delayedSpreadMeters,
- detectedAttackLevel,
- velocityMetersPerSecond,
- method);
+ mDistanceMeasurementManager.postOnDistanceMeasurementThread(
+ () ->
+ mDistanceMeasurementManager.onDistanceMeasurementResult(
+ address,
+ centimeter,
+ errorCentimeter,
+ azimuthAngle,
+ errorAzimuthAngle,
+ altitudeAngle,
+ errorAltitudeAngle,
+ elapsedRealtimeNanos,
+ confidenceLevel,
+ delayedSpreadMeters,
+ detectedAttackLevel,
+ velocityMetersPerSecond,
+ method));
}
private static int convertErrorCode(int errorCode) {
diff --git a/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java b/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java
index 5df28f5336..db0ea861b7 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattDebugUtils.java
@@ -125,7 +125,7 @@ import java.util.UUID;
return true;
}
- /** Attempts to retrieve an extra from an intent first as hex value, then as an ineger. */
+ /** Attempts to retrieve an extra from an intent first as hex value, then as an integer. */
private static int getHandleExtra(Intent intent, String extra, int defaultValue) {
Bundle extras = intent.getExtras();
Object uuid = extras != null ? extras.get(extra) : null;
diff --git a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
index 529ac579cf..0279b2b199 100644
--- a/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
+++ b/android/app/src/com/android/bluetooth/gatt/GattObjectsFactory.java
@@ -16,6 +16,7 @@
package com.android.bluetooth.gatt;
+import android.os.Looper;
import android.util.Log;
import com.android.bluetooth.Utils;
@@ -62,7 +63,7 @@ public class GattObjectsFactory {
}
public DistanceMeasurementManager createDistanceMeasurementManager(
- AdapterService adapterService) {
- return new DistanceMeasurementManager(adapterService);
+ AdapterService adapterService, Looper looper) {
+ return new DistanceMeasurementManager(adapterService, looper);
}
}
diff --git a/android/app/src/com/android/bluetooth/gatt/GattService.java b/android/app/src/com/android/bluetooth/gatt/GattService.java
index ab3b63fc0a..17fddf788a 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;
@@ -132,7 +134,7 @@ public class GattService extends ProfileService {
@Nullable public final ScanController mScanController;
- /** This is only used when Flags.scanManagerRefactor() is true. */
+ /** This is only used when Flags.onlyStartScanDuringBleOn() is true. */
private static GattService sGattService;
/** List of our registered clients. */
@@ -183,15 +185,17 @@ public class GattService extends ProfileService {
mAdvertiseManager = new AdvertiseManager(mAdapterService, mHandlerThread.getLooper());
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
mScanController = new ScanController(adapterService);
} else {
mScanController = null;
}
mDistanceMeasurementManager =
- GattObjectsFactory.getInstance().createDistanceMeasurementManager(mAdapterService);
+ GattObjectsFactory.getInstance()
+ .createDistanceMeasurementManager(
+ mAdapterService, mHandlerThread.getLooper());
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
setGattService(this);
}
}
@@ -212,11 +216,11 @@ public class GattService extends ProfileService {
public void cleanup() {
Log.i(TAG, "Cleanup Gatt Service");
- if (Flags.scanManagerRefactor() && sGattService == null) {
+ if (Flags.onlyStartScanDuringBleOn() && sGattService == null) {
Log.w(TAG, "cleanup() called before initialization");
return;
}
- if (Flags.scanManagerRefactor()) {
+ if (Flags.onlyStartScanDuringBleOn()) {
setGattService(null);
}
if (mScanController != null) {
@@ -234,7 +238,7 @@ public class GattService extends ProfileService {
mHandlerThread.quit();
}
- /** This is only used when Flags.scanManagerRefactor() is true. */
+ /** This is only used when Flags.onlyStartScanDuringBleOn() is true. */
public static synchronized GattService getGattService() {
if (sGattService == null) {
Log.w(TAG, "getGattService(): service is null");
@@ -914,9 +918,9 @@ public class GattService extends ProfileService {
+ connId
+ ", address="
+ BluetoothUtils.toAnonymizedAddress(address));
-
+ BluetoothDevice device = getDevice(address);
mClientMap.removeConnection(clientIf, connId);
- mAdapterService.notifyGattClientDisconnect(clientIf, getDevice(address));
+ mAdapterService.notifyGattClientDisconnect(clientIf, device);
ContextMap<IBluetoothGattCallback>.App app = mClientMap.getById(clientIf);
mRestrictedHandles.remove(connId);
@@ -944,10 +948,19 @@ public class GattService extends ProfileService {
}
if (app != null) {
- app.callback.onClientConnectionState(status, clientIf, false, address);
+ int disconnectStatus = status;
+ if (status == 0x16 /* HCI_ERR_CONN_CAUSE_LOCAL_HOST */
+ && mAdapterService.getDatabase().getKeyMissingCount(device) > 0) {
+ // Native stack disconnects the link on detecting the bond loss. Native GATT would
+ // return HCI_ERR_CONN_CAUSE_LOCAL_HOST in such case, but the apps should see
+ // HCI_ERR_AUTH_FAILURE.
+ Log.d(TAG, "onDisconnected() - disconnected due to bond loss for device=" + device);
+ disconnectStatus = 0x05 /* HCI_ERR_AUTH_FAILURE */;
+ }
+ app.callback.onClientConnectionState(disconnectStatus, clientIf, false, address);
MetricsLogger.getInstance()
.logBluetoothEvent(
- getDevice(address),
+ device,
BluetoothStatsLog
.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__EVENT_TYPE__GATT_DISCONNECT_JAVA,
BluetoothStatsLog.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__SUCCESS,
@@ -1472,7 +1485,7 @@ public class GattService extends ProfileService {
BluetoothDevice[] bondedDevices = mAdapterService.getBondedDevices();
for (BluetoothDevice device : bondedDevices) {
if (getDeviceType(device) != AbstractionLayer.BT_DEVICE_TYPE_BREDR) {
- deviceStates.put(device, BluetoothProfile.STATE_DISCONNECTED);
+ deviceStates.put(device, STATE_DISCONNECTED);
}
}
@@ -1485,7 +1498,7 @@ public class GattService extends ProfileService {
for (String address : connectedDevices) {
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
if (device != null) {
- deviceStates.put(device, BluetoothProfile.STATE_CONNECTED);
+ deviceStates.put(device, STATE_CONNECTED);
}
}
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java
index 5c1dca5464..97bd4e9f9e 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientBinder.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientBinder.java
@@ -18,6 +18,10 @@ package com.android.bluetooth.hap;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -26,7 +30,6 @@ import android.bluetooth.BluetoothCsipSetCoordinator;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHapClient;
import android.bluetooth.BluetoothHapPresetInfo;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothHapClient;
import android.bluetooth.IBluetoothHapClientCallback;
import android.content.AttributionSource;
@@ -102,7 +105,7 @@ class HapClientBinder extends IBluetoothHapClient.Stub
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
HapClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
requireNonNull(device);
@@ -119,8 +122,8 @@ class HapClientBinder extends IBluetoothHapClient.Stub
}
requireNonNull(device);
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connectionPolicy != CONNECTION_POLICY_ALLOWED
+ && connectionPolicy != CONNECTION_POLICY_FORBIDDEN) {
throw new IllegalArgumentException(
"Invalid connectionPolicy value: " + connectionPolicy);
}
@@ -132,7 +135,7 @@ class HapClientBinder extends IBluetoothHapClient.Stub
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
HapClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
requireNonNull(device);
diff --git a/android/app/src/com/android/bluetooth/hap/HapClientService.java b/android/app/src/com/android/bluetooth/hap/HapClientService.java
index 9e9c224d52..ae8d4b6dec 100644
--- a/android/app/src/com/android/bluetooth/hap/HapClientService.java
+++ b/android/app/src/com/android/bluetooth/hap/HapClientService.java
@@ -19,8 +19,12 @@ package com.android.bluetooth.hap;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
import static java.util.Objects.requireNonNullElseGet;
@@ -225,7 +229,7 @@ public class HapClientService extends ProfileService {
if (sm == null) {
return;
}
- if (sm.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (sm.getConnectionState() != STATE_DISCONNECTED) {
Log.i(TAG, "Disconnecting device because it was unbonded.");
disconnect(device);
return;
@@ -264,7 +268,7 @@ public class HapClientService extends ProfileService {
if (!Utils.arrayContains(featureUuids, BluetoothUuid.HAS)) {
continue;
}
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
HapClientStateMachine sm = mStateMachines.get(device);
if (sm != null) {
connectionState = sm.getConnectionState();
@@ -308,7 +312,7 @@ public class HapClientService extends ProfileService {
synchronized (mStateMachines) {
HapClientStateMachine sm = mStateMachines.get(device);
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -332,9 +336,9 @@ public class HapClientService extends ProfileService {
Log.d(TAG, "Saved connectionPolicy " + device + " = " + connectionPolicy);
mDatabaseManager.setProfileConnectionPolicy(
device, BluetoothProfile.HAP_CLIENT, connectionPolicy);
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -369,8 +373,8 @@ public class HapClientService extends ProfileService {
if (bondState != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "okToConnect: return false, bondState=" + bondState);
return false;
- } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -392,7 +396,7 @@ public class HapClientService extends ProfileService {
}
// Check if the device is disconnected - if unbond, remove the state machine
- if (toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (toState == STATE_DISCONNECTED) {
int bondState = mAdapterService.getBondState(device);
if (bondState == BluetoothDevice.BOND_NONE) {
Log.d(TAG, device + " is unbond. Remove state machine");
@@ -418,7 +422,7 @@ public class HapClientService extends ProfileService {
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
return false;
}
final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device);
diff --git a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
index a57557c1b5..88f158a0ed 100644
--- a/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
+++ b/android/app/src/com/android/bluetooth/hearingaid/HearingAidService.java
@@ -18,6 +18,9 @@ package com.android.bluetooth.hearingaid;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -206,7 +209,7 @@ public class HearingAidService extends ProfileService {
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
return false;
}
final ParcelUuid[] featureUuids = mAdapterService.getRemoteUuids(device);
@@ -346,8 +349,8 @@ public class HearingAidService extends ProfileService {
return false;
}
}
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -452,9 +455,9 @@ public class HearingAidService extends ProfileService {
device, BluetoothProfile.HEARING_AID, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -529,7 +532,7 @@ public class HearingAidService extends ProfileService {
}
Log.d(TAG, "setActiveDevice: " + device);
synchronized (mStateMachines) {
- /* No action needed since this is the same device as previousely activated */
+ /* No action needed since this is the same device as previously activated */
if (device.equals(mActiveDevice)) {
Log.d(TAG, "setActiveDevice: The device is already active. Ignoring.");
return true;
@@ -989,7 +992,7 @@ public class HearingAidService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
HearingAidService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
diff --git a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
index 8e2d0bd09f..be6c114d12 100644
--- a/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
+++ b/android/app/src/com/android/bluetooth/hfp/AtPhonebook.java
@@ -64,7 +64,7 @@ public class AtPhonebook {
new String[] {Phone._ID, Phone.DISPLAY_NAME, Phone.NUMBER, Phone.TYPE};
/**
- * Android supports as many phonebook entries as the flash can hold, but BT periphals don't.
+ * Android supports as many phonebook entries as the flash can hold, but BT peripherals don't.
* Limit the number we'll report.
*/
private static final int MAX_PHONEBOOK_SIZE = 16384;
diff --git a/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java b/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java
deleted file mode 100644
index 96a573ffd2..0000000000
--- a/android/app/src/com/android/bluetooth/hfp/BluetoothHeadsetProxy.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2020 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.hfp;
-
-import static android.Manifest.permission.BLUETOOTH_CONNECT;
-import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
-import static android.Manifest.permission.MODIFY_PHONE_STATE;
-
-import android.annotation.RequiresPermission;
-import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothHeadset;
-import android.bluetooth.BluetoothProfile;
-
-import java.util.List;
-
-/**
- * A proxy class that facilitates testing of the BluetoothInCallService class.
- *
- * <p>This is necessary due to the "final" attribute of the BluetoothHeadset class. In order to test
- * the correct functioning of the BluetoothInCallService class, the final class must be put into a
- * container that can be mocked correctly.
- */
-public class BluetoothHeadsetProxy {
-
- private BluetoothHeadset mBluetoothHeadset;
-
- public BluetoothHeadsetProxy(BluetoothHeadset headset) {
- mBluetoothHeadset = headset;
- }
-
- public void closeBluetoothHeadsetProxy(BluetoothAdapter adapter) {
- adapter.closeProfileProxy(BluetoothProfile.HEADSET, mBluetoothHeadset);
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public void phoneStateChanged(
- int numActive, int numHeld, int callState, String number, int type, String name) {
- mBluetoothHeadset.phoneStateChanged(numActive, numHeld, callState, number, type, name);
- }
-
- @RequiresPermission(BLUETOOTH_CONNECT)
- public List<BluetoothDevice> getConnectedDevices() {
- return mBluetoothHeadset.getConnectedDevices();
- }
-
- @RequiresPermission(BLUETOOTH_CONNECT)
- public int getConnectionState(BluetoothDevice device) {
- return mBluetoothHeadset.getConnectionState(device);
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
- public int getAudioState(BluetoothDevice device) {
- return mBluetoothHeadset.getAudioState(device);
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
- public int connectAudio() {
- return mBluetoothHeadset.connectAudio();
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public boolean setActiveDevice(BluetoothDevice device) {
- return mBluetoothHeadset.setActiveDevice(device);
- }
-
- @RequiresPermission(BLUETOOTH_CONNECT)
- public BluetoothDevice getActiveDevice() {
- return mBluetoothHeadset.getActiveDevice();
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
- public int disconnectAudio() {
- return mBluetoothHeadset.disconnectAudio();
- }
-
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
- public boolean isInbandRingingEnabled() {
- return mBluetoothHeadset.isInbandRingingEnabled();
- }
-}
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
index 9dbcd6d4e8..fc39ba7c43 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetNativeInterface.java
@@ -500,7 +500,7 @@ public class HeadsetNativeInterface {
* values from BtHfCallState 3. number & type: valid only for incoming & waiting call
*
* @param device target device for this update
- * @param callState callstate structure
+ * @param callState callState structure
* @return True on success, False on failure
*/
@VisibleForTesting
@@ -557,8 +557,7 @@ public class HeadsetNativeInterface {
* @param device current active SCO device
* @return True on success, False on failure
*/
- @VisibleForTesting
- public boolean enableSwb(int swbCodec, boolean enable, BluetoothDevice device) {
+ boolean enableSwb(int swbCodec, boolean enable, BluetoothDevice device) {
return enableSwbNative(swbCodec, enable, getByteAddress(device));
}
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
index 4c20b42c90..84fa8239b1 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetService.java
@@ -19,6 +19,12 @@ package com.android.bluetooth.hfp;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.MODIFY_PHONE_STATE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.media.audio.Flags.deprecateStreamBtSco;
import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
@@ -120,9 +126,7 @@ public class HeadsetService extends ProfileService {
private static final String REJECT_SCO_IF_HFPC_CONNECTED_PROPERTY =
"bluetooth.hfp.reject_sco_if_hfpc_connected";
private static final ParcelUuid[] HEADSET_UUIDS = {BluetoothUuid.HSP, BluetoothUuid.HFP};
- private static final int[] CONNECTING_CONNECTED_STATES = {
- BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_CONNECTED
- };
+ private static final int[] CONNECTING_CONNECTED_STATES = {STATE_CONNECTING, STATE_CONNECTED};
private static final int DIALING_OUT_TIMEOUT_MS = 10000;
private static final int CLCC_END_MARK_INDEX = 0;
@@ -505,7 +509,7 @@ public class HeadsetService extends ProfileService {
if (stateMachine == null) {
return;
}
- if (stateMachine.getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (stateMachine.getConnectionState() != STATE_DISCONNECTED) {
return;
}
removeStateMachine(device);
@@ -590,7 +594,7 @@ public class HeadsetService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
HeadsetService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -613,7 +617,7 @@ public class HeadsetService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
HeadsetService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
@@ -765,24 +769,6 @@ public class HeadsetService extends ProfileService {
}
@Override
- public void phoneStateChanged(
- int numActive,
- int numHeld,
- int callState,
- String number,
- int type,
- String name,
- AttributionSource source) {
- HeadsetService service = getService(source);
- if (service == null) {
- return;
- }
-
- service.enforceCallingOrSelfPermission(MODIFY_PHONE_STATE, null);
- service.phoneStateChanged(numActive, numHeld, callState, number, type, name, false);
- }
-
- @Override
public boolean sendVendorSpecificResultCode(
BluetoothDevice device, String command, String arg, AttributionSource source) {
HeadsetService service = getService(source);
@@ -840,13 +826,14 @@ public class HeadsetService extends ProfileService {
return sHeadsetService;
}
- private static synchronized void setHeadsetService(HeadsetService instance) {
+ @VisibleForTesting
+ public static synchronized void setHeadsetService(HeadsetService instance) {
logD("setHeadsetService(): set to: " + instance);
sHeadsetService = instance;
}
public boolean connect(BluetoothDevice device) {
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.w(
TAG,
"connect: CONNECTION_POLICY_FORBIDDEN, device="
@@ -881,8 +868,7 @@ public class HeadsetService extends ProfileService {
mStateMachines.put(device, stateMachine);
}
int connectionState = stateMachine.getConnectionState();
- if (connectionState == BluetoothProfile.STATE_CONNECTED
- || connectionState == BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState == STATE_CONNECTED || connectionState == STATE_CONNECTING) {
Log.w(
TAG,
"connect: device "
@@ -929,8 +915,7 @@ public class HeadsetService extends ProfileService {
return false;
}
int connectionState = stateMachine.getConnectionState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
Log.w(
TAG,
"disconnect: device "
@@ -948,7 +933,7 @@ public class HeadsetService extends ProfileService {
ArrayList<BluetoothDevice> devices = new ArrayList<>();
synchronized (mStateMachines) {
for (HeadsetStateMachine stateMachine : mStateMachines.values()) {
- if (stateMachine.getConnectionState() == BluetoothProfile.STATE_CONNECTED) {
+ if (stateMachine.getConnectionState() == STATE_CONNECTED) {
devices.add(stateMachine.getDevice());
}
}
@@ -994,7 +979,7 @@ public class HeadsetService extends ProfileService {
synchronized (mStateMachines) {
final HeadsetStateMachine stateMachine = mStateMachines.get(device);
if (stateMachine == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return stateMachine.getConnectionState();
}
@@ -1028,9 +1013,9 @@ public class HeadsetService extends ProfileService {
device, BluetoothProfile.HEADSET, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -1129,8 +1114,7 @@ public class HeadsetService extends ProfileService {
return false;
}
int connectionState = stateMachine.getConnectionState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
Log.w(TAG, "startVoiceRecognition: " + device + " is not connected or connecting");
return false;
}
@@ -1203,8 +1187,7 @@ public class HeadsetService extends ProfileService {
return false;
}
int connectionState = stateMachine.getConnectionState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
Log.w(TAG, "stopVoiceRecognition: " + device + " is not connected or connecting");
return false;
}
@@ -1357,7 +1340,7 @@ public class HeadsetService extends ProfileService {
BluetoothDevice fallbackDevice = getFallbackDevice();
if (fallbackDevice != null
&& mActiveDevice != null
- && getConnectionState(mActiveDevice) != BluetoothProfile.STATE_CONNECTED) {
+ && getConnectionState(mActiveDevice) != STATE_CONNECTED) {
setActiveDevice(fallbackDevice);
return;
}
@@ -1428,7 +1411,7 @@ public class HeadsetService extends ProfileService {
Log.i(TAG, "setActiveDevice: device " + device + " is already active");
return true;
}
- if (getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) {
+ if (getConnectionState(device) != STATE_CONNECTED) {
Log.e(
TAG,
"setActiveDevice: Cannot set "
@@ -1563,7 +1546,7 @@ public class HeadsetService extends ProfileService {
Log.w(TAG, "connectAudio, rejected SCO request to " + device);
return scoConnectionAllowedState;
}
- if (stateMachine.getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
+ if (stateMachine.getConnectionState() != STATE_CONNECTED) {
Log.w(TAG, "connectAudio: profile not connected");
return BluetoothStatusCodes.ERROR_PROFILE_NOT_CONNECTED;
}
@@ -1955,8 +1938,7 @@ public class HeadsetService extends ProfileService {
}
}
- @VisibleForTesting
- void phoneStateChanged(
+ public void phoneStateChanged(
int numActive,
int numHeld,
int callState,
@@ -2053,8 +2035,7 @@ public class HeadsetService extends ProfileService {
BluetoothDevice fallbackDevice = getFallbackDevice();
if (fallbackDevice != null
- && getConnectionState(fallbackDevice)
- == BluetoothProfile.STATE_CONNECTED) {
+ && getConnectionState(fallbackDevice) == STATE_CONNECTED) {
Log.d(
TAG,
"BluetoothSinkAudioPolicy set fallbackDevice="
@@ -2094,7 +2075,7 @@ public class HeadsetService extends ProfileService {
return false;
}
int connectionState = stateMachine.getConnectionState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return false;
}
// Currently we support only "+ANDROID".
@@ -2159,13 +2140,11 @@ public class HeadsetService extends ProfileService {
@VisibleForTesting
public void onConnectionStateChangedFromStateMachine(
BluetoothDevice device, int fromState, int toState) {
- if (fromState != BluetoothProfile.STATE_CONNECTED
- && toState == BluetoothProfile.STATE_CONNECTED) {
+ if (fromState != STATE_CONNECTED && toState == STATE_CONNECTED) {
updateInbandRinging(device, true);
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HEADSET);
}
- if (fromState != BluetoothProfile.STATE_DISCONNECTED
- && toState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (fromState != STATE_DISCONNECTED && toState == STATE_DISCONNECTED) {
updateInbandRinging(device, false);
if (device.equals(mActiveDevice)) {
setActiveDevice(null);
@@ -2270,10 +2249,10 @@ public class HeadsetService extends ProfileService {
mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO);
int ashaPolicy =
mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.HEARING_AID);
- return hfpPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED
- && a2dpPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED
- && leAudioPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED
- && ashaPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ return hfpPolicy == CONNECTION_POLICY_ALLOWED
+ && a2dpPolicy != CONNECTION_POLICY_ALLOWED
+ && leAudioPolicy != CONNECTION_POLICY_ALLOWED
+ && ashaPolicy != CONNECTION_POLICY_ALLOWED;
}
private boolean shouldCallAudioBeActive() {
@@ -2503,8 +2482,8 @@ public class HeadsetService extends ProfileService {
return false;
}
}
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connection policy is not valid.
if (!isOutgoingRequest) {
A2dpService a2dpService = A2dpService.getA2dpService();
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
index 0174aeabf5..54709d09de 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetStateMachine.java
@@ -19,6 +19,10 @@ package com.android.bluetooth.hfp;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.bluetooth.BluetoothDevice.ACCESS_ALLOWED;
import static android.bluetooth.BluetoothDevice.ACCESS_REJECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.media.audio.Flags.deprecateStreamBtSco;
import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
@@ -71,7 +75,7 @@ import java.util.Scanner;
/**
* A Bluetooth Handset StateMachine (Disconnected) | ^ CONNECT | | DISCONNECTED V | (Connecting)
* (Disconnecting) | ^ CONNECTED | | DISCONNECT V | (Connected) | ^ CONNECT_AUDIO | |
- * AUDIO_DISCONNECTED V | (AudioConnecting) (AudioDiconnecting) | ^ AUDIO_CONNECTED | |
+ * AUDIO_DISCONNECTED V | (AudioConnecting) (AudioDisconnecting) | ^ AUDIO_CONNECTED | |
* DISCONNECT_AUDIO V | (AudioOn)
*/
class HeadsetStateMachine extends StateMachine {
@@ -545,7 +549,7 @@ class HeadsetStateMachine extends StateMachine {
class Disconnected extends HeadsetStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
@Override
@@ -604,16 +608,13 @@ class HeadsetStateMachine extends StateMachine {
device,
BluetoothStatsLog
.BLUETOOTH_CROSS_LAYER_EVENT_REPORTED__STATE__HFP_CONNECT_FAIL);
- broadcastConnectionState(
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ 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;
@@ -684,16 +685,13 @@ 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(
@@ -725,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));
}
@@ -735,11 +733,11 @@ class HeadsetStateMachine extends StateMachine {
// Per HFP 1.7.1 spec page 23/144, Pending state needs to handle
// AT+BRSF, AT+CIND, AT+CMER, AT+BIND, AT+CHLD
// commands during SLC establishment
- // AT+CHLD=? will be handled by statck directly
+ // AT+CHLD=? will be handled by stack directly
class Connecting extends HeadsetStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
}
@Override
@@ -925,7 +923,7 @@ class HeadsetStateMachine extends StateMachine {
class Disconnecting extends HeadsetStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_DISCONNECTING;
+ return STATE_DISCONNECTING;
}
@Override
@@ -1016,7 +1014,7 @@ class HeadsetStateMachine extends StateMachine {
private abstract class ConnectedBase extends HeadsetStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
}
/**
@@ -1299,7 +1297,7 @@ class HeadsetStateMachine extends StateMachine {
// Reset NREC on connect event. Headset will override later
processNoiseReductionEvent(true);
// Query phone state for initial setup
- mSystemInterface.queryPhoneState();
+ mSystemInterface.queryPhoneState(mHeadsetService);
// Remove pending connection attempts that were deferred during the pending
// state. This is to prevent auto connect attempts from disconnecting
// devices that previously successfully connected.
@@ -1338,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);
@@ -1451,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));
}
@@ -1789,8 +1784,7 @@ class HeadsetStateMachine extends StateMachine {
*
* @return device in focus
*/
- @VisibleForTesting
- public BluetoothDevice getDevice() {
+ BluetoothDevice getDevice() {
return mDevice;
}
@@ -2108,7 +2102,7 @@ class HeadsetStateMachine extends StateMachine {
@VisibleForTesting
void processAtChld(int chld, BluetoothDevice device) {
- if (mSystemInterface.processChld(chld)) {
+ if (mSystemInterface.processChld(mHeadsetService, chld)) {
mNativeInterface.atResponseCode(device, HeadsetHalConstants.AT_RESPONSE_OK, 0);
} else {
mNativeInterface.atResponseCode(device, HeadsetHalConstants.AT_RESPONSE_ERROR, 0);
diff --git a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java
index 78e350fc37..4a82d74f83 100644
--- a/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java
+++ b/android/app/src/com/android/bluetooth/hfp/HeadsetSystemInterface.java
@@ -16,10 +16,7 @@
package com.android.bluetooth.hfp;
-import static android.Manifest.permission.BLUETOOTH_CONNECT;
-import static android.Manifest.permission.MODIFY_PHONE_STATE;
-import android.annotation.RequiresPermission;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothSinkAudioPolicy;
@@ -184,10 +181,10 @@ class HeadsetSystemInterface {
* @param chld index of the call to hold
*/
@VisibleForTesting
- public boolean processChld(int chld) {
+ public boolean processChld(HeadsetService headsetService, int chld) {
BluetoothInCallService bluetoothInCallService = getBluetoothInCallServiceInstance();
if (bluetoothInCallService != null) {
- return bluetoothInCallService.processChld(chld);
+ return bluetoothInCallService.processChld(headsetService, chld);
} else {
Log.e(TAG, "Handsfree phone proxy null for sending DTMF");
}
@@ -292,11 +289,10 @@ class HeadsetSystemInterface {
* through {@link BluetoothHeadset#phoneStateChanged(int, int, int, String, int)}
*/
@VisibleForTesting
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public void queryPhoneState() {
+ public void queryPhoneState(HeadsetService headsetService) {
BluetoothInCallService bluetoothInCallService = getBluetoothInCallServiceInstance();
if (bluetoothInCallService != null) {
- bluetoothInCallService.queryPhoneState();
+ bluetoothInCallService.queryPhoneState(headsetService);
} else {
Log.e(TAG, "Handsfree phone proxy null for query phone state");
}
@@ -307,8 +303,7 @@ class HeadsetSystemInterface {
*
* @return True iff we are in a phone call
*/
- @VisibleForTesting
- public boolean isInCall() {
+ boolean isInCall() {
return ((mHeadsetPhoneState.getNumActiveCall() > 0)
|| (mHeadsetPhoneState.getNumHeldCall() > 0)
|| ((mHeadsetPhoneState.getCallState() != HeadsetHalConstants.CALL_STATE_IDLE)
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
index 4e0dae8c13..9c0e416168 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientService.java
@@ -18,6 +18,12 @@ package com.android.bluetooth.hfpclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.content.pm.PackageManager.FEATURE_WATCH;
import static java.util.Objects.requireNonNull;
@@ -366,7 +372,7 @@ public class HeadsetClientService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
HeadsetClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
service.enforceCallingPermission(BLUETOOTH_PRIVILEGED, null);
@@ -391,7 +397,7 @@ public class HeadsetClientService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
HeadsetClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingPermission(BLUETOOTH_PRIVILEGED, null);
@@ -640,7 +646,7 @@ public class HeadsetClientService extends ProfileService {
public boolean connect(BluetoothDevice device) {
Log.d(TAG, "connect " + device);
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.w(
TAG,
"Connection not allowed: <"
@@ -672,8 +678,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
@@ -689,7 +694,7 @@ public class HeadsetClientService extends ProfileService {
synchronized (mStateMachineMap) {
for (BluetoothDevice bd : mStateMachineMap.keySet()) {
HeadsetClientStateMachine sm = mStateMachineMap.get(bd);
- if (sm != null && sm.getConnectionState(bd) == BluetoothProfile.STATE_CONNECTED) {
+ if (sm != null && sm.getConnectionState(bd) == STATE_CONNECTED) {
connectedDevices.add(bd);
}
}
@@ -727,7 +732,7 @@ public class HeadsetClientService extends ProfileService {
return sm.getConnectionState(device);
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -751,9 +756,9 @@ public class HeadsetClientService extends ProfileService {
device, BluetoothProfile.HEADSET_CLIENT, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -780,7 +785,7 @@ public class HeadsetClientService extends ProfileService {
return false;
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return false;
}
sm.sendMessage(HeadsetClientStateMachine.VOICE_RECOGNITION_START);
@@ -794,7 +799,7 @@ public class HeadsetClientService extends ProfileService {
return false;
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return false;
}
sm.sendMessage(HeadsetClientStateMachine.VOICE_RECOGNITION_STOP);
@@ -934,8 +939,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
Message msg = sm.obtainMessage(HeadsetClientStateMachine.HOLD_CALL);
@@ -944,7 +948,7 @@ public class HeadsetClientService extends ProfileService {
}
public boolean acceptCall(BluetoothDevice device, int flag) {
- /* Phonecalls from a single device are supported, hang up any calls on the other phone */
+ /* Phone calls from a single device are supported, hang up any calls on the other phone */
synchronized (mStateMachineMap) {
for (Map.Entry<BluetoothDevice, HeadsetClientStateMachine> entry :
mStateMachineMap.entrySet()) {
@@ -958,7 +962,7 @@ public class HeadsetClientService extends ProfileService {
+ device
+ ". Possibly disconnecting on "
+ entry.getValue());
- if (connectionState == BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState == STATE_CONNECTED) {
entry.getValue()
.obtainMessage(HeadsetClientStateMachine.TERMINATE_CALL)
.sendToTarget();
@@ -972,7 +976,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return false;
}
Message msg = sm.obtainMessage(HeadsetClientStateMachine.ACCEPT_CALL);
@@ -989,8 +993,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
@@ -1007,8 +1010,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
@@ -1026,8 +1028,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
@@ -1045,8 +1046,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return null;
}
@@ -1082,8 +1082,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
Message msg = sm.obtainMessage(HeadsetClientStateMachine.SEND_DTMF);
@@ -1104,7 +1103,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return null;
}
return sm.getCurrentCalls();
@@ -1118,8 +1117,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
Message msg = sm.obtainMessage(HeadsetClientStateMachine.EXPLICIT_CALL_TRANSFER);
@@ -1136,7 +1134,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return false;
}
@@ -1155,7 +1153,7 @@ public class HeadsetClientService extends ProfileService {
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return null;
}
return sm.getCurrentAgEvents();
@@ -1168,7 +1166,7 @@ public class HeadsetClientService extends ProfileService {
return null;
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return null;
}
return sm.getCurrentAgFeaturesBundle();
@@ -1181,7 +1179,7 @@ public class HeadsetClientService extends ProfileService {
return null;
}
int connectionState = sm.getConnectionState(device);
- if (connectionState != BluetoothProfile.STATE_CONNECTED) {
+ if (connectionState != STATE_CONNECTED) {
return null;
}
return sm.getCurrentAgFeatures();
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
index 8bb8a4700b..49153659fc 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachine.java
@@ -33,6 +33,12 @@ package com.android.bluetooth.hfpclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.content.pm.PackageManager.FEATURE_WATCH;
import static java.util.Objects.requireNonNull;
@@ -1053,21 +1059,13 @@ public class HeadsetClientStateMachine extends StateMachine {
removeMessages(QUERY_CURRENT_CALLS);
if (mPrevState == mConnecting) {
- broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
} else if (mPrevState == mConnected || mPrevState == mAudioOn) {
- broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED);
} else if (Flags.hfpClientDisconnectingState()) {
if (mPrevState == mDisconnecting) {
broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_DISCONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_DISCONNECTING);
}
} else if (mPrevState != null) {
// null is the default state before Disconnected
@@ -1097,10 +1095,7 @@ public class HeadsetClientStateMachine extends StateMachine {
BluetoothDevice device = (BluetoothDevice) message.obj;
if (!mNativeInterface.connect(device)) {
// No state transition is involved, fire broadcast immediately
- broadcastConnectionState(
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ broadcastConnectionState(device, STATE_DISCONNECTED, STATE_DISCONNECTED);
break;
}
mCurrentDevice = device;
@@ -1152,10 +1147,7 @@ public class HeadsetClientStateMachine extends StateMachine {
mNativeInterface.disconnect(device);
// the other profile connection should be initiated
// No state transition is involved, fire broadcast immediately
- broadcastConnectionState(
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ broadcastConnectionState(device, STATE_DISCONNECTED, STATE_DISCONNECTED);
}
break;
case HeadsetClientHalConstants.CONNECTION_STATE_CONNECTING:
@@ -1183,10 +1175,7 @@ public class HeadsetClientStateMachine extends StateMachine {
// the only transition is when connection attempt is initiated.
sendMessageDelayed(CONNECTING_TIMEOUT, CONNECTING_TIMEOUT_MS);
if (mPrevState == mDisconnected) {
- broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_DISCONNECTED);
+ broadcastConnectionState(mCurrentDevice, STATE_CONNECTING, STATE_DISCONNECTED);
} else {
String prevStateName = mPrevState == null ? "null" : mPrevState.getName();
error(
@@ -1357,13 +1346,8 @@ public class HeadsetClientStateMachine extends StateMachine {
warn("incoming connection event, device: " + device);
// No state transition is involved, fire broadcast immediately
broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
- broadcastConnectionState(
- device,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
+ broadcastConnectionState(device, STATE_CONNECTING, STATE_DISCONNECTED);
mCurrentDevice = device;
}
@@ -1398,10 +1382,7 @@ public class HeadsetClientStateMachine extends StateMachine {
mCommandedSpeakerVolume = -1;
if (mPrevState == mConnecting) {
- broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ broadcastConnectionState(mCurrentDevice, STATE_CONNECTED, STATE_CONNECTING);
if (mHeadsetService != null) {
mHeadsetService.updateInbandRinging(mCurrentDevice, true);
}
@@ -1970,10 +1951,7 @@ public class HeadsetClientStateMachine extends StateMachine {
+ ", message="
+ getMessageName(getCurrentMessage().what));
if (mPrevState == mConnected || mPrevState == mAudioOn) {
- broadcastConnectionState(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ broadcastConnectionState(mCurrentDevice, STATE_DISCONNECTING, STATE_CONNECTED);
} else {
String prevStateName = mPrevState == null ? "null" : mPrevState.getName();
error(
@@ -1989,7 +1967,7 @@ public class HeadsetClientStateMachine extends StateMachine {
debug("Disconnecting: Process message: " + message.what);
switch (message.what) {
- // Defering messages as state machine objects are meant to be reused and after
+ // Deferring messages as state machine objects are meant to be reused and after
// disconnect is complete we want honor other message requests
case CONNECT:
case CONNECT_AUDIO:
@@ -2194,24 +2172,24 @@ public class HeadsetClientStateMachine extends StateMachine {
public synchronized int getConnectionState(BluetoothDevice device) {
if (device == null || !device.equals(mCurrentDevice)) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
IState currentState = getCurrentState();
if (currentState == mConnecting) {
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
}
if (currentState == mConnected || currentState == mAudioOn) {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
}
if (Flags.hfpClientDisconnectingState()) {
if (currentState == mDisconnecting) {
- return BluetoothProfile.STATE_DISCONNECTING;
+ return STATE_DISCONNECTING;
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
@VisibleForTesting
@@ -2308,7 +2286,7 @@ public class HeadsetClientStateMachine extends StateMachine {
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
// add feature extras when connected
- if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (newState == STATE_CONNECTED) {
if ((mPeerFeatures & HeadsetClientHalConstants.PEER_FEAT_3WAY)
== HeadsetClientHalConstants.PEER_FEAT_3WAY) {
intent.putExtra(BluetoothHeadsetClient.EXTRA_AG_FEATURE_3WAY_CALLING, true);
@@ -2396,8 +2374,8 @@ public class HeadsetClientStateMachine extends StateMachine {
// it is likely that our SDP has not completed and peer is initiating
// the
// connection. Allow this connection, provided the device is bonded
- if ((BluetoothProfile.CONNECTION_POLICY_FORBIDDEN < connectionPolicy)
- || ((BluetoothProfile.CONNECTION_POLICY_UNKNOWN == connectionPolicy)
+ if ((CONNECTION_POLICY_FORBIDDEN < connectionPolicy)
+ || ((CONNECTION_POLICY_UNKNOWN == connectionPolicy)
&& (mAdapterService.getBondState(device) != BluetoothDevice.BOND_NONE))) {
ret = true;
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
index e18ef9f9b9..1c2deb857d 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnection.java
@@ -63,7 +63,7 @@ public class HfpClientConnection extends Connection {
finishInitializing();
}
- // Constructor to be used when a call is intiated on the HF. The call handle is obtained by
+ // Constructor to be used when a call is initiated on the HF. The call handle is obtained by
// using the dial() command.
public HfpClientConnection(
BluetoothDevice device,
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
index 2dc7bbaa6b..a697e8e4a2 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientConnectionService.java
@@ -15,6 +15,9 @@
*/
package com.android.bluetooth.hfpclient;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
@@ -120,14 +123,14 @@ public class HfpClientConnectionService extends ConnectionService {
private void onConnectionStateChangedInternal(
BluetoothDevice device, int newState, int oldState) {
- if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (newState == STATE_CONNECTED) {
Log.d(TAG, "Established connection with " + device);
HfpClientDeviceBlock block = createBlockForDevice(device);
if (block == null) {
Log.w(TAG, "Block already exists for device= " + device + ", ignoring.");
}
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ } else if (newState == STATE_DISCONNECTED) {
Log.d(TAG, "Disconnecting from " + device);
// Disconnect any inflight calls from the connection service.
@@ -382,7 +385,7 @@ public class HfpClientConnectionService extends ConnectionService {
.setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_TEL))
.setCapabilities(capabilities)
.build();
- Log.d(TAG, "phoneaccount: " + account);
+ Log.d(TAG, "PhoneAccount: " + account);
return account;
}
diff --git a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
index f33acb586d..d69cdb7d82 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/HfpClientDeviceBlock.java
@@ -197,7 +197,7 @@ public class HfpClientDeviceBlock {
|| call.getState() == HfpClientCall.CALL_STATE_ACTIVE
|| call.getState() == HfpClientCall.CALL_STATE_HELD) {
// This is an outgoing call. Even if it is an active call we do not have a way of
- // putting that parcelable in a seaprate field.
+ // putting that parcelable in a separate field.
b.putParcelable(
TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, new ParcelUuid(call.getUUID()));
mTelecomManager.addNewUnknownCall(mPhoneAccount.getAccountHandle(), b);
@@ -270,7 +270,7 @@ public class HfpClientDeviceBlock {
return connection;
}
- // Updates any conferencable connections.
+ // Updates any conferenceable connections.
private void updateConferenceableConnections() {
boolean addConf = false;
debug("Existing connections: " + mConnections + " existing conference " + mConference);
diff --git a/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java b/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
index a4ce2551f4..fbb68747fe 100644
--- a/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hfpclient/NativeInterface.java
@@ -262,9 +262,9 @@ public class NativeInterface {
*
* @param device target device
* @param atCmd command code
- * @param val1 command specific argurment1
- * @param val2 command specific argurment2
- * @param arg other command specific argurments
+ * @param val1 command specific argument1
+ * @param val2 command specific argument2
+ * @param arg other command specific arguments
* @return True on success, False on failure
*/
@VisibleForTesting
@@ -512,7 +512,7 @@ public class NativeInterface {
/**
* CIEV (Call indicators) notifying call held states.
*
- * <p>Values include: 0 - No calls held 1 - Call is placed on hold or active/held calls wapped
+ * <p>Values include: 0 - No calls held 1 - Call is placed on hold or active/held calls swapped
* (The AG has both an ACTIVE and HELD call) 2 - Call on hold, no active call
*/
@VisibleForTesting
@@ -680,7 +680,7 @@ public class NativeInterface {
if (service != null) {
service.messageFromNative(event);
} else {
- Log.w(TAG, "onUnknowEvent: Ignoring message because service not available: " + event);
+ Log.w(TAG, "onUnknownEvent: Ignoring message because service not available: " + event);
}
}
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
index 9068d666a8..67e9349a28 100644
--- a/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidDeviceService.java
@@ -18,6 +18,11 @@ package com.android.bluetooth.hid;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
import static java.util.Objects.requireNonNullElseGet;
@@ -493,8 +498,7 @@ public class HidDeviceService extends ProfileService {
public List<BluetoothDevice> getConnectedDevices(AttributionSource source) {
Log.d(TAG, "getConnectedDevices()");
- return getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}, source);
+ return getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}, source);
}
@Override
@@ -683,7 +687,7 @@ public class HidDeviceService extends ProfileService {
device, BluetoothProfile.HID_DEVICE, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -884,7 +888,7 @@ public class HidDeviceService extends ProfileService {
mAdapterService.updateProfileConnectionAdapterProperties(
device, BluetoothProfile.HID_DEVICE, newState, prevState);
- if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (newState == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HID_DEVICE);
}
@@ -899,15 +903,15 @@ public class HidDeviceService extends ProfileService {
private static int convertHalState(int halState) {
switch (halState) {
case HAL_CONN_STATE_CONNECTED:
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
case HAL_CONN_STATE_CONNECTING:
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
case HAL_CONN_STATE_DISCONNECTED:
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
case HAL_CONN_STATE_DISCONNECTING:
- return BluetoothProfile.STATE_DISCONNECTING;
+ return STATE_DISCONNECTING;
default:
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
index 39a2d398ee..1d0294cd52 100644
--- a/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
+++ b/android/app/src/com/android/bluetooth/hid/HidHostNativeInterface.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.hid;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
@@ -109,18 +114,18 @@ public class HidHostNativeInterface {
private static int convertHalState(int halState) {
switch (halState) {
case CONN_STATE_CONNECTED:
- return HidHostService.STATE_CONNECTED;
+ return STATE_CONNECTED;
case CONN_STATE_CONNECTING:
- return HidHostService.STATE_CONNECTING;
+ return STATE_CONNECTING;
case CONN_STATE_DISCONNECTED:
- return HidHostService.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
case CONN_STATE_DISCONNECTING:
- return HidHostService.STATE_DISCONNECTING;
+ return STATE_DISCONNECTING;
case CONN_STATE_ACCEPTING:
return HidHostService.STATE_ACCEPTING;
default:
Log.e(TAG, "bad hid connection state: " + halState);
- return HidHostService.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
diff --git a/android/app/src/com/android/bluetooth/hid/HidHostService.java b/android/app/src/com/android/bluetooth/hid/HidHostService.java
index a1eb100dd7..2712db71ad 100644
--- a/android/app/src/com/android/bluetooth/hid/HidHostService.java
+++ b/android/app/src/com/android/bluetooth/hid/HidHostService.java
@@ -18,6 +18,12 @@ package com.android.bluetooth.hid;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
@@ -68,8 +74,8 @@ public class HidHostService extends ProfileService {
private static class InputDevice {
int mSelectedTransport = BluetoothDevice.TRANSPORT_AUTO;
- private int mHidState = BluetoothProfile.STATE_DISCONNECTED;
- private int mHogpState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mHidState = STATE_DISCONNECTED;
+ private int mHogpState = STATE_DISCONNECTED;
int getState(int transport) {
return (transport == BluetoothDevice.TRANSPORT_LE) ? mHogpState : mHidState;
@@ -122,11 +128,7 @@ public class HidHostService extends ProfileService {
private static final int MESSAGE_SET_PREFERRED_TRANSPORT = 17;
private static final int MESSAGE_SEND_DATA = 18;
- public static final int STATE_DISCONNECTED = BluetoothProfile.STATE_DISCONNECTED;
- public static final int STATE_CONNECTING = BluetoothProfile.STATE_CONNECTING;
- public static final int STATE_CONNECTED = BluetoothProfile.STATE_CONNECTED;
- public static final int STATE_DISCONNECTING = BluetoothProfile.STATE_DISCONNECTING;
- public static final int STATE_ACCEPTING = BluetoothProfile.STATE_DISCONNECTING + 1;
+ public static final int STATE_ACCEPTING = STATE_DISCONNECTING + 1;
public HidHostService(AdapterService adapterService) {
super(adapterService);
@@ -157,12 +159,8 @@ public class HidHostService extends ProfileService {
if (mInputDevices != null) {
for (BluetoothDevice device : mInputDevices.keySet()) {
// Set both HID and HOGP connection states to disconnected
- updateConnectionState(
- device, BluetoothDevice.TRANSPORT_LE, BluetoothProfile.STATE_DISCONNECTED);
- updateConnectionState(
- device,
- BluetoothDevice.TRANSPORT_BREDR,
- BluetoothProfile.STATE_DISCONNECTED);
+ updateConnectionState(device, BluetoothDevice.TRANSPORT_LE, STATE_DISCONNECTED);
+ updateConnectionState(device, BluetoothDevice.TRANSPORT_BREDR, STATE_DISCONNECTED);
}
mInputDevices.clear();
}
@@ -265,7 +263,7 @@ public class HidHostService extends ProfileService {
return inputDevice.getState(transport);
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
public static synchronized HidHostService getHidHostService() {
@@ -423,7 +421,7 @@ public class HidHostService extends ProfileService {
/* If connections are allowed, ensure that the previous transport is disconnected and the
new transport is connected */
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_ALLOWED) {
if (prevTransport != transport) {
Log.i(
TAG,
@@ -435,8 +433,7 @@ public class HidHostService extends ProfileService {
if (Flags.ignoreUnselectedHidTransportStates()) {
// Immediately update the connection state to disconnected. From now on,
// the connection state will be updated only for the selected transport.
- updateConnectionState(
- device, prevTransport, BluetoothProfile.STATE_DISCONNECTED);
+ updateConnectionState(device, prevTransport, STATE_DISCONNECTED);
}
// Request to connect the preferred transport
nativeConnect(device, transport);
@@ -482,7 +479,7 @@ public class HidHostService extends ProfileService {
private void handleMessageOnVirtualUnplug(Message msg) {
BluetoothDevice device = mAdapterService.getDeviceFromByte((byte[]) msg.obj);
- updateConnectionState(device, getTransport(device), BluetoothProfile.STATE_DISCONNECTED);
+ updateConnectionState(device, getTransport(device), STATE_DISCONNECTED);
mInputDevices.remove(device);
int status = msg.arg2;
@@ -637,15 +634,14 @@ public class HidHostService extends ProfileService {
+ (" prevState=" + prevState));
// Process connection
- if (prevState == BluetoothProfile.STATE_DISCONNECTED
- && state == BluetoothProfile.STATE_CONNECTED) {
+ if (prevState == STATE_DISCONNECTED && state == STATE_CONNECTED) {
processConnection(device, transport);
}
// ACCEPTING state has to be treated as DISCONNECTED state
int reportedState = state;
if (state == STATE_ACCEPTING) {
- reportedState = BluetoothProfile.STATE_DISCONNECTED;
+ reportedState = STATE_DISCONNECTED;
}
updateConnectionState(device, transport, reportedState);
}
@@ -655,7 +651,7 @@ public class HidHostService extends ProfileService {
int connectionPolicy = msg.arg1;
boolean reconnectAllowed = true;
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_ALLOWED) {
reconnectAllowed = false;
}
nativeDisconnect(device, getTransport(device), reconnectAllowed);
@@ -666,7 +662,7 @@ public class HidHostService extends ProfileService {
InputDevice inputDevice = getOrCreateInputDevice(device);
int connectionPolicy = getConnectionPolicy(device);
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_ALLOWED) {
Log.e(
TAG,
"handleMessageConnect: Connection not allowed."
@@ -775,15 +771,14 @@ public class HidHostService extends ProfileService {
public int getConnectionState(BluetoothDevice device, AttributionSource source) {
HidHostService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
}
@Override
public List<BluetoothDevice> getConnectedDevices(AttributionSource source) {
- return getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}, source);
+ return getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}, source);
}
@Override
@@ -811,7 +806,7 @@ public class HidHostService extends ProfileService {
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
HidHostService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
return service.getConnectionPolicy(device);
@@ -932,11 +927,11 @@ public class HidHostService extends ProfileService {
public boolean connect(BluetoothDevice device) {
Log.d(TAG, "connect: device=" + device);
int state = getConnectionState(device);
- if (state != BluetoothProfile.STATE_DISCONNECTED) {
+ if (state != STATE_DISCONNECTED) {
Log.e(TAG, "Device " + device + " not disconnected. state=" + state);
return false;
}
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "Device " + device + " CONNECTION_POLICY_FORBIDDEN");
return false;
}
@@ -986,7 +981,7 @@ public class HidHostService extends ProfileService {
if (inputDevice != null) {
return inputDevice.getState();
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
@VisibleForTesting
@@ -1020,10 +1015,10 @@ public class HidHostService extends ProfileService {
return false;
}
Log.d(TAG, "Saved connectionPolicy=" + connectionPolicy + " for device=" + device);
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
- disconnect(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
+ disconnect(device, CONNECTION_POLICY_FORBIDDEN);
MetricsLogger.getInstance()
.count(BluetoothProtoEnums.HIDH_COUNT_CONNECTION_POLICY_DISABLED, 1);
}
@@ -1093,7 +1088,7 @@ public class HidHostService extends ProfileService {
boolean getProtocolMode(BluetoothDevice device) {
Log.d(TAG, "getProtocolMode: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_PROTOCOL_MODE, device);
@@ -1105,7 +1100,7 @@ public class HidHostService extends ProfileService {
boolean virtualUnplug(BluetoothDevice device) {
Log.d(TAG, "virtualUnplug: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_VIRTUAL_UNPLUG, device);
@@ -1117,7 +1112,7 @@ public class HidHostService extends ProfileService {
boolean setProtocolMode(BluetoothDevice device, int protocolMode) {
Log.d(TAG, "setProtocolMode: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_SET_PROTOCOL_MODE);
@@ -1131,7 +1126,7 @@ public class HidHostService extends ProfileService {
boolean getReport(BluetoothDevice device, byte reportType, byte reportId, int bufferSize) {
Log.d(TAG, "getReport: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_REPORT);
@@ -1149,7 +1144,7 @@ public class HidHostService extends ProfileService {
boolean setReport(BluetoothDevice device, byte reportType, String report) {
Log.d(TAG, "setReport: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_SET_REPORT);
@@ -1166,7 +1161,7 @@ public class HidHostService extends ProfileService {
boolean sendData(BluetoothDevice device, String report) {
Log.d(TAG, "sendData: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
@@ -1181,7 +1176,7 @@ public class HidHostService extends ProfileService {
boolean getIdleTime(BluetoothDevice device) {
Log.d(TAG, "getIdleTime: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_GET_IDLE_TIME, device);
@@ -1192,7 +1187,7 @@ public class HidHostService extends ProfileService {
boolean setIdleTime(BluetoothDevice device, byte idleTime) {
Log.d(TAG, "setIdleTime: device=" + device);
int state = this.getConnectionState(device);
- if (state != BluetoothProfile.STATE_CONNECTED) {
+ if (state != STATE_CONNECTED) {
return false;
}
Message msg = mHandler.obtainMessage(MESSAGE_SET_IDLE_TIME);
@@ -1302,7 +1297,7 @@ public class HidHostService extends ProfileService {
return;
}
- if (newState == BluetoothProfile.STATE_CONNECTED) {
+ if (newState == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.HID_HOST);
}
@@ -1409,8 +1404,8 @@ public class HidHostService extends ProfileService {
return false;
}
}
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(
TAG,
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
index ca63422a93..463f55383f 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioService.java
@@ -19,6 +19,11 @@ package com.android.bluetooth.le_audio;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID;
import static com.android.bluetooth.bass_client.BassConstants.INVALID_BROADCAST_ID;
@@ -298,7 +303,7 @@ public class LeAudioService extends ProfileService {
}
private class LeAudioGroupDescriptor {
- LeAudioGroupDescriptor(int groupId, boolean isInbandRingtonEnabled) {
+ LeAudioGroupDescriptor(int groupId, boolean isInbandRingtoneEnabled) {
mGroupId = groupId;
mIsConnected = false;
mActiveState = ACTIVE_STATE_INACTIVE;
@@ -309,7 +314,7 @@ public class LeAudioService extends ProfileService {
mCodecStatus = null;
mLostLeadDeviceWhileStreaming = null;
mCurrentLeadDevice = null;
- mInbandRingtoneEnabled = isInbandRingtonEnabled;
+ mInbandRingtoneEnabled = isInbandRingtoneEnabled;
mAvailableContexts = Flags.leaudioUnicastNoAvailableContexts() ? null : 0;
mInputSelectableConfig = new ArrayList<>();
mOutputSelectableConfig = new ArrayList<>();
@@ -421,13 +426,13 @@ public class LeAudioService extends ProfileService {
}
private static class LeAudioDeviceDescriptor {
- LeAudioDeviceDescriptor(boolean isInbandRingtonEnabled) {
+ LeAudioDeviceDescriptor(boolean isInbandRingtoneEnabled) {
mAclConnected = false;
mStateMachine = null;
mGroupId = LE_AUDIO_GROUP_ID_INVALID;
mSinkAudioLocation = BluetoothLeAudio.AUDIO_LOCATION_INVALID;
mDirection = AUDIO_DIRECTION_NONE;
- mDevInbandRingtoneEnabled = isInbandRingtonEnabled;
+ mDevInbandRingtoneEnabled = isInbandRingtoneEnabled;
}
public boolean mAclConnected;
@@ -883,7 +888,7 @@ public class LeAudioService extends ProfileService {
public boolean connect(BluetoothDevice device) {
Log.d(TAG, "connect(): " + device);
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.e(TAG, "Cannot connect to " + device + " : CONNECTION_POLICY_FORBIDDEN");
return false;
}
@@ -994,7 +999,7 @@ public class LeAudioService extends ProfileService {
if (!Utils.arrayContains(featureUuids, BluetoothUuid.LE_AUDIO)) {
continue;
}
- int connectionState = BluetoothProfile.STATE_DISCONNECTED;
+ int connectionState = STATE_DISCONNECTED;
LeAudioDeviceDescriptor descriptor = getDeviceDescriptor(device);
if (descriptor == null) {
Log.e(
@@ -1056,12 +1061,12 @@ public class LeAudioService extends ProfileService {
try {
LeAudioDeviceDescriptor descriptor = getDeviceDescriptor(device);
if (descriptor == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
LeAudioStateMachine sm = descriptor.mStateMachine;
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
} finally {
@@ -1271,7 +1276,7 @@ public class LeAudioService extends ProfileService {
}
if (leaudioBigDependsOnAudioState()) {
- /* Start timeout to recover from stucked/error create Broadcast operation */
+ /* Start timeout to recover from stuck/error create Broadcast operation */
if (mCreateBroadcastTimeoutEvent != null) {
Log.w(TAG, "CreateBroadcastTimeoutEvent already scheduled");
} else {
@@ -1346,7 +1351,7 @@ public class LeAudioService extends ProfileService {
* LeAudioService#createBroadcast
*/
if (!leaudioBigDependsOnAudioState()) {
- /* Start timeout to recover from stucked/error start Broadcast operation */
+ /* Start timeout to recover from stuck/error start Broadcast operation */
mCreateBroadcastTimeoutEvent = new CreateBroadcastTimeoutEvent(broadcastId);
mHandler.postDelayed(mCreateBroadcastTimeoutEvent, CREATE_BROADCAST_TIMEOUT_MS);
}
@@ -1560,6 +1565,15 @@ public class LeAudioService extends ProfileService {
}
/**
+ * Check if broadcast is active or ready to be re-activated
+ *
+ * @return true if there is active broadcast or ready to be re-activated, false otherwise
+ */
+ public boolean isBroadcastStarted() {
+ return isBroadcastActive() || isBroadcastReadyToBeReActivated();
+ }
+
+ /**
* Get the maximum number of supported simultaneous broadcasts.
*
* @return number of supported simultaneous broadcasts
@@ -1742,8 +1756,7 @@ public class LeAudioService extends ProfileService {
}
if (groupDescriptor.mCurrentLeadDevice != null
- && getConnectionState(groupDescriptor.mCurrentLeadDevice)
- == BluetoothProfile.STATE_CONNECTED) {
+ && getConnectionState(groupDescriptor.mCurrentLeadDevice) == STATE_CONNECTED) {
return groupDescriptor.mCurrentLeadDevice;
}
@@ -1753,7 +1766,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();
@@ -2212,10 +2225,10 @@ public class LeAudioService extends ProfileService {
if (device.equals(mActiveAudioInDevice) || device.equals(mActiveAudioOutDevice)) {
mEventLogger.loge(
TAG,
- "[From AudioManager]: Audio manager autonomusly disactivated LeAudio device "
+ "[From AudioManager]: Audio manager autonomously deactivated LeAudio device."
+ + " Probably restarting and device shall be re-added "
+ mExposedActiveDevice);
- mExposedActiveDevice = null;
- setActiveDevice(null);
+
return;
}
@@ -2229,7 +2242,7 @@ public class LeAudioService extends ProfileService {
: mActiveAudioOutDevice)));
}
- /* Notifications of audio device connection/disconn events. */
+ /* Notifications of audio device connection/disconnection events. */
private class AudioManagerAudioDeviceCallback extends AudioDeviceCallback {
@Override
public void onAudioDevicesAdded(AudioDeviceInfo[] addedDevices) {
@@ -2637,7 +2650,7 @@ public class LeAudioService extends ProfileService {
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("
@@ -2825,25 +2838,22 @@ public class LeAudioService extends ProfileService {
Log.d(TAG, "Disable LE_AUDIO for the device: " + activeGroupDevice);
final ParcelUuid[] uuids = mAdapterService.getRemoteUuids(activeGroupDevice);
- setConnectionPolicy(activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_FORBIDDEN);
if (hsService != null && !isDualMode && Utils.arrayContains(uuids, BluetoothUuid.HFP)) {
Log.d(TAG, "Enable HFP for the device: " + activeGroupDevice);
- hsService.setConnectionPolicy(
- activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ hsService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED);
}
if (a2dpService != null
&& !isDualMode
&& (Utils.arrayContains(uuids, BluetoothUuid.A2DP_SINK)
|| Utils.arrayContains(uuids, BluetoothUuid.ADV_AUDIO_DIST))) {
Log.d(TAG, "Enable A2DP for the device: " + activeGroupDevice);
- a2dpService.setConnectionPolicy(
- activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ a2dpService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED);
}
if (hearingAidService != null
&& Utils.arrayContains(uuids, BluetoothUuid.HEARING_AID)) {
Log.d(TAG, "Enable ASHA for the device: " + activeGroupDevice);
- hearingAidService.setConnectionPolicy(
- activeGroupDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ hearingAidService.setConnectionPolicy(activeGroupDevice, CONNECTION_POLICY_ALLOWED);
}
}
}
@@ -2979,6 +2989,11 @@ public class LeAudioService extends ProfileService {
if (!device.equals(mActiveBroadcastAudioDevice)) {
updateBroadcastActiveDevice(device, mActiveBroadcastAudioDevice, true);
}
+
+ /* After group de-activation a fallback broadcast to unicast device would be
+ * potential ringtone streaming device.
+ */
+ updateInbandRingtoneForTheGroup(mUnicastGroupIdDeactivatedForBroadcastTransition);
}
updateActiveDevices(
@@ -3009,7 +3024,7 @@ public class LeAudioService extends ProfileService {
* activating Unicast group.
*
* When stream is suspended there should be a reverse handover. Active Unicast group should
- * become inactive and broadcast should be resumed grom paused state.
+ * become inactive and broadcast should be resumed from paused state.
*/
if (status == LeAudioStackEvent.STATUS_LOCAL_STREAM_REQUESTED) {
Optional<Integer> broadcastId = getFirstNotStoppedBroadcastId();
@@ -3140,6 +3155,15 @@ public class LeAudioService extends ProfileService {
mHfpHandoverDevice = null;
}
+ /* Return true if Fallback Unicast Group For Broadcast is the given groupId and broadcast is
+ * active or ready to be activated.
+ */
+ boolean isFallbackUnicastGroupDuringBroadcast(int groupId) {
+ return (groupId != IBluetoothLeAudio.LE_AUDIO_GROUP_ID_INVALID)
+ && (groupId == mUnicastGroupIdDeactivatedForBroadcastTransition)
+ && isBroadcastStarted();
+ }
+
void updateInbandRingtoneForTheGroup(int groupId) {
if (!mLeAudioInbandRingtoneSupportedByPlatform) {
Log.d(TAG, "Platform does not support inband ringtone");
@@ -3167,7 +3191,7 @@ public class LeAudioService extends ProfileService {
}
/* Enables in-band ringtone only for the currently active device or
- * primary device in broadcast scenarios.
+ * fallback broadcast to unicast device in broadcast scenarios.
* Devices are notified of its state over GTBS.
* When enabled, remote devices will not generate an internal ringtone upon
* receiving a GTBS incoming call notification. Instead, they will wait for a
@@ -3181,15 +3205,14 @@ public class LeAudioService extends ProfileService {
boolean isRingtoneEnabled =
ringtoneContextAvailable
&& (groupDescriptor.isActive()
- || isPrimaryGroup(groupId)
- || isBroadcastReadyToBeReActivated());
-
+ || isFallbackUnicastGroupDuringBroadcast(groupId));
Log.i(
TAG,
"updateInbandRingtoneForTheGroup groupId: "
+ (groupId + ", active state: " + groupDescriptor.mActiveState)
+ (", ringtone supported: " + ringtoneContextAvailable)
- + (", is primary group: " + isPrimaryGroup(groupId))
+ + (", is fallback Unicast group during broadcast: "
+ + isFallbackUnicastGroupDuringBroadcast(groupId))
+ (", isBroadcastReadyToBeReActivated: "
+ isBroadcastReadyToBeReActivated())
+ (", state change: "
@@ -3273,6 +3296,11 @@ public class LeAudioService extends ProfileService {
+ ", with device: "
+ unicastDevice);
+ /* After group activation a fallback broadcast to unicast device should be no longer
+ * potential ringtone streaming device.
+ */
+ updateInbandRingtoneForTheGroup(mUnicastGroupIdDeactivatedForBroadcastTransition);
+
if (!Flags.leaudioBroadcastPrimaryGroupSelection()) {
updateFallbackUnicastGroupIdForBroadcast(LE_AUDIO_GROUP_ID_INVALID);
}
@@ -3369,7 +3397,7 @@ public class LeAudioService extends ProfileService {
!= next.getOutputCodecConfig().getSampleRate()) {
Log.d(
TAG,
- "Different output samplerate: "
+ "Different output sampleRate: "
+ (previous.getOutputCodecConfig().getSampleRate()
+ " != "
+ next.getOutputCodecConfig().getSampleRate()));
@@ -3420,7 +3448,7 @@ public class LeAudioService extends ProfileService {
!= next.getInputCodecConfig().getSampleRate()) {
Log.d(
TAG,
- "Different input samplerate: "
+ "Different input sampleRate: "
+ (previous.getInputCodecConfig().getSampleRate()
+ " != "
+ next.getInputCodecConfig().getSampleRate()));
@@ -3453,7 +3481,7 @@ public class LeAudioService extends ProfileService {
* streaming group, while there are still other devices streaming,
* LeAudioService will not notify audio framework or other users about
* Le Audio lead device disconnection. Instead we try to reconnect under
- * the hood and keep using lead device as a audio device indetifier in
+ * the hood and keep using lead device as a audio device identifier in
* the audio framework in order to not stop the stream.
*/
int groupId = deviceDescriptor.mGroupId;
@@ -3940,7 +3968,7 @@ public class LeAudioService extends ProfileService {
/* Stop here if Broadcast was not in Streaming state before */
if (previousState != LeAudioStackEvent.BROADCAST_STATE_STREAMING) {
- // Stop Big Monitoring in case that was some actions on extarnal broadcast
+ // Stop Big Monitoring in case that was some actions on external broadcast
if (bassClientService != null) {
bassClientService.stopBigMonitoring();
}
@@ -4146,7 +4174,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;
@@ -4354,8 +4382,8 @@ public class LeAudioService extends ProfileService {
if (bondState != BluetoothDevice.BOND_BONDED) {
Log.w(TAG, "okToConnect: return false, bondState=" + bondState);
return false;
- } else if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ } else if (connectionPolicy != CONNECTION_POLICY_UNKNOWN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Otherwise, reject the connection if connectionPolicy is not valid.
Log.w(TAG, "okToConnect: return false, connectionPolicy=" + connectionPolicy);
return false;
@@ -4367,7 +4395,7 @@ public class LeAudioService extends ProfileService {
* Get device audio location.
*
* @param device LE Audio capable device
- * @return the sink audioi location that this device currently exposed
+ * @return the sink audio location that this device currently exposed
*/
public int getAudioLocation(BluetoothDevice device) {
if (device == null) {
@@ -4505,7 +4533,7 @@ public class LeAudioService extends ProfileService {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
setEnabledState(device, /* enabled= */ true);
// Authorizes LEA GATT server services if already assigned to a group
int groupId = getGroupId(device);
@@ -4513,7 +4541,7 @@ public class LeAudioService extends ProfileService {
setAuthorizationForRelatedProfiles(device, true);
}
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
setEnabledState(device, /* enabled= */ false);
// Remove authorization for LEA GATT server services
setAuthorizationForRelatedProfiles(device, false);
@@ -4697,7 +4725,7 @@ public class LeAudioService extends ProfileService {
* Check if group is available for streaming. If there is no available context types then group
* is not available for streaming.
*
- * @param groupId groupid
+ * @param groupId groupId
* @return true if available, false otherwise
*/
public boolean isGroupAvailableForStream(int groupId) {
@@ -4879,11 +4907,10 @@ public class LeAudioService extends ProfileService {
}
for (BluetoothDevice device : mDeviceDescriptors.keySet()) {
int connection_policy = getConnectionPolicy(device);
- if (connection_policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connection_policy != CONNECTION_POLICY_FORBIDDEN) {
setAuthorizationForRelatedProfiles(device, true);
}
- setEnabledState(
- device, connection_policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ setEnabledState(device, connection_policy != CONNECTION_POLICY_FORBIDDEN);
}
} finally {
mGroupReadLock.unlock();
@@ -5031,7 +5058,7 @@ public class LeAudioService extends ProfileService {
}
private void handleGroupNodeRemoved(BluetoothDevice device, int groupId) {
- Log.d(TAG, "Removing device " + device + " grom group " + groupId);
+ Log.d(TAG, "Removing device " + device + " from group " + groupId);
boolean isGroupEmpty = true;
mGroupReadLock.lock();
@@ -5272,8 +5299,19 @@ public class LeAudioService extends ProfileService {
+ mUnicastGroupIdDeactivatedForBroadcastTransition
+ " to : "
+ groupId);
+ int oldBroadcastToUnicastFallbackGroup = mUnicastGroupIdDeactivatedForBroadcastTransition;
mUnicastGroupIdDeactivatedForBroadcastTransition = groupId;
+ // Revise inband ringtone support for old and new Fallback Unicast group
+ if (isBroadcastStarted()) {
+ if (oldBroadcastToUnicastFallbackGroup != LE_AUDIO_GROUP_ID_INVALID) {
+ updateInbandRingtoneForTheGroup(oldBroadcastToUnicastFallbackGroup);
+ }
+ if (groupId != LE_AUDIO_GROUP_ID_INVALID) {
+ updateInbandRingtoneForTheGroup(groupId);
+ }
+ }
+
// waive WRITE_SECURE_SETTINGS permission check
final long callingIdentity = Binder.clearCallingIdentity();
try {
@@ -5771,7 +5809,7 @@ public class LeAudioService extends ProfileService {
LeAudioService service = getServiceAndEnforceConnect(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -5854,7 +5892,7 @@ public class LeAudioService extends ProfileService {
LeAudioService service = getServiceAndEnforceConnect(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
service.enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, null);
diff --git a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
index 54e68641e0..fc5c54bbf5 100644
--- a/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
+++ b/android/app/src/com/android/bluetooth/le_audio/LeAudioStateMachine.java
@@ -43,8 +43,13 @@
package com.android.bluetooth.le_audio;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+import static android.bluetooth.BluetoothProfile.getConnectionStateName;
+
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
@@ -74,7 +79,7 @@ final class LeAudioStateMachine extends StateMachine {
private Connecting mConnecting;
private Disconnecting mDisconnecting;
private Connected mConnected;
- private int mConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mConnectionState = STATE_DISCONNECTED;
private int mLastConnectionState = -1;
@@ -137,13 +142,13 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ mConnectionState = STATE_DISCONNECTED;
removeDeferredMessages(DISCONNECT);
if (mLastConnectionState != -1) {
// Don't broadcast during startup
- broadcastConnectionState(BluetoothProfile.STATE_DISCONNECTED, mLastConnectionState);
+ broadcastConnectionState(STATE_DISCONNECTED, mLastConnectionState);
}
}
@@ -154,7 +159,7 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTED;
+ mLastConnectionState = STATE_DISCONNECTED;
}
@Override
@@ -252,8 +257,8 @@ final class LeAudioStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs);
- mConnectionState = BluetoothProfile.STATE_CONNECTING;
- broadcastConnectionState(BluetoothProfile.STATE_CONNECTING, mLastConnectionState);
+ mConnectionState = STATE_CONNECTING;
+ broadcastConnectionState(STATE_CONNECTING, mLastConnectionState);
}
@Override
@@ -263,7 +268,7 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTING;
+ mLastConnectionState = STATE_CONNECTING;
removeMessages(CONNECT_TIMEOUT);
}
@@ -354,8 +359,8 @@ final class LeAudioStateMachine extends StateMachine {
+ "): "
+ messageWhatToString(getCurrentMessage().what));
sendMessageDelayed(CONNECT_TIMEOUT, sConnectTimeoutMs);
- mConnectionState = BluetoothProfile.STATE_DISCONNECTING;
- broadcastConnectionState(BluetoothProfile.STATE_DISCONNECTING, mLastConnectionState);
+ mConnectionState = STATE_DISCONNECTING;
+ broadcastConnectionState(STATE_DISCONNECTING, mLastConnectionState);
}
@Override
@@ -365,7 +370,7 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_DISCONNECTING;
+ mLastConnectionState = STATE_DISCONNECTING;
removeMessages(CONNECT_TIMEOUT);
}
@@ -463,9 +468,9 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mConnectionState = BluetoothProfile.STATE_CONNECTED;
+ mConnectionState = STATE_CONNECTED;
removeDeferredMessages(CONNECT);
- broadcastConnectionState(BluetoothProfile.STATE_CONNECTED, mLastConnectionState);
+ broadcastConnectionState(STATE_CONNECTED, mLastConnectionState);
}
@Override
@@ -475,7 +480,7 @@ final class LeAudioStateMachine extends StateMachine {
+ mDevice
+ "): "
+ messageWhatToString(getCurrentMessage().what));
- mLastConnectionState = BluetoothProfile.STATE_CONNECTED;
+ mLastConnectionState = STATE_CONNECTED;
}
@Override
@@ -544,7 +549,7 @@ final class LeAudioStateMachine extends StateMachine {
}
synchronized boolean isConnected() {
- return (getConnectionState() == BluetoothProfile.STATE_CONNECTED);
+ return (getConnectionState() == STATE_CONNECTED);
}
// This method does not check for error condition (newState == prevState)
@@ -553,9 +558,9 @@ final class LeAudioStateMachine extends StateMachine {
"Connection state "
+ mDevice
+ ": "
- + profileStateToString(prevState)
+ + getConnectionStateName(prevState)
+ "->"
- + profileStateToString(newState));
+ + getConnectionStateName(newState));
mService.notifyConnectionStateChanged(mDevice, newState, prevState);
}
@@ -575,22 +580,6 @@ final class LeAudioStateMachine extends StateMachine {
return Integer.toString(what);
}
- private static String profileStateToString(int state) {
- switch (state) {
- case BluetoothProfile.STATE_DISCONNECTED:
- return "DISCONNECTED";
- case BluetoothProfile.STATE_CONNECTING:
- return "CONNECTING";
- case BluetoothProfile.STATE_CONNECTED:
- return "CONNECTED";
- case BluetoothProfile.STATE_DISCONNECTING:
- return "DISCONNECTING";
- default:
- break;
- }
- return Integer.toString(state);
- }
-
public void dump(StringBuilder sb) {
ProfileService.println(sb, "mDevice: " + mDevice);
ProfileService.println(sb, " StateMachine: " + this);
diff --git a/android/app/src/com/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/PeriodicScanManager.java b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
index c06bdd465a..ccb081d643 100644
--- a/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
+++ b/android/app/src/com/android/bluetooth/le_scan/PeriodicScanManager.java
@@ -27,15 +27,16 @@ import android.os.IInterface;
import android.os.RemoteException;
import android.util.Log;
-import com.android.bluetooth.btservice.AdapterService;
import com.android.bluetooth.gatt.GattServiceConfig;
import com.android.internal.annotations.VisibleForTesting;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.stream.Collectors;
/** Manages Bluetooth LE Periodic scans */
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
@@ -43,16 +44,17 @@ public class PeriodicScanManager {
private static final String TAG =
GattServiceConfig.TAG_PREFIX + PeriodicScanManager.class.getSimpleName();
- private final BluetoothAdapter mAdapter;
- private final PeriodicScanNativeInterface mNativeInterface;
+ static int sTempRegistrationId = -1;
+
private final Map<IBinder, SyncInfo> mSyncs = new ConcurrentHashMap<>();
private final Map<IBinder, SyncTransferInfo> mSyncTransfers =
Collections.synchronizedMap(new HashMap<>());
- static int sTempRegistrationId = -1;
+ private final BluetoothAdapter mAdapter;
+ private final PeriodicScanNativeInterface mNativeInterface;
/** Constructor of {@link PeriodicScanManager}. */
- PeriodicScanManager(AdapterService adapterService) {
- Log.d(TAG, "periodic scan manager created");
+ PeriodicScanManager() {
+ Log.d(TAG, "Periodic Scan Manager created");
mAdapter = BluetoothAdapter.getDefaultAdapter();
mNativeInterface = PeriodicScanNativeInterface.getInstance();
mNativeInterface.init(this);
@@ -65,114 +67,63 @@ public class PeriodicScanManager {
sTempRegistrationId = -1;
}
- static class SyncTransferInfo {
- public String address;
- public SyncDeathRecipient deathRecipient;
- public IPeriodicAdvertisingCallback callback;
-
- SyncTransferInfo(String address, IPeriodicAdvertisingCallback callback) {
- this.address = address;
- this.callback = callback;
- }
- }
-
- static class SyncInfo {
- /* When id is negative, the registration is ongoing. When the registration finishes, id
- * becomes equal to sync_handle */
- public Integer id;
- public Integer advSid;
- public String address;
- public Integer skip;
- public Integer timeout;
- public SyncDeathRecipient deathRecipient;
- public IPeriodicAdvertisingCallback callback;
-
- SyncInfo(
- Integer id,
- Integer advSid,
- String address,
- Integer skip,
- Integer timeout,
- SyncDeathRecipient deathRecipient,
- IPeriodicAdvertisingCallback callback) {
- this.id = id;
- this.advSid = advSid;
- this.address = address;
- this.skip = skip;
- this.timeout = timeout;
- this.deathRecipient = deathRecipient;
- this.callback = callback;
- }
- }
-
- Map.Entry<IBinder, SyncTransferInfo> findSyncTransfer(String address) {
- Map.Entry<IBinder, SyncTransferInfo> entry = null;
- for (Map.Entry<IBinder, SyncTransferInfo> e : mSyncTransfers.entrySet()) {
- if (e.getValue().address.equals(address)) {
- entry = e;
- break;
- }
- }
- return entry;
- }
+ private record SyncTransferInfo(String address, IPeriodicAdvertisingCallback callback) {}
- IBinder toBinder(IPeriodicAdvertisingCallback e) {
- return ((IInterface) e).asBinder();
- }
+ private record SyncInfo(
+ /* When id is negative, the registration is ongoing. When the registration finishes, id
+ * becomes equal to sync_handle */
+ Integer id,
+ Integer advSid,
+ String address,
+ Integer skip,
+ Integer timeout,
+ SyncDeathRecipient deathRecipient,
+ IPeriodicAdvertisingCallback callback) {}
- class SyncDeathRecipient implements IBinder.DeathRecipient {
- public IPeriodicAdvertisingCallback callback;
+ private final class SyncDeathRecipient implements IBinder.DeathRecipient {
+ private final IPeriodicAdvertisingCallback mCallback;
SyncDeathRecipient(IPeriodicAdvertisingCallback callback) {
- this.callback = callback;
+ mCallback = callback;
}
@Override
public void binderDied() {
Log.d(TAG, "Binder is dead - unregistering advertising set");
- stopSync(callback);
+ stopSync(mCallback);
}
}
- Map.Entry<IBinder, SyncInfo> findSync(int syncHandle) {
- Map.Entry<IBinder, SyncInfo> entry = null;
- for (Map.Entry<IBinder, SyncInfo> e : mSyncs.entrySet()) {
- if (e.getValue().id == syncHandle) {
- entry = e;
- break;
- }
- }
- return entry;
+ private static IBinder toBinder(IPeriodicAdvertisingCallback e) {
+ return ((IInterface) e).asBinder();
}
- Map.Entry<IBinder, SyncInfo> findMatchingSync(int advSid, String address) {
- Map.Entry<IBinder, SyncInfo> entry = null;
- for (Map.Entry<IBinder, SyncInfo> e : mSyncs.entrySet()) {
- if (e.getValue().advSid == advSid && e.getValue().address.equals(address)) {
- return entry = e;
- }
- }
- return entry;
+ private Map.Entry<IBinder, SyncTransferInfo> findSyncTransfer(String address) {
+ return mSyncTransfers.entrySet().stream()
+ .filter(e -> e.getValue().address.equals(address))
+ .findFirst()
+ .orElse(null);
}
- Map<IBinder, SyncInfo> findAllSync(int syncHandle) {
- Map<IBinder, SyncInfo> syncMap = new HashMap<IBinder, SyncInfo>();
- for (Map.Entry<IBinder, SyncInfo> e : mSyncs.entrySet()) {
- if (e.getValue().id != syncHandle) {
- continue;
- }
- syncMap.put(
- e.getKey(),
- new SyncInfo(
- e.getValue().id,
- e.getValue().advSid,
- e.getValue().address,
- e.getValue().skip,
- e.getValue().timeout,
- e.getValue().deathRecipient,
- e.getValue().callback));
- }
- return syncMap;
+ private Map.Entry<IBinder, SyncInfo> findSync(int syncHandle) {
+ return mSyncs.entrySet().stream()
+ .filter(e -> e.getValue().id == syncHandle)
+ .findFirst()
+ .orElse(null);
+ }
+
+ private Map.Entry<IBinder, SyncInfo> findMatchingSync(int advSid, String address) {
+ return mSyncs.entrySet().stream()
+ .filter(e -> e.getValue().advSid == advSid && e.getValue().address.equals(address))
+ .findFirst()
+ .orElse(null);
+ }
+
+ private List<IPeriodicAdvertisingCallback> getAllCallbacks(int syncHandle) {
+ return mSyncs.values().stream()
+ .filter(v -> v.id == syncHandle)
+ .map(v -> v.callback)
+ .collect(Collectors.toList());
}
void onSyncStarted(
@@ -185,8 +136,8 @@ public class PeriodicScanManager {
int interval,
int status)
throws Exception {
- Map<IBinder, SyncInfo> syncMap = findAllSync(regId);
- if (syncMap.size() == 0) {
+ List<IPeriodicAdvertisingCallback> callbacks = getAllCallbacks(regId);
+ if (callbacks.isEmpty()) {
Log.d(TAG, "onSyncStarted() - no callback found for regId " + regId);
mNativeInterface.stopSync(syncHandle);
return;
@@ -236,13 +187,12 @@ public class PeriodicScanManager {
void onSyncReport(int syncHandle, int txPower, int rssi, int dataStatus, byte[] data)
throws Exception {
- Map<IBinder, SyncInfo> syncMap = findAllSync(syncHandle);
- if (syncMap.isEmpty()) {
+ List<IPeriodicAdvertisingCallback> callbacks = getAllCallbacks(syncHandle);
+ if (callbacks.isEmpty()) {
Log.i(TAG, "onSyncReport() - no callback found for syncHandle " + syncHandle);
return;
}
- for (Map.Entry<IBinder, SyncInfo> e : syncMap.entrySet()) {
- IPeriodicAdvertisingCallback callback = e.getValue().callback;
+ for (IPeriodicAdvertisingCallback callback : callbacks) {
PeriodicAdvertisingReport report =
new PeriodicAdvertisingReport(
syncHandle, txPower, rssi, dataStatus, ScanRecord.parseFromBytes(data));
@@ -251,13 +201,12 @@ public class PeriodicScanManager {
}
void onSyncLost(int syncHandle) throws Exception {
- Map<IBinder, SyncInfo> syncMap = findAllSync(syncHandle);
- if (syncMap.isEmpty()) {
+ List<IPeriodicAdvertisingCallback> callbacks = getAllCallbacks(syncHandle);
+ if (callbacks.isEmpty()) {
Log.i(TAG, "onSyncLost() - no callback found for syncHandle " + syncHandle);
return;
}
- for (Map.Entry<IBinder, SyncInfo> e : syncMap.entrySet()) {
- IPeriodicAdvertisingCallback callback = e.getValue().callback;
+ for (IPeriodicAdvertisingCallback callback : callbacks) {
IBinder binder = toBinder(callback);
synchronized (mSyncs) {
mSyncs.remove(binder);
@@ -267,13 +216,12 @@ public class PeriodicScanManager {
}
void onBigInfoReport(int syncHandle, boolean encrypted) throws Exception {
- Map<IBinder, SyncInfo> syncMap = findAllSync(syncHandle);
- if (syncMap.isEmpty()) {
+ List<IPeriodicAdvertisingCallback> callbacks = getAllCallbacks(syncHandle);
+ if (callbacks.isEmpty()) {
Log.i(TAG, "onBigInfoReport() - no callback found for syncHandle " + syncHandle);
return;
}
- for (Map.Entry<IBinder, SyncInfo> e : syncMap.entrySet()) {
- IPeriodicAdvertisingCallback callback = e.getValue().callback;
+ for (IPeriodicAdvertisingCallback callback : callbacks) {
callback.onBigInfoAdvertisingReport(syncHandle, encrypted);
}
}
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..b0354381be 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,29 @@ 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())
+ .append(" scannerId ")
+ .append(mScannerId);
+
+ if (mStats != null && mStats.mAppName != null) {
+ sb.append(" [appScanStats ").append(mStats.mAppName).append("]");
}
- sb.append("]");
- return sb.toString();
+
+ return sb.append("]").toString();
}
/**
@@ -103,20 +105,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 6dc3073178..623e478c54 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScanController.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScanController.java
@@ -19,6 +19,7 @@ package com.android.bluetooth.le_scan;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.BLUETOOTH_SCAN;
import static android.Manifest.permission.UPDATE_DEVICE_STATS;
+import static android.bluetooth.BluetoothUtils.extractBytes;
import static com.android.bluetooth.Utils.checkCallerTargetSdk;
import static com.android.bluetooth.flags.Flags.leaudioBassScanWithInternalScanController;
@@ -40,7 +41,6 @@ import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
-import android.companion.AssociationInfo;
import android.companion.CompanionDeviceManager;
import android.content.AttributionSource;
import android.content.Intent;
@@ -71,15 +71,18 @@ import com.android.internal.annotations.VisibleForTesting;
import libcore.util.HexEncoding;
+import com.google.common.primitives.Bytes;
import com.google.protobuf.ByteString;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@@ -89,12 +92,11 @@ import java.util.stream.Collectors;
public class ScanController {
private static final String TAG = ScanController.class.getSimpleName();
- // Batch scan related constants.
- private static final int TRUNCATED_RESULT_SIZE = 11;
-
/** The default floor value for LE batch scan report delays greater than 0 */
static final long DEFAULT_REPORT_DELAY_FLOOR = 5000L;
+ // Batch scan related constants.
+ private static final int TRUNCATED_RESULT_SIZE = 11;
private static final int NUM_SCAN_EVENTS_KEPT = 20;
// onFoundLost related constants
@@ -113,13 +115,12 @@ public class ScanController {
"0201061AFF4C000215426C7565436861726D426561636F6E730EFE1355C509168020691E0EFE13551109426C7565436861726D5F31363936383500000000",
};
- static class PendingIntentInfo {
- public PendingIntent intent;
- public ScanSettings settings;
- public List<ScanFilter> filters;
- public String callingPackage;
- public int callingUid;
-
+ record PendingIntentInfo(
+ PendingIntent intent,
+ ScanSettings settings,
+ List<ScanFilter> filters,
+ String callingPackage,
+ int callingUid) {
@Override
public boolean equals(Object other) {
if (!(other instanceof PendingIntentInfo)) {
@@ -142,9 +143,10 @@ public class ScanController {
}
};
+ private final BluetoothAdapter mAdapter;
private final AdapterService mAdapterService;
- private final HashMap<Integer, Integer> mFilterIndexToMsftAdvMonitorMap = new HashMap<>();
+ private final Map<Integer, Integer> mFilterIndexToMsftAdvMonitorMap = new HashMap<>();
private final String mExposureNotificationPackage;
private final AppOpsManager mAppOps;
@@ -152,12 +154,11 @@ public class ScanController {
private final PeriodicScanManager mPeriodicScanManager;
private final ScanManager mScanManager;
- public final HandlerThread mScanThread;
-
private final ScanBinder mBinder;
+ private final HandlerThread mScanThread;
/** Internal list of scan events to use with the proto */
- private final ArrayDeque<BluetoothMetricsProto.ScanEvent> mScanEvents =
+ private final Deque<BluetoothMetricsProto.ScanEvent> mScanEvents =
new ArrayDeque<>(NUM_SCAN_EVENTS_KEPT);
private final Predicate<ScanResult> mLocationDenylistPredicate;
@@ -172,6 +173,7 @@ public class ScanController {
private final Object mTestModeLock = new Object();
public ScanController(AdapterService adapterService) {
+ mAdapter = BluetoothAdapter.getDefaultAdapter();
mAdapterService = requireNonNull(adapterService);
mExposureNotificationPackage =
mAdapterService.getString(R.string.exposure_notification_package);
@@ -207,9 +209,7 @@ public class ScanController {
this,
BluetoothAdapterProxy.getInstance(),
mScanThread.getLooper());
-
- mPeriodicScanManager =
- ScanObjectsFactory.getInstance().createPeriodicScanManager(mAdapterService);
+ mPeriodicScanManager = ScanObjectsFactory.getInstance().createPeriodicScanManager();
}
public void stop() {
@@ -422,17 +422,16 @@ public class ScanController {
byte[] legacyAdvData = Arrays.copyOfRange(advData, 0, 62);
- BluetoothDevice device =
- BluetoothAdapter.getDefaultAdapter().getRemoteLeDevice(address, addressType);
+ BluetoothDevice device = mAdapter.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()) {
@@ -462,23 +461,23 @@ public class ScanController {
scanRecord,
SystemClock.elapsedRealtimeNanos());
- if (client.hasDisavowedLocation) {
+ if (client.mHasDisavowedLocation) {
if (mLocationDenylistPredicate.test(result)) {
- Log.i(TAG, "Skipping client " + client.scannerId + " for location deny list");
+ Log.i(TAG, "Skipping client " + client.mScannerId + " for location deny list");
continue;
}
}
boolean hasPermission = hasScanResultPermission(client);
if (!hasPermission) {
- for (String associatedDevice : client.associatedDevices) {
+ for (String associatedDevice : client.mAssociatedDevices) {
if (associatedDevice.equalsIgnoreCase(address)) {
hasPermission = true;
break;
}
}
}
- if (!hasPermission && client.eligibleForSanitizedExposureNotification) {
+ if (!hasPermission && client.mEligibleForSanitizedExposureNotification) {
ScanResult sanitized = getSanitizedExposureNotification(result);
if (sanitized != null) {
hasPermission = true;
@@ -501,14 +500,13 @@ public class ScanController {
}
try {
- app.mAppScanStats.addResult(client.scannerId);
+ app.mAppScanStats.addResult(client.mScannerId);
if (app.mCallback != null) {
app.mCallback.onScanResult(result);
} else {
Log.v(TAG, "Callback is null, sending scan results by pendingIntent");
// Send the PendingIntent
- ArrayList<ScanResult> results = new ArrayList<>();
- results.add(result);
+ List<ScanResult> results = new ArrayList<>(Arrays.asList(result));
sendResultsByPendingIntent(
app.mInfo, results, ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
}
@@ -521,28 +519,26 @@ public class ScanController {
private void sendResultByPendingIntent(
PendingIntentInfo pii, ScanResult result, int callbackType, ScanClient client) {
- ArrayList<ScanResult> results = new ArrayList<>();
- results.add(result);
+ List<ScanResult> results = new ArrayList<>(Arrays.asList(result));
try {
sendResultsByPendingIntent(pii, results, callbackType);
} 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);
}
}
}
- @SuppressWarnings("NonApiType")
private void sendResultsByPendingIntent(
- PendingIntentInfo pii, ArrayList<ScanResult> results, int callbackType)
+ PendingIntentInfo pii, List<ScanResult> results, int callbackType)
throws PendingIntent.CanceledException {
Intent extrasIntent = new Intent();
extrasIntent.putParcelableArrayListExtra(
- BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT, results);
+ BluetoothLeScanner.EXTRA_LIST_SCAN_RESULT, new ArrayList<>(results));
extrasIntent.putExtra(BluetoothLeScanner.EXTRA_CALLBACK_TYPE, callbackType);
pii.intent.send(mAdapterService, 0, extrasIntent);
}
@@ -590,20 +586,36 @@ 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);
+ }
+
+ private List<ScanResult> permittedResults(final ScanClient client, Set<ScanResult> results) {
+ if (hasScanResultPermission(client)) {
+ return new ArrayList<>(results);
+ }
+
+ List<ScanResult> permittedResults = new ArrayList<>();
+ for (ScanResult scanResult : results) {
+ for (String associatedDevice : client.mAssociatedDevices) {
+ if (associatedDevice.equalsIgnoreCase(scanResult.getDevice().getAddress())) {
+ permittedResults.add(scanResult);
+ }
+ }
+ }
+ return permittedResults;
}
// Check if a scan record matches a specific filters.
@@ -614,11 +626,11 @@ public class ScanController {
// Check if a scan record matches a specific filters or original address
private static boolean matchesFilters(
ScanClient client, ScanResult scanResult, String originalAddress) {
- if (client.filters == null || client.filters.isEmpty()) {
+ if (client.mFilters == null || client.mFilters.isEmpty()) {
// TODO: Do we really wanna return true here?
return true;
}
- for (ScanFilter filter : client.filters) {
+ for (ScanFilter filter : client.mFilters) {
// Need to check the filter matches, and the original address without changing the API
if (filter.matches(scanResult)) {
return true;
@@ -632,15 +644,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. */
@@ -712,7 +724,7 @@ public class ScanController {
ScanClient findBatchScanClientById(int scannerId) {
for (ScanClient client : mScanManager.getBatchScanQueue()) {
- if (client.scannerId == scannerId) {
+ if (client.mScannerId == scannerId) {
return client;
}
}
@@ -758,22 +770,9 @@ public class ScanController {
return;
}
- ArrayList<ScanResult> permittedResults;
- if (hasScanResultPermission(client)) {
- permittedResults = new ArrayList<ScanResult>(results);
- } else {
- permittedResults = new ArrayList<ScanResult>();
- for (ScanResult scanResult : results) {
- for (String associatedDevice : client.associatedDevices) {
- if (associatedDevice.equalsIgnoreCase(
- scanResult.getDevice().getAddress())) {
- permittedResults.add(scanResult);
- }
- }
- }
- }
+ List<ScanResult> permittedResults = permittedResults(client, results);
- if (client.hasDisavowedLocation) {
+ if (client.mHasDisavowedLocation) {
permittedResults.removeIf(mLocationDenylistPredicate);
}
if (permittedResults.isEmpty()) {
@@ -802,9 +801,8 @@ public class ScanController {
mScanManager.callbackDone(scannerId, status);
}
- @SuppressWarnings("NonApiType")
private void sendBatchScanResults(
- ScannerMap.ScannerApp app, ScanClient client, ArrayList<ScanResult> results) {
+ ScannerMap.ScannerApp app, ScanClient client, List<ScanResult> results) {
if (results.isEmpty()) {
return;
}
@@ -813,7 +811,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 {
@@ -834,31 +832,19 @@ 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;
}
- ArrayList<ScanResult> permittedResults;
- if (hasScanResultPermission(client)) {
- permittedResults = new ArrayList<ScanResult>(allResults);
- } else {
- permittedResults = new ArrayList<ScanResult>();
- for (ScanResult scanResult : allResults) {
- for (String associatedDevice : client.associatedDevices) {
- if (associatedDevice.equalsIgnoreCase(scanResult.getDevice().getAddress())) {
- permittedResults.add(scanResult);
- }
- }
- }
- }
+ List<ScanResult> permittedResults = permittedResults(client, allResults);
- if (client.filters == null || client.filters.isEmpty()) {
+ if (client.mFilters == null || client.mFilters.isEmpty()) {
sendBatchScanResults(app, client, permittedResults);
return;
}
// Reconstruct the scan results.
- ArrayList<ScanResult> results = new ArrayList<ScanResult>();
+ List<ScanResult> results = new ArrayList<>();
for (ScanResult scanResult : permittedResults) {
if (matchesFilters(client, scanResult)) {
results.add(scanResult);
@@ -888,8 +874,8 @@ public class ScanController {
byte[] record =
extractBytes(batchRecord, i * TRUNCATED_RESULT_SIZE, TRUNCATED_RESULT_SIZE);
byte[] address = extractBytes(record, 0, 6);
- reverse(address);
- BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
+ Bytes.reverse(address);
+ BluetoothDevice device = mAdapter.getRemoteDevice(address);
int rssi = record[8];
long timestampNanos = now - parseTimestampNanos(extractBytes(record, 9, 2));
results.add(
@@ -914,8 +900,8 @@ public class ScanController {
while (position < batchRecord.length) {
byte[] address = extractBytes(batchRecord, position, 6);
// TODO: remove temp hack.
- reverse(address);
- BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
+ Bytes.reverse(address);
+ BluetoothDevice device = mAdapter.getRemoteDevice(address);
position += 6;
// Skip address type.
position++;
@@ -944,23 +930,6 @@ public class ScanController {
return results;
}
- // Reverse byte array.
- private static void reverse(byte[] address) {
- int len = address.length;
- for (int i = 0; i < len / 2; ++i) {
- byte b = address[i];
- address[i] = address[len - 1 - i];
- address[len - 1 - i] = b;
- }
- }
-
- // Helper method to extract bytes from byte array.
- private static byte[] extractBytes(byte[] scanRecord, int start, int length) {
- byte[] bytes = new byte[length];
- System.arraycopy(scanRecord, start, bytes, 0, length);
- return bytes;
- }
-
void onBatchScanThresholdCrossed(int clientIf) {
Log.d(TAG, "onBatchScanThresholdCrossed() - clientIf=" + clientIf);
flushPendingBatchResultsInternal(clientIf);
@@ -1015,8 +984,7 @@ public class ScanController {
}
BluetoothDevice device =
- BluetoothAdapter.getDefaultAdapter()
- .getRemoteLeDevice(trackingInfo.address(), trackingInfo.addressType());
+ mAdapter.getRemoteLeDevice(trackingInfo.address(), trackingInfo.addressType());
int advertiserState = trackingInfo.advState();
ScanResult result =
new ScanResult(
@@ -1026,8 +994,8 @@ public class ScanController {
SystemClock.elapsedRealtimeNanos());
for (ScanClient client : mScanManager.getRegularScanQueue()) {
- if (client.scannerId == trackingInfo.clientIf()) {
- ScanSettings settings = client.settings;
+ if (client.mScannerId == trackingInfo.clientIf()) {
+ ScanSettings settings = client.mSettings;
if ((advertiserState == ADVT_STATE_ONFOUND)
&& ((settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
!= 0)) {
@@ -1052,7 +1020,7 @@ public class ScanController {
"Not reporting onlost/onfound : "
+ advertiserState
+ " scannerId = "
- + client.scannerId
+ + client.mScannerId
+ " callbackType "
+ settings.getCallbackType());
}
@@ -1198,8 +1166,7 @@ public class ScanController {
info.getPackageName().equals(callingPackage)
&& !info.isSelfManaged()
&& info.getDeviceMacAddress() != null)
- .map(AssociationInfo::getDeviceMacAddress)
- .map(MacAddress::toString)
+ .map(info -> info.getDeviceMacAddress().toString())
.collect(Collectors.toList());
} catch (SecurityException se) {
// Not an app with associated devices
@@ -1229,35 +1196,35 @@ public class ScanController {
settings = enforceReportDelayFloor(settings);
enforcePrivilegedPermissionIfNeeded(filters);
final ScanClient scanClient = new ScanClient(scannerId, settings, filters);
- scanClient.userHandle = Binder.getCallingUserHandle();
+ scanClient.mUserHandle = Binder.getCallingUserHandle();
mAppOps.checkPackage(Binder.getCallingUid(), callingPackage);
- scanClient.eligibleForSanitizedExposureNotification =
+ scanClient.mEligibleForSanitizedExposureNotification =
callingPackage.equals(mExposureNotificationPackage);
- scanClient.hasDisavowedLocation =
+ scanClient.mHasDisavowedLocation =
Utils.hasDisavowedLocationForScan(
mAdapterService, attributionSource, mTestModeEnabled);
- scanClient.isQApp =
+ scanClient.mIsQApp =
checkCallerTargetSdk(mAdapterService, callingPackage, Build.VERSION_CODES.Q);
- if (!scanClient.hasDisavowedLocation) {
- if (scanClient.isQApp) {
- scanClient.hasLocationPermission =
+ if (!scanClient.mHasDisavowedLocation) {
+ if (scanClient.mIsQApp) {
+ scanClient.mHasLocationPermission =
Utils.checkCallerHasFineLocation(
- mAdapterService, attributionSource, scanClient.userHandle);
+ mAdapterService, attributionSource, scanClient.mUserHandle);
} else {
- scanClient.hasLocationPermission =
+ scanClient.mHasLocationPermission =
Utils.checkCallerHasCoarseOrFineLocation(
- mAdapterService, attributionSource, scanClient.userHandle);
+ mAdapterService, attributionSource, scanClient.mUserHandle);
}
}
- scanClient.hasNetworkSettingsPermission =
+ scanClient.mHasNetworkSettingsPermission =
Utils.checkCallerHasNetworkSettingsPermission(mAdapterService);
- scanClient.hasNetworkSetupWizardPermission =
+ scanClient.mHasNetworkSetupWizardPermission =
Utils.checkCallerHasNetworkSetupWizardPermission(mAdapterService);
- scanClient.hasScanWithoutLocationPermission =
+ scanClient.mHasScanWithoutLocationPermission =
Utils.checkCallerHasScanWithoutLocationPermission(mAdapterService);
- scanClient.associatedDevices = getAssociatedDevices(callingPackage);
+ scanClient.mAssociatedDevices = getAssociatedDevices(callingPackage);
startScan(scannerId, settings, filters, scanClient);
}
@@ -1265,18 +1232,18 @@ public class ScanController {
/** Intended for internal use within the Bluetooth app. Bypass permission check */
public void startScanInternal(int scannerId, ScanSettings settings, List<ScanFilter> filters) {
final ScanClient scanClient = new ScanClient(scannerId, settings, filters);
- scanClient.isInternalClient = true;
- scanClient.userHandle = Binder.getCallingUserHandle();
- scanClient.eligibleForSanitizedExposureNotification = false;
- scanClient.hasDisavowedLocation = false;
- scanClient.isQApp = true;
- scanClient.hasNetworkSettingsPermission =
+ scanClient.mIsInternalClient = true;
+ scanClient.mUserHandle = Binder.getCallingUserHandle();
+ scanClient.mEligibleForSanitizedExposureNotification = false;
+ scanClient.mHasDisavowedLocation = false;
+ scanClient.mIsQApp = true;
+ scanClient.mHasNetworkSettingsPermission =
Utils.checkCallerHasNetworkSettingsPermission(mAdapterService);
- scanClient.hasNetworkSetupWizardPermission =
+ scanClient.mHasNetworkSetupWizardPermission =
Utils.checkCallerHasNetworkSetupWizardPermission(mAdapterService);
- scanClient.hasScanWithoutLocationPermission =
+ scanClient.mHasScanWithoutLocationPermission =
Utils.checkCallerHasScanWithoutLocationPermission(mAdapterService);
- scanClient.associatedDevices = Collections.emptyList();
+ scanClient.mAssociatedDevices = Collections.emptyList();
startScan(scannerId, settings, filters, scanClient);
}
@@ -1285,7 +1252,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;
@@ -1323,12 +1290,8 @@ public class ScanController {
UUID uuid = UUID.randomUUID();
String callingPackage = attributionSource.getPackageName();
int callingUid = attributionSource.getUid();
- PendingIntentInfo piInfo = new PendingIntentInfo();
- piInfo.intent = pendingIntent;
- piInfo.settings = settings;
- piInfo.filters = filters;
- piInfo.callingPackage = callingPackage;
- piInfo.callingUid = callingUid;
+ PendingIntentInfo piInfo =
+ new PendingIntentInfo(pendingIntent, settings, filters, callingPackage, callingUid);
Log.d(
TAG,
"startScan(PI) -"
@@ -1337,7 +1300,7 @@ public class ScanController {
+ (" UID=" + callingUid));
// Don't start scan if the Pi scan already in mScannerMap.
- if (mScannerMap.getByPendingIntentInfo(piInfo) != null) {
+ if (mScannerMap.getByPendingIntentInfo(pendingIntent) != null) {
Log.d(TAG, "Don't startScan(PI) since the same Pi scan already in mScannerMap.");
return;
}
@@ -1392,20 +1355,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,
@@ -1467,9 +1431,7 @@ public class ScanController {
/** Intended for internal use within the Bluetooth app. Bypass permission check */
private void stopScanInternal(PendingIntent intent) {
- PendingIntentInfo pii = new PendingIntentInfo();
- pii.intent = intent;
- ScannerMap.ScannerApp app = mScannerMap.getByPendingIntentInfo(pii);
+ ScannerMap.ScannerApp app = mScannerMap.getByPendingIntentInfo(intent);
Log.v(TAG, "stopScan(PendingIntent): app found = " + app);
if (app != null) {
intent.removeCancelListener(mScanIntentCancelListener);
@@ -1575,12 +1537,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;
}
}
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 b5614ea927..ad191ac02e 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScanFilterQueue.java
@@ -22,6 +22,8 @@ import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.TransportBlockFilter;
import android.os.ParcelUuid;
+import com.android.internal.annotations.VisibleForTesting;
+
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
@@ -30,23 +32,22 @@ import java.util.UUID;
/** Helper class used to manage advertisement package filters. */
/* package */ class ScanFilterQueue {
- public static final int TYPE_DEVICE_ADDRESS = 0;
- public static final int TYPE_SERVICE_DATA_CHANGED = 1;
- public static final int TYPE_SERVICE_UUID = 2;
- public static final int TYPE_SOLICIT_UUID = 3;
- public static final int TYPE_LOCAL_NAME = 4;
- public static final int TYPE_MANUFACTURER_DATA = 5;
- public static final int TYPE_SERVICE_DATA = 6;
- public static final int TYPE_TRANSPORT_DISCOVERY_DATA = 7;
- public static final int TYPE_ADVERTISING_DATA_TYPE = 8;
+ @VisibleForTesting static final int TYPE_DEVICE_ADDRESS = 0;
+ @VisibleForTesting static final int TYPE_SERVICE_DATA_CHANGED = 1;
+ @VisibleForTesting static final int TYPE_SERVICE_UUID = 2;
+ @VisibleForTesting static final int TYPE_SOLICIT_UUID = 3;
+ @VisibleForTesting static final int TYPE_LOCAL_NAME = 4;
+ @VisibleForTesting static final int TYPE_MANUFACTURER_DATA = 5;
+ @VisibleForTesting static final int TYPE_SERVICE_DATA = 6;
+ @VisibleForTesting static final int TYPE_TRANSPORT_DISCOVERY_DATA = 7;
+ @VisibleForTesting static final int TYPE_ADVERTISING_DATA_TYPE = 8;
+
+ private static final int TYPE_INVALID = 0x00; // Meta data type for Transport Block Filter
+ private static final int TYPE_WIFI_NAN_HASH = 0x01; // WIFI NAN HASH type
// Max length is 31 - 3(flags) - 2 (one byte for length and one byte for type).
private static final int MAX_LEN_PER_FIELD = 26;
- // Meta data type for Transport Block Filter
- public static final int TYPE_INVALID = 0x00;
- public static final int TYPE_WIFI_NAN_HASH = 0x01; // WIFI NAN HASH type
-
static class Entry {
public byte type;
public String address;
@@ -67,8 +68,9 @@ import java.util.UUID;
public byte[] meta_data;
}
- private Set<Entry> mEntries = new HashSet<Entry>();
+ private final Set<Entry> mEntries = new HashSet<>();
+ @VisibleForTesting
void addDeviceAddress(String address, byte type, byte[] irk) {
Entry entry = new Entry();
entry.type = TYPE_DEVICE_ADDRESS;
@@ -78,20 +80,12 @@ import java.util.UUID;
mEntries.add(entry);
}
- void addServiceChanged() {
- Entry entry = new Entry();
- entry.type = TYPE_SERVICE_DATA_CHANGED;
- mEntries.add(entry);
- }
-
+ @VisibleForTesting
void addUuid(UUID uuid) {
- Entry entry = new Entry();
- entry.type = TYPE_SERVICE_UUID;
- entry.uuid = uuid;
- entry.uuid_mask = new UUID(0, 0);
- mEntries.add(entry);
+ addUuid(uuid, new UUID(0, 0));
}
+ @VisibleForTesting
void addUuid(UUID uuid, UUID uuidMask) {
Entry entry = new Entry();
entry.type = TYPE_SERVICE_UUID;
@@ -100,14 +94,12 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addSolicitUuid(UUID uuid) {
- Entry entry = new Entry();
- entry.type = TYPE_SOLICIT_UUID;
- entry.uuid = uuid;
- entry.uuid_mask = new UUID(0, 0);
- mEntries.add(entry);
+ addSolicitUuid(uuid, new UUID(0, 0));
}
+ @VisibleForTesting
void addSolicitUuid(UUID uuid, UUID uuidMask) {
Entry entry = new Entry();
entry.type = TYPE_SOLICIT_UUID;
@@ -116,6 +108,7 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addName(String name) {
Entry entry = new Entry();
entry.type = TYPE_LOCAL_NAME;
@@ -123,17 +116,15 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addManufacturerData(int company, byte[] data) {
- Entry entry = new Entry();
- entry.type = TYPE_MANUFACTURER_DATA;
- entry.company = company;
- entry.company_mask = 0xFFFF;
- entry.data = data;
- entry.data_mask = new byte[data.length];
- Arrays.fill(entry.data_mask, (byte) 0xFF);
- mEntries.add(entry);
+ int companyMask = 0xFFFF;
+ byte[] dataMask = new byte[data.length];
+ Arrays.fill(dataMask, (byte) 0xFF);
+ addManufacturerData(company, companyMask, data, dataMask);
}
+ @VisibleForTesting
void addManufacturerData(int company, int companyMask, byte[] data, byte[] dataMask) {
Entry entry = new Entry();
entry.type = TYPE_MANUFACTURER_DATA;
@@ -144,6 +135,7 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addServiceData(byte[] data, byte[] dataMask) {
Entry entry = new Entry();
entry.type = TYPE_SERVICE_DATA;
@@ -152,6 +144,7 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addTransportDiscoveryData(
int orgId,
int tdsFlags,
@@ -172,6 +165,7 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
void addAdvertisingDataType(int adType, byte[] data, byte[] dataMask) {
Entry entry = new Entry();
entry.type = TYPE_ADVERTISING_DATA_TYPE;
@@ -181,6 +175,7 @@ import java.util.UUID;
mEntries.add(entry);
}
+ @VisibleForTesting
Entry pop() {
if (mEntries.isEmpty()) {
return null;
@@ -191,7 +186,7 @@ import java.util.UUID;
return entry;
}
- /** Compute feature selection based on the filters presented. */
+ // Compute feature selection based on the filters presented.
int getFeatureSelection() {
int selection = 0;
for (Entry entry : mEntries) {
@@ -204,7 +199,7 @@ import java.util.UUID;
return mEntries.toArray(new ScanFilterQueue.Entry[mEntries.size()]);
}
- /** Add ScanFilter to scan filter queue. */
+ // Add ScanFilter to scan filter queue.
void addScanFilter(ScanFilter filter) {
if (filter == null) {
return;
diff --git a/android/app/src/com/android/bluetooth/le_scan/ScanManager.java b/android/app/src/com/android/bluetooth/le_scan/ScanManager.java
index b5e8a047e0..32e725e123 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,12 @@
package com.android.bluetooth.le_scan;
+import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED;
+import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
+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;
@@ -69,12 +75,18 @@ import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
/** Class that handles Bluetooth LE scan related operations. */
public class ScanManager {
private static final String TAG =
GattServiceConfig.TAG_PREFIX + ScanManager.class.getSimpleName();
+ public static final int SCAN_MODE_SCREEN_OFF_LOW_POWER_WINDOW_MS = 512;
+ public static final int SCAN_MODE_SCREEN_OFF_LOW_POWER_INTERVAL_MS = 10240;
+ public static final int SCAN_MODE_SCREEN_OFF_BALANCED_WINDOW_MS = 183;
+ public static final int SCAN_MODE_SCREEN_OFF_BALANCED_INTERVAL_MS = 730;
+
/** Scan params corresponding to regular scan setting */
@VisibleForTesting static final int SCAN_MODE_LOW_POWER_WINDOW_MS = 140;
@@ -83,10 +95,6 @@ public class ScanManager {
@VisibleForTesting static final int SCAN_MODE_BALANCED_INTERVAL_MS = 730;
@VisibleForTesting static final int SCAN_MODE_LOW_LATENCY_WINDOW_MS = 100;
@VisibleForTesting static final int SCAN_MODE_LOW_LATENCY_INTERVAL_MS = 100;
- public static final int SCAN_MODE_SCREEN_OFF_LOW_POWER_WINDOW_MS = 512;
- public static final int SCAN_MODE_SCREEN_OFF_LOW_POWER_INTERVAL_MS = 10240;
- public static final int SCAN_MODE_SCREEN_OFF_BALANCED_WINDOW_MS = 183;
- public static final int SCAN_MODE_SCREEN_OFF_BALANCED_INTERVAL_MS = 730;
// Result type defined in bt stack. Need to be accessed by ScanController.
static final int SCAN_RESULT_TYPE_TRUNCATED = 1;
@@ -109,59 +117,53 @@ public class ScanManager {
private static final String ACTION_REFRESH_BATCHED_SCAN =
"com.android.bluetooth.gatt.REFRESH_BATCHED_SCAN";
+ private static final int FOREGROUND_IMPORTANCE_CUTOFF = IMPORTANCE_FOREGROUND_SERVICE;
+ private static final boolean DEFAULT_UID_IS_FOREGROUND = true;
+ private static final int SCAN_MODE_APP_IN_BACKGROUND = ScanSettings.SCAN_MODE_LOW_POWER;
+ private static final int SCAN_MODE_FORCE_DOWNGRADED = ScanSettings.SCAN_MODE_LOW_POWER;
+ private static final int SCAN_MODE_MAX_IN_CONCURRENCY = ScanSettings.SCAN_MODE_BALANCED;
+
// Timeout for each controller operation.
private static final int OPERATION_TIME_OUT_MILLIS = 500;
private static final int MAX_IS_UID_FOREGROUND_MAP_SIZE = 500;
+ @VisibleForTesting final ScanNative mScanNative;
+ @VisibleForTesting final ClientHandler mHandler;
+
+ private final Object mCurUsedTrackableAdvertisementsLock = new Object();
+ private final Set<ScanClient> mRegularScanClients =
+ Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
+ private final Set<ScanClient> mBatchClients =
+ Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
+ private final Set<ScanClient> mSuspendedScanClients =
+ Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
+ private final SparseIntArray mPriorityMap = new SparseIntArray();
+ private final SparseBooleanArray mIsUidForegroundMap = new SparseBooleanArray();
+ private final AdapterService mAdapterService;
+ private final ScanController mScanController;
+ private final TimeProvider mTimeProvider;
+ private final BluetoothAdapterProxy mBluetoothAdapterProxy;
+ private final DisplayManager mDisplayManager;
+ private final ActivityManager mActivityManager;
+ private final LocationManager mLocationManager;
+ private final BatchScanThrottler mBatchScanThrottler;
+
+ @VisibleForTesting boolean mIsConnecting;
+ @VisibleForTesting int mProfilesConnecting;
+
private int mLastConfiguredScanSetting1m = Integer.MIN_VALUE;
private int mLastConfiguredScanSettingCoded = Integer.MIN_VALUE;
// Scan parameters for batch scan.
private BatchScanParams mBatchScanParams;
- private final Object mCurUsedTrackableAdvertisementsLock = new Object();
-
@GuardedBy("mCurUsedTrackableAdvertisementsLock")
private int mCurUsedTrackableAdvertisements = 0;
- private final ScanController mScanController;
- private final AdapterService mAdapterService;
- private final TimeProvider mTimeProvider;
- @VisibleForTesting ScanNative mScanNative;
- private BluetoothAdapterProxy mBluetoothAdapterProxy;
- @VisibleForTesting final ClientHandler mHandler;
-
- private Set<ScanClient> mRegularScanClients;
- private Set<ScanClient> mBatchClients;
- private Set<ScanClient> mSuspendedScanClients;
- private SparseIntArray mPriorityMap = new SparseIntArray();
-
- private DisplayManager mDisplayManager;
-
- private ActivityManager mActivityManager;
- private LocationManager mLocationManager;
- private static final int FOREGROUND_IMPORTANCE_CUTOFF =
- ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
- private static final boolean DEFAULT_UID_IS_FOREGROUND = true;
- private static final int SCAN_MODE_APP_IN_BACKGROUND = ScanSettings.SCAN_MODE_LOW_POWER;
- private static final int SCAN_MODE_FORCE_DOWNGRADED = ScanSettings.SCAN_MODE_LOW_POWER;
- private static final int SCAN_MODE_MAX_IN_CONCURRENCY = ScanSettings.SCAN_MODE_BALANCED;
- private final SparseBooleanArray mIsUidForegroundMap = new SparseBooleanArray();
private boolean mScreenOn = false;
- @VisibleForTesting boolean mIsConnecting;
- @VisibleForTesting int mProfilesConnecting;
private int mProfilesConnected, mProfilesDisconnecting;
- private final BatchScanThrottler mBatchScanThrottler;
@VisibleForTesting
- static class UidImportance {
- public int uid;
- public int importance;
-
- UidImportance(int uid, int importance) {
- this.uid = uid;
- this.importance = importance;
- }
- }
+ record UidImportance(int uid, int importance) {}
ScanManager(
AdapterService adapterService,
@@ -169,11 +171,6 @@ public class ScanManager {
BluetoothAdapterProxy bluetoothAdapterProxy,
Looper looper,
TimeProvider timeProvider) {
- mRegularScanClients =
- Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
- mBatchClients = Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
- mSuspendedScanClients =
- Collections.newSetFromMap(new ConcurrentHashMap<ScanClient, Boolean>());
mScanController = scanController;
mAdapterService = adapterService;
mTimeProvider = timeProvider;
@@ -183,7 +180,6 @@ public class ScanManager {
mLocationManager = mAdapterService.getSystemService(LocationManager.class);
mBluetoothAdapterProxy = bluetoothAdapterProxy;
mIsConnecting = false;
-
mPriorityMap.put(ScanSettings.SCAN_MODE_OPPORTUNISTIC, 0);
mPriorityMap.put(ScanSettings.SCAN_MODE_SCREEN_OFF, 1);
mPriorityMap.put(ScanSettings.SCAN_MODE_LOW_POWER, 2);
@@ -192,7 +188,6 @@ public class ScanManager {
mPriorityMap.put(ScanSettings.SCAN_MODE_BALANCED, 4);
mPriorityMap.put(ScanSettings.SCAN_MODE_AMBIENT_DISCOVERY, 4);
mPriorityMap.put(ScanSettings.SCAN_MODE_LOW_LATENCY, 5);
-
mHandler = new ClientHandler(looper);
if (mDisplayManager != null) {
mDisplayManager.registerDisplayListener(mDisplayListener, null);
@@ -266,13 +261,9 @@ public class ScanManager {
Set<ScanClient> getFullBatchScanQueue() {
// TODO: split full batch scan clients and truncated batch clients so we don't need to
// construct this every time.
- Set<ScanClient> fullBatchClients = new HashSet<ScanClient>();
- for (ScanClient client : mBatchClients) {
- if (client.settings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) {
- fullBatchClients.add(client);
- }
- }
- return fullBatchClients;
+ return mBatchClients.stream()
+ .filter(c -> c.mSettings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL)
+ .collect(Collectors.toSet());
}
void startScan(ScanClient client) {
@@ -361,7 +352,7 @@ public class ScanManager {
handleScreenOn();
break;
case MSG_REVERT_SCAN_MODE_UPGRADE:
- revertScanModeUpgrade((ScanClient) msg.obj);
+ handleRevertScanModeUpgrade((ScanClient) msg.obj);
break;
case MSG_IMPORTANCE_CHANGE:
handleImportanceChange((UidImportance) msg.obj);
@@ -378,7 +369,7 @@ public class ScanManager {
}
}
- void handleStartScan(ScanClient client) {
+ private void handleStartScan(ScanClient client) {
Log.d(TAG, "handling starting scan");
fetchAppForegroundState(client);
@@ -388,7 +379,7 @@ public class ScanManager {
}
if (mRegularScanClients.contains(client) || mBatchClients.contains(client)) {
- Log.e(TAG, "Scan already started");
+ Log.e(TAG, "Scan already started for scanner id: " + client.mScannerId);
return;
}
@@ -397,10 +388,10 @@ public class ScanManager {
TAG,
"Cannot start unfiltered scan in screen-off. This scan will be resumed "
+ "later: "
- + client.scannerId);
+ + client.mScannerId);
mSuspendedScanClients.add(client);
- if (client.stats != null) {
- client.stats.recordScanSuspend(client.scannerId);
+ if (client.mStats != null) {
+ client.mStats.recordScanSuspend(client.mScannerId);
}
return;
}
@@ -411,10 +402,10 @@ public class ScanManager {
TAG,
"Cannot start unfiltered scan in location-off. This scan will be"
+ " resumed when location is on: "
- + client.scannerId);
+ + client.mScannerId);
mSuspendedScanClients.add(client);
- if (client.stats != null) {
- client.stats.recordScanSuspend(client.scannerId);
+ if (client.mStats != null) {
+ client.mStats.recordScanSuspend(client.mScannerId);
}
return;
}
@@ -451,11 +442,11 @@ public class ScanManager {
+ mAdapterService.getScanTimeoutMillis()
+ ")"
+ "to scannerId "
- + client.scannerId);
+ + client.mScannerId);
}
}
}
- client.started = true;
+ client.mStarted = true;
}
private boolean requiresScreenOn(ScanClient client) {
@@ -465,16 +456,16 @@ public class ScanManager {
private static boolean requiresLocationOn(ScanClient client) {
boolean isFiltered = isFilteredScan(client);
- return !client.hasDisavowedLocation && !isFiltered;
+ return !client.mHasDisavowedLocation && !isFiltered;
}
private static boolean isFilteredScan(ScanClient client) {
- if ((client.filters == null) || client.filters.isEmpty()) {
+ if ((client.mFilters == null) || client.mFilters.isEmpty()) {
return false;
}
boolean atLeastOneValidFilter = false;
- for (ScanFilter filter : client.filters) {
+ for (ScanFilter filter : client.mFilters) {
// A valid filter need at least one field not empty
if (!filter.isAllFieldsEmpty()) {
atLeastOneValidFilter = true;
@@ -484,7 +475,7 @@ public class ScanManager {
return atLeastOneValidFilter;
}
- void handleStopScan(ScanClient client) {
+ private void handleStopScan(ScanClient client) {
if (client == null) {
return;
}
@@ -507,35 +498,35 @@ 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);
}
}
- void handleFlushBatchResults(ScanClient client) {
+ private void handleFlushBatchResults(ScanClient client) {
Log.d(TAG, "handleFlushBatchResults() " + client);
if (!mBatchClients.contains(client)) {
Log.d(TAG, "There is no batch scan client to flush " + client);
return;
}
- mScanNative.flushBatchResults(client.scannerId);
+ mScanNative.flushBatchResults(client.mScannerId);
}
private static boolean isBatchClient(ScanClient client) {
- if (client == null || client.settings == null) {
+ if (client == null || client.mSettings == null) {
return false;
}
- ScanSettings settings = client.settings;
+ ScanSettings settings = client.mSettings;
return settings.getCallbackType() == ScanSettings.CALLBACK_TYPE_ALL_MATCHES
&& settings.getReportDelayMillis() != 0;
}
private boolean isScanSupported(ScanClient client) {
- if (client == null || client.settings == null) {
+ if (client == null || client.mSettings == null) {
return true;
}
- ScanSettings settings = client.settings;
+ ScanSettings settings = client.mSettings;
if (isFilteringSupported()) {
return true;
}
@@ -543,7 +534,7 @@ public class ScanManager {
&& settings.getReportDelayMillis() == 0;
}
- void handleScreenOff() {
+ private void handleScreenOff() {
AppScanStats.setScreenState(false, mTimeProvider);
if (!mScreenOn) {
return;
@@ -556,7 +547,7 @@ public class ScanManager {
updateRegularScanToBatchScanClients();
}
- void handleConnectingState() {
+ private void handleConnectingState() {
if (mAdapterService.getScanDowngradeDurationMillis() == 0) {
return;
}
@@ -577,7 +568,7 @@ public class ScanManager {
sendMessageDelayed(msg, mAdapterService.getScanDowngradeDurationMillis());
}
- void handleClearConnectingState() {
+ private void handleClearConnectingState() {
if (!mIsConnecting) {
Log.e(TAG, "handleClearConnectingState() - not connecting state");
return;
@@ -597,13 +588,13 @@ public class ScanManager {
mIsConnecting = false;
}
- void handleSuspendScans() {
+ private void handleSuspendScans() {
for (ScanClient client : mRegularScanClients) {
if ((requiresScreenOn(client) && !mScreenOn)
|| (requiresLocationOn(client) && !mLocationManager.isLocationEnabled())) {
/*Suspend unfiltered scans*/
- if (client.stats != null) {
- client.stats.recordScanSuspend(client.scannerId);
+ if (client.mStats != null) {
+ client.mStats.recordScanSuspend(client.mScannerId);
}
Log.d(TAG, "suspend scan " + client);
handleStopScan(client);
@@ -653,8 +644,8 @@ public class ScanManager {
TAG,
"Scan mode update during setAutoBatchScanClient() to "
+ getScanModeString(ScanSettings.SCAN_MODE_SCREEN_OFF));
- if (client.stats != null) {
- client.stats.setAutoBatchScan(client.scannerId, true);
+ if (client.mStats != null) {
+ client.mStats.setAutoBatchScan(client.mScannerId, true);
}
}
@@ -662,13 +653,13 @@ public class ScanManager {
if (!isAutoBatchScanClientEnabled(client)) {
return;
}
- client.updateScanMode(client.scanModeApp);
+ client.updateScanMode(client.mScanModeApp);
Log.d(
TAG,
"Scan mode update during clearAutoBatchScanClient() to "
- + getScanModeString(client.scanModeApp));
- if (client.stats != null) {
- client.stats.setAutoBatchScan(client.scannerId, false);
+ + getScanModeString(client.mScanModeApp));
+ if (client.mStats != null) {
+ client.mStats.setAutoBatchScan(client.mScannerId, false);
}
}
@@ -688,13 +679,13 @@ public class ScanManager {
if (mScanNative.isOpportunisticScanClient(client)) {
return false;
}
- int updatedScanMode = client.scanModeApp;
+ int updatedScanMode = client.mScanModeApp;
if (!isAppForeground(client) || mScanNative.isForceDowngradedScanClient(client)) {
updatedScanMode = ScanSettings.SCAN_MODE_SCREEN_OFF;
} else {
// The following codes are effectively only for services
// Apps are either already or will be soon handled by handleImportanceChange().
- switch (client.scanModeApp) {
+ switch (client.mScanModeApp) {
case ScanSettings.SCAN_MODE_LOW_POWER:
updatedScanMode = ScanSettings.SCAN_MODE_SCREEN_OFF;
break;
@@ -713,7 +704,7 @@ public class ScanManager {
Log.d(
TAG,
"Scan mode update during screen off from "
- + getScanModeString(client.scanModeApp)
+ + getScanModeString(client.mScanModeApp)
+ " to "
+ getScanModeString(updatedScanMode));
return client.updateScanMode(updatedScanMode);
@@ -724,7 +715,7 @@ public class ScanManager {
* background triggering onUidImportance().
*/
private boolean isAppForeground(ScanClient client) {
- return mIsUidForegroundMap.get(client.appUid, DEFAULT_UID_IS_FOREGROUND);
+ return mIsUidForegroundMap.get(client.mAppUid, DEFAULT_UID_IS_FOREGROUND);
}
private void fetchAppForegroundState(ScanClient client) {
@@ -732,19 +723,17 @@ 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;
}
- int importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CACHED;
+ int importance = IMPORTANCE_CACHED;
for (String packageName : packages) {
importance =
Math.min(importance, mActivityManager.getPackageImportance(packageName));
}
- boolean isForeground =
- importance
- <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
- mIsUidForegroundMap.put(client.appUid, isForeground);
+ boolean isForeground = importance <= IMPORTANCE_FOREGROUND_SERVICE;
+ mIsUidForegroundMap.put(client.mAppUid, isForeground);
}
private boolean updateScanModeBeforeStart(ScanClient client) {
@@ -766,10 +755,10 @@ public class ScanManager {
}
private boolean upgradeScanModeBeforeStart(ScanClient client) {
- if (client.started || mAdapterService.getScanUpgradeDurationMillis() == 0) {
+ if (client.mStarted || mAdapterService.getScanUpgradeDurationMillis() == 0) {
return false;
}
- if (client.stats == null || client.stats.hasRecentScan()) {
+ if (client.mStats == null || client.mStats.hasRecentScan()) {
return false;
}
if (!isAppForeground(client) || isBatchClient(client)) {
@@ -782,7 +771,7 @@ public class ScanManager {
Log.d(
TAG,
"scanMode is upgraded to "
- + getScanModeString(client.settings.getScanMode())
+ + getScanModeString(client.mSettings.getScanMode())
+ " for "
+ client);
sendMessageDelayed(msg, mAdapterService.getScanUpgradeDurationMillis());
@@ -792,7 +781,7 @@ public class ScanManager {
}
private static boolean upgradeScanModeByOneLevel(ScanClient client) {
- switch (client.scanModeApp) {
+ switch (client.mScanModeApp) {
case ScanSettings.SCAN_MODE_LOW_POWER:
return client.updateScanMode(ScanSettings.SCAN_MODE_BALANCED);
case ScanSettings.SCAN_MODE_BALANCED:
@@ -805,28 +794,77 @@ public class ScanManager {
}
}
- void revertScanModeUpgrade(ScanClient client) {
- if (mPriorityMap.get(client.settings.getScanMode())
- <= mPriorityMap.get(client.scanModeApp)) {
+ private void handleRevertScanModeUpgrade(ScanClient client) {
+ 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();
}
}
+ private void handleImportanceChange(UidImportance imp) {
+ if (imp == null) {
+ return;
+ }
+ int uid = imp.uid;
+ int importance = imp.importance;
+ boolean updatedScanParams = false;
+ boolean isForeground = importance <= IMPORTANCE_FOREGROUND_SERVICE;
+
+ if (mIsUidForegroundMap.size() < MAX_IS_UID_FOREGROUND_MAP_SIZE) {
+ mIsUidForegroundMap.put(uid, isForeground);
+ }
+
+ for (ScanClient client : mRegularScanClients) {
+ if (client.mAppUid != uid || mScanNative.isOpportunisticScanClient(client)) {
+ continue;
+ }
+ if (isForeground) {
+ int scanMode = client.mScanModeApp;
+ int maxScanMode =
+ mScanNative.isForceDowngradedScanClient(client)
+ ? SCAN_MODE_FORCE_DOWNGRADED
+ : scanMode;
+ if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) {
+ updatedScanParams = true;
+ }
+ } else {
+ int scanMode = client.mSettings.getScanMode();
+ int maxScanMode =
+ mScreenOn
+ ? SCAN_MODE_APP_IN_BACKGROUND
+ : ScanSettings.SCAN_MODE_SCREEN_OFF;
+ if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) {
+ updatedScanParams = true;
+ }
+ }
+ Log.d(
+ TAG,
+ ("uid " + uid)
+ + (" isForeground " + isForeground)
+ + (" scanMode "
+ + getScanModeString(client.mSettings.getScanMode())));
+ }
+
+ if (updatedScanParams) {
+ mScanNative.configureRegularScanParams();
+ }
+ }
+
private boolean updateScanModeScreenOn(ScanClient client) {
if (mScanNative.isOpportunisticScanClient(client)) {
return false;
}
int scanMode =
- isAppForeground(client) ? client.scanModeApp : SCAN_MODE_APP_IN_BACKGROUND;
+ isAppForeground(client) ? client.mScanModeApp : SCAN_MODE_APP_IN_BACKGROUND;
int maxScanMode =
mScanNative.isForceDowngradedScanClient(client)
? SCAN_MODE_FORCE_DOWNGRADED
@@ -834,20 +872,20 @@ public class ScanManager {
Log.d(
TAG,
"Scan mode update during screen on from "
- + getScanModeString(client.scanModeApp)
+ + getScanModeString(client.mScanModeApp)
+ " to "
+ getScanModeString(getMinScanMode(scanMode, maxScanMode)));
return client.updateScanMode(getMinScanMode(scanMode, maxScanMode));
}
private boolean downgradeScanModeFromMaxDuty(ScanClient client) {
- if ((client.stats == null) || mAdapterService.getScanDowngradeDurationMillis() == 0) {
+ if ((client.mStats == null) || mAdapterService.getScanDowngradeDurationMillis() == 0) {
return false;
}
int updatedScanMode =
- getMinScanMode(client.settings.getScanMode(), SCAN_MODE_MAX_IN_CONCURRENCY);
+ getMinScanMode(client.mSettings.getScanMode(), SCAN_MODE_MAX_IN_CONCURRENCY);
if (client.updateScanMode(updatedScanMode)) {
- client.stats.setScanDowngrade(client.scannerId, true);
+ client.mStats.setScanDowngrade(client.mScannerId, true);
Log.d(
TAG,
"downgradeScanModeFromMaxDuty() to "
@@ -863,8 +901,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) {
@@ -874,7 +912,7 @@ public class ScanManager {
}
}
- void handleScreenOn() {
+ private void handleScreenOn() {
AppScanStats.setScreenState(true, mTimeProvider);
if (mScreenOn) {
return;
@@ -887,14 +925,14 @@ public class ScanManager {
updateRegularScanClientsScreenOn();
}
- void handleResumeScans() {
+ private void handleResumeScans() {
Iterator<ScanClient> iterator = mSuspendedScanClients.iterator();
while (iterator.hasNext()) {
ScanClient client = iterator.next();
if ((!requiresScreenOn(client) || mScreenOn)
&& (!requiresLocationOn(client) || mLocationManager.isLocationEnabled())) {
- if (client.stats != null) {
- client.stats.recordScanResume(client.scannerId);
+ if (client.mStats != null) {
+ client.mStats.recordScanResume(client.mScannerId);
}
Log.d(TAG, "resume scan " + client);
handleStartScan(client);
@@ -1087,10 +1125,10 @@ public class ScanManager {
ScanClient client1m = getAggressiveClient(mRegularScanClients, true, false);
ScanClient clientCoded = getAggressiveClient(mRegularScanClients, false, false);
if (client1m != null) {
- newScanSetting1m = client1m.settings.getScanMode();
+ newScanSetting1m = client1m.mSettings.getScanMode();
}
if (clientCoded != null) {
- newScanSettingCoded = clientCoded.settings.getScanMode();
+ newScanSettingCoded = clientCoded.mSettings.getScanMode();
}
int curPhyMask =
@@ -1142,10 +1180,10 @@ public class ScanManager {
+ " / "
+ clientCoded);
mNativeInterface.gattSetScanParameters(
- client1m == null ? 0 : client1m.scannerId,
+ client1m == null ? 0 : client1m.mScannerId,
scanInterval1m,
scanWindow1m,
- clientCoded == null ? 0 : clientCoded.scannerId,
+ clientCoded == null ? 0 : clientCoded.mScannerId,
scanIntervalCoded,
scanWindowCoded,
scanPhyMask);
@@ -1167,7 +1205,7 @@ public class ScanManager {
if (!isBatch && !isPhyConfigured(client, use1mPhy)) {
continue;
}
- int priority = mPriorityMap.get(client.settings.getScanMode());
+ int priority = mPriorityMap.get(client.mSettings.getScanMode());
if (priority > currentScanModePriority) {
result = client;
currentScanModePriority = priority;
@@ -1181,12 +1219,12 @@ public class ScanManager {
// When the flag is off the PHY setting is ignored and all clients scan on 1m
return use1mPhy;
}
- if (client.settings.getPhy() == ScanSettings.PHY_LE_ALL_SUPPORTED) {
+ if (client.mSettings.getPhy() == ScanSettings.PHY_LE_ALL_SUPPORTED) {
return true;
}
return use1mPhy
- ? client.settings.getPhy() == BluetoothDevice.PHY_LE_1M
- : client.settings.getPhy() == BluetoothDevice.PHY_LE_CODED;
+ ? client.mSettings.getPhy() == BluetoothDevice.PHY_LE_1M
+ : client.mSettings.getPhy() == BluetoothDevice.PHY_LE_CODED;
}
private static boolean shouldUpdateScan(int newScanSetting, int oldScanSetting) {
@@ -1196,12 +1234,12 @@ public class ScanManager {
}
private int getScanWindow(@Nullable ScanClient client) {
- return client == null ? 0 : Utils.millsToUnit(getScanWindowMillis(client.settings));
+ return client == null ? 0 : Utils.millsToUnit(getScanWindowMillis(client.mSettings));
}
private int getScanInterval(@Nullable ScanClient client) {
// convert scanWindow and scanInterval from ms to LE scan units(0.625ms)
- return client == null ? 0 : Utils.millsToUnit(getScanIntervalMillis(client.settings));
+ return client == null ? 0 : Utils.millsToUnit(getScanIntervalMillis(client.mSettings));
}
private void recordScanRadioStart(
@@ -1221,13 +1259,13 @@ public class ScanManager {
: clientCoded;
}
if (chosenClient != null
- && chosenClient.stats != null
+ && chosenClient.mStats != null
&& !AppScanStats.recordScanRadioStart(
- chosenClient.scanModeApp,
- chosenClient.scannerId,
- chosenClient.stats,
- getScanWindowMillis(chosenClient.settings),
- getScanIntervalMillis(chosenClient.settings),
+ chosenClient.mScanModeApp,
+ chosenClient.mScannerId,
+ chosenClient.mStats,
+ getScanWindowMillis(chosenClient.mSettings),
+ getScanIntervalMillis(chosenClient.mSettings),
mTimeProvider)) {
Log.w(TAG, "Scan radio already started");
}
@@ -1247,18 +1285,18 @@ public class ScanManager {
// Start scan native only for the first client.
if (numRegularScanClients() == 1
- && client.settings != null
- && client.settings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
+ && client.mSettings != null
+ && client.mSettings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
Log.d(TAG, "start gattClientScanNative from startRegularScan()");
mNativeInterface.gattClientScan(true);
if (!Flags.bleScanAdvMetricsRedesign()) {
- if (client.stats != null
+ if (client.mStats != null
&& !AppScanStats.recordScanRadioStart(
- client.settings.getScanMode(),
- client.scannerId,
- client.stats,
- getScanWindowMillis(client.settings),
- getScanIntervalMillis(client.settings),
+ client.mSettings.getScanMode(),
+ client.mScannerId,
+ client.mStats,
+ getScanWindowMillis(client.mSettings),
+ getScanIntervalMillis(client.mSettings),
mTimeProvider)) {
Log.w(TAG, "Scan radio already started");
}
@@ -1269,7 +1307,7 @@ public class ScanManager {
private int numRegularScanClients() {
int num = 0;
for (ScanClient client : mRegularScanClients) {
- if (client.settings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
+ if (client.mSettings.getScanMode() != ScanSettings.SCAN_MODE_OPPORTUNISTIC) {
num++;
}
}
@@ -1297,24 +1335,24 @@ public class ScanManager {
}
private static boolean isAutoBatchScanClientEnabled(ScanClient client) {
- return client.stats != null && client.stats.isAutoBatchScan(client.scannerId);
+ return client.mStats != null && client.mStats.isAutoBatchScan(client.mScannerId);
}
private static boolean isAllMatchesAutoBatchScanClient(ScanClient client) {
- return client.settings.getCallbackType()
+ return client.mSettings.getCallbackType()
== ScanSettings.CALLBACK_TYPE_ALL_MATCHES_AUTO_BATCH;
}
private static boolean isOpportunisticScanClient(ScanClient client) {
- return client.settings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC;
+ return client.mSettings.getScanMode() == ScanSettings.SCAN_MODE_OPPORTUNISTIC;
}
private static boolean isTimeoutScanClient(ScanClient client) {
- return (client.stats != null) && client.stats.isScanTimeout(client.scannerId);
+ return (client.mStats != null) && client.mStats.isScanTimeout(client.mScannerId);
}
private static boolean isDowngradedScanClient(ScanClient client) {
- return (client.stats != null) && client.stats.isScanDowngraded(client.scannerId);
+ return (client.mStats != null) && client.mStats.isScanDowngraded(client.mScannerId);
}
private static boolean isForceDowngradedScanClient(ScanClient client) {
@@ -1322,12 +1360,12 @@ public class ScanManager {
}
private static boolean isFirstMatchScanClient(ScanClient client) {
- return (client.settings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
+ return (client.mSettings.getCallbackType() & ScanSettings.CALLBACK_TYPE_FIRST_MATCH)
!= 0;
}
private void resetBatchScan(ScanClient client) {
- int scannerId = client.scannerId;
+ int scannerId = client.mScannerId;
BatchScanParams batchScanParams = getBatchScanParams();
// Stop batch if batch scan params changed and previous params is not null.
if (mBatchScanParams != null && (!mBatchScanParams.equals(batchScanParams))) {
@@ -1346,9 +1384,9 @@ public class ScanManager {
int resultType = getResultType(batchScanParams);
int fullScanPercent = getFullScanStoragePercent(resultType);
resetCountDownLatch();
- Log.d(TAG, "configuring batch scan storage, appIf " + client.scannerId);
+ Log.d(TAG, "configuring batch scan storage, appIf " + client.mScannerId);
mNativeInterface.gattClientConfigBatchScanStorage(
- client.scannerId, fullScanPercent, 100 - fullScanPercent, notifyThreshold);
+ client.mScannerId, fullScanPercent, 100 - fullScanPercent, notifyThreshold);
waitForCallback();
resetCountDownLatch();
int scanInterval =
@@ -1388,15 +1426,15 @@ public class ScanManager {
BatchScanParams params = new BatchScanParams();
ScanClient winner = getAggressiveClient(mBatchClients, true, true);
if (winner != null) {
- params.mScanMode = winner.settings.getScanMode();
+ params.mScanMode = winner.mSettings.getScanMode();
}
// TODO: split full batch scan results and truncated batch scan results to different
// collections.
for (ScanClient client : mBatchClients) {
- if (client.settings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) {
- params.mFullScanScannerId = client.scannerId;
+ if (client.mSettings.getScanResultType() == ScanSettings.SCAN_RESULT_TYPE_FULL) {
+ params.mFullScanScannerId = client.mScannerId;
} else {
- params.mTruncatedScanScannerId = client.scannerId;
+ params.mTruncatedScanScannerId = client.mScannerId;
}
}
return params;
@@ -1472,8 +1510,8 @@ public class ScanManager {
int deliveryMode = getDeliveryMode(client);
if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) {
// Decrement the count of trackable advertisements in use
- int entriesToFreePerFilter = getNumOfTrackingAdvertisements(client.settings);
- for (int i = 0; i < client.filters.size(); i++) {
+ int entriesToFreePerFilter = getNumOfTrackingAdvertisements(client.mSettings);
+ for (int i = 0; i < client.mFilters.size(); i++) {
if (!manageAllocationOfTrackingAdvertisement(entriesToFreePerFilter, false)) {
Log.e(
TAG,
@@ -1481,7 +1519,7 @@ public class ScanManager {
+ entriesToFreePerFilter);
try {
mScanController.onScanManagerErrorCallback(
- client.scannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
+ client.mScannerId, ScanCallback.SCAN_FAILED_INTERNAL_ERROR);
} catch (RemoteException e) {
Log.e(TAG, "failed on onScanManagerCallback at freeing", e);
}
@@ -1498,7 +1536,7 @@ public class ScanManager {
}
if (!mIsMsftSupported) {
- removeScanFilters(client.scannerId);
+ removeScanFilters(client.mScannerId);
} else {
removeFiltersMsft(client);
}
@@ -1506,31 +1544,31 @@ public class ScanManager {
void regularScanTimeout(ScanClient client) {
if (!isExemptFromScanTimeout(client)
- && (client.stats == null || client.stats.isScanningTooLong())) {
+ && (client.mStats == null || client.mStats.isScanningTooLong())) {
Log.d(TAG, "regularScanTimeout - client scan time was too long");
- if (client.filters == null || client.filters.isEmpty()) {
+ if (client.mFilters == null || client.mFilters.isEmpty()) {
Log.w(
TAG,
"Moving unfiltered scan client to opportunistic scan (scannerId "
- + client.scannerId
+ + client.mScannerId
+ ")");
setOpportunisticScanClient(client);
- removeScanFilters(client.scannerId);
+ removeScanFilters(client.mScannerId);
} else {
Log.w(
TAG,
"Moving filtered scan client to downgraded scan (scannerId "
- + client.scannerId
+ + client.mScannerId
+ ")");
- int scanMode = client.settings.getScanMode();
+ int scanMode = client.mSettings.getScanMode();
int maxScanMode = SCAN_MODE_FORCE_DOWNGRADED;
client.updateScanMode(getMinScanMode(scanMode, maxScanMode));
}
- if (client.stats != null) {
- client.stats.setScanTimeout(client.scannerId);
- client.stats.recordScanTimeoutCountMetrics(
- client.scannerId, mAdapterService.getScanTimeoutMillis());
+ if (client.mStats != null) {
+ client.mStats.setScanTimeout(client.mScannerId);
+ client.mStats.recordScanTimeoutCountMetrics(
+ client.mScannerId, mAdapterService.getScanTimeoutMillis());
}
}
@@ -1549,19 +1587,19 @@ public class ScanManager {
// TODO: Add constructor to ScanSettings.Builder
// that can copy values from an existing ScanSettings object
ScanSettings.Builder builder = new ScanSettings.Builder();
- ScanSettings settings = client.settings;
+ ScanSettings settings = client.mSettings;
builder.setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC);
builder.setCallbackType(settings.getCallbackType());
builder.setScanResultType(settings.getScanResultType());
builder.setReportDelay(settings.getReportDelayMillis());
builder.setNumOfMatches(settings.getNumOfMatches());
- client.settings = builder.build();
+ client.mSettings = builder.build();
}
// Find the regular scan client information.
ScanClient getRegularScanClient(int scannerId) {
for (ScanClient client : mRegularScanClients) {
- if (client.scannerId == scannerId) {
+ if (client.mScannerId == scannerId) {
return client;
}
}
@@ -1570,7 +1608,7 @@ public class ScanManager {
ScanClient getSuspendedScanClient(int scannerId) {
for (ScanClient client : mSuspendedScanClients) {
- if (client.scannerId == scannerId) {
+ if (client.mScannerId == scannerId) {
return client;
}
}
@@ -1579,7 +1617,7 @@ public class ScanManager {
void stopBatchScan(ScanClient client) {
mBatchClients.remove(client);
- removeScanFilters(client.scannerId);
+ removeScanFilters(client.mScannerId);
if (!isOpportunisticScanClient(client)) {
resetBatchScan(client);
}
@@ -1615,9 +1653,9 @@ public class ScanManager {
private long getBatchTriggerIntervalMillis() {
long intervalMillis = Long.MAX_VALUE;
for (ScanClient client : mBatchClients) {
- if (client.settings != null && client.settings.getReportDelayMillis() > 0) {
+ if (client.mSettings != null && client.mSettings.getReportDelayMillis() > 0) {
intervalMillis =
- Math.min(intervalMillis, client.settings.getReportDelayMillis());
+ Math.min(intervalMillis, client.mSettings.getReportDelayMillis());
}
}
return intervalMillis;
@@ -1627,7 +1665,7 @@ public class ScanManager {
// If no offload filter can/needs to be set, set ALL_PASS filter.
// Otherwise offload all filters to hardware and enable all filters.
private void configureScanFilters(ScanClient client) {
- int scannerId = client.scannerId;
+ int scannerId = client.mScannerId;
int deliveryMode = getDeliveryMode(client);
int trackEntries = 0;
@@ -1656,7 +1694,7 @@ public class ScanManager {
waitForCallback();
} else {
Deque<Integer> clientFilterIndices = new ArrayDeque<Integer>();
- for (ScanFilter filter : client.filters) {
+ for (ScanFilter filter : client.mFilters) {
ScanFilterQueue queue = new ScanFilterQueue();
queue.addScanFilter(filter);
int featureSelection = queue.getFeatureSelection();
@@ -1669,15 +1707,15 @@ public class ScanManager {
resetCountDownLatch();
if (deliveryMode == DELIVERY_MODE_ON_FOUND_LOST) {
- trackEntries = getNumOfTrackingAdvertisements(client.settings);
+ trackEntries = getNumOfTrackingAdvertisements(client.mSettings);
if (!manageAllocationOfTrackingAdvertisement(trackEntries, true)) {
Log.e(
TAG,
"No hardware resources for onfound/onlost filter "
+ trackEntries);
- if (client.stats != null) {
- client.stats.recordTrackingHwFilterNotAvailableCountMetrics(
- client.scannerId,
+ if (client.mStats != null) {
+ client.mStats.recordTrackingHwFilterNotAvailableCountMetrics(
+ client.mScannerId,
mAdapterService.getTotalNumOfTrackableAdvertisements());
}
try {
@@ -1706,10 +1744,10 @@ public class ScanManager {
}
if (deliveryMode == DELIVERY_MODE_BATCH) {
- mAllPassBatchClients.add(client.scannerId);
+ mAllPassBatchClients.add(client.mScannerId);
return mAllPassBatchClients.size() == 1;
} else {
- mAllPassRegularClients.add(client.scannerId);
+ mAllPassRegularClients.add(client.mScannerId);
return mAllPassRegularClients.size() == 1;
}
}
@@ -1745,7 +1783,7 @@ public class ScanManager {
private ScanClient getBatchScanClient(int scannerId) {
for (ScanClient client : mBatchClients) {
- if (client.scannerId == scannerId) {
+ if (client.mScannerId == scannerId) {
return client;
}
}
@@ -1771,13 +1809,13 @@ public class ScanManager {
if (client == null) {
return true;
}
- if (client.filters == null || client.filters.isEmpty()) {
+ if (client.mFilters == null || client.mFilters.isEmpty()) {
return true;
}
- if (client.filters.size() > mFilterIndexStack.size()) {
- if (client.stats != null) {
- client.stats.recordHwFilterNotAvailableCountMetrics(
- client.scannerId,
+ if (client.mFilters.size() > mFilterIndexStack.size()) {
+ if (client.mStats != null) {
+ client.mStats.recordHwFilterNotAvailableCountMetrics(
+ client.mScannerId,
mAdapterService.getNumOfOffloadedScanFilterSupported());
}
return true;
@@ -1811,7 +1849,7 @@ public class ScanManager {
int numOfTrackingEntries) {
int deliveryMode = getDeliveryMode(client);
int rssiThreshold = Byte.MIN_VALUE;
- ScanSettings settings = client.settings;
+ ScanSettings settings = client.mSettings;
int onFoundTimeout = getOnFoundOnLostTimeoutMillis(settings, true);
int onFoundCount = getOnFoundOnLostSightings(settings);
int onLostTimeout = 10000;
@@ -1847,7 +1885,7 @@ public class ScanManager {
if (client == null) {
return DELIVERY_MODE_IMMEDIATE;
}
- ScanSettings settings = client.settings;
+ ScanSettings settings = client.mSettings;
if (settings == null) {
return DELIVERY_MODE_IMMEDIATE;
}
@@ -2051,16 +2089,16 @@ public class ScanManager {
}
if (client == null
- || client.filters == null
- || client.filters.isEmpty()
- || client.filters.size() > mFilterIndexStack.size()) {
+ || client.mFilters == null
+ || client.mFilters.isEmpty()
+ || client.mFilters.size() > mFilterIndexStack.size()) {
// Use all-pass filter
updateScanMsft();
return;
}
Deque<Integer> clientFilterIndices = new ArrayDeque<>();
- for (ScanFilter filter : client.filters) {
+ for (ScanFilter filter : client.mFilters) {
MsftAdvMonitor monitor = new MsftAdvMonitor(filter);
if (monitor.getAddress().bd_addr != null) {
@@ -2104,13 +2142,13 @@ public class ScanManager {
clientFilterIndices.add(existingFilterIndex);
}
- mClientFilterIndexMap.put(client.scannerId, clientFilterIndices);
+ mClientFilterIndexMap.put(client.mScannerId, clientFilterIndices);
updateScanMsft();
}
private void removeFiltersMsft(ScanClient client) {
- Deque<Integer> clientFilterIndices = mClientFilterIndexMap.remove(client.scannerId);
+ Deque<Integer> clientFilterIndices = mClientFilterIndexMap.remove(client.mScannerId);
if (clientFilterIndices != null) {
for (int filterIndex : clientFilterIndices) {
if (mMsftAdvMonitorMergedPatternList.remove(filterIndex)) {
@@ -2130,11 +2168,11 @@ public class ScanManager {
!mRegularScanClients.stream()
.anyMatch(
c ->
- c.settings != null
- && c.settings.getScanMode()
+ c.mSettings != null
+ && c.mSettings.getScanMode()
!= ScanSettings.SCAN_MODE_OPPORTUNISTIC
&& !this.mClientFilterIndexMap.containsKey(
- c.scannerId));
+ c.mScannerId));
if (scanEnabledMsft != shouldEnableScanMsft) {
resetCountDownLatch();
mNativeInterface.gattClientMsftAdvMonitorEnable(shouldEnableScanMsft);
@@ -2222,7 +2260,7 @@ public class ScanManager {
private boolean updateCountersAndCheckForConnectingState(int state, int prevState) {
switch (prevState) {
- case BluetoothProfile.STATE_CONNECTING:
+ case STATE_CONNECTING:
if (mProfilesConnecting > 0) {
mProfilesConnecting--;
} else {
@@ -2231,7 +2269,7 @@ public class ScanManager {
"Invalid state transition, " + prevState + " -> " + state);
}
break;
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTED:
if (mProfilesConnected > 0) {
mProfilesConnected--;
} else {
@@ -2240,7 +2278,7 @@ public class ScanManager {
"Invalid state transition, " + prevState + " -> " + state);
}
break;
- case BluetoothProfile.STATE_DISCONNECTING:
+ case STATE_DISCONNECTING:
if (mProfilesDisconnecting > 0) {
mProfilesDisconnecting--;
} else {
@@ -2251,16 +2289,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:
}
@@ -2272,53 +2310,6 @@ public class ScanManager {
return (mProfilesConnecting > 0);
}
- private void handleImportanceChange(UidImportance imp) {
- if (imp == null) {
- return;
- }
- int uid = imp.uid;
- int importance = imp.importance;
- boolean updatedScanParams = false;
- boolean isForeground =
- importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
-
- if (mIsUidForegroundMap.size() < MAX_IS_UID_FOREGROUND_MAP_SIZE) {
- mIsUidForegroundMap.put(uid, isForeground);
- }
-
- for (ScanClient client : mRegularScanClients) {
- if (client.appUid != uid || mScanNative.isOpportunisticScanClient(client)) {
- continue;
- }
- if (isForeground) {
- int scanMode = client.scanModeApp;
- int maxScanMode =
- mScanNative.isForceDowngradedScanClient(client)
- ? SCAN_MODE_FORCE_DOWNGRADED
- : scanMode;
- if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) {
- updatedScanParams = true;
- }
- } else {
- int scanMode = client.settings.getScanMode();
- int maxScanMode =
- mScreenOn ? SCAN_MODE_APP_IN_BACKGROUND : ScanSettings.SCAN_MODE_SCREEN_OFF;
- if (client.updateScanMode(getMinScanMode(scanMode, maxScanMode))) {
- updatedScanParams = true;
- }
- }
- Log.d(
- TAG,
- ("uid " + uid)
- + (" isForeground " + isForeground)
- + (" scanMode " + getScanModeString(client.settings.getScanMode())));
- }
-
- if (updatedScanParams) {
- mScanNative.configureRegularScanParams();
- }
- }
-
private int getMinScanMode(int oldScanMode, int newScanMode) {
return mPriorityMap.get(oldScanMode) <= mPriorityMap.get(newScanMode)
? oldScanMode
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 7f0b1ef7b3..cca760249f 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScanObjectsFactory.java
@@ -83,7 +83,7 @@ public class ScanObjectsFactory {
adapterService, scanController, bluetoothAdapterProxy, looper, getSystemClock());
}
- public PeriodicScanManager createPeriodicScanManager(AdapterService adapterService) {
- return new PeriodicScanManager(adapterService);
+ public PeriodicScanManager createPeriodicScanManager() {
+ return new PeriodicScanManager();
}
}
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 57a9cc53c1..30a7d0ffd8 100644
--- a/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java
+++ b/android/app/src/com/android/bluetooth/le_scan/ScannerMap.java
@@ -19,6 +19,7 @@ import static com.android.bluetooth.Utils.getSystemClock;
import static com.android.bluetooth.util.AttributionSourceUtil.getLastAttributionTag;
import android.annotation.Nullable;
+import android.app.PendingIntent;
import android.bluetooth.le.IScannerCallback;
import android.content.AttributionSource;
import android.os.Binder;
@@ -89,8 +90,8 @@ public class ScannerMap {
int appUid;
String appName = null;
if (piInfo != null) {
- appUid = piInfo.callingUid;
- appName = piInfo.callingPackage;
+ appUid = piInfo.callingUid();
+ appName = piInfo.callingPackage();
} else {
appUid = Binder.getCallingUid();
appName = adapterService.getPackageManager().getNameForUid(appUid);
@@ -184,12 +185,13 @@ public class ScannerMap {
.collect(Collectors.toUnmodifiableList());
}
- /** Get an application context by the pending intent info object. */
- ScannerApp getByPendingIntentInfo(ScanController.PendingIntentInfo info) {
+ /** Get an application context by the pending intent info object's intent. */
+ ScannerApp getByPendingIntentInfo(PendingIntent intent) {
ScannerApp app =
- getAppByPredicate(entry -> entry.mInfo != null && entry.mInfo.equals(info));
+ getAppByPredicate(
+ entry -> entry.mInfo != null && entry.mInfo.intent().equals(intent));
if (app == null) {
- Log.e(TAG, "Context not found for info " + info);
+ Log.e(TAG, "Context not found for intent " + intent);
}
return app;
}
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java
index 10f8c788eb..852ee8375f 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAppObserver.java
@@ -180,7 +180,7 @@ public class BluetoothMapAppObserver {
+ Thread.currentThread().getId()
+ " Uri: "
+ uri
- + " selfchange: "
+ + " selfChange: "
+ selfChange);
if (uri != null) {
handleAccountChanges(uri.getHost());
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java b/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java
index 0e06971960..0ad7618e24 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapAppParams.java
@@ -60,7 +60,7 @@ public class BluetoothMapAppParams {
private static final int STATUS_INDICATOR = 0x17;
private static final int STATUS_VALUE = 0x18;
private static final int MSE_TIME = 0x19;
- private static final int DATABASE_INDETIFIER = 0x1A;
+ private static final int DATABASE_IDENTIFIER = 0x1A;
private static final int CONVO_LIST_VER_COUNTER = 0x1B;
private static final int PRESENCE_AVAILABLE = 0x1C;
private static final int PRESENCE_TEXT = 0x1D;
@@ -97,7 +97,7 @@ public class BluetoothMapAppParams {
private static final int FRACTION_DELIVER_LEN = 0x01; // , 0x0000, 0x0001),
private static final int STATUS_INDICATOR_LEN = 0x01; // , 0x0000, 0x0001),
private static final int STATUS_VALUE_LEN = 0x01; // , 0x0000, 0x0001),
- private static final int DATABASE_INDETIFIER_LEN = 0x10;
+ private static final int DATABASE_IDENTIFIER_LEN = 0x10;
private static final int CONVO_LIST_VER_COUNTER_LEN = 0x10;
private static final int PRESENCE_AVAILABLE_LEN = 0X01;
private static final int CHAT_STATE_LEN = 0x01;
@@ -669,14 +669,14 @@ public class BluetoothMapAppParams {
case MSE_TIME:
setMseTime(new String(appParams, i, tagLength));
break;
- case DATABASE_INDETIFIER:
- if ((tagLength != DATABASE_INDETIFIER_LEN)) {
+ case DATABASE_IDENTIFIER:
+ if ((tagLength != DATABASE_IDENTIFIER_LEN)) {
Log.w(
TAG,
"DATABASE_IDENTIFIER: Wrong length received: "
+ tagLength
+ " expected: "
- + DATABASE_INDETIFIER_LEN);
+ + DATABASE_IDENTIFIER_LEN);
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
BluetoothProtoEnums.BLUETOOTH_MAP_APP_PARAMS,
@@ -1105,8 +1105,8 @@ public class BluetoothMapAppParams {
}
// Note: New for IM
if (getDatabaseIdentifier() != null) {
- appParamBuf.put((byte) DATABASE_INDETIFIER);
- appParamBuf.put((byte) DATABASE_INDETIFIER_LEN);
+ appParamBuf.put((byte) DATABASE_IDENTIFIER);
+ appParamBuf.put((byte) DATABASE_IDENTIFIER_LEN);
appParamBuf.put(getDatabaseIdentifier());
}
if (getConvoListingVerCounter() != null) {
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
index d3d87e660a..6a8d91b839 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapContent.java
@@ -103,7 +103,7 @@ public class BluetoothMapContent {
private static final int CONVO_PARAM_MASK_CONVO_READ_STATUS = 0x00000004;
private static final int CONVO_PARAM_MASK_CONVO_VERSION_COUNTER = 0x00000008;
private static final int CONVO_PARAM_MASK_CONVO_SUMMARY = 0x00000010;
- private static final int CONVO_PARAM_MASK_PARTTICIPANTS = 0x00000020;
+ private static final int CONVO_PARAM_MASK_PARTICIPANTS = 0x00000020;
private static final int CONVO_PARAM_MASK_PART_UCI = 0x00000040;
private static final int CONVO_PARAM_MASK_PART_DISP_NAME = 0x00000080;
private static final int CONVO_PARAM_MASK_PART_CHAT_STATE = 0x00000100;
@@ -121,7 +121,7 @@ public class BluetoothMapContent {
public static final long CONVO_PARAMETER_MASK_ALL_ENABLED = 0xFFFFFFFFL;
public static final long CONVO_PARAMETER_MASK_DEFAULT =
CONVO_PARAM_MASK_CONVO_NAME
- | CONVO_PARAM_MASK_PARTTICIPANTS
+ | CONVO_PARAM_MASK_PARTICIPANTS
| CONVO_PARAM_MASK_PART_UCI
| CONVO_PARAM_MASK_PART_DISP_NAME;
@@ -560,9 +560,9 @@ public class BluetoothMapContent {
} else if (fi.mMsgType == FilterInfo.TYPE_EMAIL || fi.mMsgType == FilterInfo.TYPE_IM) {
read = c.getInt(fi.mMessageColRead);
}
- String setread = null;
+ String setRead = null;
- Log.v(TAG, "setRead: " + setread);
+ Log.v(TAG, "setRead: " + setRead);
e.setRead((read == 1), ((ap.getParameterMask() & MASK_READ) != 0));
}
@@ -1477,17 +1477,17 @@ public class BluetoothMapContent {
*
* @return true if found a match
*/
- private boolean matchRecipientMms(Cursor c, String recip) {
+ private boolean matchRecipientMms(Cursor c, String recipient) {
boolean res;
long id = c.getLong(c.getColumnIndex(BaseColumns._ID));
String phone = getAddressMms(mResolver, id, MMS_TO);
if (phone != null && phone.length() > 0) {
- if (phone.matches(recip)) {
+ if (phone.matches(recipient)) {
Log.v(TAG, "matchRecipientMms: match recipient phone = " + phone);
res = true;
} else {
String name = getContactNameFromPhone(phone, mResolver);
- if (name != null && name.length() > 0 && name.matches(recip)) {
+ if (name != null && name.length() > 0 && name.matches(recipient)) {
Log.v(TAG, "matchRecipientMms: match recipient name = " + name);
res = true;
} else {
@@ -1500,16 +1500,16 @@ public class BluetoothMapContent {
return res;
}
- private boolean matchRecipientSms(Cursor c, FilterInfo fi, String recip) {
+ private boolean matchRecipientSms(Cursor c, FilterInfo fi, String recipient) {
boolean res;
int msgType = c.getInt(c.getColumnIndex(Sms.TYPE));
if (msgType == 1) {
String phone = fi.mPhoneNum;
String name = fi.mPhoneAlphaTag;
- if (phone != null && phone.length() > 0 && phone.matches(recip)) {
+ if (phone != null && phone.length() > 0 && phone.matches(recipient)) {
Log.v(TAG, "matchRecipientSms: match recipient phone = " + phone);
res = true;
- } else if (name != null && name.length() > 0 && name.matches(recip)) {
+ } else if (name != null && name.length() > 0 && name.matches(recipient)) {
Log.v(TAG, "matchRecipientSms: match recipient name = " + name);
res = true;
} else {
@@ -1518,12 +1518,12 @@ public class BluetoothMapContent {
} else {
String phone = c.getString(c.getColumnIndex(Sms.ADDRESS));
if (phone != null && phone.length() > 0) {
- if (phone.matches(recip)) {
+ if (phone.matches(recipient)) {
Log.v(TAG, "matchRecipientSms: match recipient phone = " + phone);
res = true;
} else {
String name = getContactNameFromPhone(phone, mResolver);
- if (name != null && name.length() > 0 && name.matches(recip)) {
+ if (name != null && name.length() > 0 && name.matches(recipient)) {
Log.v(TAG, "matchRecipientSms: match recipient name = " + name);
res = true;
} else {
@@ -1539,14 +1539,14 @@ public class BluetoothMapContent {
private boolean matchRecipient(Cursor c, FilterInfo fi, BluetoothMapAppParams ap) {
boolean res;
- String recip = ap.getFilterRecipient();
- if (recip != null && recip.length() > 0) {
- recip = recip.replace("*", ".*");
- recip = ".*" + recip + ".*";
+ String recipient = ap.getFilterRecipient();
+ if (recipient != null && recipient.length() > 0) {
+ recipient = recipient.replace("*", ".*");
+ recipient = ".*" + recipient + ".*";
if (fi.mMsgType == FilterInfo.TYPE_SMS) {
- res = matchRecipientSms(c, fi, recip);
+ res = matchRecipientSms(c, fi, recipient);
} else if (fi.mMsgType == FilterInfo.TYPE_MMS) {
- res = matchRecipientMms(c, recip);
+ res = matchRecipientMms(c, recipient);
} else {
Log.d(TAG, "matchRecipient: Unknown msg type: " + fi.mMsgType);
res = false;
@@ -1876,24 +1876,24 @@ public class BluetoothMapContent {
private static String setWhereFilterRecipientEmail(BluetoothMapAppParams ap) {
String where = "";
- String recip = ap.getFilterRecipient();
+ String recipient = ap.getFilterRecipient();
/* Be aware of wild cards in the beginning of string, may not be valid? */
- if (recip != null && recip.length() > 0) {
- recip = recip.replace("*", "%");
+ if (recipient != null && recipient.length() > 0) {
+ recipient = recipient.replace("*", "%");
where =
" AND ("
+ BluetoothMapContract.MessageColumns.TO_LIST
+ " LIKE '%"
- + recip
+ + recipient
+ "%' OR "
+ BluetoothMapContract.MessageColumns.CC_LIST
+ " LIKE '%"
- + recip
+ + recipient
+ "%' OR "
+ BluetoothMapContract.MessageColumns.BCC_LIST
+ " LIKE '%"
- + recip
+ + recipient
+ "%' )";
}
return where;
@@ -2412,7 +2412,7 @@ public class BluetoothMapContent {
}
}
- Log.d(TAG, "messagelisting end");
+ Log.d(TAG, "msgListing end");
return bmList;
}
@@ -3028,7 +3028,7 @@ public class BluetoothMapContent {
/**
* Refreshes the entire list of SMS/MMS conversation version counters. Use it to generate a new
- * ConvoListVersinoCounter in mSmsMmsConvoListVersion
+ * ConvoListVersionCounter in mSmsMmsConvoListVersion
*
* @return true if a list change has been detected
*/
@@ -3103,7 +3103,7 @@ public class BluetoothMapContent {
convoElement.setSummary(summary);
}
/* If the query returned one row for each contact, skip all the
- dublicates */
+ duplicates */
do {
nextThreadId = imEmailCursor.getLong(fi.mConvoColConvoId);
Log.v(TAG, " threadId = " + id + " newThreadId = " + nextThreadId);
@@ -3289,7 +3289,7 @@ public class BluetoothMapContent {
ele.setSummary(summary);
}
- if ((parameterMask & CONVO_PARAM_MASK_PARTTICIPANTS) != 0) {
+ if ((parameterMask & CONVO_PARAM_MASK_PARTICIPANTS) != 0) {
if (ap.getFilterRecipient() == null) {
// Add contacts only if not already added
String idsStr = smsMmsCursor.getString(MMS_SMS_THREAD_COL_RECIPIENT_IDS);
@@ -3337,7 +3337,7 @@ public class BluetoothMapContent {
}
// TODO: For optimization, we could avoid joining the contact and convo tables
// if we have no filter nor this bit is set.
- if ((parameterMask & CONVO_PARAM_MASK_PARTTICIPANTS) != 0) {
+ if ((parameterMask & CONVO_PARAM_MASK_PARTICIPANTS) != 0) {
do {
BluetoothMapConvoContactElement c = new BluetoothMapConvoContactElement();
if ((parameterMask & CONVO_PARAM_MASK_PART_X_BT_UID) != 0) {
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java
index 1061ea6714..39f5359392 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapConvoContactElement.java
@@ -195,7 +195,7 @@ public class BluetoothMapConvoContactElement
/* Encode the MapConvoContactElement into the StringBuilder reference.
* Here we have taken the choice not to report empty attributes, to reduce the
- * amount of data to be transfered over BT. */
+ * amount of data to be transferred over BT. */
public void encode(XmlSerializer xmlConvoElement)
throws IllegalArgumentException, IllegalStateException, IOException {
// construct the XML tag for a single contact in the convolisting element.
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
index 578cb4b4c5..cae3eaaf4e 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapMasInstance.java
@@ -90,7 +90,7 @@ public class BluetoothMapMasInstance implements IObexConnectionHandler {
private boolean mEnableSmsMms = false;
BluetoothMapContentObserver mObserver;
private BluetoothMapObexServer mMapServer;
- private AtomicLong mDbIndetifier = new AtomicLong();
+ private AtomicLong mDbIdentifier = new AtomicLong();
private AtomicLong mFolderVersionCounter = new AtomicLong(0);
private AtomicLong mSmsMmsConvoListVersionCounter = new AtomicLong(0);
private AtomicLong mImEmailConvoListVersionCounter = new AtomicLong(0);
@@ -143,7 +143,7 @@ public class BluetoothMapMasInstance implements IObexConnectionHandler {
+ ", SDP handle: "
+ mSdpHandle);
boolean status = nativeInterface.removeSdpRecord(mSdpHandle);
- debug("RemoveSDPrecord returns " + status);
+ debug("RemoveSDPRecord returns " + status);
mSdpHandle = -1;
}
}
@@ -168,7 +168,7 @@ public class BluetoothMapMasInstance implements IObexConnectionHandler {
*/
@SuppressWarnings("JavaUtilDate") // TODO: b/365629730 -- prefer Instant or LocalDate
private void updateDbIdentifier() {
- mDbIndetifier.set(Calendar.getInstance().getTime().getTime());
+ mDbIdentifier.set(Calendar.getInstance().getTime().getTime());
}
/**
@@ -246,7 +246,7 @@ public class BluetoothMapMasInstance implements IObexConnectionHandler {
/* package*/
long getDbIdentifier() {
- return mDbIndetifier.get();
+ return mDbIdentifier.get();
}
/* package*/
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
index 77430eb319..b817750d05 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapObexServer.java
@@ -331,69 +331,46 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
// always assume version 1.0 to start with
mMessageVersion = BluetoothMapUtils.MAP_V10_STR;
notifyUpdateWakeLock();
- Long threadedMailKey = null;
- try {
- byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
- threadedMailKey = (Long) request.getHeader(THREADED_MAIL_HEADER_ID);
- if (uuid == null) {
- return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
- }
- Log.d(TAG, "onConnect(): uuid=" + Arrays.toString(uuid));
+ byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
+ Long threadedMailKey = (Long) request.getHeader(THREADED_MAIL_HEADER_ID);
+ if (uuid == null) {
+ return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
+ }
+ Log.d(TAG, "onConnect(): uuid=" + Arrays.toString(uuid));
- if (uuid.length != UUID_LENGTH) {
- Log.w(TAG, "Wrong UUID length");
+ if (uuid.length != UUID_LENGTH) {
+ Log.w(TAG, "Wrong UUID length");
+ ContentProfileErrorReportUtils.report(
+ BluetoothProfile.MAP,
+ BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
+ BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__LOG_WARN,
+ 0);
+ return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
+ }
+ for (int i = 0; i < UUID_LENGTH; i++) {
+ if (uuid[i] != MAP_TARGET[i]) {
+ Log.w(TAG, "Wrong UUID");
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__LOG_WARN,
- 0);
+ 1);
return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
}
- for (int i = 0; i < UUID_LENGTH; i++) {
- if (uuid[i] != MAP_TARGET[i]) {
- Log.w(TAG, "Wrong UUID");
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.MAP,
- BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
- BluetoothStatsLog
- .BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__LOG_WARN,
- 1);
- return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
- }
- }
- reply.setHeader(HeaderSet.WHO, uuid);
- } catch (IOException e) {
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.MAP,
- BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
- BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
- 2);
- Log.e(TAG, "Exception during onConnect:", e);
- return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
+ reply.setHeader(HeaderSet.WHO, uuid);
- try {
- byte[] remote = (byte[]) request.getHeader(HeaderSet.WHO);
- if (remote != null) {
- Log.d(TAG, "onConnect(): remote=" + Arrays.toString(remote));
- reply.setHeader(HeaderSet.TARGET, remote);
- }
- if (threadedMailKey != null && threadedMailKey.longValue() == THREAD_MAIL_KEY) {
- /* If the client provides the correct key we enable threaded e-mail support
- * and reply to the client that we support the requested feature.
- * This is currently an Android only feature. */
- mThreadIdSupport = true;
- reply.setHeader(THREADED_MAIL_HEADER_ID, THREAD_MAIL_KEY);
- }
- } catch (IOException e) {
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.MAP,
- BluetoothProtoEnums.BLUETOOTH_MAP_OBEX_SERVER,
- BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
- 3);
- Log.e(TAG, "Exception during onConnect:", e);
- mThreadIdSupport = false;
- return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+ byte[] remote = (byte[]) request.getHeader(HeaderSet.WHO);
+ if (remote != null) {
+ Log.d(TAG, "onConnect(): remote=" + Arrays.toString(remote));
+ reply.setHeader(HeaderSet.TARGET, remote);
+ }
+ if (threadedMailKey != null && threadedMailKey.longValue() == THREAD_MAIL_KEY) {
+ /* If the client provides the correct key we enable threaded e-mail support
+ * and reply to the client that we support the requested feature.
+ * This is currently an Android only feature. */
+ mThreadIdSupport = true;
+ reply.setHeader(THREADED_MAIL_HEADER_ID, THREAD_MAIL_KEY);
}
if ((mRemoteFeatureMask & BluetoothMapUtils.MAP_FEATURE_MESSAGE_LISTING_FORMAT_V11_BIT)
@@ -498,7 +475,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
+ appParams.getStatusIndicator()
+ ", StatusValue: "
+ appParams.getStatusValue()
- + ", ExtentedData: "); // TODO: appParams.getExtendedImData());
+ + ", ExtendedData: "); // TODO: appParams.getExtendedImData());
if (!isUserUnlocked()) {
Log.e(TAG, "Storage locked, " + type + " failed");
ContentProfileErrorReportUtils.report(
@@ -513,7 +490,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
} else if (type.equals(TYPE_MESSAGE)) {
Log.v(
TAG,
- "TYPE_MESSAGE: Transparet: "
+ "TYPE_MESSAGE: Transparent: "
+ appParams.getTransparent()
+ ", retry: "
+ appParams.getRetry()
@@ -1209,7 +1186,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
if (appParams != null) {
Log.v(
TAG,
- "TYPE_MESSAGE (GET): MASInstandeId = " + appParams.getMasInstanceId());
+ "TYPE_MESSAGE (GET): MASInstanceId = " + appParams.getMasInstanceId());
}
// Block until all packets have been send.
return sendMASInstanceInformationRsp(op, appParams);
@@ -1307,8 +1284,8 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
}
/* MAP Spec 1.3 introduces the following
- * Messagehandle filtering:
- * msgListing (messageHandle=X) -> other allowed filters: parametereMask, subjectMaxLength
+ * messageHandle filtering:
+ * msgListing (messageHandle=X) -> other allowed filters: parameterMask, subjectMaxLength
* ConversationID filtering:
* msgListing (convoId empty) -> should work as normal msgListing in valid folders
* msgListing (convoId=0, no other filters) -> should return all messages in all folders
@@ -1386,8 +1363,8 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
} else {
outAppParams.setNewMessage(0);
}
- if ((mRemoteFeatureMask & BluetoothMapUtils.MAP_FEATURE_DATABASE_INDENTIFIER_BIT)
- == BluetoothMapUtils.MAP_FEATURE_DATABASE_INDENTIFIER_BIT) {
+ if ((mRemoteFeatureMask & BluetoothMapUtils.MAP_FEATURE_DATABASE_IDENTIFIER_BIT)
+ == BluetoothMapUtils.MAP_FEATURE_DATABASE_IDENTIFIER_BIT) {
outAppParams.setDatabaseIdentifier(0, mMasInstance.getDbIdentifier());
}
if ((mRemoteFeatureMask & BluetoothMapUtils.MAP_FEATURE_FOLDER_VERSION_COUNTER_BIT)
@@ -1946,7 +1923,7 @@ public class BluetoothMapObexServer extends ServerRequestHandler {
/* Ensure byte array max length is 200 containing valid UTF-8 characters */
outBytes =
- BluetoothMapUtils.truncateUtf8StringToBytearray(
+ BluetoothMapUtils.truncateUtf8StringToByteArray(
outString, MAS_INSTANCE_INFORMATION_LENGTH);
// Open the OBEX body stream
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
index d1850815b0..456e052470 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapService.java
@@ -17,6 +17,10 @@ package com.android.bluetooth.map;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -504,7 +508,7 @@ public class BluetoothMapService extends ProfileService {
BluetoothStatsLog
.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
4);
- Log.e(TAG, "ContentObserverRegistarion Failed: " + e);
+ Log.e(TAG, "ContentObserverRegistration Failed: " + e);
}
}
break;
@@ -648,9 +652,9 @@ public class BluetoothMapService extends ProfileService {
if (getState() == BluetoothMap.STATE_CONNECTED
&& getRemoteDevice() != null
&& getRemoteDevice().equals(device)) {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
} else {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
}
@@ -678,7 +682,7 @@ public class BluetoothMapService extends ProfileService {
device, BluetoothProfile.MAP, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -1276,7 +1280,7 @@ public class BluetoothMapService extends ProfileService {
return false;
}
- return service.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
+ return service.getConnectionState(device) == STATE_CONNECTED;
} catch (RuntimeException e) {
ContentProfileErrorReportUtils.report(
BluetoothProfile.MAP,
@@ -1356,7 +1360,7 @@ public class BluetoothMapService extends ProfileService {
try {
BluetoothMapService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -1395,7 +1399,7 @@ public class BluetoothMapService extends ProfileService {
try {
BluetoothMapService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
return service.getConnectionPolicy(device);
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java
index b22065ac28..04f9d0a2d1 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapSmsPdu.java
@@ -647,7 +647,7 @@ public class BluetoothMapSmsPdu {
// We could verify that the address-length is no longer than 11 bytes
if (addressLength >= data.length) {
throw new IllegalArgumentException(
- "Length of address exeeds the length of the PDU data.");
+ "Length of address exceeds the length of the PDU data.");
}
int pduLength = data.length - (1 + addressLength);
byte[] newData = new byte[pduLength];
@@ -847,14 +847,14 @@ public class BluetoothMapSmsPdu {
}
private static class SmsConstants {
- /** User data text encoding code unit size */
+ // User data text encoding code unit size
public static final int ENCODING_UNKNOWN = 0;
public static final int ENCODING_7BIT = 1;
public static final int ENCODING_8BIT = 2;
public static final int ENCODING_16BIT = 3;
- /** This value is not defined in global standard. Only in Korea, this is used. */
+ // This value is not defined in global standard. Only in Korea, this is used.
public static final int ENCODING_KSC5601 = 4;
}
}
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java b/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java
index 7fdc6601fb..bbb5f2ee11 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapUtils.java
@@ -80,7 +80,7 @@ public class BluetoothMapUtils {
static final int MAP_FEATURE_MESSAGE_FORMAT_V11_BIT = 1 << 8;
static final int MAP_FEATURE_MESSAGE_LISTING_FORMAT_V11_BIT = 1 << 9;
static final int MAP_FEATURE_PERSISTENT_MESSAGE_HANDLE_BIT = 1 << 10;
- static final int MAP_FEATURE_DATABASE_INDENTIFIER_BIT = 1 << 11;
+ static final int MAP_FEATURE_DATABASE_IDENTIFIER_BIT = 1 << 11;
static final int MAP_FEATURE_FOLDER_VERSION_COUNTER_BIT = 1 << 12;
static final int MAP_FEATURE_CONVERSATION_VERSION_COUNTER_BIT = 1 << 13;
static final int MAP_FEATURE_PARTICIPANT_PRESENCE_CHANGE_BIT = 1 << 14;
@@ -424,7 +424,7 @@ public class BluetoothMapUtils {
* @param maxLength Max length of byte array returned including null termination
* @return byte array containing valid utf8 characters with max length
*/
- public static byte[] truncateUtf8StringToBytearray(String utf8String, int maxLength) {
+ public static byte[] truncateUtf8StringToByteArray(String utf8String, int maxLength) {
byte[] utf8Bytes = new byte[utf8String.length() + 1];
System.arraycopy(
@@ -465,7 +465,7 @@ public class BluetoothMapUtils {
if (utf8InBytes.length <= maxBytesLength) {
return utf8InString;
}
- // Create a buffer that wildly truncate at desired lengtht.
+ // Create a buffer that wildly truncate at desired length.
// It may contain invalid utf-8 char.
ByteBuffer truncatedString = ByteBuffer.wrap(utf8InBytes, 0, maxBytesLength);
CharBuffer validUtf8Buffer = CharBuffer.allocate(maxBytesLength);
@@ -684,7 +684,7 @@ public class BluetoothMapUtils {
/**
* Encodes an array of bytes into an array of quoted-printable 7-bit characters. Unsafe
- * characters are escaped. Simplified version of encoder from QuetedPrintableCodec.java (Apache
+ * characters are escaped. Simplified version of encoder from QuotedPrintableCodec.java (Apache
* external)
*
* @param bytes array of bytes to be encoded
diff --git a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java
index a93f85dd3b..cc1ac4f7cd 100644
--- a/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java
+++ b/android/app/src/com/android/bluetooth/map/BluetoothMapbMessageMime.java
@@ -176,7 +176,7 @@ public class BluetoothMapbMessageMime extends BluetoothMapbMessage {
private ArrayList<MimePart> mParts = null;
private String mContentType = null;
private String mBoundary = null;
- private boolean mTextonly = false;
+ private boolean mTextOnly = false;
private boolean mIncludeAttachments;
private String mMyEncoding = null;
@@ -349,11 +349,11 @@ public class BluetoothMapbMessageMime extends BluetoothMapbMessage {
}
public void setTextOnly(boolean textOnly) {
- this.mTextonly = textOnly;
+ this.mTextOnly = textOnly;
}
public boolean getTextOnly() {
- return mTextonly;
+ return mTextOnly;
}
public void setIncludeAttachments(boolean includeAttachments) {
diff --git a/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java b/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java
index 62bd674145..053d5c8d95 100644
--- a/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java
+++ b/android/app/src/com/android/bluetooth/map/SmsMmsContacts.java
@@ -75,7 +75,7 @@ public class SmsMmsContacts {
* Get a contacts phone number based on the canonical addresses id of the contact. (The ID
* listed in the Threads table.)
*
- * @param resolver the ContantResolver to be used.
+ * @param resolver the ContentResolver to be used.
* @param id the id of the contact, as listed in the Threads table
* @return the phone number of the contact - or null if id does not exist.
*/
@@ -128,7 +128,7 @@ public class SmsMmsContacts {
* Refreshes the cache, by clearing all cached values and fill the cache with the result of a
* new query.
*
- * @param resolver the ContantResolver to be used.
+ * @param resolver the ContentResolver to be used.
*/
@VisibleForTesting
void fillPhoneCache(ContentResolver resolver) {
diff --git a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
index 506c2a3bb7..5e2be59b11 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MapClientService.java
@@ -18,6 +18,12 @@ package com.android.bluetooth.mapclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
import static java.util.Objects.requireNonNullElseGet;
@@ -134,7 +140,7 @@ public class MapClientService extends ProfileService {
throw new IllegalArgumentException("Null device");
}
Log.d(TAG, "connect(device= " + device + "): devices=" + mMapInstanceMap.keySet());
- if (getConnectionPolicy(device) == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) == CONNECTION_POLICY_FORBIDDEN) {
Log.w(
TAG,
"Connection not allowed: <"
@@ -166,17 +172,16 @@ public class MapClientService extends ProfileService {
}
}
- // statemachine already exists in the map.
+ // 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;
}
- // Statemachine exists but not in connecting or connected state! it should
+ // StateMachine exists but not in connecting or connected state! it should
// have been removed form the map. lets get rid of it and add a new one.
- Log.d(TAG, "Statemachine exists for a device in unexpected state: " + state);
+ Log.d(TAG, "StateMachine exists for a device in unexpected state: " + state);
mMapInstanceMap.remove(device);
mapStateMachine.doQuit();
@@ -186,7 +191,7 @@ public class MapClientService extends ProfileService {
}
private synchronized void addDeviceToMapAndConnect(BluetoothDevice device) {
- // When creating a new statemachine, its state is set to CONNECTING - which will trigger
+ // When creating a new StateMachine, its state is set to CONNECTING - which will trigger
// connect.
MceStateMachine mapStateMachine;
if (mStateMachinesLooper != null) {
@@ -206,8 +211,7 @@ public class MapClientService extends ProfileService {
return false;
}
int connectionState = mapStateMachine.getState();
- if (connectionState != BluetoothProfile.STATE_CONNECTED
- && connectionState != BluetoothProfile.STATE_CONNECTING) {
+ if (connectionState != STATE_CONNECTED && connectionState != STATE_CONNECTING) {
return false;
}
mapStateMachine.disconnect();
@@ -244,9 +248,7 @@ public class MapClientService extends ProfileService {
public synchronized int getConnectionState(BluetoothDevice device) {
MceStateMachine mapStateMachine = mMapInstanceMap.get(device);
// a map state machine instance doesn't exist yet, create a new one if we can.
- return (mapStateMachine == null)
- ? BluetoothProfile.STATE_DISCONNECTED
- : mapStateMachine.getState();
+ return (mapStateMachine == null) ? STATE_DISCONNECTED : mapStateMachine.getState();
}
/**
@@ -270,9 +272,9 @@ public class MapClientService extends ProfileService {
device, BluetoothProfile.MAP_CLIENT, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -359,7 +361,7 @@ public class MapClientService extends ProfileService {
while (iterator.hasNext()) {
Map.Entry<BluetoothDevice, MceStateMachine> profileConnection =
(Map.Entry) iterator.next();
- if (profileConnection.getValue().getState() == BluetoothProfile.STATE_DISCONNECTED) {
+ if (profileConnection.getValue().getState() == STATE_DISCONNECTED) {
iterator.remove();
}
}
@@ -518,7 +520,7 @@ public class MapClientService extends ProfileService {
MapClientService service = getServiceAndEnforcePrivileged(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -543,7 +545,7 @@ public class MapClientService extends ProfileService {
MapClientService service = getServiceAndEnforcePrivileged(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
return service.getConnectionPolicy(device);
@@ -579,7 +581,7 @@ public class MapClientService extends ProfileService {
private void handleAclDisconnected(BluetoothDevice device, int transport) {
MceStateMachine stateMachine = mMapInstanceMap.get(device);
if (stateMachine == null) {
- Log.e(TAG, "No Statemachine found for the device=" + device);
+ Log.e(TAG, "No StateMachine found for the device=" + device);
return;
}
@@ -591,7 +593,7 @@ public class MapClientService extends ProfileService {
return;
}
- if (stateMachine.getState() == BluetoothProfile.STATE_CONNECTED) {
+ if (stateMachine.getState() == STATE_CONNECTED) {
stateMachine.disconnect();
}
}
@@ -606,7 +608,7 @@ public class MapClientService extends ProfileService {
MceStateMachine stateMachine = mMapInstanceMap.get(device);
Log.d(TAG, "Received SDP Record, device=" + device + ", uuid=" + uuid);
if (stateMachine == null) {
- Log.e(TAG, "No Statemachine found for the device=" + device);
+ Log.e(TAG, "No StateMachine found for the device=" + device);
return;
}
if (uuid.equals(BluetoothUuid.MAS)) {
diff --git a/android/app/src/com/android/bluetooth/mapclient/MasClient.java b/android/app/src/com/android/bluetooth/mapclient/MasClient.java
index 864bc46cd9..09072876f3 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MasClient.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MasClient.java
@@ -117,7 +117,7 @@ public class MasClient {
} else {
Log.d(
TAG,
- "Connecting to OBEX on RFCOM channel "
+ "Connecting to OBEX on RFCOMM channel "
+ mSdpMasRecord.getRfcommCannelNumber());
mSocket = mRemoteDevice.createRfcommSocket(mSdpMasRecord.getRfcommCannelNumber());
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
index 057823fa5c..f5f53a7378 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MceStateMachine.java
@@ -41,6 +41,10 @@ package com.android.bluetooth.mapclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.RECEIVE_SMS;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
@@ -165,8 +169,8 @@ class MceStateMachine extends StateMachine {
private final AdapterService mAdapterService;
// Connectivity States
- private int mPreviousState = BluetoothProfile.STATE_DISCONNECTED;
- private int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mPreviousState = STATE_DISCONNECTED;
+ private int mMostRecentState = STATE_DISCONNECTED;
private MasClient mMasClient;
private MapClientContent mDatabase;
@@ -266,8 +270,7 @@ class MceStateMachine extends StateMachine {
}
private void initStateMachine() {
- mPreviousState = BluetoothProfile.STATE_DISCONNECTED;
-
+ mPreviousState = STATE_DISCONNECTED;
addState(mDisconnected);
addState(mConnecting);
@@ -307,7 +310,7 @@ class MceStateMachine extends StateMachine {
+ prevState
+ ", new="
+ state);
- if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) {
+ if (prevState != state && state == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.MAP_CLIENT);
}
setState(state);
@@ -360,7 +363,7 @@ class MceStateMachine extends StateMachine {
if (contacts == null || contacts.length <= 0) {
return false;
}
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
+ if (mMostRecentState == STATE_CONNECTED) {
Bmessage bmsg = new Bmessage();
// Set type and status.
bmsg.setType(getDefaultMessageType());
@@ -413,7 +416,7 @@ class MceStateMachine extends StateMachine {
synchronized boolean getMessage(String handle) {
Log.d(TAG, "getMessage" + handle);
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
+ if (mMostRecentState == STATE_CONNECTED) {
sendMessage(MSG_INBOUND_MESSAGE, handle);
return true;
}
@@ -422,7 +425,7 @@ class MceStateMachine extends StateMachine {
synchronized boolean getUnreadMessages() {
Log.d(TAG, "getMessage");
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
+ if (mMostRecentState == STATE_CONNECTED) {
sendMessage(MSG_GET_MESSAGE_LISTING, FOLDER_INBOX);
return true;
}
@@ -430,7 +433,7 @@ class MceStateMachine extends StateMachine {
}
synchronized int getSupportedFeatures() {
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTED && mMasClient != null) {
+ if (mMostRecentState == STATE_CONNECTED && mMasClient != null) {
Log.d(TAG, "returning getSupportedFeatures from SDP record");
return mMasClient.getSdpMasRecord().getSupportedFeatures();
}
@@ -440,7 +443,7 @@ class MceStateMachine extends StateMachine {
synchronized boolean setMessageStatus(String handle, int status) {
Log.d(TAG, "setMessageStatus(" + handle + ", " + status + ")");
- if (mMostRecentState == BluetoothProfile.STATE_CONNECTED) {
+ if (mMostRecentState == STATE_CONNECTED) {
RequestSetMessageStatus.StatusIndicator statusIndicator;
byte value;
switch (status) {
@@ -536,14 +539,14 @@ class MceStateMachine extends StateMachine {
Utils.getLoggableAddress(mDevice)
+ " [Disconnected]: Entered, message="
+ getMessageName(getCurrentMessage().what));
- onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTED);
- mPreviousState = BluetoothProfile.STATE_DISCONNECTED;
+ onConnectionStateChanged(mPreviousState, STATE_DISCONNECTED);
+ mPreviousState = STATE_DISCONNECTED;
quit();
}
@Override
public void exit() {
- mPreviousState = BluetoothProfile.STATE_DISCONNECTED;
+ mPreviousState = STATE_DISCONNECTED;
}
}
@@ -555,7 +558,7 @@ class MceStateMachine extends StateMachine {
Utils.getLoggableAddress(mDevice)
+ " [Connecting]: Entered, message="
+ getMessageName(getCurrentMessage().what));
- onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTING);
+ onConnectionStateChanged(mPreviousState, STATE_CONNECTING);
// When commanded to connect begin SDP to find the MAS server.
mDevice.sdpSearch(BluetoothUuid.MAS);
@@ -646,7 +649,7 @@ class MceStateMachine extends StateMachine {
@Override
public void exit() {
- mPreviousState = BluetoothProfile.STATE_CONNECTING;
+ mPreviousState = STATE_CONNECTING;
removeMessages(MSG_CONNECTING_TIMEOUT);
}
}
@@ -671,7 +674,7 @@ class MceStateMachine extends StateMachine {
if (mDatabase == null) {
mDatabase = new MapClientContent(mService, callbacks, mDevice);
}
- onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_CONNECTED);
+ onConnectionStateChanged(mPreviousState, STATE_CONNECTED);
if (Utils.isPtsTestMode()) return;
mMasClient.makeRequest(new RequestSetPath(FOLDER_TELECOM));
@@ -862,7 +865,7 @@ class MceStateMachine extends StateMachine {
public void exit() {
mDatabase.cleanUp();
mDatabase = null;
- mPreviousState = BluetoothProfile.STATE_CONNECTED;
+ mPreviousState = STATE_CONNECTED;
}
/**
@@ -1272,7 +1275,7 @@ class MceStateMachine extends StateMachine {
+ " [Disconnecting]: Entered, message="
+ getMessageName(getCurrentMessage().what));
- onConnectionStateChanged(mPreviousState, BluetoothProfile.STATE_DISCONNECTING);
+ onConnectionStateChanged(mPreviousState, STATE_DISCONNECTING);
if (mMasClient != null) {
mMasClient.makeRequest(new RequestSetNotificationRegistration(false));
@@ -1316,7 +1319,7 @@ class MceStateMachine extends StateMachine {
@Override
public void exit() {
- mPreviousState = BluetoothProfile.STATE_DISCONNECTING;
+ mPreviousState = STATE_DISCONNECTING;
removeMessages(MSG_DISCONNECTING_TIMEOUT);
}
}
diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java b/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
index e72cca015c..69e0baaae4 100644
--- a/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
+++ b/android/app/src/com/android/bluetooth/mapclient/MnsObexServer.java
@@ -66,15 +66,9 @@ class MnsObexServer extends ServerRequestHandler {
public int onConnect(final HeaderSet request, HeaderSet reply) {
Log.v(TAG, "onConnect");
- try {
- byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
- if (!Arrays.equals(uuid, MNS_TARGET)) {
- return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
- }
- } catch (IOException e) {
- // this should never happen since getHeader won't throw exception it
- // declares to throw
- return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+ byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
+ if (!Arrays.equals(uuid, MNS_TARGET)) {
+ return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
}
reply.setHeader(HeaderSet.WHO, MNS_TARGET);
diff --git a/android/app/src/com/android/bluetooth/mapclient/MnsService.java b/android/app/src/com/android/bluetooth/mapclient/MnsService.java
index 99cee09481..1b5b9451b8 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;
@@ -118,15 +119,15 @@ public class MnsService {
if (stateMachine == null) {
Log.e(
TAG,
- "Error: NO statemachine for device: "
+ "Error: NO StateMachine for device: "
+ device
+ " (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: "
+ "Error: StateMachine for device: "
+ device
+ " (name: "
+ Utils.getName(device)
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 5d425d0864..9cae8b30da 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestGetMessage.java
@@ -99,12 +99,7 @@ class RequestGetMessage extends Request {
}
public String getHandle() {
- try {
- return (String) mHeaderSet.getHeader(HeaderSet.NAME);
- } catch (IOException e) {
- Log.e(TAG, "Unexpected exception while reading handle!", e);
- return null;
- }
+ return (String) mHeaderSet.getHeader(HeaderSet.NAME);
}
@Override
diff --git a/android/app/src/com/android/bluetooth/mapclient/obex/RequestPushMessage.java b/android/app/src/com/android/bluetooth/mapclient/obex/RequestPushMessage.java
index de8f7edaa1..b115c77795 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestPushMessage.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestPushMessage.java
@@ -65,8 +65,6 @@ public class RequestPushMessage extends Request {
}
} catch (NumberFormatException e) {
mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
- } catch (IOException e) {
- mResponseCode = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
}
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 73c7193b21..01af11c80e 100644
--- a/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java
+++ b/android/app/src/com/android/bluetooth/mapclient/obex/RequestSetMessageStatus.java
@@ -16,7 +16,6 @@
package com.android.bluetooth.mapclient;
-import android.util.Log;
import com.android.bluetooth.ObexAppParameters;
import com.android.obex.ClientSession;
@@ -61,12 +60,7 @@ final class RequestSetMessageStatus extends Request {
}
public String getHandle() {
- try {
- return (String) mHeaderSet.getHeader(HeaderSet.NAME);
- } catch (IOException e) {
- Log.e(TAG, "Unexpected exception while reading handle!", e);
- return null;
- }
+ return (String) mHeaderSet.getHeader(HeaderSet.NAME);
}
@Override
diff --git a/android/app/src/com/android/bluetooth/mcp/McpService.java b/android/app/src/com/android/bluetooth/mcp/McpService.java
index a011fe26c4..c0ba4f12bb 100644
--- a/android/app/src/com/android/bluetooth/mcp/McpService.java
+++ b/android/app/src/com/android/bluetooth/mcp/McpService.java
@@ -18,9 +18,9 @@
package com.android.bluetooth.mcp;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothMcpServiceManager;
import android.content.AttributionSource;
import android.content.Context;
@@ -180,8 +180,7 @@ public class McpService extends ProfileService {
return BluetoothDevice.ACCESS_UNKNOWN;
}
- if (leAudioService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (leAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.d(TAG, "MCS authorization allowed based on supported LeAudio service");
setDeviceAuthorized(device, true);
return BluetoothDevice.ACCESS_ALLOWED;
diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
index 0be28709f0..7de6296193 100644
--- a/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
+++ b/android/app/src/com/android/bluetooth/mcp/MediaControlGattService.java
@@ -23,6 +23,8 @@ import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_NOTIFY;
import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_READ;
import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE;
import static android.bluetooth.BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -935,7 +937,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface
BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
- if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (newState == STATE_DISCONNECTED) {
ClearUnauthorizedGattOperations(device);
}
}
@@ -1259,7 +1261,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface
public boolean isDeviceConnected(BluetoothDevice device) {
return mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT_SERVER)
- == BluetoothProfile.STATE_CONNECTED;
+ == STATE_CONNECTED;
}
}
@@ -2096,7 +2098,7 @@ public class MediaControlGattService implements MediaControlGattServiceInterface
public long byteArray2ObjId(byte[] buffer) {
ByteBuffer bb = ByteBuffer.allocate(Long.BYTES).order(ByteOrder.LITTLE_ENDIAN);
bb.put(buffer, 0, 6);
- // Move position to beginnng after putting data to buffer
+ // Move position to beginning after putting data to buffer
bb.position(0);
return bb.getLong();
}
diff --git a/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java b/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
index 96028d8840..86eaabfd69 100644
--- a/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
+++ b/android/app/src/com/android/bluetooth/mcp/MediaControlProfile.java
@@ -82,7 +82,7 @@ public class MediaControlProfile implements MediaControlServiceCallbacks {
// MCP service instance
private MediaControlGattServiceInterface mGMcsService;
- // MCP Service requests for stete fields needed to fill the characteristic values
+ // MCP Service requests for state fields needed to fill the characteristic values
private List<PlayerStateField> mPendingStateRequest;
private MediaPlayerWrapper mLastActivePlayer = null;
@@ -99,7 +99,7 @@ public class MediaControlProfile implements MediaControlServiceCallbacks {
@VisibleForTesting
long getCurrentPlayerSupportedActions() {
- // Notice: Stay compatible with the currently hard-codded ACRVP supported player features
+ // Notice: Stay compatible with the currently hard-codded AVRCP supported player features
if (mCurrentData != null && mCurrentData.state != null) {
return Long.valueOf(mCurrentData.state.getActions() | BASE_PLAYER_ACTION_SET);
}
diff --git a/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
index b81187604a..a9a7d9a408 100644
--- a/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
+++ b/android/app/src/com/android/bluetooth/notification/NotificationHelperService.java
@@ -173,7 +173,7 @@ public class NotificationHelperService extends Service {
// * … 1 week since the first display (aka recurring only once)
// * … 6 months since the last display (aka recurring forever)
//
- // Comparison is +/- 1 hour, allowing for both battery optimisation and consistency
+ // Comparison is +/- 1 hour, allowing for both battery optimization and consistency
if (date != null) {
savedDate = LocalDateTime.parse(date);
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivity.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivity.java
index 58255a4d5b..e871cbb684 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivity.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppBtEnableActivity.java
@@ -80,7 +80,7 @@ public class BluetoothOppBtEnableActivity extends AlertActivity {
}
private void onEnableBluetooth() {
- mOppManager.enableBluetooth(); // this is an asyn call
+ mOppManager.enableBluetooth(); // this is an async call
mOppManager.mSendingFlag = true;
Toast.makeText(this, getString(R.string.enabling_progress_content), Toast.LENGTH_SHORT)
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java
index fda2697750..a6110ffc1f 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppManager.java
@@ -190,7 +190,7 @@ public class BluetoothOppManager {
mAcceptlist.add(new Pair<String, Long>(address, SystemClock.elapsedRealtime()));
}
- public synchronized boolean isAcceptlisted(String address) {
+ public synchronized boolean isAcceptListed(String address) {
cleanupAcceptlist();
for (Pair<String, Long> entry : mAcceptlist) {
if (entry.first.equals(address)) {
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
index 8e5a95ffd7..5279c78f6d 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppNotification.java
@@ -362,7 +362,7 @@ class BluetoothOppNotification {
+ item.id
+ "; batchID="
+ batchID
- + "; totoalCurrent"
+ + "; totalCurrent"
+ item.totalCurrent
+ "; totalTotal="
+ item.totalTotal);
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
index 1b2e0a15fd..6581c63644 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexClientSession.java
@@ -714,7 +714,7 @@ public class BluetoothOppObexClientSession implements BluetoothOppObexSession {
return;
}
if (address.startsWith("00:04:48")) {
- // Poloroid Pogo
+ // Polaroid Pogo
// Rejects filenames with more than one '.'. Rename to '_'.
// for example: 'a.b.jpg' -> 'a_b.jpg'
// 'abc.jpg' NOT CHANGED
@@ -740,7 +740,7 @@ public class BluetoothOppObexClientSession implements BluetoothOppObexSession {
+ filename
+ "\" as \""
+ newFilename
- + "\" to workaround Poloroid filename quirk");
+ + "\" to workaround Polaroid filename quirk");
}
}
}
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java
index 17a7bdae36..9031df5c7d 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppObexServerSession.java
@@ -185,8 +185,8 @@ public class BluetoothOppObexServerSession extends ServerRequestHandler
} else {
destination = "FF:FF:FF:00:00:00";
}
- boolean isAcceptlisted =
- BluetoothOppManager.getInstance(mContext).isAcceptlisted(destination);
+ boolean isAcceptListed =
+ BluetoothOppManager.getInstance(mContext).isAcceptListed(destination);
HeaderSet request;
String name, mimeType;
@@ -262,7 +262,7 @@ public class BluetoothOppObexServerSession extends ServerRequestHandler
// Reject anything outside the "acceptlist" plus unspecified MIME Types.
if (mimeType == null
- || (!isAcceptlisted
+ || (!isAcceptListed
&& !Constants.mimeTypeMatches(
mimeType, Constants.ACCEPTABLE_SHARE_INBOUND_TYPES))) {
Log.w(TAG, "mimeType is null or in unacceptable list, reject the transfer");
@@ -291,7 +291,7 @@ public class BluetoothOppObexServerSession extends ServerRequestHandler
BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED);
}
- if (isAcceptlisted) {
+ if (isAcceptListed) {
values.put(
BluetoothShare.USER_CONFIRMATION,
BluetoothShare.USER_CONFIRMATION_HANDOVER_CONFIRMED);
@@ -620,31 +620,20 @@ public class BluetoothOppObexServerSession extends ServerRequestHandler
Log.d(TAG, "onConnect");
Constants.logHeader(request);
- Long objectCount = null;
- try {
- byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
- Log.v(TAG, "onConnect(): uuid =" + Arrays.toString(uuid));
- if (uuid != null) {
- return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
- }
-
- objectCount = (Long) request.getHeader(HeaderSet.COUNT);
- } catch (IOException e) {
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.OPP,
- BluetoothProtoEnums.BLUETOOTH_OPP_OBEX_SERVER_SESSION,
- BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
- 14);
- Log.e(TAG, e.toString());
- return ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
+ byte[] uuid = (byte[]) request.getHeader(HeaderSet.TARGET);
+ Log.v(TAG, "onConnect(): uuid =" + Arrays.toString(uuid));
+ if (uuid != null) {
+ return ResponseCodes.OBEX_HTTP_NOT_ACCEPTABLE;
}
+
+ Long objectCount = (Long) request.getHeader(HeaderSet.COUNT);
String destination;
if (mTransport instanceof BluetoothObexTransport) {
destination = ((BluetoothObexTransport) mTransport).getRemoteAddress();
} else {
destination = "FF:FF:FF:00:00:00";
}
- boolean isHandover = BluetoothOppManager.getInstance(mContext).isAcceptlisted(destination);
+ boolean isHandover = BluetoothOppManager.getInstance(mContext).isAcceptListed(destination);
if (isHandover) {
// Notify the handover requester file transfer has started
Intent intent = new Intent(Constants.ACTION_HANDOVER_STARTED);
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java
index 13dc28f2a2..6164cb4f58 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppPreference.java
@@ -126,7 +126,7 @@ public class BluetoothOppPreference {
String brEdrAddress = getBrEdrAddress(remoteDevice);
Log.v(
TAG,
- "Setname for " + BluetoothUtils.toAnonymizedAddress(brEdrAddress) + " to " + name);
+ "setName for " + BluetoothUtils.toAnonymizedAddress(brEdrAddress) + " to " + name);
if (name != null && !name.equals(getName(remoteDevice))) {
Editor ed = mNamePreference.edit();
ed.putString(brEdrAddress, name);
@@ -138,7 +138,7 @@ public class BluetoothOppPreference {
public void setChannel(BluetoothDevice remoteDevice, int uuid, int channel) {
Log.v(
TAG,
- "Setchannel for "
+ "setChannel for "
+ BluetoothUtils.toAnonymizedAddress(getBrEdrAddress(remoteDevice))
+ "_"
+ Integer.toHexString(uuid)
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java
index d0c0d660a3..55004bbd1d 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppReceiveFileInfo.java
@@ -126,7 +126,7 @@ public class BluetoothOppReceiveFileInfo {
return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_ERROR_NO_SDCARD);
}
- String filename = choosefilename(hint);
+ String filename = chooseFilename(hint);
if (filename == null) {
// should not happen. It must be pre-rejected
return new BluetoothOppReceiveFileInfo(BluetoothShare.STATUS_FILE_ERROR);
@@ -157,21 +157,21 @@ public class BluetoothOppReceiveFileInfo {
Log.i(Constants.TAG, " File Name Length :" + filename.length());
Log.i(Constants.TAG, " File Name Length in Bytes:" + filename.getBytes().length);
- byte[] oldfilename = filename.getBytes(StandardCharsets.UTF_8);
- byte[] newfilename = new byte[OPP_LENGTH_OF_FILE_NAME];
- System.arraycopy(oldfilename, 0, newfilename, 0, OPP_LENGTH_OF_FILE_NAME);
- filename = new String(newfilename, StandardCharsets.UTF_8);
+ byte[] oldFilename = filename.getBytes(StandardCharsets.UTF_8);
+ byte[] newFilename = new byte[OPP_LENGTH_OF_FILE_NAME];
+ System.arraycopy(oldFilename, 0, newFilename, 0, OPP_LENGTH_OF_FILE_NAME);
+ filename = new String(newFilename, StandardCharsets.UTF_8);
Log.d(Constants.TAG, "File name is too long. Name is truncated as: " + filename);
}
DateFormat dateFormat = new SimpleDateFormat("_hhmmss");
String currentTime = dateFormat.format(Calendar.getInstance().getTime());
- String fullfilename = filename + currentTime + extension;
+ String fullFilename = filename + currentTime + extension;
- Log.v(Constants.TAG, "Generated received filename " + fullfilename);
+ Log.v(Constants.TAG, "Generated received filename " + fullFilename);
ContentValues mediaContentValues = new ContentValues();
- mediaContentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fullfilename);
+ mediaContentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, fullFilename);
mediaContentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);
mediaContentValues.put(
MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
@@ -183,7 +183,7 @@ public class BluetoothOppReceiveFileInfo {
mediaContentValues);
if (insertUri == null) {
- Log.e(Constants.TAG, "Error when creating file " + fullfilename);
+ Log.e(Constants.TAG, "Error when creating file " + fullFilename);
ContentProfileErrorReportUtils.report(
BluetoothProfile.OPP,
BluetoothProtoEnums.BLUETOOTH_OPP_RECEIVE_FILE_INFO,
@@ -194,10 +194,10 @@ public class BluetoothOppReceiveFileInfo {
Log.d(Constants.TAG, "file crated, insertUri:" + insertUri.toString());
- return new BluetoothOppReceiveFileInfo(fullfilename, length, insertUri, 0);
+ return new BluetoothOppReceiveFileInfo(fullFilename, length, insertUri, 0);
}
- private static String choosefilename(String hint) {
+ private static String chooseFilename(String hint) {
String filename = null;
// First, try to use the hint from the application, if there's one
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
index 75af82b1ea..6d102fec39 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppService.java
@@ -503,7 +503,7 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti
acceptNewConnections();
SdpManagerNativeInterface nativeInterface = SdpManagerNativeInterface.getInstance();
if (!nativeInterface.isAvailable()) {
- Log.e(TAG, "ERROR:serversocket: SdpManagerNativeInterface is not available");
+ Log.e(TAG, "ERROR:serverSocket: SdpManagerNativeInterface is not available");
ContentProfileErrorReportUtils.report(
BluetoothProfile.OPP,
BluetoothProtoEnums.BLUETOOTH_OPP_SERVICE,
@@ -512,7 +512,7 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti
return;
}
if (mServerSocket == null) {
- Log.e(TAG, "ERROR:serversocket: mServerSocket is null");
+ Log.e(TAG, "ERROR:serverSocket: mServerSocket is null");
ContentProfileErrorReportUtils.report(
BluetoothProfile.OPP,
BluetoothProtoEnums.BLUETOOTH_OPP_SERVICE,
@@ -1215,7 +1215,7 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti
static void trimDatabase(ContentResolver contentResolver) {
// Try-catch is important because trimDatabase can run even when the OPP_PROVIDER is
// disabled (by OPP service, shell command, etc.).
- // At the sametime, it's ok to retry trimDatabase later when the service restart
+ // At the same time, it's ok to retry trimDatabase later when the service restart
try {
// remove the invisible/unconfirmed inbound shares
int delNum =
@@ -1332,7 +1332,7 @@ public class BluetoothOppService extends ProfileService implements IObexConnecti
if (mOppSdpHandle >= 0 && nativeInterface.isAvailable()) {
Log.d(TAG, "Removing SDP record mOppSdpHandle :" + mOppSdpHandle);
boolean status = nativeInterface.removeSdpRecord(mOppSdpHandle);
- Log.d(TAG, "RemoveSDPrecord returns " + status);
+ Log.d(TAG, "RemoveSDPRecord returns " + status);
mOppSdpHandle = -1;
}
if (mServerSocket != null) {
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java
index 7ce5ef6bb2..95db09defa 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppTransfer.java
@@ -550,7 +550,7 @@ public class BluetoothOppTransfer implements BluetoothOppBatch.BluetoothOppBatch
mBatch.mStatus = Constants.BATCH_STATUS_FAILED;
return;
}
- registerConnectionreceiver();
+ registerConnectionReceiver();
if (mHandlerThread == null) {
Log.v(TAG, "Create handler thread for batch " + mBatch.mId);
mHandlerThread =
@@ -655,7 +655,7 @@ public class BluetoothOppTransfer implements BluetoothOppBatch.BluetoothOppBatch
processCurrentShare();
}
- private void registerConnectionreceiver() {
+ private void registerConnectionReceiver() {
/*
* OBEX channel need to be monitored for unexpected ACL disconnection
* such as Remote Battery removal
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java b/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java
index bb8df3da0e..d7b75bfde2 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothOppUtility.java
@@ -207,7 +207,7 @@ public class BluetoothOppUtility {
}
if (!isBluetoothShareUri(uri)) {
- Log.e(TAG, "Trying to open a file that wasn't transfered over Bluetooth");
+ Log.e(TAG, "Trying to open a file that wasn't transferred over Bluetooth");
ContentProfileErrorReportUtils.report(
BluetoothProfile.OPP,
BluetoothProtoEnums.BLUETOOTH_OPP_UTILITY,
diff --git a/android/app/src/com/android/bluetooth/opp/BluetoothShare.java b/android/app/src/com/android/bluetooth/opp/BluetoothShare.java
index 1e539a3701..a5dd7fac00 100644
--- a/android/app/src/com/android/bluetooth/opp/BluetoothShare.java
+++ b/android/app/src/com/android/bluetooth/opp/BluetoothShare.java
@@ -259,7 +259,7 @@ public final class BluetoothShare implements BaseColumns {
/**
* This transfer has successfully completed. Warning: there might be other status values that
- * indicate success in the future. Use isSucccess() to capture the entire category.
+ * indicate success in the future. Use isSuccess() to capture the entire category.
*/
public static final int STATUS_SUCCESS = 200;
diff --git a/android/app/src/com/android/bluetooth/opp/Constants.java b/android/app/src/com/android/bluetooth/opp/Constants.java
index 490c7e14c8..7ef50429ea 100644
--- a/android/app/src/com/android/bluetooth/opp/Constants.java
+++ b/android/app/src/com/android/bluetooth/opp/Constants.java
@@ -35,8 +35,6 @@ package com.android.bluetooth.opp;
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
-import android.bluetooth.BluetoothProfile;
-import android.bluetooth.BluetoothProtoEnums;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
@@ -44,11 +42,8 @@ import android.net.Uri;
import android.util.Log;
import com.android.bluetooth.BluetoothMethodProxy;
-import com.android.bluetooth.BluetoothStatsLog;
-import com.android.bluetooth.content_profiles.ContentProfileErrorReportUtils;
import com.android.obex.HeaderSet;
-import java.io.IOException;
import java.util.regex.Pattern;
/** Bluetooth OPP internal constant definitions */
@@ -278,26 +273,17 @@ public class Constants {
static void logHeader(HeaderSet hs) {
Log.v(TAG, "Dumping HeaderSet " + hs.toString());
- try {
- Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
- Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
- Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
- Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
- Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
- Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
- Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
- Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
- Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
- Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
- Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
- Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
- } catch (IOException e) {
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.OPP,
- BluetoothProtoEnums.BLUETOOTH_OPP_CONSTANTS,
- BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
- 0);
- Log.e(TAG, "dump HeaderSet error " + e);
- }
+ Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
+ Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
+ Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
+ Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
+ Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
+ Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
+ Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
+ Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
+ Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
+ Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
+ Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
+ Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
}
}
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 0fdcd96049..d873628c12 100644
--- a/android/app/src/com/android/bluetooth/pan/PanService.java
+++ b/android/app/src/com/android/bluetooth/pan/PanService.java
@@ -19,6 +19,12 @@ package com.android.bluetooth.pan;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.TETHER_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.bluetooth.BluetoothUtils.logRemoteException;
import static java.util.Objects.requireNonNull;
@@ -178,11 +184,7 @@ public class PanService extends ProfileService {
setPanService(null);
- int[] desiredStates = {
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTING
- };
+ int[] desiredStates = {STATE_CONNECTING, STATE_CONNECTED, STATE_DISCONNECTING};
List<BluetoothDevice> devList = getDevicesMatchingConnectionStates(desiredStates);
for (BluetoothDevice device : devList) {
BluetoothPanDevice panDevice = mPanDevices.get(device);
@@ -191,7 +193,7 @@ public class PanService extends ProfileService {
handlePanDeviceStateChange(
device,
mPanIfName,
- BluetoothProfile.STATE_DISCONNECTED,
+ STATE_DISCONNECTED,
panDevice.mLocalRole,
panDevice.mRemoteRole);
}
@@ -216,13 +218,13 @@ public class PanService extends ProfileService {
handlePanDeviceStateChange(
connectDevice,
null,
- BluetoothProfile.STATE_CONNECTING,
+ STATE_CONNECTING,
BluetoothPan.LOCAL_PANU_ROLE,
BluetoothPan.REMOTE_NAP_ROLE);
handlePanDeviceStateChange(
connectDevice,
null,
- BluetoothProfile.STATE_DISCONNECTED,
+ STATE_DISCONNECTED,
BluetoothPan.LOCAL_PANU_ROLE,
BluetoothPan.REMOTE_NAP_ROLE);
}
@@ -238,13 +240,13 @@ public class PanService extends ProfileService {
handlePanDeviceStateChange(
disconnectDevice,
mPanIfName,
- BluetoothProfile.STATE_DISCONNECTING,
+ STATE_DISCONNECTING,
BluetoothPan.LOCAL_PANU_ROLE,
BluetoothPan.REMOTE_NAP_ROLE);
handlePanDeviceStateChange(
disconnectDevice,
mPanIfName,
- BluetoothProfile.STATE_DISCONNECTED,
+ STATE_DISCONNECTED,
BluetoothPan.LOCAL_PANU_ROLE,
BluetoothPan.REMOTE_NAP_ROLE);
}
@@ -412,7 +414,7 @@ public class PanService extends ProfileService {
Log.w(TAG, "Guest user does not have the permission to change the WiFi network");
return false;
}
- if (getConnectionState(device) != BluetoothProfile.STATE_DISCONNECTED) {
+ if (getConnectionState(device) != STATE_DISCONNECTED) {
Log.e(TAG, "Pan Device not disconnected: " + device);
return false;
}
@@ -503,9 +505,9 @@ public class PanService extends ProfileService {
device, BluetoothProfile.PAN, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -527,7 +529,7 @@ public class PanService extends ProfileService {
public List<BluetoothDevice> getConnectedDevices() {
List<BluetoothDevice> devices =
- getDevicesMatchingConnectionStates(new int[] {BluetoothProfile.STATE_CONNECTED});
+ getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED});
return devices;
}
@@ -608,7 +610,7 @@ public class PanService extends ProfileService {
BluetoothPanDevice panDevice = mPanDevices.get(device);
if (panDevice == null) {
Log.i(TAG, "state " + state + " Num of connected pan devices: " + mPanDevices.size());
- prevState = BluetoothProfile.STATE_DISCONNECTED;
+ prevState = STATE_DISCONNECTED;
panDevice = new BluetoothPanDevice(state, localRole, remoteRole);
mPanDevices.put(device, panDevice);
} else {
@@ -623,8 +625,7 @@ public class PanService extends ProfileService {
// connect call will put us in STATE_DISCONNECTED. Then, the disconnect completes and
// changes the state to STATE_DISCONNECTING. All future calls to BluetoothPan#connect
// will fail until the caller explicitly calls BluetoothPan#disconnect.
- if (prevState == BluetoothProfile.STATE_DISCONNECTED
- && state == BluetoothProfile.STATE_DISCONNECTING) {
+ if (prevState == STATE_DISCONNECTED && state == STATE_DISCONNECTING) {
Log.d(TAG, "Ignoring state change from " + prevState + " to " + state);
mPanDevices.remove(device);
return;
@@ -635,7 +636,7 @@ public class PanService extends ProfileService {
return;
}
if (remoteRole == BluetoothPan.LOCAL_PANU_ROLE) {
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
if ((!mTetherOn) || (localRole == BluetoothPan.LOCAL_PANU_ROLE)) {
Log.d(
TAG,
@@ -659,7 +660,7 @@ public class PanService extends ProfileService {
logRemoteException(TAG, e);
}
}
- } else if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ } else if (state == STATE_DISCONNECTED) {
mPanDevices.remove(device);
Log.i(
TAG,
@@ -684,12 +685,12 @@ public class PanService extends ProfileService {
+ state
+ ", prevState = "
+ prevState);
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
mNetworkFactory =
new BluetoothTetheringNetworkFactory(
getBaseContext(), getMainLooper(), this);
mNetworkFactory.startReverseTether(iface);
- } else if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ } else if (state == STATE_DISCONNECTED) {
if (mNetworkFactory != null) {
mNetworkFactory.stopReverseTether();
mNetworkFactory = null;
@@ -697,7 +698,7 @@ public class PanService extends ProfileService {
mPanDevices.remove(device);
}
}
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PAN);
}
mAdapterService.updateProfileConnectionAdapterProperties(
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java
index 99b0b13bea..85f07b687b 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapCallLogComposer.java
@@ -89,13 +89,12 @@ public class BluetoothPbapCallLogComposer implements AutoCloseable {
private static final String VCARD_PROPERTY_CALLTYPE_OUTGOING = "DIALED";
private static final String VCARD_PROPERTY_CALLTYPE_MISSED = "MISSED";
+
private final Context mContext;
private Cursor mCursor;
private String mErrorReason = NO_ERROR;
- private final String RFC_2455_FORMAT = "yyyyMMdd'T'HHmmss";
-
public BluetoothPbapCallLogComposer(final Context context) {
mContext = context;
}
@@ -197,7 +196,7 @@ public class BluetoothPbapCallLogComposer implements AutoCloseable {
/** This static function is to compose vCard for phone own number */
public static String composeVCardForPhoneOwnNumber(
- int phonetype, String phoneName, String phoneNumber, boolean vcardVer21) {
+ int phoneType, String phoneName, String phoneNumber, boolean vcardVer21) {
final int vcardType =
(vcardVer21
? VCardConfig.VCARD_TYPE_V21_GENERIC
@@ -212,28 +211,29 @@ public class BluetoothPbapCallLogComposer implements AutoCloseable {
builder.appendLine(VCardConstants.PROPERTY_N, phoneName, needCharset, false);
if (!TextUtils.isEmpty(phoneNumber)) {
- String label = Integer.toString(phonetype);
- builder.appendTelLine(phonetype, label, phoneNumber, false);
+ String label = Integer.toString(phoneType);
+ builder.appendTelLine(phoneType, label, phoneNumber, false);
}
return builder.toString();
}
/** Format according to RFC 2445 DATETIME type. The format is: ("%Y%m%dT%H%M%S"). */
- private String toRfc2455Format(final long millSecs) {
+ private static String toRfc2455Format(final long millSecs) {
+ String rfc2455Format = "yyyyMMdd'T'HHmmss";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millSecs);
- SimpleDateFormat df = new SimpleDateFormat(RFC_2455_FORMAT);
+ SimpleDateFormat df = new SimpleDateFormat(rfc2455Format);
return df.format(cal.getTime());
}
/**
* Try to append the property line for a call history time stamp field if possible. Do nothing
- * if the call log type gotton from the database is invalid.
+ * if the call log type gotten from the database is invalid.
*/
private void tryAppendCallHistoryTimeStampField(final VCardBuilder builder) {
// Extension for call history as defined in
- // in the Specification for Ic Mobile Communcation - ver 1.1,
+ // in the Specification for Ic Mobile Communication - ver 1.1,
// Oct 2000. This is used to send the details of the call
// history - missed, incoming, outgoing along with date and time
// to the requesting device (For example, transferring phone book
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java
index c755e1b67c..c4ca07931b 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapObexServer.java
@@ -475,8 +475,8 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
return ResponseCodes.OBEX_HTTP_UNAVAILABLE;
}
- // Accroding to specification,the name header could be omitted such as
- // sony erriccsonHBH-DS980
+ // According to specification,the name header could be omitted such as
+ // sony ericssonHBH-DS980
// For "x-bt/phonebook" and "x-bt/vcard-listing":
// if name == null, guess what carkit actually want from current path
@@ -526,7 +526,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
} else if (isSimEnabled && mCurrentPath.equals(SIM_PB_PATH)) {
appParamValue.needTag = ContentType.SIM_PHONEBOOK;
} else {
- Log.w(TAG, "mCurrentpath is not valid path!!!");
+ Log.w(TAG, "mCurrentPath is not valid path!!!");
ContentProfileErrorReportUtils.report(
BluetoothProfile.PBAP,
BluetoothProtoEnums.BLUETOOTH_PBAP_OBEX_SERVER,
@@ -671,8 +671,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
// Indicate which sorting order shall be used for the
// <x-bt/vcard-listing> listing object.
- // Can be "Alphabetical | Indexed | Phonetical", default value is
- // "Indexed".
+ // Can be "Alphabetical | Indexed | Phonetic", default value is "Indexed".
public String order;
public int needTag;
@@ -1088,7 +1087,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
BluetoothProtoEnums.BLUETOOTH_PBAP_OBEX_SERVER,
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
17);
- Log.e(TAG, "open/write outputstrem failed" + e.toString());
+ Log.e(TAG, "open/write outputStream failed" + e.toString());
pushResult = ResponseCodes.OBEX_HTTP_INTERNAL_ERROR;
}
@@ -1174,7 +1173,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
setFolderVersionCounters(ap);
}
if (needSendCallHistoryVersionCounters) {
- setCallversionCounters(ap, appParamValue);
+ setCallVersionCounters(ap, appParamValue);
}
reply.setHeader(HeaderSet.APPLICATION_PARAMETER, ap.getHeader());
@@ -1270,7 +1269,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
}
if (needSendCallHistoryVersionCounters) {
- setCallversionCounters(ap, appParamValue);
+ setCallVersionCounters(ap, appParamValue);
reply.setHeader(HeaderSet.APPLICATION_PARAMETER, ap.getHeader());
try {
op.sendHeaders(reply);
@@ -1631,7 +1630,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
}
public static boolean closeStream(final OutputStream out, final Operation op) {
- boolean returnvalue = true;
+ boolean returnValue = true;
try {
if (out != null) {
out.close();
@@ -1643,7 +1642,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
31);
Log.e(TAG, "outputStream close failed" + e.toString());
- returnvalue = false;
+ returnValue = false;
}
try {
if (op != null) {
@@ -1656,9 +1655,9 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
32);
Log.e(TAG, "operation close failed" + e.toString());
- returnvalue = false;
+ returnValue = false;
}
- return returnvalue;
+ return returnValue;
}
// Reserved for future use. In case PSE challenge PCE and PCE input wrong
@@ -1738,28 +1737,18 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
public static final void logHeader(HeaderSet hs) {
Log.v(TAG, "Dumping HeaderSet " + hs.toString());
- try {
-
- Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
- Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
- Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
- Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
- Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
- Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
- Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
- Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
- Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
- Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
- Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
- Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
- } catch (IOException e) {
- ContentProfileErrorReportUtils.report(
- BluetoothProfile.PBAP,
- BluetoothProtoEnums.BLUETOOTH_PBAP_OBEX_SERVER,
- BluetoothStatsLog.BLUETOOTH_CONTENT_PROFILE_ERROR_REPORTED__TYPE__EXCEPTION,
- 33);
- Log.e(TAG, "dump HeaderSet error " + e);
- }
+ Log.v(TAG, "COUNT : " + hs.getHeader(HeaderSet.COUNT));
+ Log.v(TAG, "NAME : " + hs.getHeader(HeaderSet.NAME));
+ Log.v(TAG, "TYPE : " + hs.getHeader(HeaderSet.TYPE));
+ Log.v(TAG, "LENGTH : " + hs.getHeader(HeaderSet.LENGTH));
+ Log.v(TAG, "TIME_ISO_8601 : " + hs.getHeader(HeaderSet.TIME_ISO_8601));
+ Log.v(TAG, "TIME_4_BYTE : " + hs.getHeader(HeaderSet.TIME_4_BYTE));
+ Log.v(TAG, "DESCRIPTION : " + hs.getHeader(HeaderSet.DESCRIPTION));
+ Log.v(TAG, "TARGET : " + hs.getHeader(HeaderSet.TARGET));
+ Log.v(TAG, "HTTP : " + hs.getHeader(HeaderSet.HTTP));
+ Log.v(TAG, "WHO : " + hs.getHeader(HeaderSet.WHO));
+ Log.v(TAG, "OBJECT_CLASS : " + hs.getHeader(HeaderSet.OBJECT_CLASS));
+ Log.v(TAG, "APPLICATION_PARAMETER : " + hs.getHeader(HeaderSet.APPLICATION_PARAMETER));
}
@VisibleForTesting
@@ -1783,7 +1772,7 @@ public class BluetoothPbapObexServer extends ServerRequestHandler {
}
@VisibleForTesting
- static void setCallversionCounters(ApplicationParameter ap, AppParamValue appParamValue) {
+ static void setCallVersionCounters(ApplicationParameter ap, AppParamValue appParamValue) {
ap.addTriplet(
ApplicationParameter.TRIPLET_TAGID.PRIMARYVERSIONCOUNTER_TAGID,
ApplicationParameter.TRIPLET_LENGTH.PRIMARYVERSIONCOUNTER_LENGTH,
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
index 305adbe571..a63006065d 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapService.java
@@ -20,6 +20,9 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.bluetooth.BluetoothDevice.ACCESS_ALLOWED;
import static android.bluetooth.BluetoothDevice.ACCESS_REJECTED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -626,7 +629,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect
synchronized (mPbapStateMachineMap) {
PbapStateMachine sm = mPbapStateMachineMap.get(device);
if (sm == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return sm.getConnectionState();
}
@@ -675,7 +678,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect
device, BluetoothProfile.PBAP, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -906,7 +909,7 @@ public class BluetoothPbapService extends ProfileService implements IObexConnect
Log.d(TAG, "getPhonebookAccessPermission() = " + permission);
if (permission == ACCESS_ALLOWED) {
- setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
stateMachine.sendMessage(PbapStateMachine.AUTHORIZED);
} else if (permission == ACCESS_REJECTED) {
stateMachine.sendMessage(PbapStateMachine.REJECTED);
diff --git a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java
index f19d008912..886c6135f0 100644
--- a/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java
+++ b/android/app/src/com/android/bluetooth/pbap/BluetoothPbapUtils.java
@@ -496,7 +496,7 @@ class BluetoothPbapUtils {
return true;
/* when new fields are added for a type(phone/email/address) in a contact
- * for which there were no fields of this type earliar.*/
+ * for which there were no fields of this type earlier.*/
} else if (oldFields == null && newFields != null && newFields.size() > 0) {
sTotalSvcFields += newFields.size();
sTotalFields += newFields.size();
@@ -507,7 +507,7 @@ class BluetoothPbapUtils {
/* fetchAndSetContacts reads contacts and caches them
* isLoad = true indicates its loading all contacts
- * isLoad = false indiacates its caching recently added contact in database*/
+ * isLoad = false indicates its caching recently added contact in database*/
@VisibleForTesting
static synchronized int fetchAndSetContacts(
Context context,
@@ -584,7 +584,7 @@ class BluetoothPbapUtils {
}
/* This code checks if there is any update in contacts after last pbap
- * disconnect has happenned (even if BT is turned OFF during this time)*/
+ * disconnect has happened (even if BT is turned OFF during this time)*/
if (isLoad && currentTotalFields != sTotalFields) {
sPrimaryVersionCounter += Math.abs(sTotalContacts - sContactSet.size());
diff --git a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java
index 254d8d50d2..43ec2bb3a5 100644
--- a/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java
+++ b/android/app/src/com/android/bluetooth/pbap/PbapStateMachine.java
@@ -17,6 +17,10 @@
package com.android.bluetooth.pbap;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import android.annotation.NonNull;
import android.app.Notification;
@@ -53,10 +57,17 @@ import com.android.obex.ServerSession;
import java.io.IOException;
-/**
- * Bluetooth PBAP StateMachine (New connection socket) WAITING FOR AUTH | | (request permission from
- * Settings UI) | (Accept) / \ (Reject) / \ v v CONNECTED -----> FINISHED (OBEX Server done)
- */
+// Bluetooth PBAP StateMachine
+// (New connection socket)
+// WAITING FOR AUTH
+// |
+// | (request permission from Settings UI)
+// |
+// (Accept) / \ (Reject)
+// / \
+// v v
+// CONNECTED -----> FINISHED
+// (OBEX Server done)
// Next tag value for ContentProfileErrorReportUtils.report(): 3
@VisibleForTesting(visibility = Visibility.PACKAGE)
public class PbapStateMachine extends StateMachine {
@@ -181,7 +192,7 @@ public class PbapStateMachine extends StateMachine {
/** Broadcast connection state change for this state machine */
void broadcastStateTransitions() {
- int prevStateInt = BluetoothProfile.STATE_DISCONNECTED;
+ int prevStateInt = STATE_DISCONNECTED;
if (mPrevState != null) {
prevStateInt = mPrevState.getConnectionStateInt();
}
@@ -232,7 +243,7 @@ public class PbapStateMachine extends StateMachine {
class WaitingForAuth extends PbapStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
}
@Override
@@ -292,7 +303,7 @@ public class PbapStateMachine extends StateMachine {
class Finished extends PbapStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
@Override
@@ -328,7 +339,7 @@ public class PbapStateMachine extends StateMachine {
class Connected extends PbapStateBase {
@Override
int getConnectionStateInt() {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
}
@Override
@@ -345,7 +356,7 @@ public class PbapStateMachine extends StateMachine {
}
broadcastStateTransitions();
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PBAP);
- mService.setConnectionPolicy(mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED);
}
@Override
@@ -378,8 +389,7 @@ public class PbapStateMachine extends StateMachine {
Log.v(TAG, "Pbap Service startObexServerSession");
// acquire the wakeLock before start Obex transaction thread
- mServiceHandler.sendMessage(
- mServiceHandler.obtainMessage(BluetoothPbapService.MSG_ACQUIRE_WAKE_LOCK));
+ mServiceHandler.sendEmptyMessage(BluetoothPbapService.MSG_ACQUIRE_WAKE_LOCK);
mPbapServer =
new BluetoothPbapObexServer(mServiceHandler, mService, PbapStateMachine.this);
@@ -483,7 +493,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/PbapClientAccountManager.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientAccountManager.java
index 4c07177ef5..65efaa3ab0 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientAccountManager.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientAccountManager.java
@@ -363,7 +363,7 @@ class PbapClientAccountManager {
* ready. The AccountManager framework doesn't have a good way for us to know _exactly_ when
* this is, so the best we can do is try to interact with our account type and see if it works.
*
- * <p>We use a fake device address and our accoun ttype here to see if our account is visible
+ * <p>We use a fake device address and our account type here to see if our account is visible
* yet.
*
* <p>This function is used in conjunction with the handler and a polling scheme to see
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java
index 868e9d2472..f3bcd1e7b5 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientBinder.java
@@ -18,10 +18,11 @@ package com.android.bluetooth.pbapclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import android.annotation.RequiresPermission;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothPbapClient;
import android.content.AttributionSource;
import android.util.Log;
@@ -119,7 +120,7 @@ class PbapClientBinder extends IBluetoothPbapClient.Stub implements IProfileServ
Log.d(TAG, "getConnectionState(device=" + device + ")");
PbapClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
}
@@ -141,7 +142,7 @@ class PbapClientBinder extends IBluetoothPbapClient.Stub implements IProfileServ
Log.d(TAG, "getConnectionPolicy(device=" + device + ")");
PbapClientService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
return service.getConnectionPolicy(device);
}
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
index f2453d0b8d..c83e856a72 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/PbapClientService.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.pbapclient;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static java.util.Objects.requireNonNull;
import android.accounts.Account;
@@ -89,7 +94,7 @@ public class PbapClientService extends ProfileService {
+ oldState
+ ", new="
+ newState);
- if (oldState != newState && newState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (oldState != newState && newState == STATE_DISCONNECTED) {
removeDevice(mDevice);
}
}
@@ -295,7 +300,7 @@ public class PbapClientService extends ProfileService {
PbapClientStateMachine pbapClientStateMachine = mPbapClientStateMachineMap.get(device);
if (pbapClientStateMachine != null) {
int state = pbapClientStateMachine.getConnectionState();
- if (state != BluetoothProfile.STATE_DISCONNECTED) {
+ if (state != STATE_DISCONNECTED) {
Log.w(TAG, "Removing connected device, device=" + device + ", state=" + state);
}
mPbapClientStateMachineMap.remove(device);
@@ -357,11 +362,11 @@ public class PbapClientService extends ProfileService {
/**
* Ensure that after HFP disconnects, we remove call logs. This addresses the situation when
* PBAP was never connected while calls were made. Ideally {@link PbapClientConnectionHandler}
- * has code to remove calllogs when PBAP disconnects.
+ * has code to remove call logs when PBAP disconnects.
*/
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);
@@ -439,7 +444,7 @@ public class PbapClientService extends ProfileService {
return;
}
- if (getConnectionState(device) == BluetoothProfile.STATE_CONNECTED) {
+ if (getConnectionState(device) == STATE_CONNECTED) {
disconnect(device);
}
}
@@ -470,14 +475,14 @@ public class PbapClientService extends ProfileService {
if (Flags.pbapClientStorageRefactor()) {
PbapClientStateMachine stateMachine = getDeviceStateMachine(device);
if (stateMachine == null) {
- Log.e(TAG, "No Statemachine found for the device=" + device.toString());
+ Log.e(TAG, "No StateMachine found for the device=" + device.toString());
return;
}
stateMachine.onSdpResultReceived(status, new PbapSdpRecord(device, pseRecord));
} else {
PbapClientStateMachineOld smOld = mPbapClientStateMachineOldMap.get(device);
if (smOld == null) {
- Log.e(TAG, "No Statemachine found for the device=" + device.toString());
+ Log.e(TAG, "No StateMachine found for the device=" + device.toString());
return;
}
smOld.onSdpResultReceived(status, new PbapSdpRecord(device, pseRecord));
@@ -524,7 +529,7 @@ public class PbapClientService extends ProfileService {
throw new IllegalArgumentException("Null device");
}
Log.d(TAG, "connect(device=" + device.getAddress() + ")");
- if (getConnectionPolicy(device) <= BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (getConnectionPolicy(device) <= CONNECTION_POLICY_FORBIDDEN) {
return false;
}
@@ -585,7 +590,7 @@ public class PbapClientService extends ProfileService {
* @return The list of connected PBAP Server devices
*/
public List<BluetoothDevice> getConnectedDevices() {
- int[] desiredStates = {BluetoothProfile.STATE_CONNECTED};
+ int[] desiredStates = {STATE_CONNECTED};
return getDevicesMatchingConnectionStates(desiredStates);
}
@@ -593,7 +598,7 @@ public class PbapClientService extends ProfileService {
* Get the list of PBAP Server devices this PBAP Client device know about, who are in a given
* state.
*
- * @param states The array of BluutoothProfile states you want to match on
+ * @param states The array of BluetoothProfile states you want to match on
* @return The list of connected PBAP Server devices
*/
public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
@@ -645,14 +650,14 @@ public class PbapClientService extends ProfileService {
if (Flags.pbapClientStorageRefactor()) {
PbapClientStateMachine pbapClientStateMachine = getDeviceStateMachine(device);
if (pbapClientStateMachine == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
} else {
return pbapClientStateMachine.getConnectionState();
}
} else {
PbapClientStateMachineOld smOld = mPbapClientStateMachineOldMap.get(device);
if (smOld == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
} else {
return smOld.getConnectionState(device);
}
@@ -683,9 +688,9 @@ public class PbapClientService extends ProfileService {
device, BluetoothProfile.PBAP_CLIENT, connectionPolicy)) {
return false;
}
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy == CONNECTION_POLICY_ALLOWED) {
connect(device);
- } else if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ } else if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachine.java
index 2023bfa90a..3aca289ef4 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
@@ -421,7 +425,7 @@ class PbapClientStateMachine extends StateMachine {
case MSG_SDP_FAILED:
int failureCode = message.arg1;
- info("Connecting: SDP unsuccessful, code=" + sdpCodetoString(failureCode));
+ info("Connecting: SDP unsuccessful, code=" + sdpCodeToString(failureCode));
if (failureCode == SDP_BUSY) {
mDevice.sdpSearch(BluetoothUuid.PBAP_PSE);
} else {
@@ -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();
}
}
@@ -1014,7 +1018,7 @@ class PbapClientStateMachine extends StateMachine {
}
}
- private static String sdpCodetoString(int code) {
+ private static String sdpCodeToString(int code) {
switch (code) {
case SDP_SUCCESS:
return "SDP_SUCCESS";
diff --git a/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java b/android/app/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOld.java
index ce3ad2b8da..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;
@@ -121,7 +125,7 @@ class PbapClientStateMachineOld extends StateMachine {
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, HandlerThread handlerThread) {
@@ -163,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();
}
}
@@ -175,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.
@@ -272,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
@@ -330,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();
}
@@ -403,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);
@@ -458,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) {
@@ -490,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() {
diff --git a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java
index 896962ee10..e8b461b797 100644
--- a/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java
+++ b/android/app/src/com/android/bluetooth/pbapclient/obex/PbapClientObexClient.java
@@ -18,6 +18,10 @@ package com.android.bluetooth.pbapclient;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static java.util.Objects.requireNonNull;
@@ -85,7 +89,7 @@ class PbapClientObexClient {
private final BluetoothDevice mDevice;
private final int mLocalSupportedFeatures;
- private int mState = BluetoothProfile.STATE_DISCONNECTED;
+ private int mState = STATE_DISCONNECTED;
private AtomicInteger mPsm = new AtomicInteger(L2CAP_INVALID_PSM);
private AtomicInteger mChannelId = new AtomicInteger(RFCOMM_INVALID_CHANNEL_ID);
@@ -234,7 +238,7 @@ class PbapClientObexClient {
* @return True if connected, False otherwise
*/
public boolean isConnected() {
- return getConnectionState() == BluetoothProfile.STATE_CONNECTED;
+ return getConnectionState() == STATE_CONNECTED;
}
/**
@@ -355,7 +359,7 @@ class PbapClientObexClient {
if (mThread != null) {
mThread.quit();
}
- setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
+ setConnectionState(STATE_DISCONNECTED);
}
/** Handles this PBAP Client OBEX Client's requests */
@@ -370,7 +374,7 @@ class PbapClientObexClient {
debug("Handling Message, type=" + messageToString(msg.what));
switch (msg.what) {
case MSG_CONNECT:
- if (getConnectionState() != BluetoothProfile.STATE_DISCONNECTED) {
+ if (getConnectionState() != STATE_DISCONNECTED) {
warn("Cannot connect, device not disconnected");
return;
}
@@ -402,13 +406,13 @@ class PbapClientObexClient {
return;
}
- setConnectionState(BluetoothProfile.STATE_CONNECTING);
+ setConnectionState(STATE_CONNECTING);
mSocket = connectSocket(transport, psmOrChannel);
if (mSocket == null) {
mPsm.set(L2CAP_INVALID_PSM);
mChannelId.set(RFCOMM_INVALID_CHANNEL_ID);
- setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
+ setConnectionState(STATE_DISCONNECTED);
return;
}
@@ -418,22 +422,22 @@ class PbapClientObexClient {
mSocket = null;
mPsm.set(L2CAP_INVALID_PSM);
mChannelId.set(RFCOMM_INVALID_CHANNEL_ID);
- setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
+ setConnectionState(STATE_DISCONNECTED);
return;
}
- setConnectionState(BluetoothProfile.STATE_CONNECTED);
+ setConnectionState(STATE_CONNECTED);
break;
case MSG_DISCONNECT:
removeCallbacksAndMessages(null);
- if (getConnectionState() != BluetoothProfile.STATE_CONNECTED) {
+ if (getConnectionState() != STATE_CONNECTED) {
warn("Cannot disconnect, device not connected");
return;
}
- setConnectionState(BluetoothProfile.STATE_DISCONNECTING);
+ setConnectionState(STATE_DISCONNECTING);
// To disconnect, first bring down the OBEX session, then bring down the
// underlying transport/socket. If there are any errors while bringing down the
@@ -449,7 +453,7 @@ class PbapClientObexClient {
mPsm.set(L2CAP_INVALID_PSM);
mChannelId.set(RFCOMM_INVALID_CHANNEL_ID);
- setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
+ setConnectionState(STATE_DISCONNECTED);
break;
case MSG_REQUEST:
diff --git a/android/app/src/com/android/bluetooth/sap/SapMessage.java b/android/app/src/com/android/bluetooth/sap/SapMessage.java
index f1d7dee878..0b5fed1195 100644
--- a/android/app/src/com/android/bluetooth/sap/SapMessage.java
+++ b/android/app/src/com/android/bluetooth/sap/SapMessage.java
@@ -135,7 +135,7 @@ public class SapMessage {
public static final int CON_STATUS_OK_ONGOING_CALL = 0x04;
/* Disconnection type */
- public static final int DISC_GRACEFULL = 0x00;
+ public static final int DISC_GRACEFUL = 0x00;
public static final int DISC_IMMEDIATE = 0x01;
public static final int DISC_FORCED = 0x100; // Used internal only
public static final int DISC_RFCOMM = 0x101; // Used internal only
diff --git a/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java b/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java
index af9cedf745..61452055ca 100644
--- a/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java
+++ b/android/app/src/com/android/bluetooth/sap/SapRilReceiver.java
@@ -29,7 +29,7 @@ import com.android.modules.utils.build.SdkLevel;
import java.util.concurrent.atomic.AtomicLong;
-/** SapRiilReceiver is the AIDL implementation of ISapRilReceiver */
+/** SapRilReceiver is the AIDL implementation of ISapRilReceiver */
public class SapRilReceiver implements ISapRilReceiver {
private static final String TAG = SapRilReceiver.class.getSimpleName();
@@ -105,7 +105,7 @@ public class SapRilReceiver implements ISapRilReceiver {
/**
* Set callback that has response and unsolicited indication functions
*
- * @param sapCallback Object containing response and unosolicited indication callbacks
+ * @param sapCallback Object containing response and unsolicited indication callbacks
*/
@Override
public void setCallback(android.hardware.radio.sap.ISapCallback sapCallback)
diff --git a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java
index b97d860bc6..89a576c870 100644
--- a/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java
+++ b/android/app/src/com/android/bluetooth/sap/SapRilReceiverHidl.java
@@ -28,7 +28,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
-/** SapRiilReceiverHidl is the HIDL implementation of ISapRilReceiver */
+/** SapRilReceiverHidl is the HIDL implementation of ISapRilReceiver */
@SuppressWarnings("NonApiType") // We cannot change hidl anymore
public class SapRilReceiverHidl implements ISapRilReceiver {
private static final String TAG = SapRilReceiverHidl.class.getSimpleName();
@@ -114,7 +114,7 @@ public class SapRilReceiverHidl implements ISapRilReceiver {
/**
* Set callback that has response and unsolicited indication functions
*
- * @param sapCallback Object containing response and unosolicited indication callbacks
+ * @param sapCallback Object containing response and unsolicited indication callbacks
*/
@Override
public void setCallback(android.hardware.radio.sap.ISapCallback sapCallback)
diff --git a/android/app/src/com/android/bluetooth/sap/SapServer.java b/android/app/src/com/android/bluetooth/sap/SapServer.java
index a7486b9396..97cce16ffb 100644
--- a/android/app/src/com/android/bluetooth/sap/SapServer.java
+++ b/android/app/src/com/android/bluetooth/sap/SapServer.java
@@ -157,7 +157,7 @@ public class SapServer extends Thread implements Handler.Callback {
} else if (intent.getAction().equals(SAP_DISCONNECT_ACTION)) {
int disconnectType =
intent.getIntExtra(
- SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_GRACEFULL);
+ SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_GRACEFUL);
Log.v(TAG, " - Received SAP_DISCONNECT_ACTION type: " + disconnectType);
if (disconnectType == SapMessage.DISC_RFCOMM) {
@@ -198,7 +198,7 @@ public class SapServer extends Thread implements Handler.Callback {
sendClientMessage(discInd);
/* Handle local disconnect procedures */
- if (discType == SapMessage.DISC_GRACEFULL) {
+ if (discType == SapMessage.DISC_GRACEFUL) {
/* Update the notification to allow the user to initiate a force disconnect */
setNotification(SapMessage.DISC_IMMEDIATE, PendingIntent.FLAG_CANCEL_CURRENT);
@@ -241,7 +241,7 @@ public class SapServer extends Thread implements Handler.Callback {
/* put notification up for the user to be able to disconnect from the client*/
Intent sapDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
- if (type == SapMessage.DISC_GRACEFULL) {
+ if (type == SapMessage.DISC_GRACEFUL) {
title = mContext.getString(R.string.bluetooth_sap_notif_title);
button = mContext.getString(R.string.bluetooth_sap_notif_disconnect_button);
text = mContext.getString(R.string.bluetooth_sap_notif_message);
@@ -281,14 +281,14 @@ public class SapServer extends Thread implements Handler.Callback {
.build();
} else {
sapDisconnectIntent.putExtra(
- SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_GRACEFULL);
+ SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_GRACEFUL);
Intent sapForceDisconnectIntent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
sapForceDisconnectIntent.putExtra(
SapServer.SAP_DISCONNECT_TYPE_EXTRA, SapMessage.DISC_IMMEDIATE);
PendingIntent pIntentDisconnect =
PendingIntent.getBroadcast(
mContext,
- SapMessage.DISC_GRACEFULL,
+ SapMessage.DISC_GRACEFUL,
sapDisconnectIntent,
flags | PendingIntent.FLAG_IMMUTABLE);
PendingIntent pIntentForceDisconnect =
@@ -507,7 +507,7 @@ public class SapServer extends Thread implements Handler.Callback {
try {
mDeinitSignal.await();
} catch (InterruptedException e) {
- Log.e(TAG, "Interrupt received while waitinf for de-init to complete", e);
+ Log.e(TAG, "Interrupt received while waiting for de-init to complete", e);
}
}
@@ -891,7 +891,7 @@ public class SapServer extends Thread implements Handler.Callback {
msg.what = SapService.MSG_CHANGE_STATE;
msg.arg1 = BluetoothSap.STATE_CONNECTED;
msg.sendToTarget();
- setNotification(SapMessage.DISC_GRACEFULL, 0);
+ setNotification(SapMessage.DISC_GRACEFUL, 0);
Log.d(TAG, "MSG_CHANGE_STATE sent out.");
}
break;
@@ -954,7 +954,7 @@ public class SapServer extends Thread implements Handler.Callback {
if (!mRilBtReceiver.isProxyValid()) {
Log.e(
TAG_HANDLER,
- "sendRiilMessage: Unable to send message to Ril; sapProxy is invalid");
+ "sendRilMessage: Unable to send message to Ril; sapProxy is invalid");
sendClientMessage(new SapMessage(SapMessage.ID_ERROR_RESP));
return;
}
diff --git a/android/app/src/com/android/bluetooth/sap/SapService.java b/android/app/src/com/android/bluetooth/sap/SapService.java
index ac76fd3fa7..277acc4cf2 100644
--- a/android/app/src/com/android/bluetooth/sap/SapService.java
+++ b/android/app/src/com/android/bluetooth/sap/SapService.java
@@ -18,6 +18,11 @@ package com.android.bluetooth.sap;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -534,7 +539,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
private synchronized void setState(int state, int result) {
if (state != mState) {
Log.d(TAG, "Sap state " + mState + " -> " + state + ", result = " + result);
- if (state == BluetoothProfile.STATE_CONNECTED) {
+ if (state == STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.SAP);
}
int prevState = mState;
@@ -617,9 +622,9 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
if (getState() == BluetoothSap.STATE_CONNECTED
&& getRemoteDevice() != null
&& getRemoteDevice().equals(device)) {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
} else {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
}
}
@@ -645,7 +650,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
mAdapterService
.getDatabase()
.setProfileConnectionPolicy(device, BluetoothProfile.SAP, connectionPolicy);
- if (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (connectionPolicy == CONNECTION_POLICY_FORBIDDEN) {
disconnect(device);
}
return true;
@@ -820,9 +825,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
BluetoothDevice.ACCESS_ALLOWED);
Log.v(TAG, "setSimAccessPermission(ACCESS_ALLOWED) result=" + result);
}
- boolean result =
- setConnectionPolicy(
- mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ boolean result = setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED);
Log.d(TAG, "setConnectionPolicy ALLOWED, result = " + result);
try {
@@ -843,8 +846,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
Log.v(TAG, "setSimAccessPermission(ACCESS_REJECTED) result=" + result);
}
boolean result =
- setConnectionPolicy(
- mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN);
Log.d(TAG, "setConnectionPolicy FORBIDDEN, result = " + result);
// Ensure proper cleanup, and prepare for new connect.
mSessionStatusHandler.sendEmptyMessage(MSG_SERVERSESSION_CLOSE);
@@ -955,7 +957,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
return false;
}
- return service.getConnectionState(device) == BluetoothProfile.STATE_CONNECTED;
+ return service.getConnectionState(device) == STATE_CONNECTED;
}
@Override
@@ -1001,7 +1003,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
SapService service = getService(source);
if (service == null) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
return service.getConnectionState(device);
@@ -1022,7 +1024,7 @@ public class SapService extends ProfileService implements AdapterService.Bluetoo
public int getConnectionPolicy(BluetoothDevice device, AttributionSource source) {
SapService service = getService(source);
if (service == null) {
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
return service.getConnectionPolicy(device);
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsGatt.java b/android/app/src/com/android/bluetooth/tbs/TbsGatt.java
index 6cf2642366..b5cdddf339 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;
@@ -948,7 +948,7 @@ public class TbsGatt {
+ requestedOpcode
+ " callIndex="
+ callIndex
- + " requesuResult="
+ + " requestResult="
+ requestResult);
mCallControlPointCharacteristic.setResult(
device, requestedOpcode, callIndex, requestResult);
@@ -1452,8 +1452,8 @@ public class TbsGatt {
}
}
- private void clearUnauthorizedGattOperationss(BluetoothDevice device) {
- Log.d(TAG, "clearUnauthorizedGattOperationss device: " + device);
+ private void clearUnauthorizedGattOperations(BluetoothDevice device) {
+ Log.d(TAG, "clearUnauthorizedGattOperations device: " + device);
synchronized (mPendingGattOperationsLock) {
mPendingGattOperations.remove(device);
@@ -1474,7 +1474,7 @@ public class TbsGatt {
onRejectedAuthorizationGattOperation(device, op);
}
}
- clearUnauthorizedGattOperationss(device);
+ clearUnauthorizedGattOperations(device);
}
}
}
@@ -1491,8 +1491,8 @@ public class TbsGatt {
BluetoothDevice device, int status, int newState) {
super.onConnectionStateChange(device, status, newState);
Log.d(TAG, "BluetoothGattServerCallback: onConnectionStateChange");
- if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- clearUnauthorizedGattOperationss(device);
+ if (newState == STATE_DISCONNECTED) {
+ clearUnauthorizedGattOperations(device);
}
}
diff --git a/android/app/src/com/android/bluetooth/tbs/TbsService.java b/android/app/src/com/android/bluetooth/tbs/TbsService.java
index 58a1736bc8..6a29848ef6 100644
--- a/android/app/src/com/android/bluetooth/tbs/TbsService.java
+++ b/android/app/src/com/android/bluetooth/tbs/TbsService.java
@@ -19,13 +19,13 @@ package com.android.bluetooth.tbs;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static java.util.Objects.requireNonNull;
import android.annotation.RequiresPermission;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothLeCall;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothLeCallControl;
import android.bluetooth.IBluetoothLeCallControlCallback;
import android.content.AttributionSource;
@@ -178,8 +178,7 @@ public class TbsService extends ProfileService {
return BluetoothDevice.ACCESS_UNKNOWN;
}
- if (leAudioService.getConnectionPolicy(device)
- > BluetoothProfile.CONNECTION_POLICY_FORBIDDEN) {
+ if (leAudioService.getConnectionPolicy(device) > CONNECTION_POLICY_FORBIDDEN) {
Log.d(TAG, "TBS authorization allowed based on supported LeAudio service");
setDeviceAuthorized(device, true);
return BluetoothDevice.ACCESS_ALLOWED;
diff --git a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java
index 99b0efc2a3..88633d61f6 100644
--- a/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java
+++ b/android/app/src/com/android/bluetooth/telephony/BluetoothInCallService.java
@@ -16,16 +16,12 @@
package com.android.bluetooth.telephony;
-import static android.Manifest.permission.BLUETOOTH_CONNECT;
-import static android.Manifest.permission.MODIFY_PHONE_STATE;
import static java.util.Objects.requireNonNull;
import static java.util.Objects.requireNonNullElseGet;
import android.annotation.NonNull;
-import android.annotation.RequiresPermission;
import android.bluetooth.BluetoothAdapter;
-import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothLeCall;
import android.bluetooth.BluetoothLeCallControl;
import android.bluetooth.BluetoothManager;
@@ -57,7 +53,6 @@ import androidx.annotation.VisibleForTesting;
import com.android.bluetooth.Utils;
import com.android.bluetooth.flags.Flags;
-import com.android.bluetooth.hfp.BluetoothHeadsetProxy;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.tbs.BluetoothLeCallControlProxy;
@@ -124,8 +119,6 @@ public class BluetoothInCallService extends InCallService {
private static final Object LOCK = new Object();
- @VisibleForTesting BluetoothHeadsetProxy mBluetoothHeadset;
-
@VisibleForTesting BluetoothLeCallControlProxy mBluetoothLeCallControl;
private ExecutorService mExecutor;
@@ -157,14 +150,9 @@ public class BluetoothInCallService extends InCallService {
private final BluetoothProfile.ServiceListener mProfileListener =
new BluetoothProfile.ServiceListener() {
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onServiceConnected(int profile, BluetoothProfile proxy) {
Log.d(TAG, "onServiceConnected for profile: " + profile);
synchronized (LOCK) {
- if (profile == BluetoothProfile.HEADSET) {
- mBluetoothHeadset = new BluetoothHeadsetProxy((BluetoothHeadset) proxy);
- updateHeadsetWithCallState(true /* force */);
- } else {
mBluetoothLeCallControl =
new BluetoothLeCallControlProxy((BluetoothLeCallControl) proxy);
@@ -179,7 +167,6 @@ public class BluetoothInCallService extends InCallService {
mBluetoothLeCallControlCallback);
Log.d(TAG, "isBearerRegistered: " + isBearerRegistered);
sendTbsCurrentCallsList();
- }
}
Log.d(TAG, "Calls updated for profile: " + profile);
}
@@ -187,11 +174,7 @@ public class BluetoothInCallService extends InCallService {
@Override
public void onServiceDisconnected(int profile) {
synchronized (LOCK) {
- if (profile == BluetoothProfile.HEADSET) {
- mBluetoothHeadset = null;
- } else {
mBluetoothLeCallControl = null;
- }
}
}
};
@@ -204,7 +187,7 @@ public class BluetoothInCallService extends InCallService {
intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
Log.d(TAG, "Bluetooth Adapter state: " + state);
if (state == BluetoothAdapter.STATE_ON) {
- queryPhoneState();
+ queryPhoneState(HeadsetService.getHeadsetService());
} else if (state == BluetoothAdapter.STATE_TURNING_OFF) {
clear();
}
@@ -229,7 +212,6 @@ public class BluetoothInCallService extends InCallService {
return mLastState;
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
void onStateChanged(BluetoothCall call, int state) {
if (mCallInfo.isNullCall(call)) {
return;
@@ -272,37 +254,39 @@ public class BluetoothInCallService extends InCallService {
return;
}
mLastState = state;
- updateHeadsetWithCallState(false /* force */);
+ updateHeadsetWithCallState(HeadsetService.getHeadsetService(), false /* force */);
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onStateChanged(Call call, int state) {
super.onStateChanged(call, state);
onStateChanged(getBluetoothCallById(System.identityHashCode(call)), state);
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- void onDetailsChanged(BluetoothCall call, Call.Details details) {
+ @VisibleForTesting
+ void onDetailsChanged(
+ HeadsetService headsetService, BluetoothCall call, Call.Details details) {
if (mCallInfo.isNullCall(call)) {
return;
}
if (call.isExternalCall()) {
- onCallRemoved(call, false /* forceRemoveCallback */);
+ onCallRemoved(headsetService, call, false /* forceRemoveCallback */);
} else {
- onCallAdded(call);
+ onCallAdded(headsetService, call);
}
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onDetailsChanged(Call call, Call.Details details) {
super.onDetailsChanged(call, details);
- onDetailsChanged(getBluetoothCallById(System.identityHashCode(call)), details);
+ onDetailsChanged(
+ HeadsetService.getHeadsetService(),
+ getBluetoothCallById(System.identityHashCode(call)),
+ details);
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- void onParentChanged(BluetoothCall call) {
+ @VisibleForTesting
+ void onParentChanged(HeadsetService headsetService, BluetoothCall call) {
if (mCallInfo.isNullCall(call) || call.isExternalCall()) {
Log.w(TAG, "null call or external call");
return;
@@ -315,18 +299,20 @@ public class BluetoothInCallService extends InCallService {
"Ignoring onIsConferenceChanged from child BluetoothCall with new parent");
return;
}
- updateHeadsetWithCallState(false /* force */);
+ updateHeadsetWithCallState(headsetService, false /* force */);
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onParentChanged(Call call, Call parent) {
super.onParentChanged(call, parent);
- onParentChanged(getBluetoothCallById(System.identityHashCode(call)));
+ onParentChanged(
+ HeadsetService.getHeadsetService(),
+ getBluetoothCallById(System.identityHashCode(call)));
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- void onChildrenChanged(BluetoothCall call, List<BluetoothCall> children) {
+ @VisibleForTesting
+ void onChildrenChanged(
+ HeadsetService headsetService, BluetoothCall call, List<BluetoothCall> children) {
if (mCallInfo.isNullCall(call) || call.isExternalCall()) {
Log.w(TAG, "null call or external call");
return;
@@ -339,14 +325,14 @@ public class BluetoothInCallService extends InCallService {
Log.d(TAG, "Ignoring onIsConferenceChanged from parent with only one child call");
return;
}
- updateHeadsetWithCallState(false /* force */);
+ updateHeadsetWithCallState(headsetService, false /* force */);
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onChildrenChanged(Call call, List<Call> children) {
super.onChildrenChanged(call, children);
onChildrenChanged(
+ HeadsetService.getHeadsetService(),
getBluetoothCallById(System.identityHashCode(call)),
getBluetoothCallsByIds(BluetoothCall.getIds(children)));
}
@@ -378,10 +364,8 @@ public class BluetoothInCallService extends InCallService {
BluetoothInCallService(
Context context,
CallInfo callInfo,
- BluetoothHeadsetProxy headset,
BluetoothLeCallControlProxy leCallControl) {
this(callInfo);
- mBluetoothHeadset = headset;
mBluetoothLeCallControl = leCallControl;
attachBaseContext(context);
}
@@ -465,7 +449,7 @@ public class BluetoothInCallService extends InCallService {
}
/**
- * Gets the brearer technology.
+ * Gets the bearer technology.
*
* @return bearer technology as defined in Bluetooth Assigned Numbers
*/
@@ -546,7 +530,7 @@ public class BluetoothInCallService extends InCallService {
mHeadsetUpdatedRecently = false;
if (logQuery) {
- Log.i(TAG, "listcurrentCalls");
+ Log.i(TAG, "listCurrentCalls");
}
sendListOfCalls(headsetService, logQuery);
@@ -554,11 +538,10 @@ public class BluetoothInCallService extends InCallService {
}
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public boolean queryPhoneState() {
+ public boolean queryPhoneState(HeadsetService headsetService) {
synchronized (LOCK) {
Log.i(TAG, "queryPhoneState");
- updateHeadsetWithCallState(true);
+ updateHeadsetWithCallState(headsetService, true);
return true;
}
}
@@ -596,20 +579,20 @@ public class BluetoothInCallService extends InCallService {
return isHighDef;
}
- public boolean processChld(int chld) {
+ public boolean processChld(HeadsetService headsetService, int chld) {
synchronized (LOCK) {
final long token = Binder.clearCallingIdentity();
try {
Log.i(TAG, "processChld " + chld);
- return _processChld(chld);
+ return processChldLocked(headsetService, chld);
} finally {
Binder.restoreCallingIdentity(token);
}
}
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public void onCallAdded(BluetoothCall call) {
+ @VisibleForTesting
+ void onCallAdded(HeadsetService headsetService, BluetoothCall call) {
synchronized (LOCK) {
if (call.isExternalCall()) {
Log.d(TAG, "onCallAdded: external call");
@@ -626,7 +609,7 @@ public class BluetoothInCallService extends InCallService {
mMaxNumberOfCalls =
Integer.max(mMaxNumberOfCalls, mBluetoothCallHashMap.size());
}
- updateHeadsetWithCallState(false /* force */);
+ updateHeadsetWithCallState(headsetService, false /* force */);
BluetoothLeCall tbsCall = createTbsCall(call);
if (mBluetoothLeCallControl != null && tbsCall != null) {
@@ -666,10 +649,9 @@ public class BluetoothInCallService extends InCallService {
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onCallAdded(Call call) {
super.onCallAdded(call);
- onCallAdded(new BluetoothCall(call));
+ onCallAdded(HeadsetService.getHeadsetService(), new BluetoothCall(call));
}
/**
@@ -681,8 +663,8 @@ public class BluetoothInCallService extends InCallService {
* callback when the {@code BluetoothCall} is external so that the call can be added back if
* no longer external.
*/
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- public void onCallRemoved(BluetoothCall call, boolean forceRemoveCallback) {
+ public void onCallRemoved(
+ HeadsetService headsetService, BluetoothCall call, boolean forceRemoveCallback) {
synchronized (LOCK) {
Log.i(TAG, "onCallRemoved, forceRemoveCallback=" + forceRemoveCallback);
CallStateCallback callback = getCallback(call);
@@ -727,7 +709,7 @@ public class BluetoothInCallService extends InCallService {
}
}
- updateHeadsetWithCallState(false /* force */);
+ updateHeadsetWithCallState(headsetService, false /* force */);
if (Flags.maintainCallIndexAfterConference()
&& mConferenceCallClccIndexMap.size() > 0) {
@@ -747,7 +729,6 @@ public class BluetoothInCallService extends InCallService {
}
@Override
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
public void onCallRemoved(Call call) {
super.onCallRemoved(call);
BluetoothCall bluetoothCall = getBluetoothCallById(System.identityHashCode(call));
@@ -755,7 +736,8 @@ public class BluetoothInCallService extends InCallService {
Log.w(TAG, "onCallRemoved, BluetoothCall is removed before registered");
return;
}
- onCallRemoved(bluetoothCall, true /* forceRemoveCallback */);
+ onCallRemoved(
+ HeadsetService.getHeadsetService(), bluetoothCall, true /* forceRemoveCallback */);
}
@Override
@@ -772,7 +754,6 @@ public class BluetoothInCallService extends InCallService {
mAdapter = requireNonNull(getSystemService(BluetoothManager.class)).getAdapter();
mTelephonyManager = requireNonNull(getSystemService(TelephonyManager.class));
mTelecomManager = requireNonNull(getSystemService(TelecomManager.class));
- mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.HEADSET);
mAdapter.getProfileProxy(this, mProfileListener, BluetoothProfile.LE_CALL_CONTROL);
mBluetoothAdapterReceiver = new BluetoothAdapterReceiver();
IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
@@ -804,10 +785,6 @@ public class BluetoothInCallService extends InCallService {
unregisterReceiver(mBluetoothAdapterReceiver);
mBluetoothAdapterReceiver = null;
}
- if (mBluetoothHeadset != null) {
- mBluetoothHeadset.closeBluetoothHeadsetProxy(mAdapter);
- mBluetoothHeadset = null;
- }
if (mBluetoothLeCallControl != null) {
mBluetoothLeCallControl.unregisterBearer();
mBluetoothLeCallControl.closeBluetoothLeCallControlProxy(mAdapter);
@@ -1125,8 +1102,7 @@ public class BluetoothInCallService extends InCallService {
return call.mClccIndex;
}
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- private boolean _processChld(int chld) {
+ private boolean processChldLocked(HeadsetService headsetService, int chld) {
BluetoothCall activeCall = mCallInfo.getActiveCall();
BluetoothCall ringingCall = mCallInfo.getRingingOrSimulatedRingingCall();
if (ringingCall == null) {
@@ -1185,7 +1161,7 @@ public class BluetoothInCallService extends InCallService {
&& activeCall.can(Connection.CAPABILITY_SWAP_CONFERENCE)) {
activeCall.swapConference();
Log.i(TAG, "CDMA calls in conference swapped, updating headset");
- updateHeadsetWithCallState(true /* force */);
+ updateHeadsetWithCallState(headsetService, true /* force */);
return true;
} else if (!mCallInfo.isNullCall(ringingCall)) {
ringingCall.answer(VideoProfile.STATE_AUDIO_ONLY);
@@ -1225,8 +1201,12 @@ public class BluetoothInCallService extends InCallService {
* state have occurred, {@code false} if the state should only be sent if the state has
* changed.
*/
- @RequiresPermission(allOf = {BLUETOOTH_CONNECT, MODIFY_PHONE_STATE})
- private void updateHeadsetWithCallState(boolean force) {
+ private void updateHeadsetWithCallState(HeadsetService headsetService, boolean force) {
+ if (headsetService == null) {
+ Log.i(TAG, "updateHeadsetWithCallState skipped: No headset service");
+ return;
+ }
+
BluetoothCall activeCall = mCallInfo.getActiveCall();
BluetoothCall ringingCall = mCallInfo.getRingingOrSimulatedRingingCall();
BluetoothCall heldCall = mCallInfo.getHeldCall();
@@ -1288,85 +1268,58 @@ public class BluetoothInCallService extends InCallService {
}
}
- if (mBluetoothHeadset != null
- && (force
- || (!callsPendingSwitch
- && (numActiveCalls != mNumActiveCalls
- || numChildrenOfActiveCall != mNumChildrenOfActiveCall
- || numHeldCalls != mNumHeldCalls
- || bluetoothCallState != mBluetoothCallState
- || !TextUtils.equals(ringingAddress, mRingingAddress)
- || ringingAddressType != mRingingAddressType
- || (!Objects.equals(heldCall, mOldHeldCall)
- && !ignoreHeldCallChange))))) {
-
- // If the BluetoothCall is transitioning into the alerting state, send DIALING first.
- // Some devices expect to see a DIALING state prior to seeing an ALERTING state
- // so we need to send it first.
- boolean sendDialingFirst =
- mBluetoothCallState != bluetoothCallState
- && bluetoothCallState == CALL_STATE_ALERTING;
-
- mOldHeldCall = heldCall;
- mNumActiveCalls = numActiveCalls;
- mNumChildrenOfActiveCall = numChildrenOfActiveCall;
- mNumHeldCalls = numHeldCalls;
- mBluetoothCallState = bluetoothCallState;
- mRingingAddress = ringingAddress;
- mRingingAddressType = ringingAddressType;
-
- if (sendDialingFirst) {
- // Log in full to make logs easier to debug.
- Log.i(
- TAG,
- "updateHeadsetWithCallState "
- + "numActive "
- + mNumActiveCalls
- + ", "
- + "numHeld "
- + mNumHeldCalls
- + ", "
- + "callState "
- + CALL_STATE_DIALING
- + ", "
- + "ringing type "
- + mRingingAddressType);
- mBluetoothHeadset.phoneStateChanged(
- mNumActiveCalls,
- mNumHeldCalls,
- CALL_STATE_DIALING,
- mRingingAddress,
- mRingingAddressType,
- ringingName);
- }
+ boolean callsDetailsChanged =
+ numActiveCalls != mNumActiveCalls
+ || numChildrenOfActiveCall != mNumChildrenOfActiveCall
+ || numHeldCalls != mNumHeldCalls
+ || bluetoothCallState != mBluetoothCallState
+ || !TextUtils.equals(ringingAddress, mRingingAddress)
+ || ringingAddressType != mRingingAddressType
+ || (!Objects.equals(heldCall, mOldHeldCall) && !ignoreHeldCallChange);
- Log.i(
- TAG,
- "updateHeadsetWithCallState "
- + "numActive "
- + mNumActiveCalls
- + ", "
- + "numHeld "
- + mNumHeldCalls
- + ", "
- + "callState "
- + mBluetoothCallState
- + ", "
- + "ringing type "
- + mRingingAddressType);
-
- mBluetoothHeadset.phoneStateChanged(
- mNumActiveCalls,
- mNumHeldCalls,
- mBluetoothCallState,
- mRingingAddress,
- mRingingAddressType,
- ringingName);
-
- mHeadsetUpdatedRecently = true;
- } else {
+ if (!(force || (!callsPendingSwitch && callsDetailsChanged))) {
Log.i(TAG, "updateHeadsetWithCallState skipped");
+ return;
}
+
+ mOldHeldCall = heldCall;
+ mNumActiveCalls = numActiveCalls;
+ mNumChildrenOfActiveCall = numChildrenOfActiveCall;
+ mNumHeldCalls = numHeldCalls;
+ mRingingAddress = ringingAddress;
+ mRingingAddressType = ringingAddressType;
+
+ // If the BluetoothCall is transitioning into the alerting state, send DIALING first.
+ // Some devices expect to see a DIALING state prior to seeing an ALERTING state
+ // so we need to send it first.
+ if (mBluetoothCallState != bluetoothCallState
+ && bluetoothCallState == CALL_STATE_ALERTING) {
+ phoneStateChanged(headsetService, CALL_STATE_DIALING, ringingName);
+ }
+
+ phoneStateChanged(headsetService, bluetoothCallState, ringingName);
+
+ mBluetoothCallState = bluetoothCallState;
+ mHeadsetUpdatedRecently = true;
+ }
+
+ private void phoneStateChanged(
+ HeadsetService headsetService, int callState, String ringingName) {
+ Log.i(
+ TAG,
+ "updateHeadsetWithCallState "
+ + (" numActive=" + mNumActiveCalls)
+ + (" numHeld=" + mNumHeldCalls)
+ + (" callState=" + callState)
+ + (" ringingType=" + mRingingAddressType));
+ headsetService.phoneStateChanged(
+ mNumActiveCalls,
+ mNumHeldCalls,
+ callState,
+ mRingingAddress,
+ mRingingAddressType,
+ ringingName,
+ false); // isVirtualCall
}
private int getBluetoothCallStateForUpdate() {
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java b/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java
index 800f53f809..5a1e3580b3 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlInputDescriptor.java
@@ -45,7 +45,7 @@ class VolumeControlInputDescriptor {
mNativeInterface = requireNonNull(nativeInterface);
mDevice = requireNonNull(device);
mVolumeInputs = new Descriptor[numberOfExternalInputs];
- // Stack delivers us number of AICSs instances. ids are countinous from [0;n[
+ // Stack delivers us number of AICSs instances. ids are continuous from [0;n[
for (int i = 0; i < numberOfExternalInputs; i++) {
mVolumeInputs[i] = new Descriptor();
}
diff --git a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
index 6adc1df93f..628a36b6e8 100644
--- a/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
+++ b/android/app/src/com/android/bluetooth/vc/VolumeControlService.java
@@ -1186,7 +1186,7 @@ public class VolumeControlService extends ProfileService {
}
/* Stack delivers us number of audio outputs.
- * Offset ids a countinous from 1 to number_of_ext_outputs*/
+ * Offset ids a continuous from 1 to number_of_ext_outputs*/
for (int i = 1; i <= numberOfExternalOutputs; i++) {
offsets.add(i);
/* Native stack is doing required reads under the hood */
@@ -1206,9 +1206,9 @@ public class VolumeControlService extends ProfileService {
}
void handleDeviceAvailable(
- BluetoothDevice device, int numberOfExternalOutputs, int numberOfExternaInputs) {
+ BluetoothDevice device, int numberOfExternalOutputs, int numberOfExternalInputs) {
handleExternalOutputs(device, numberOfExternalOutputs);
- handleExternalInputs(device, numberOfExternaInputs);
+ handleExternalInputs(device, numberOfExternalInputs);
}
void handleDeviceExtAudioOffsetChanged(BluetoothDevice device, int id, int value) {
diff --git a/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java
index 439186e4fa..768c62ee34 100644
--- a/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java
+++ b/android/app/tests/instrumentation/com/android/bluetooth/btservice/AdapterServiceTest.java
@@ -23,6 +23,7 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_ON;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
import static com.google.common.truth.Truth.assertThat;
@@ -202,9 +203,7 @@ public class AdapterServiceTest {
doReturn(true).when(mMockLeAudioService).isAvailable();
LeAudioService.setLeAudioService(mMockLeAudioService);
- doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED)
- .when(mMockLeAudioService)
- .getConnectionPolicy(any());
+ doReturn(CONNECTION_POLICY_ALLOWED).when(mMockLeAudioService).getConnectionPolicy(any());
AdapterNativeInterface.setInstance(mNativeInterface);
BluetoothKeystoreNativeInterface.setInstance(mKeystoreNativeInterface);
@@ -364,7 +363,7 @@ public class AdapterServiceTest {
}
private List<ProfileService> listOfMockServices() {
- return Flags.scanManagerRefactor()
+ return Flags.onlyStartScanDuringBleOn()
? List.of(mMockGattService, mMockService, mMockService2)
: List.of(mMockService, mMockService2);
}
@@ -375,7 +374,7 @@ public class AdapterServiceTest {
syncHandler(AdapterState.BLE_TURN_ON);
verifyStateChange(STATE_OFF, STATE_BLE_TURNING_ON);
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
syncHandler(MESSAGE_PROFILE_SERVICE_REGISTERED);
syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED);
}
@@ -392,7 +391,7 @@ public class AdapterServiceTest {
syncHandler(AdapterState.USER_TURN_OFF);
verifyStateChange(STATE_ON, STATE_TURNING_OFF);
- // Stop (if Flags.scanManagerRefactor GATT), PBAP, and PAN services
+ // Stop (if Flags.onlyStartScanDuringBleOn GATT), PBAP, and PAN services
assertThat(mAdapterService.mSetProfileServiceStateCounter)
.isEqualTo(listOfMockServices().size() * 2);
@@ -423,7 +422,7 @@ public class AdapterServiceTest {
syncHandler(AdapterState.USER_TURN_ON);
verifyStateChange(STATE_BLE_ON, STATE_TURNING_ON);
- // Start Mock (if Flags.scanManagerRefactor GATT), PBAP, and PAN services
+ // Start Mock (if Flags.onlyStartScanDuringBleOn GATT), PBAP, and PAN services
assertThat(mAdapterService.mSetProfileServiceStateCounter)
.isEqualTo(listOfMockServices().size());
@@ -467,7 +466,7 @@ public class AdapterServiceTest {
syncHandler(AdapterState.BLE_TURN_OFF);
verifyStateChange(STATE_BLE_ON, STATE_BLE_TURNING_OFF, CONTEXT_SWITCH_MS);
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
syncHandler(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); // stop GATT
syncHandler(MESSAGE_PROFILE_SERVICE_UNREGISTERED);
}
diff --git a/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
index a9eea3da60..e15141dcb7 100644
--- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
+++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/BluetoothInCallServiceTest.java
@@ -17,6 +17,7 @@
package com.android.bluetooth.telephony;
import static com.android.bluetooth.TestUtils.MockitoRule;
+import static com.android.bluetooth.TestUtils.mockGetSystemService;
import static com.google.common.truth.Truth.assertThat;
@@ -49,12 +50,11 @@ import androidx.test.core.app.ApplicationProvider;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.bluetooth.TestUtils;
import com.android.bluetooth.flags.Flags;
-import com.android.bluetooth.hfp.BluetoothHeadsetProxy;
import com.android.bluetooth.hfp.HeadsetService;
import com.android.bluetooth.tbs.BluetoothLeCallControlProxy;
+import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -71,7 +71,7 @@ import java.util.UUID;
@MediumTest
@RunWith(AndroidJUnit4.class)
public class BluetoothInCallServiceTest {
- private static final String TAG = BluetoothInCallServiceTest.class.getSimpleName();
+ private static final String TAG = "BluetoothInCallServiceTest";
private static final int TEST_DTMF_TONE = 0;
private static final String TEST_ACCOUNT_ADDRESS = "//foo.com/";
@@ -99,7 +99,6 @@ public class BluetoothInCallServiceTest {
@Rule public final MockitoRule mMockitoRule = new MockitoRule();
@Rule public final SetFlagsRule mSetFlagsRule = new SetFlagsRule();
- @Mock private BluetoothHeadsetProxy mMockBluetoothHeadset;
@Mock private HeadsetService mHeadsetService;
@Mock private BluetoothLeCallControlProxy mLeCallControl;
@Mock private BluetoothInCallService.CallInfo mMockCallInfo;
@@ -108,20 +107,27 @@ public class BluetoothInCallServiceTest {
@Before
public void setUp() {
+ doReturn(true).when(mHeadsetService).isAvailable();
+ HeadsetService.setHeadsetService(mHeadsetService);
+
doReturn(true).when(mMockCallInfo).isNullCall(null);
doReturn(false).when(mMockCallInfo).isNullCall(notNull());
Context spiedContext = spy(new ContextWrapper(ApplicationProvider.getApplicationContext()));
mMockTelephonyManager =
- TestUtils.mockGetSystemService(
+ mockGetSystemService(
spiedContext, Context.TELEPHONY_SERVICE, TelephonyManager.class);
mBluetoothInCallService =
- new BluetoothInCallService(
- spiedContext, mMockCallInfo, mMockBluetoothHeadset, mLeCallControl);
+ new BluetoothInCallService(spiedContext, mMockCallInfo, mLeCallControl);
mBluetoothInCallService.onCreate();
}
+ @After
+ public void tearDown() {
+ HeadsetService.setHeadsetService(null);
+ }
+
@Test
public void headsetAnswerCall() {
BluetoothCall mockCall = createRingingCall(UUID.randomUUID());
@@ -211,7 +217,7 @@ public class BluetoothInCallServiceTest {
doReturn(Uri.parse("tel:555-000")).when(activeCall).getHandle();
doReturn(List.of(activeCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
@@ -227,7 +233,7 @@ public class BluetoothInCallServiceTest {
@Test
public void bluetoothCallQualityReport() {
BluetoothCall activeCall = createForegroundCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
mBluetoothInCallService.sendBluetoothCallQualityReport(
10, // long timestamp
@@ -264,7 +270,7 @@ public class BluetoothInCallServiceTest {
doReturn(List.of(silentRingingCall)).when(mMockCallInfo).getBluetoothCalls();
doReturn(silentRingingCall).when(mMockCallInfo).getRingingOrSimulatedRingingCall();
- mBluetoothInCallService.onCallAdded(silentRingingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, silentRingingCall);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
@@ -282,9 +288,11 @@ public class BluetoothInCallServiceTest {
BluetoothCall parentCall = createActiveCall(UUID.randomUUID());
final BluetoothCall confCall1 = getMockCall(UUID.randomUUID());
final BluetoothCall confCall2 = createHeldCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(parentCall);
- mBluetoothInCallService.onCallAdded(confCall1);
- mBluetoothInCallService.onCallAdded(confCall2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
+ verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
+
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2);
doReturn(List.of(parentCall, confCall1, confCall2)).when(mMockCallInfo).getBluetoothCalls();
doReturn(Call.STATE_ACTIVE).when(confCall1).getState();
@@ -308,31 +316,32 @@ public class BluetoothInCallServiceTest {
doReturn(parentId).when(confCall1).getParentId();
doReturn(parentId).when(confCall2).getParentId();
- clearInvocations(mMockBluetoothHeadset);
- mBluetoothInCallService.queryPhoneState();
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ mBluetoothInCallService.queryPhoneState(mHeadsetService);
+ verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false);
doReturn(true).when(parentCall).wasConferencePreviouslyMerged();
List<BluetoothCall> children =
mBluetoothInCallService.getBluetoothCallsByIds(parentCall.getChildrenIds());
- mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ mBluetoothInCallService
+ .getCallback(parentCall)
+ .onChildrenChanged(mHeadsetService, parentCall, children);
+ verify(mHeadsetService, times(2))
+ .phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
// Spurious BluetoothCall to onIsConferencedChanged.
- mBluetoothInCallService.getCallback(parentCall).onChildrenChanged(parentCall, children);
+ mBluetoothInCallService
+ .getCallback(parentCall)
+ .onChildrenChanged(mHeadsetService, parentCall, children);
// Make sure the BluetoothCall has only occurred collectively 2 times (not on the third)
- verify(mMockBluetoothHeadset, times(2))
+ verify(mHeadsetService, times(3))
.phoneStateChanged(
- any(int.class),
- any(int.class),
- any(int.class),
+ anyInt(),
+ anyInt(),
+ anyInt(),
+ anyString(),
+ anyInt(),
nullable(String.class),
- any(int.class),
- nullable(String.class));
+ eq(false));
}
@Test
@@ -344,9 +353,9 @@ public class BluetoothInCallServiceTest {
doReturn(Uri.parse("tel:555-0001")).when(foregroundCall).getHandle();
final BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555-0002")).when(heldCall).getHandle();
- mBluetoothInCallService.onCallAdded(parentCall);
- mBluetoothInCallService.onCallAdded(foregroundCall);
- mBluetoothInCallService.onCallAdded(heldCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, foregroundCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall);
doReturn(List.of(parentCall, foregroundCall, heldCall))
.when(mMockCallInfo)
@@ -394,9 +403,9 @@ public class BluetoothInCallServiceTest {
doReturn(Uri.parse("tel:555-0000")).when(parentCall).getHandle();
doReturn(Uri.parse("tel:555-0001")).when(confCall1).getHandle();
doReturn(Uri.parse("tel:555-0002")).when(confCall2).getHandle();
- mBluetoothInCallService.onCallAdded(parentCall);
- mBluetoothInCallService.onCallAdded(confCall1);
- mBluetoothInCallService.onCallAdded(confCall2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2);
doReturn(List.of(parentCall, confCall1, confCall2)).when(mMockCallInfo).getBluetoothCalls();
doReturn(Call.STATE_ACTIVE).when(confCall1).getState();
@@ -436,7 +445,7 @@ public class BluetoothInCallServiceTest {
// This test does not define a value for getForegroundCall(), so this ringing
// BluetoothCall will be treated as if it is a waiting BluetoothCall
// when listCurrentCalls() is invoked.
- mBluetoothInCallService.onCallAdded(waitingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, waitingCall);
doReturn(true).when(waitingCall).isIncoming();
doReturn(new GatewayInfo(null, null, Uri.parse("tel:555-0000")))
@@ -471,7 +480,7 @@ public class BluetoothInCallServiceTest {
public void newCallClccResponse() {
BluetoothCall newCall = createForegroundCall(UUID.randomUUID());
doReturn(List.of(newCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(newCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, newCall);
doReturn(Call.STATE_NEW).when(newCall).getState();
@@ -494,7 +503,7 @@ public class BluetoothInCallServiceTest {
BluetoothCall activeCall = createForegroundCall(UUID.randomUUID());
doReturn(List.of(activeCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(Call.STATE_ACTIVE).when(activeCall).getState();
doReturn(true).when(activeCall).isIncoming();
@@ -535,7 +544,7 @@ public class BluetoothInCallServiceTest {
public void ringingCallClccResponse() {
BluetoothCall ringingCall = createForegroundCall(UUID.randomUUID());
doReturn(List.of(ringingCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
doReturn(Call.STATE_RINGING).when(ringingCall).getState();
doReturn(true).when(ringingCall).isIncoming();
@@ -572,7 +581,7 @@ public class BluetoothInCallServiceTest {
doReturn(calls).when(mMockCallInfo).getBluetoothCalls();
BluetoothCall ringingCall = createForegroundCall(UUID.randomUUID());
calls.add(ringingCall);
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
doReturn(Call.STATE_RINGING).when(ringingCall).getState();
doReturn(true).when(ringingCall).isIncoming();
@@ -581,7 +590,6 @@ public class BluetoothInCallServiceTest {
.when(ringingCall)
.getGatewayInfo();
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
.clccResponse(
@@ -597,7 +605,7 @@ public class BluetoothInCallServiceTest {
doReturn(Call.STATE_ACTIVE).when(ringingCall).getState();
BluetoothCall newHoldingCall = createHeldCall(UUID.randomUUID());
calls.add(0, newHoldingCall);
- mBluetoothInCallService.onCallAdded(newHoldingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, newHoldingCall);
doReturn(Call.STATE_HOLDING).when(newHoldingCall).getState();
doReturn(true).when(newHoldingCall).isIncoming();
@@ -620,7 +628,7 @@ public class BluetoothInCallServiceTest {
public void alertingCallClccResponse() {
BluetoothCall dialingCall = createForegroundCall(UUID.randomUUID());
doReturn(List.of(dialingCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(dialingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, dialingCall);
doReturn(Call.STATE_DIALING).when(dialingCall).getState();
doReturn(Uri.parse("tel:555-0000")).when(dialingCall).getHandle();
@@ -628,7 +636,6 @@ public class BluetoothInCallServiceTest {
.when(dialingCall)
.getGatewayInfo();
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
.clccResponse(
@@ -657,7 +664,7 @@ public class BluetoothInCallServiceTest {
doReturn(calls).when(mMockCallInfo).getBluetoothCalls();
BluetoothCall dialingCall = createForegroundCall(UUID.randomUUID());
calls.add(dialingCall);
- mBluetoothInCallService.onCallAdded(dialingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, dialingCall);
doReturn(Call.STATE_DIALING).when(dialingCall).getState();
doReturn(Uri.parse("tel:555-0000")).when(dialingCall).getHandle();
@@ -666,7 +673,7 @@ public class BluetoothInCallServiceTest {
.getGatewayInfo();
BluetoothCall holdingCall = createHeldCall(UUID.randomUUID());
calls.add(holdingCall);
- mBluetoothInCallService.onCallAdded(holdingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall);
doReturn(Call.STATE_HOLDING).when(holdingCall).getState();
doReturn(true).when(holdingCall).isIncoming();
@@ -675,7 +682,6 @@ public class BluetoothInCallServiceTest {
.when(holdingCall)
.getGatewayInfo();
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
.clccResponse(
@@ -712,9 +718,8 @@ public class BluetoothInCallServiceTest {
doReturn(Uri.parse("tel:555-0000")).when(parentCall).getHandle();
doReturn(List.of(parentCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService).clccResponse(1, 1, CALL_STATE_ACTIVE, 0, true, "5550000", 129);
@@ -733,9 +738,9 @@ public class BluetoothInCallServiceTest {
doReturn(Uri.parse("tel:555-0001")).when(childCall1).getHandle();
doReturn(Uri.parse("tel:555-0002")).when(childCall2).getHandle();
- mBluetoothInCallService.onCallAdded(parentCall);
- mBluetoothInCallService.onCallAdded(childCall1);
- mBluetoothInCallService.onCallAdded(childCall2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, childCall1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, childCall2);
addCallCapability(parentCall, Connection.CAPABILITY_MANAGE_CONFERENCE);
Integer parentId = parentCall.getId();
@@ -751,7 +756,6 @@ public class BluetoothInCallServiceTest {
doReturn(true).when(parentCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE);
doReturn(true).when(parentCall).isIncoming();
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
@@ -775,9 +779,8 @@ public class BluetoothInCallServiceTest {
doReturn(true).when(conferenceCall).hasProperty(Call.Details.PROPERTY_GENERIC_CONFERENCE);
doReturn(true).when(conferenceCall).isIncoming();
- mBluetoothInCallService.onCallAdded(conferenceCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall);
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService).clccResponse(1, 1, 0, 0, true, "5551234", 129);
}
@@ -792,7 +795,7 @@ public class BluetoothInCallServiceTest {
// active call is added
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
calls.add(activeCall);
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(Call.STATE_ACTIVE).when(activeCall).getState();
doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle();
@@ -803,7 +806,7 @@ public class BluetoothInCallServiceTest {
// holding call is added
BluetoothCall holdingCall = createHeldCall(UUID.randomUUID());
calls.add(holdingCall);
- mBluetoothInCallService.onCallAdded(holdingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall);
doReturn(Call.STATE_HOLDING).when(holdingCall).getState();
doReturn(true).when(holdingCall).isIncoming();
@@ -813,7 +816,6 @@ public class BluetoothInCallServiceTest {
.getGatewayInfo();
// needs to have at least one CLCC response before merge to enable call inference
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
.clccResponse(
@@ -827,8 +829,8 @@ public class BluetoothInCallServiceTest {
DisconnectCause cause = new DisconnectCause(DisconnectCause.OTHER);
doReturn(cause).when(activeCall).getDisconnectCause();
doReturn(cause).when(holdingCall).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall, true);
- mBluetoothInCallService.onCallRemoved(holdingCall, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, holdingCall, true);
BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID());
addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE);
@@ -843,9 +845,8 @@ public class BluetoothInCallServiceTest {
// parent call arrived, but children have not, then do inference on children
calls.add(conferenceCall);
assertThat(calls).hasSize(1);
- mBluetoothInCallService.onCallAdded(conferenceCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall);
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
verify(mHeadsetService)
.clccResponse(
@@ -856,10 +857,10 @@ public class BluetoothInCallServiceTest {
// real children arrive, no change on CLCC response
calls.add(activeCall);
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(true).when(activeCall).isConference();
calls.add(holdingCall);
- mBluetoothInCallService.onCallAdded(holdingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, holdingCall);
doReturn(Call.STATE_ACTIVE).when(holdingCall).getState();
doReturn(true).when(holdingCall).isConference();
doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds();
@@ -877,8 +878,8 @@ public class BluetoothInCallServiceTest {
cause = new DisconnectCause(DisconnectCause.LOCAL);
doReturn(cause).when(activeCall).getDisconnectCause();
doReturn(cause).when(holdingCall).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall, true);
- mBluetoothInCallService.onCallRemoved(holdingCall, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, holdingCall, true);
calls.remove(activeCall);
calls.remove(holdingCall);
assertThat(calls).hasSize(1);
@@ -890,7 +891,7 @@ public class BluetoothInCallServiceTest {
// when parent is removed
doReturn(cause).when(conferenceCall).getDisconnectCause();
calls.remove(conferenceCall);
- mBluetoothInCallService.onCallRemoved(conferenceCall, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, conferenceCall, true);
clearInvocations(mHeadsetService);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
@@ -921,8 +922,8 @@ public class BluetoothInCallServiceTest {
new DisconnectCause(DisconnectCause.OTHER, "IMS_MERGED_SUCCESSFULLY");
doReturn(cause).when(activeCall_1).getDisconnectCause();
doReturn(cause).when(activeCall_2).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall_1, true);
- mBluetoothInCallService.onCallRemoved(activeCall_2, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true);
BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID());
addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE);
@@ -938,14 +939,14 @@ public class BluetoothInCallServiceTest {
calls.add(conferenceCall);
doReturn(3).when(conferenceCall).getParentId();
doReturn(3).when(conferenceCall).getId();
- mBluetoothInCallService.onCallAdded(conferenceCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall);
// Call_1 and Call_2 are part of conference
calls.add(activeCall_1);
- mBluetoothInCallService.onCallAdded(activeCall_1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1);
doReturn(true).when(activeCall_1).isConference();
calls.add(activeCall_2);
- mBluetoothInCallService.onCallAdded(activeCall_2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2);
doReturn(Call.STATE_ACTIVE).when(activeCall_2).getState();
doReturn(true).when(activeCall_2).isConference();
doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds();
@@ -977,7 +978,7 @@ public class BluetoothInCallServiceTest {
// Call 1 active call is added
BluetoothCall activeCall_1 = createActiveCall(UUID.randomUUID());
calls.add(activeCall_1);
- mBluetoothInCallService.onCallAdded(activeCall_1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1);
doReturn(Call.STATE_ACTIVE).when(activeCall_1).getState();
doReturn(Uri.parse("tel:555-0001")).when(activeCall_1).getHandle();
@@ -988,7 +989,7 @@ public class BluetoothInCallServiceTest {
// Call 2 holding call is added
BluetoothCall activeCall_2 = createHeldCall(UUID.randomUUID());
calls.add(activeCall_2);
- mBluetoothInCallService.onCallAdded(activeCall_2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2);
doReturn(Call.STATE_HOLDING).when(activeCall_2).getState();
doReturn(true).when(activeCall_2).isIncoming();
@@ -1013,8 +1014,8 @@ public class BluetoothInCallServiceTest {
new DisconnectCause(DisconnectCause.OTHER, "IMS_MERGED_SUCCESSFULLY");
doReturn(cause).when(activeCall_1).getDisconnectCause();
doReturn(cause).when(activeCall_2).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall_1, true);
- mBluetoothInCallService.onCallRemoved(activeCall_2, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true);
BluetoothCall conferenceCall = createActiveCall(UUID.randomUUID());
addCallCapability(conferenceCall, Connection.CAPABILITY_MANAGE_CONFERENCE);
@@ -1029,7 +1030,7 @@ public class BluetoothInCallServiceTest {
// parent call arrived, but children have not, then do inference on children
calls.add(conferenceCall);
assertThat(calls).hasSize(1);
- mBluetoothInCallService.onCallAdded(conferenceCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceCall);
clearInvocations(mHeadsetService);
mBluetoothInCallService.listCurrentCalls(mHeadsetService);
@@ -1042,10 +1043,10 @@ public class BluetoothInCallServiceTest {
// real children arrive, no change on CLCC response
calls.add(activeCall_1);
- mBluetoothInCallService.onCallAdded(activeCall_1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_1);
doReturn(true).when(activeCall_1).isConference();
calls.add(activeCall_2);
- mBluetoothInCallService.onCallAdded(activeCall_2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall_2);
doReturn(Call.STATE_ACTIVE).when(activeCall_2).getState();
doReturn(true).when(activeCall_2).isConference();
doReturn(List.of(1, 2)).when(conferenceCall).getChildrenIds();
@@ -1063,14 +1064,14 @@ public class BluetoothInCallServiceTest {
doReturn(Call.STATE_DISCONNECTED).when(activeCall_1).getState();
cause = new DisconnectCause(DisconnectCause.OTHER);
doReturn(cause).when(activeCall_1).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall_1, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_1, true);
doReturn(false).when(activeCall_1).isConference();
calls.remove(activeCall_1);
assertThat(calls).hasSize(2);
// Call 2 removed from conf
doReturn(cause).when(activeCall_2).getDisconnectCause();
- mBluetoothInCallService.onCallRemoved(activeCall_2, true);
+ mBluetoothInCallService.onCallRemoved(mHeadsetService, activeCall_2, true);
doReturn(false).when(activeCall_2).isConference();
clearInvocations(mHeadsetService);
@@ -1087,17 +1088,17 @@ public class BluetoothInCallServiceTest {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
doReturn(Uri.parse("tel:5550000")).when(ringingCall).getHandle();
- clearInvocations(mMockBluetoothHeadset);
- mBluetoothInCallService.queryPhoneState();
+ mBluetoothInCallService.queryPhoneState(mHeadsetService);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("5550000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "5550000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
}
@Test
@@ -1105,8 +1106,8 @@ public class BluetoothInCallServiceTest {
BluetoothCall parentConfCall = createActiveCall(UUID.randomUUID());
final BluetoothCall confCall1 = getMockCall(UUID.randomUUID());
final BluetoothCall confCall2 = getMockCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(confCall1);
- mBluetoothInCallService.onCallAdded(confCall2);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall1);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, confCall2);
doReturn(Uri.parse("tel:555-0000")).when(parentConfCall).getHandle();
addCallCapability(parentConfCall, Connection.CAPABILITY_SWAP_CONFERENCE);
doReturn(true).when(parentConfCall).wasConferencePreviouslyMerged();
@@ -1114,11 +1115,9 @@ public class BluetoothInCallServiceTest {
List<Integer> childrenIds = Arrays.asList(confCall1.getId(), confCall2.getId());
doReturn(childrenIds).when(parentConfCall).getChildrenIds();
- clearInvocations(mMockBluetoothHeadset);
- mBluetoothInCallService.queryPhoneState();
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ mBluetoothInCallService.queryPhoneState(mHeadsetService);
+ verify(mHeadsetService, times(2))
+ .phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
@@ -1126,7 +1125,8 @@ public class BluetoothInCallServiceTest {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
Log.i("BluetoothInCallService", "asdf start " + Integer.toString(ringingCall.hashCode()));
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_RELEASEHELD);
verify(ringingCall).reject(eq(false), nullable(String.class));
assertThat(didProcess).isTrue();
@@ -1135,7 +1135,8 @@ public class BluetoothInCallServiceTest {
@Test
public void processChldTypeReleaseHeldHold() {
BluetoothCall onHoldCall = createHeldCall(UUID.randomUUID());
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_RELEASEHELD);
verify(onHoldCall).disconnect();
assertThat(didProcess).isTrue();
@@ -1147,7 +1148,8 @@ public class BluetoothInCallServiceTest {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
boolean didProcess =
- mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
verify(activeCall).disconnect();
verify(ringingCall).answer(any(int.class));
@@ -1159,7 +1161,8 @@ public class BluetoothInCallServiceTest {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
boolean didProcess =
- mBluetoothInCallService.processChld(CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_RELEASEACTIVE_ACCEPTHELD);
verify(activeCall).disconnect();
// BluetoothCall unhold will occur as part of CallsManager auto-unholding
@@ -1171,7 +1174,9 @@ public class BluetoothInCallServiceTest {
public void processChldHoldActiveRinging() {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
verify(ringingCall).answer(any(int.class));
assertThat(didProcess).isTrue();
@@ -1181,7 +1186,9 @@ public class BluetoothInCallServiceTest {
public void processChldHoldActiveUnhold() {
BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
verify(heldCall).unhold();
assertThat(didProcess).isTrue();
@@ -1192,7 +1199,9 @@ public class BluetoothInCallServiceTest {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
addCallCapability(activeCall, Connection.CAPABILITY_HOLD);
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
verify(activeCall).hold();
assertThat(didProcess).isTrue();
@@ -1203,7 +1212,8 @@ public class BluetoothInCallServiceTest {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
addCallCapability(activeCall, Connection.CAPABILITY_MERGE_CONFERENCE);
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_ADDHELDTOCONF);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_ADDHELDTOCONF);
verify(activeCall).mergeConference();
assertThat(didProcess).isTrue();
@@ -1215,11 +1225,12 @@ public class BluetoothInCallServiceTest {
BluetoothCall conferenceableCall = getMockCall(UUID.randomUUID());
ArrayList<Integer> conferenceableCalls = new ArrayList<>();
conferenceableCalls.add(conferenceableCall.getId());
- mBluetoothInCallService.onCallAdded(conferenceableCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, conferenceableCall);
doReturn(conferenceableCalls).when(activeCall).getConferenceableCalls();
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_ADDHELDTOCONF);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(mHeadsetService, CHLD_TYPE_ADDHELDTOCONF);
verify(activeCall).conference(conferenceableCall);
assertThat(didProcess).isTrue();
@@ -1240,13 +1251,12 @@ public class BluetoothInCallServiceTest {
List<Integer> childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId());
doReturn(childrenIds).when(parentCall).getChildrenIds();
- clearInvocations(mMockBluetoothHeadset);
- boolean didProcess = mBluetoothInCallService.processChld(CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
+ boolean didProcess =
+ mBluetoothInCallService.processChld(
+ mHeadsetService, CHLD_TYPE_HOLDACTIVE_ACCEPTHELD);
verify(parentCall).swapConference();
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false);
assertThat(didProcess).isTrue();
}
@@ -1256,16 +1266,17 @@ public class BluetoothInCallServiceTest {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("555000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "555000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
}
@Test
@@ -1274,16 +1285,17 @@ public class BluetoothInCallServiceTest {
doReturn(true).when(ringingCall).isSilentRingingRequested();
doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
- verify(mMockBluetoothHeadset, never())
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
}
@Test
@@ -1299,56 +1311,51 @@ public class BluetoothInCallServiceTest {
List<Integer> childrenIds = Arrays.asList(foregroundCall.getId(), heldCall.getId());
doReturn(childrenIds).when(parentCall).getChildrenIds();
- mBluetoothInCallService.onCallAdded(parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
public void onCallRemoved() {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(null).when(mMockCallInfo).getActiveCall();
doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle();
- mBluetoothInCallService.onCallRemoved(activeCall, true /* forceRemoveCallback */);
+ mBluetoothInCallService.onCallRemoved(
+ mHeadsetService, activeCall, true /* forceRemoveCallback */);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
public void onDetailsChangeExternalRemovesCall() {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(null).when(mMockCallInfo).getActiveCall();
doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle();
doReturn(true).when(activeCall).isExternalCall();
- mBluetoothInCallService.getCallback(activeCall).onDetailsChanged(activeCall, null);
+ mBluetoothInCallService
+ .getCallback(activeCall)
+ .onDetailsChanged(mHeadsetService, activeCall, null);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
public void onDetailsChangeExternalAddsCall() {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
doReturn(Uri.parse("tel:555-0001")).when(activeCall).getHandle();
BluetoothInCallService.CallStateCallback callBack =
mBluetoothInCallService.getCallback(activeCall);
doReturn(true).when(activeCall).isExternalCall();
- callBack.onDetailsChanged(activeCall, null);
+ callBack.onDetailsChanged(mHeadsetService, activeCall, null);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
@@ -1359,37 +1366,39 @@ public class BluetoothInCallServiceTest {
doReturn(List.of(connectingCall, activeCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(connectingCall);
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, connectingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
mBluetoothInCallService
.getCallback(activeCall)
.onStateChanged(activeCall, Call.STATE_HOLDING);
- verify(mMockBluetoothHeadset, never())
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
}
@Test
public void onCallAddedAudioProcessing() {
BluetoothCall call = getMockCall(UUID.randomUUID());
doReturn(Call.STATE_AUDIO_PROCESSING).when(call).getState();
- mBluetoothInCallService.onCallAdded(call);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, call);
- verify(mMockBluetoothHeadset, never())
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
}
@Test
@@ -1397,16 +1406,17 @@ public class BluetoothInCallServiceTest {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555000")).when(ringingCall).getHandle();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("555000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "555000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
doReturn(Call.STATE_AUDIO_PROCESSING).when(ringingCall).getState();
doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall();
@@ -1415,42 +1425,39 @@ public class BluetoothInCallServiceTest {
.getCallback(ringingCall)
.onStateChanged(ringingCall, Call.STATE_AUDIO_PROCESSING);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
public void onCallStateChangedAudioProcessingToSimulatedRinging() {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555-0000")).when(ringingCall).getHandle();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
mBluetoothInCallService
.getCallback(ringingCall)
.onStateChanged(ringingCall, Call.STATE_SIMULATED_RINGING);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("555-0000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "555-0000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
}
@Test
public void onCallStateChangedAudioProcessingToActive() {
BluetoothCall activeCall = createActiveCall(UUID.randomUUID());
doReturn(Call.STATE_ACTIVE).when(activeCall).getState();
- mBluetoothInCallService.onCallAdded(activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
mBluetoothInCallService
.getCallback(activeCall)
.onStateChanged(activeCall, Call.STATE_ACTIVE);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
@@ -1467,74 +1474,56 @@ public class BluetoothInCallServiceTest {
.get(activeCall.getId())
.onStateChanged(activeCall, Call.STATE_DIALING);
- verify(mMockBluetoothHeadset, never())
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
}
@Test
public void onCallStateChangedAlerting() {
BluetoothCall outgoingCall = createOutgoingCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(outgoingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, outgoingCall);
mBluetoothInCallService
.getCallback(outgoingCall)
.onStateChanged(outgoingCall, Call.STATE_DIALING);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_DIALING),
- eq(""),
- eq(128),
- nullable(String.class));
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_ALERTING),
- eq(""),
- eq(128),
- nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_DIALING, "", 128, null, false);
+ verify(mHeadsetService).phoneStateChanged(0, 0, CALL_STATE_ALERTING, "", 128, null, false);
}
@Test
public void onCallStateChangedDisconnected() {
BluetoothCall disconnectedCall = createDisconnectedCall(UUID.randomUUID());
doReturn(true).when(mMockCallInfo).hasOnlyDisconnectedCalls();
- mBluetoothInCallService.onCallAdded(disconnectedCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, disconnectedCall);
mBluetoothInCallService
.getCallback(disconnectedCall)
.onStateChanged(disconnectedCall, Call.STATE_DISCONNECTED);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_DISCONNECTED),
- eq(""),
- eq(128),
- nullable(String.class));
+ verify(mHeadsetService)
+ .phoneStateChanged(0, 0, CALL_STATE_DISCONNECTED, "", 128, null, false);
}
@Test
public void onCallStateChanged() {
BluetoothCall ringingCall = createRingingCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555-0000")).when(ringingCall).getHandle();
- mBluetoothInCallService.onCallAdded(ringingCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, ringingCall);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("555-0000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "555-0000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
// Switch to active
doReturn(null).when(mMockCallInfo).getRingingOrSimulatedRingingCall();
@@ -1544,29 +1533,27 @@ public class BluetoothInCallServiceTest {
.getCallback(ringingCall)
.onStateChanged(ringingCall, Call.STATE_ACTIVE);
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(0), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ verify(mHeadsetService).phoneStateChanged(1, 0, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
public void onCallStateChangedGSMSwap() {
BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
doReturn(Uri.parse("tel:555-0000")).when(heldCall).getHandle();
- mBluetoothInCallService.onCallAdded(heldCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall);
doReturn(2).when(mMockCallInfo).getNumHeldCalls();
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.getCallback(heldCall).onStateChanged(heldCall, Call.STATE_HOLDING);
- verify(mMockBluetoothHeadset, never())
+ verify(mHeadsetService, never())
.phoneStateChanged(
- eq(0),
- eq(2),
- eq(CALL_STATE_HELD),
- eq("5550000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 2,
+ CALL_STATE_HELD,
+ "5550000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
}
@Test
@@ -1577,9 +1564,9 @@ public class BluetoothInCallServiceTest {
BluetoothCall parentCall = createActiveCall(UUID.randomUUID());
BluetoothCall activeCall = getMockCall(UUID.randomUUID());
BluetoothCall heldCall = createHeldCall(UUID.randomUUID());
- mBluetoothInCallService.onCallAdded(parentCall);
- mBluetoothInCallService.onCallAdded(activeCall);
- mBluetoothInCallService.onCallAdded(heldCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, parentCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, activeCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall);
Integer parentId = parentCall.getId();
doReturn(parentId).when(activeCall).getParentId();
doReturn(parentId).when(heldCall).getParentId();
@@ -1592,51 +1579,58 @@ public class BluetoothInCallServiceTest {
addCallCapability(parentCall, Connection.CAPABILITY_SWAP_CONFERENCE);
- clearInvocations(mMockBluetoothHeadset);
+ clearInvocations(mHeadsetService);
// Be sure that onIsConferencedChanged rejects spurious changes during set up of
// CDMA "conference"
- mBluetoothInCallService.getCallback(activeCall).onParentChanged(activeCall);
- verify(mMockBluetoothHeadset, never())
+ mBluetoothInCallService
+ .getCallback(activeCall)
+ .onParentChanged(mHeadsetService, activeCall);
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
- mBluetoothInCallService.getCallback(heldCall).onParentChanged(heldCall);
- verify(mMockBluetoothHeadset, never())
+ mBluetoothInCallService.getCallback(heldCall).onParentChanged(mHeadsetService, heldCall);
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
mBluetoothInCallService
.getCallback(parentCall)
.onChildrenChanged(
- parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls));
- verify(mMockBluetoothHeadset, never())
+ mHeadsetService,
+ parentCall,
+ mBluetoothInCallService.getBluetoothCallsByIds(calls));
+ verify(mHeadsetService, never())
.phoneStateChanged(
anyInt(),
anyInt(),
anyInt(),
anyString(),
anyInt(),
- nullable(String.class));
+ nullable(String.class),
+ eq(false));
calls.add(heldCall.getId());
- mBluetoothInCallService.onCallAdded(heldCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, heldCall);
mBluetoothInCallService
.getCallback(parentCall)
.onChildrenChanged(
- parentCall, mBluetoothInCallService.getBluetoothCallsByIds(calls));
- verify(mMockBluetoothHeadset)
- .phoneStateChanged(
- eq(1), eq(1), eq(CALL_STATE_IDLE), eq(""), eq(128), nullable(String.class));
+ mHeadsetService,
+ parentCall,
+ mBluetoothInCallService.getBluetoothCallsByIds(calls));
+ verify(mHeadsetService).phoneStateChanged(1, 1, CALL_STATE_IDLE, "", 128, null, false);
}
@Test
@@ -1646,20 +1640,20 @@ public class BluetoothInCallServiceTest {
Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
- clearInvocations(mMockBluetoothHeadset);
mBluetoothInCallService.mBluetoothAdapterReceiver =
mBluetoothInCallService.new BluetoothAdapterReceiver();
mBluetoothInCallService.mBluetoothAdapterReceiver.onReceive(
mBluetoothInCallService, intent);
- verify(mMockBluetoothHeadset)
+ verify(mHeadsetService)
.phoneStateChanged(
- eq(0),
- eq(0),
- eq(CALL_STATE_INCOMING),
- eq("5550000"),
- eq(PhoneNumberUtils.TOA_Unknown),
- nullable(String.class));
+ 0,
+ 0,
+ CALL_STATE_INCOMING,
+ "5550000",
+ PhoneNumberUtils.TOA_Unknown,
+ null,
+ false);
}
@Test
@@ -1667,7 +1661,6 @@ public class BluetoothInCallServiceTest {
mBluetoothInCallService.clear();
assertThat(mBluetoothInCallService.mBluetoothAdapterReceiver).isNull();
- assertThat(mBluetoothInCallService.mBluetoothHeadset).isNull();
}
@Test
@@ -1844,9 +1837,9 @@ public class BluetoothInCallServiceTest {
doReturn(List.of(baseCall, firstCall, secondCall)).when(mMockCallInfo).getBluetoothCalls();
- mBluetoothInCallService.onCallAdded(baseCall);
- mBluetoothInCallService.onCallAdded(firstCall);
- mBluetoothInCallService.onCallAdded(secondCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, secondCall);
doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle();
doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle();
@@ -1877,8 +1870,8 @@ public class BluetoothInCallServiceTest {
doReturn(Call.STATE_ACTIVE).when(baseCall).getState();
doReturn(Call.STATE_RINGING).when(firstCall).getState();
- mBluetoothInCallService.onCallAdded(baseCall);
- mBluetoothInCallService.onCallAdded(firstCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall);
doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle();
doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle();
@@ -1910,9 +1903,9 @@ public class BluetoothInCallServiceTest {
doReturn(Call.STATE_RINGING).when(firstCall).getState();
doReturn(Call.STATE_RINGING).when(secondCall).getState();
- mBluetoothInCallService.onCallAdded(baseCall);
- mBluetoothInCallService.onCallAdded(firstCall);
- mBluetoothInCallService.onCallAdded(secondCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, baseCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, firstCall);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, secondCall);
doReturn(Uri.parse("tel:111-111")).when(baseCall).getHandle();
doReturn(Uri.parse("tel:222-222")).when(firstCall).getHandle();
@@ -2000,7 +1993,7 @@ public class BluetoothInCallServiceTest {
}
private void ManageCall(BluetoothCall call, String TeleString, int STATE) {
- mBluetoothInCallService.onCallAdded(call);
+ mBluetoothInCallService.onCallAdded(mHeadsetService, call);
doReturn(STATE).when(call).getState();
doReturn(Uri.parse(TeleString)).when(call).getHandle();
doReturn(new GatewayInfo(null, null, Uri.parse(TeleString))).when(call).getGatewayInfo();
diff --git a/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java
index 79ebced7de..18a4b4d053 100644
--- a/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java
+++ b/android/app/tests/instrumentation/com/android/bluetooth/telephony/CallInfoTest.java
@@ -72,7 +72,7 @@ public class CallInfoTest {
mockGetSystemService(
spiedContext, Context.TELECOM_SERVICE, TelecomManager.class, mTelecomManager);
- mBluetoothInCallService = new BluetoothInCallService(spiedContext, null, null, null);
+ mBluetoothInCallService = new BluetoothInCallService(spiedContext, null, null);
mBluetoothInCallService.onCreate();
mMockCallInfo = spy(mBluetoothInCallService.new CallInfo());
diff --git a/android/app/tests/unit/Android.bp b/android/app/tests/unit/Android.bp
index e0ed60ac22..01d195cc43 100644
--- a/android/app/tests/unit/Android.bp
+++ b/android/app/tests/unit/Android.bp
@@ -43,6 +43,7 @@ android_test {
"flag-junit",
"framework-bluetooth-pre-jarjar",
"gson",
+ "guava-android-testlib",
"mmslib",
"mockito-target-extended",
"modules-utils-handlerexecutor",
diff --git a/android/app/tests/unit/AndroidTest.xml b/android/app/tests/unit/AndroidTest.xml
index 7196d996d0..21fa4cb955 100644
--- a/android/app/tests/unit/AndroidTest.xml
+++ b/android/app/tests/unit/AndroidTest.xml
@@ -62,6 +62,8 @@
So instead we use the app cache folder for filter -->
<option name="test-filter-dir" value="/data/data/com.android.bluetooth/cache" />
<option name="hidden-api-checks" value="false"/>
+ <!-- Ignores tests introduced by guava-android-testlib -->
+ <option name="exclude-annotation" value="org.junit.Ignore"/>
</test>
<!-- Only run if the Bluetooth Mainline module is installed. -->
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 94e86b3778..cb61bc2853 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/TestUtils.java
@@ -153,7 +153,7 @@ public class TestUtils {
}
/**
- * Dispatch all the message on the Loopper and check that the `what` is expected
+ * Dispatch all the message on the Looper 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
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
index 0f41af59dd..eb3def2b89 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceBinderTest.java
@@ -17,6 +17,8 @@
package com.android.bluetooth.a2dp;
import static android.bluetooth.BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -29,7 +31,6 @@ import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothCodecConfig;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.AttributionSource;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
@@ -89,7 +90,7 @@ public class A2dpServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, sSource);
verify(mA2dpService).getDevicesMatchingConnectionStates(states);
@@ -121,7 +122,7 @@ public class A2dpServiceBinderTest {
@Test
public void setConnectionPolicy() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(sDevice, connectionPolicy, sSource);
verify(mA2dpService).setConnectionPolicy(sDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
index 5b17d2805f..943e80f7bf 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpServiceTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.a2dp;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -205,19 +208,17 @@ public class A2dpServiceTest {
@Test
public void testGetPriority() {
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
- assertThat(mA2dpService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
+ assertThat(mA2dpService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_UNKNOWN);
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
assertThat(mA2dpService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .isEqualTo(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
- assertThat(mA2dpService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
+ assertThat(mA2dpService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
}
/** Test okToConnect method using various test cases */
@@ -228,62 +229,43 @@ public class A2dpServiceTest {
testOkToConnectCase(
mDevice,
BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
+ testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(
mDevice,
BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
- testOkToConnectCase(
- mDevice,
- BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToConnectCase(mDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false);
testOkToConnectCase(
mDevice,
BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
testOkToConnectCase(
- mDevice,
- BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(
mDevice,
BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false);
+ testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true);
testOkToConnectCase(
- mDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- true);
- testOkToConnectCase(
- mDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
- testOkToConnectCase(
- mDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- true);
+ mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false);
+ testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_ALLOWED, true);
testOkToConnectCase(mDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false);
testOkToConnectCase(
mDevice,
badBondState,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
- testOkToConnectCase(
- mDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
+ testOkToConnectCase(mDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(
mDevice,
badBondState,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToConnectCase(mDevice, badBondState, badPriorityValue, false);
}
@@ -293,7 +275,7 @@ public class A2dpServiceTest {
public void testOutgoingConnectMissingAudioSinkUuid() {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -314,7 +296,7 @@ public class A2dpServiceTest {
// Set the device priority to PRIORITY_OFF so connect() should fail
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Send a connect request
assertThat(mA2dpService.connect(mDevice)).isFalse();
@@ -325,7 +307,7 @@ public class A2dpServiceTest {
public void testOutgoingConnectTimeout() {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -353,7 +335,7 @@ public class A2dpServiceTest {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -417,7 +399,7 @@ public class A2dpServiceTest {
BluetoothDevice testDevice = getTestDevice(i);
testDevices[i] = testDevice;
when(mDatabaseManager.getProfileConnectionPolicy(testDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
// Send a connect request
assertThat(mA2dpService.connect(testDevice)).isTrue();
dispatchAtLeastOneMessage();
@@ -441,7 +423,7 @@ public class A2dpServiceTest {
// Prepare and connect the extra test device. The connect request should fail
extraTestDevice = getTestDevice(MAX_CONNECTED_AUDIO_DEVICES);
when(mDatabaseManager.getProfileConnectionPolicy(extraTestDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
// Send a connect request
assertThat(mA2dpService.connect(extraTestDevice)).isFalse();
}
@@ -454,7 +436,7 @@ public class A2dpServiceTest {
public void testCreateStateMachineStackEvents() {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -537,7 +519,7 @@ public class A2dpServiceTest {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -552,8 +534,7 @@ public class A2dpServiceTest {
assertThat(mA2dpService.getDevices()).doesNotContain(mDevice);
// A2DP stack event: CONNECTION_STATE_CONNECTED - state machine should be created
- generateConnectionMessageFromNative(
- mDevice, STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+ generateConnectionMessageFromNative(mDevice, STATE_CONNECTED, STATE_DISCONNECTED);
assertThat(mA2dpService.getConnectionState(mDevice)).isEqualTo(STATE_CONNECTED);
assertThat(mA2dpService.getDevices()).contains(mDevice);
@@ -597,7 +578,7 @@ public class A2dpServiceTest {
public void testDeleteDisconnectedStateMachineUnbondEvents() {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -650,7 +631,7 @@ public class A2dpServiceTest {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -720,7 +701,7 @@ public class A2dpServiceTest {
public void testDeleteStateMachineDisconnectEvents() {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(any(BluetoothDevice.class));
doReturn(true).when(mMockNativeInterface).disconnectA2dp(any(BluetoothDevice.class));
@@ -769,7 +750,7 @@ public class A2dpServiceTest {
verify(mMockNativeInterface).setSilenceDevice(mDevice, true);
assertThat(mA2dpService.getActiveDevice()).isNull();
- // Test whether active device been resumeed after disable silence mode.
+ // Test whether active device been resumed after disable silence mode.
assertThat(mA2dpService.setSilenceMode(mDevice, false)).isTrue();
verify(mMockNativeInterface).setSilenceDevice(mDevice, false);
assertThat(mA2dpService.getActiveDevice()).isEqualTo(mDevice);
@@ -1045,7 +1026,7 @@ public class A2dpServiceTest {
// Update the device priority so okToConnect() returns true
when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.A2DP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
doReturn(true).when(mMockNativeInterface).connectA2dp(device);
doReturn(true).when(mMockNativeInterface).disconnectA2dp(device);
doReturn(true)
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java
index bd79d386ed..d51bae8f63 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dp/A2dpStateMachineTest.java
@@ -218,7 +218,7 @@ public class A2dpStateMachineTest {
testProcessCodecConfigEventCase(true);
}
- /** Helper methold to test processCodecConfigEvent() */
+ /** Helper method to test processCodecConfigEvent() */
public void testProcessCodecConfigEventCase(boolean offloadEnabled) {
doNothing()
.when(mService)
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java
index 3c653bf444..24ead6e4b8 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.a2dpsink;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.AttributionSource;
import org.junit.After;
@@ -75,7 +77,7 @@ public class A2dpSinkServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
AttributionSource source = new AttributionSource.Builder(0).build();
mBinder.getDevicesMatchingConnectionStates(states, source);
@@ -94,7 +96,7 @@ public class A2dpSinkServiceBinderTest {
@Test
public void setConnectionPolicy() {
BluetoothDevice device = getTestDevice(0);
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
AttributionSource source = new AttributionSource.Builder(0).build();
mBinder.setConnectionPolicy(device, connectionPolicy, source);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java
index 21dc3d7f34..5d13e09c9b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/A2dpSinkStateMachineTest.java
@@ -15,6 +15,9 @@
*/
package com.android.bluetooth.a2dpsink;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -31,7 +34,6 @@ import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothAudioConfig;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.media.AudioFormat;
import androidx.test.runner.AndroidJUnit4;
@@ -132,7 +134,7 @@ public class A2dpSinkStateMachineTest {
@Test
public void testAllowedIncomingConnectionInDisconnected() {
- mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED);
sendConnectionEvent(STATE_CONNECTING);
assertThat(mStateMachine.getState()).isEqualTo(STATE_CONNECTING);
@@ -141,7 +143,7 @@ public class A2dpSinkStateMachineTest {
@Test
public void testForbiddenIncomingConnectionInDisconnected() {
- mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN);
sendConnectionEvent(STATE_CONNECTING);
verify(mNativeInterface).disconnectA2dpSink(mDevice);
@@ -150,7 +152,7 @@ public class A2dpSinkStateMachineTest {
@Test
public void testUnknownIncomingConnectionInDisconnected() {
- mockDeviceConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ mockDeviceConnectionPolicy(mDevice, CONNECTION_POLICY_UNKNOWN);
sendConnectionEvent(STATE_CONNECTING);
assertThat(mStateMachine.getState()).isEqualTo(STATE_CONNECTING);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java b/android/app/tests/unit/src/com/android/bluetooth/a2dpsink/StackEventTest.java
index 25723ab0c9..b4944c2324 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) {
@@ -66,7 +70,7 @@ public class StackEventTest {
}
@Test
- public void testCreateAudioStateStartedvent() {
+ public void testCreateAudioStateStartedEvent() {
testAudioStateChangedBase(StackEvent.AUDIO_STATE_STARTED);
}
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 7a084783fb..29a3fc2be5 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
@@ -147,7 +147,7 @@ public class MediaPlayerListTest {
doReturn(prepareMediaData(PlaybackState.STATE_PAUSED))
.when(mMockPlayerWrapper)
.getCurrentMediaData();
- mMediaPlayerList.injectAudioPlaybacActive(true);
+ mMediaPlayerList.injectAudioPlaybackActive(true);
verify(mMediaUpdateCallback).run(mMediaUpdateData.capture());
MediaData data = mMediaUpdateData.getValue();
assertThat(data.state.getState()).isEqualTo(PlaybackState.STATE_PLAYING);
@@ -155,7 +155,7 @@ public class MediaPlayerListTest {
// verify update media data with current media player media data
MediaData currentMediaData = prepareMediaData(PlaybackState.STATE_PAUSED);
doReturn(currentMediaData).when(mMockPlayerWrapper).getCurrentMediaData();
- mMediaPlayerList.injectAudioPlaybacActive(false);
+ mMediaPlayerList.injectAudioPlaybackActive(false);
verify(mMediaUpdateCallback, times(2)).run(mMediaUpdateData.capture());
data = mMediaUpdateData.getValue();
assertThat(data.metadata).isEqualTo(currentMediaData.metadata);
@@ -180,8 +180,8 @@ public class MediaPlayerListTest {
doReturn(prepareMediaData(PlaybackState.STATE_PLAYING))
.when(mMockPlayerWrapper)
.getCurrentMediaData();
- mMediaPlayerList.injectAudioPlaybacActive(true);
- mMediaPlayerList.injectAudioPlaybacActive(false);
+ mMediaPlayerList.injectAudioPlaybackActive(true);
+ mMediaPlayerList.injectAudioPlaybackActive(false);
verify(mMediaUpdateCallback, never()).run(any());
}
@@ -190,7 +190,7 @@ public class MediaPlayerListTest {
doReturn(prepareMediaData(PlaybackState.STATE_PLAYING))
.when(mMockPlayerWrapper)
.getCurrentMediaData();
- mMediaPlayerList.injectAudioPlaybacActive(true);
+ mMediaPlayerList.injectAudioPlaybackActive(true);
verify(mMediaUpdateCallback, never()).run(any());
// Verify not update active player media data when audio playback is active
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 0ad8530e75..df6efa4a56 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
@@ -532,7 +532,7 @@ public class MetadataTest {
}
/**
- * Make sure you can create a Metadata object from a MediaDesciption with a bundle of extras
+ * Make sure you can create a Metadata object from a MediaDescription with a bundle of extras
* that provide more detailed information about the item.
*/
@Test
@@ -977,7 +977,7 @@ public class MetadataTest {
* cover art.
*/
@Test
- public void testBuildMetadataFromQueueItemWithIconUriandUrisDisabled() {
+ public void testBuildMetadataFromQueueItemWithIconUriAndUrisDisabled() {
Util.sUriImagesSupport = false;
MediaDescription description = getMediaDescription(null, IMAGE_URI_1, null);
QueueItem queueItem = getQueueItem(description);
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 93c2fe0678..73978edd1e 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
@@ -198,7 +198,7 @@ public class AvrcpBipObexServerTest {
/** Make sure onDisconnect notifies the callbacks in the proper way */
@Test
- public void testDisonnect() {
+ public void testDisconnect() {
mAvrcpBipObexServer.onDisconnect(mRequest, mReply);
verify(mCallback).onDisconnected();
}
@@ -284,7 +284,7 @@ public class AvrcpBipObexServerTest {
}
/**
- * Make sure a getImageProperties request with a valid handle returns a valie properties object
+ * Make sure a getImageProperties request with a valid handle returns a valid properties object
*/
@Test
public void testGetImagePropertiesWithValidHandle() throws Exception {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
index d4213b5b9f..d88f8122be 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpBipClientTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.avrcpcontroller;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.getConnectionStateName;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -24,7 +27,6 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import androidx.test.filters.SmallTest;
@@ -95,28 +97,9 @@ public class AvrcpBipClientTest {
@Test
public void setConnectionState() {
- mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING);
-
- assertThat(mClient.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTING);
- }
-
- @Test
- public void getConnectionState() {
- mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTED);
- assertThat(mClient.getStateName()).isEqualTo("Disconnected");
-
- mClient.setConnectionState(BluetoothProfile.STATE_CONNECTING);
- assertThat(mClient.getStateName()).isEqualTo("Connecting");
-
- mClient.setConnectionState(BluetoothProfile.STATE_CONNECTED);
- assertThat(mClient.getStateName()).isEqualTo("Connected");
-
- mClient.setConnectionState(BluetoothProfile.STATE_DISCONNECTING);
- assertThat(mClient.getStateName()).isEqualTo("Disconnecting");
+ mClient.setConnectionState(STATE_CONNECTING);
- int invalidState = 4;
- mClient.setConnectionState(invalidState);
- assertThat(mClient.getStateName()).isEqualTo("Unknown");
+ assertThat(mClient.getState()).isEqualTo(STATE_CONNECTING);
}
@Test
@@ -125,7 +108,7 @@ public class AvrcpBipClientTest {
"<AvrcpBipClient"
+ (" device=" + mDevice)
+ (" psm=" + TEST_PSM)
- + (" state=" + mClient.getStateName())
+ + (" state=" + getConnectionStateName(mClient.getState()))
+ ">";
assertThat(mClient.toString()).isEqualTo(expected);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java
index ac5c5dce3d..dd12985a44 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceBinderTest.java
@@ -16,13 +16,14 @@
package com.android.bluetooth.avrcpcontroller;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -58,7 +59,7 @@ public class AvrcpControllerServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
index 15d0d54926..e082270619 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerServiceTest.java
@@ -15,6 +15,9 @@
*/
package com.android.bluetooth.avrcpcontroller;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.android.bluetooth.TestUtils.mockGetSystemService;
@@ -31,7 +34,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
@@ -121,14 +123,14 @@ public class AvrcpControllerServiceTest {
@Test
public void disconnect_whenDisconnected_returnsFalse() {
- when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_DISCONNECTED);
+ when(mStateMachine.getState()).thenReturn(STATE_DISCONNECTED);
assertThat(mService.disconnect(mDevice)).isFalse();
}
@Test
public void disconnect_whenDisconnected_returnsTrue() {
- when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachine.getState()).thenReturn(STATE_CONNECTED);
assertThat(mService.disconnect(mDevice)).isTrue();
verify(mStateMachine).disconnect();
@@ -146,7 +148,7 @@ public class AvrcpControllerServiceTest {
@Test
public void getConnectedDevices() {
when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mDevice});
- when(mStateMachine.getState()).thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachine.getState()).thenReturn(STATE_CONNECTED);
assertThat(mService.getConnectedDevices()).contains(mDevice);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
index 66ad64ddea..368eac6c00 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpControllerStateMachineTest.java
@@ -16,6 +16,8 @@
package com.android.bluetooth.avrcpcontroller;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -101,7 +103,7 @@ public class AvrcpControllerStateMachineTest {
public void setUp() throws Exception {
mBrowseTree = new BrowseTree(null);
- doReturn(BluetoothProfile.STATE_DISCONNECTED).when(mCoverArtManager).getState(any());
+ doReturn(STATE_DISCONNECTED).when(mCoverArtManager).getState(any());
doReturn(15).when(mAudioManager).getStreamMaxVolume(anyInt());
doReturn(8).when(mAudioManager).getStreamVolume(anyInt());
@@ -157,13 +159,13 @@ public class AvrcpControllerStateMachineTest {
/** Destroy a state machine you created to test */
private void destroyStateMachine(AvrcpControllerStateMachine sm) {
- if (sm == null || sm.getState() == BluetoothProfile.STATE_DISCONNECTED) return;
+ if (sm == null || sm.getState() == STATE_DISCONNECTED) return;
sm.disconnect();
TestUtils.waitForLooperToBeIdle(sm.getHandler().getLooper());
// is disconnected
- assertThat(sm.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(sm.getState()).isEqualTo(STATE_DISCONNECTED);
// told mAvrcpControllerService to remove it
verify(mAvrcpControllerService).removeStateMachine(eq(sm));
@@ -203,9 +205,9 @@ public class AvrcpControllerStateMachineTest {
.sendBroadcast(mIntentArgument.capture(), eq(BLUETOOTH_CONNECT), any(Bundle.class));
assertThat(mAvrcpStateMachine.getCurrentState())
.isInstanceOf(AvrcpControllerStateMachine.Connected.class);
- assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_CONNECTED);
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
}
private AvrcpItem makeTrack(
@@ -356,10 +358,10 @@ public class AvrcpControllerStateMachineTest {
assertThat(mIntentArgument.getValue().getAction())
.isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED);
assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mAvrcpStateMachine.getCurrentState())
.isInstanceOf(AvrcpControllerStateMachine.Disconnected.class);
- assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED);
verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine));
}
@@ -385,10 +387,10 @@ public class AvrcpControllerStateMachineTest {
assertThat(mIntentArgument.getValue().getAction())
.isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED);
assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mAvrcpStateMachine.getCurrentState())
.isInstanceOf(AvrcpControllerStateMachine.Disconnected.class);
- assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED);
verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine));
}
@@ -414,10 +416,10 @@ public class AvrcpControllerStateMachineTest {
assertThat(mIntentArgument.getValue().getAction())
.isEqualTo(BluetoothAvrcpController.ACTION_CONNECTION_STATE_CHANGED);
assertThat(mIntentArgument.getValue().getIntExtra(BluetoothProfile.EXTRA_STATE, -1))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mAvrcpStateMachine.getCurrentState())
.isInstanceOf(AvrcpControllerStateMachine.Disconnected.class);
- assertThat(mAvrcpStateMachine.getState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mAvrcpStateMachine.getState()).isEqualTo(STATE_DISCONNECTED);
verify(mAvrcpControllerService).removeStateMachine(eq(mAvrcpStateMachine));
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java
index 58020003c3..98d00ebe5d 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpCoverArtStorageTest.java
@@ -42,20 +42,17 @@ import java.io.InputStream;
/** A test suite for the AvrcpCoverArtStorage class. */
@RunWith(AndroidJUnit4.class)
public final class AvrcpCoverArtStorageTest {
- private Context mTargetContext;
- private Resources mTestResources;
+ private final Context mTargetContext =
+ InstrumentationRegistry.getInstrumentation().getTargetContext();
+ private final Resources mTestResources = TestUtils.getTestApplicationResources(mTargetContext);
private final BluetoothDevice mDevice1 = getTestDevice(56);
private final BluetoothDevice mDevice2 = getTestDevice(57);
private Bitmap mImage1;
private Bitmap mImage2;
- private final String mHandle1 = "1";
- private final String mHandle2 = "2";
private AvrcpCoverArtStorage mAvrcpCoverArtStorage;
@Before
public void setUp() {
- mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
- mTestResources = TestUtils.getTestApplicationResources(mTargetContext);
InputStream is =
mTestResources.openRawResource(com.android.bluetooth.tests.R.raw.image_200_200);
mImage1 = BitmapFactory.decodeStream(is);
@@ -75,8 +72,6 @@ public final class AvrcpCoverArtStorageTest {
}
mImage1 = null;
mImage2 = null;
- mTestResources = null;
- mTargetContext = null;
}
private void assertImageSame(Bitmap expected, BluetoothDevice device, String handle) {
@@ -86,259 +81,251 @@ public final class AvrcpCoverArtStorageTest {
@Test
public void addNewImage_imageExists() {
- Uri expectedUri = AvrcpCoverArtProvider.getImageUri(mDevice1, mHandle1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ Uri expectedUri = AvrcpCoverArtProvider.getImageUri(mDevice1, "1");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
- Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
+ Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
assertThat(uri).isEqualTo(expectedUri);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void addExistingImage_imageUpdated() {
- Uri expectedUri = AvrcpCoverArtProvider.getImageUri(mDevice1, mHandle1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ Uri expectedUri = AvrcpCoverArtProvider.getImageUri(mDevice1, "1");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
- Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
assertThat(uri).isEqualTo(expectedUri);
- assertImageSame(mImage1, mDevice1, mHandle1);
+ assertImageSame(mImage1, mDevice1, "1");
- uri = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ uri = mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage2);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
assertThat(uri).isEqualTo(expectedUri);
- assertImageSame(mImage2, mDevice1, mHandle1);
+ assertImageSame(mImage2, mDevice1, "1");
}
@Test
public void addTwoImageSameDevice_bothExist() {
- Uri expectedUri1 = AvrcpCoverArtProvider.getImageUri(mDevice1, mHandle1);
- Uri expectedUri2 = AvrcpCoverArtProvider.getImageUri(mDevice1, mHandle2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isFalse();
+ Uri expectedUri1 = AvrcpCoverArtProvider.getImageUri(mDevice1, "1");
+ Uri expectedUri2 = AvrcpCoverArtProvider.getImageUri(mDevice1, "2");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isFalse();
- Uri uri1 = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- Uri uri2 = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage2);
+ Uri uri1 = mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ Uri uri2 = mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
assertThat(uri1).isEqualTo(expectedUri1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isTrue();
assertThat(uri2).isEqualTo(expectedUri2);
}
@Test
public void addTwoImageDifferentDevices_bothExist() {
- Uri expectedUri1 = AvrcpCoverArtProvider.getImageUri(mDevice1, mHandle1);
- Uri expectedUri2 = AvrcpCoverArtProvider.getImageUri(mDevice2, mHandle1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle1)).isFalse();
+ Uri expectedUri1 = AvrcpCoverArtProvider.getImageUri(mDevice1, "1");
+ Uri expectedUri2 = AvrcpCoverArtProvider.getImageUri(mDevice2, "1");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "1")).isFalse();
- Uri uri1 = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- Uri uri2 = mAvrcpCoverArtStorage.addImage(mDevice2, mHandle1, mImage1);
+ Uri uri1 = mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ Uri uri2 = mAvrcpCoverArtStorage.addImage(mDevice2, "1", mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
assertThat(uri1).isEqualTo(expectedUri1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
assertThat(uri2).isEqualTo(expectedUri2);
}
@Test
public void addNullImage_imageNotAdded() {
- Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, null);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, "1", null);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
assertThat(uri).isNull();
}
@Test
public void addImageNullDevice_imageNotAdded() {
- Uri uri = mAvrcpCoverArtStorage.addImage(null, mHandle1, mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ Uri uri = mAvrcpCoverArtStorage.addImage(null, "1", mImage1);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
assertThat(uri).isNull();
}
@Test
public void addImageNullHandle_imageNotAdded() {
Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, null, mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
assertThat(uri).isNull();
}
@Test
public void addImageEmptyHandle_imageNotAdded() {
Uri uri = mAvrcpCoverArtStorage.addImage(mDevice1, "", mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
assertThat(uri).isNull();
}
@Test
public void getImage_canGetImageFromStorage() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
- assertImageSame(mImage1, mDevice1, mHandle1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
+ assertImageSame(mImage1, mDevice1, "1");
}
@Test
public void getImageSameHandleDifferentDevices_canGetImagesFromStorage() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice2, mHandle1, mImage2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle1)).isTrue();
- assertImageSame(mImage1, mDevice1, mHandle1);
- assertImageSame(mImage2, mDevice2, mHandle1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice2, "1", mImage2);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "1")).isTrue();
+ assertImageSame(mImage1, mDevice1, "1");
+ assertImageSame(mImage2, mDevice2, "1");
}
@Test
public void getImageThatDoesntExist_returnsNull() {
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- Bitmap image = mAvrcpCoverArtStorage.getImage(mDevice1, mHandle1);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ Bitmap image = mAvrcpCoverArtStorage.getImage(mDevice1, "1");
assertThat(image).isNull();
}
@Test
public void getImageNullDevice_returnsNull() {
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- Bitmap image = mAvrcpCoverArtStorage.getImage(null, mHandle1);
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ Bitmap image = mAvrcpCoverArtStorage.getImage(null, "1");
assertThat(image).isNull();
}
@Test
public void getImageNullHandle_returnsNull() {
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
Bitmap image = mAvrcpCoverArtStorage.getImage(mDevice1, null);
assertThat(image).isNull();
}
@Test
public void getImageEmptyHandle_returnsNull() {
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
Bitmap image = mAvrcpCoverArtStorage.getImage(mDevice1, "");
assertThat(image).isNull();
}
@Test
public void removeExistingImage_imageDoesntExist() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice2, mHandle1, mImage1);
- mAvrcpCoverArtStorage.removeImage(mDevice1, mHandle1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isTrue();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle1)).isTrue();
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice2, "1", mImage1);
+ mAvrcpCoverArtStorage.removeImage(mDevice1, "1");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "1")).isTrue();
}
@Test
public void removeNonExistentImage_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.removeImage(mDevice1, mHandle2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.removeImage(mDevice1, "2");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void removeImageNullDevice_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.removeImage(null, mHandle1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.removeImage(null, "1");
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void removeImageNullHandle_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
mAvrcpCoverArtStorage.removeImage(mDevice1, null);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void removeImageEmptyHandle_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
mAvrcpCoverArtStorage.removeImage(mDevice1, "");
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void removeImageNullInputs_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
mAvrcpCoverArtStorage.removeImage(null, null);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
}
@Test
public void removeAllImagesForDevice_onlyOneDeviceImagesGone() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice2, mHandle1, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice2, "1", mImage1);
mAvrcpCoverArtStorage.removeImagesForDevice(mDevice1);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle1)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "1")).isTrue();
}
@Test
public void removeAllImagesForDeviceDne_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
mAvrcpCoverArtStorage.removeImagesForDevice(mDevice2);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isTrue();
}
@Test
public void removeAllImagesForNullDevice_nothingHappens() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
mAvrcpCoverArtStorage.removeImagesForDevice(null);
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isTrue();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isTrue();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isTrue();
}
@Test
public void clearStorageOneDevice_allImagesRemoved() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
mAvrcpCoverArtStorage.clear();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isFalse();
}
@Test
public void clearStorageManyDevices_allImagesRemoved() {
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle2, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice2, mHandle1, mImage1);
- mAvrcpCoverArtStorage.addImage(mDevice2, mHandle2, mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice1, "2", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice2, "1", mImage1);
+ mAvrcpCoverArtStorage.addImage(mDevice2, "2", mImage1);
mAvrcpCoverArtStorage.clear();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, mHandle2)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle1)).isFalse();
- assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, mHandle2)).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice1, "2")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "1")).isFalse();
+ assertThat(mAvrcpCoverArtStorage.doesImageExist(mDevice2, "2")).isFalse();
}
@Test
public void toString_returnsDeviceInfo() {
String expectedString =
- "CoverArtStorage:\n"
- + " "
- + mDevice1
- + " ("
- + 1
- + "):"
- + "\n "
- + mHandle1
- + "\n";
-
- mAvrcpCoverArtStorage.addImage(mDevice1, mHandle1, mImage1);
+ "CoverArtStorage:\n" + " " + mDevice1 + " (" + 1 + "):" + "\n " + "1" + "\n";
+
+ mAvrcpCoverArtStorage.addImage(mDevice1, "1", mImage1);
assertThat(mAvrcpCoverArtStorage.toString()).isEqualTo(expectedString);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java
index a059bb12c4..dbadfc526a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/AvrcpItemTest.java
@@ -20,7 +20,6 @@ import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.google.common.truth.Truth.assertThat;
-import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.net.Uri;
import android.support.v4.media.MediaBrowserCompat.MediaItem;
@@ -29,6 +28,8 @@ import android.support.v4.media.MediaMetadataCompat;
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -601,33 +602,15 @@ public final class AvrcpItemTest {
}
@Test
- public void equals_withItself() {
- AvrcpItem.Builder builder = new AvrcpItem.Builder();
+ public void equals() {
+ AvrcpItem item = new AvrcpItem.Builder().build();
+ AvrcpItem itemEqual = new AvrcpItem.Builder().build();
- AvrcpItem item = builder.build();
-
- assertThat(item).isEqualTo(item);
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void equals_withDifferentInstance() {
- AvrcpItem.Builder builder = new AvrcpItem.Builder();
String notAvrcpItem = "notAvrcpItem";
- AvrcpItem item = builder.build();
-
- assertThat(item).isNotEqualTo(notAvrcpItem);
- }
-
- @Test
- public void equals_withItemContainingSameInfo() {
- AvrcpItem.Builder builder = new AvrcpItem.Builder();
- AvrcpItem.Builder builderEqual = new AvrcpItem.Builder();
-
- AvrcpItem item = builder.build();
- AvrcpItem itemEqual = builderEqual.build();
-
- assertThat(item).isEqualTo(itemEqual);
+ new EqualsTester()
+ .addEqualityGroup(item, item, itemEqual)
+ .addEqualityGroup(notAvrcpItem)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java
index edf38bad24..dab7613a9a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/BrowseNodeTest.java
@@ -20,7 +20,6 @@ import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.google.common.truth.Truth.assertThat;
-import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.platform.test.annotations.EnableFlags;
import android.platform.test.flag.junit.SetFlagsRule;
@@ -31,6 +30,8 @@ import androidx.test.runner.AndroidJUnit4;
import com.android.bluetooth.avrcpcontroller.BrowseTree.BrowseNode;
import com.android.bluetooth.flags.Flags;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -223,21 +224,18 @@ public class BrowseNodeTest {
}
@Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void equals_withDifferentClass() {
- AvrcpItem avrcpItem = new AvrcpItem.Builder().setUuid(TEST_UUID).build();
-
- assertThat(mRootNode).isNotEqualTo(avrcpItem);
- }
-
- @Test
- public void equals_withSameId() {
+ public void equals() {
BrowseNode browseNodeOne =
mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build());
BrowseNode browseNodeTwo =
mBrowseTree.new BrowseNode(new AvrcpItem.Builder().setUuid(TEST_UUID).build());
- assertThat(browseNodeOne).isEqualTo(browseNodeTwo);
+ AvrcpItem avrcpItem = new AvrcpItem.Builder().setUuid(TEST_UUID).build();
+
+ new EqualsTester()
+ .addEqualityGroup(browseNodeOne, browseNodeTwo)
+ .addEqualityGroup(avrcpItem)
+ .testEquals();
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java
index 6f232a7883..782621d77a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/PlayerApplicationSettingsTest.java
@@ -116,43 +116,43 @@ public class PlayerApplicationSettingsTest {
}
@Test
- public void mapAvrcpPlayerSettingstoBTattribVal() {
+ public void mapAvrcpPlayerSettingsToBTattribVal() {
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.REPEAT_STATUS,
PlaybackStateCompat.REPEAT_MODE_NONE))
.isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_OFF);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.REPEAT_STATUS,
PlaybackStateCompat.REPEAT_MODE_ONE))
.isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_SINGLE_TRACK_REPEAT);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.REPEAT_STATUS,
PlaybackStateCompat.REPEAT_MODE_ALL))
.isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_ALL_TRACK_REPEAT);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.REPEAT_STATUS,
PlaybackStateCompat.REPEAT_MODE_GROUP))
.isEqualTo(PlayerApplicationSettings.JNI_REPEAT_STATUS_GROUP_REPEAT);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.SHUFFLE_STATUS,
PlaybackStateCompat.SHUFFLE_MODE_NONE))
.isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_OFF);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.SHUFFLE_STATUS,
PlaybackStateCompat.SHUFFLE_MODE_ALL))
.isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_ALL_TRACK_SHUFFLE);
assertThat(
- PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(
+ PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(
PlayerApplicationSettings.SHUFFLE_STATUS,
PlaybackStateCompat.SHUFFLE_MODE_GROUP))
.isEqualTo(PlayerApplicationSettings.JNI_SHUFFLE_STATUS_GROUP_SHUFFLE);
- assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingstoBTattribVal(-1, -1))
+ assertThat(PlayerApplicationSettings.mapAvrcpPlayerSettingsToBTattribVal(-1, -1))
.isEqualTo(PlayerApplicationSettings.JNI_STATUS_INVALID);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java
index 02a63b298b..03afb2826a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipAttachmentFormatTest.java
@@ -22,6 +22,8 @@ import android.annotation.SuppressLint;
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -422,30 +424,17 @@ public class BipAttachmentFormatTest {
}
@Test
- public void testEquals_withSameInstance() {
- BipAttachmentFormat attachment =
- new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null);
-
- assertThat(attachment).isEqualTo(attachment);
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void testEquals_withDifferentClass() {
- BipAttachmentFormat attachment =
- new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null);
- String notAttachment = "notAttachment";
-
- assertThat(attachment).isNotEqualTo(notAttachment);
- }
-
- @Test
- public void testEquals_withSameInfo() {
+ public void testEquals() {
BipAttachmentFormat attachment =
new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null);
BipAttachmentFormat attachmentEqual =
new BipAttachmentFormat("text/plain", null, "thisisatextfile.txt", -1, null, null);
- assertThat(attachment).isEqualTo(attachmentEqual);
+ String notAttachment = "notAttachment";
+
+ new EqualsTester()
+ .addEqualityGroup(attachment, attachment, attachmentEqual)
+ .addEqualityGroup(notAttachment)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java
index bf3b29a00d..5d93884efb 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipDatetimeTest.java
@@ -22,6 +22,8 @@ import android.annotation.SuppressLint;
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -213,29 +215,7 @@ public class BipDatetimeTest {
}
@Test
- public void testEquals_withSameInstance() {
- TimeZone utc = TimeZone.getTimeZone("UTC");
- utc.setRawOffset(0);
-
- BipDateTime bipDate = new BipDateTime(makeDate(1, 1, 2000, 6, 1, 15, utc));
-
- assertThat(bipDate).isEqualTo(bipDate);
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void testEquals_withDifferentClass() {
- TimeZone utc = TimeZone.getTimeZone("UTC");
- utc.setRawOffset(0);
-
- BipDateTime bipDate = new BipDateTime(makeDate(1, 1, 2000, 6, 1, 15, utc));
- String notBipDate = "notBipDate";
-
- assertThat(bipDate).isNotEqualTo(notBipDate);
- }
-
- @Test
- public void testEquals_withSameInfo() {
+ public void testEquals() {
TimeZone utc = TimeZone.getTimeZone("UTC");
utc.setRawOffset(0);
Date date = makeDate(1, 1, 2000, 6, 1, 15, utc);
@@ -243,6 +223,11 @@ public class BipDatetimeTest {
BipDateTime bipDate = new BipDateTime(date);
BipDateTime bipDateEqual = new BipDateTime(date);
- assertThat(bipDate).isEqualTo(bipDateEqual);
+ String notBipDate = "notBipDate";
+
+ new EqualsTester()
+ .addEqualityGroup(bipDate, bipDate, bipDateEqual)
+ .addEqualityGroup(notBipDate)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java
index 58f89753cd..8d0415dcaa 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageDescriptorTest.java
@@ -18,10 +18,10 @@ package com.android.bluetooth.avrcpcontroller;
import static com.google.common.truth.Truth.assertThat;
-import android.annotation.SuppressLint;
-
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -240,33 +240,15 @@ public class BipImageDescriptorTest {
}
@Test
- public void testEquals_sameInstance() {
- BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder();
-
- BipImageDescriptor descriptor = builder.build();
-
- assertThat(descriptor).isEqualTo(descriptor);
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void testEquals_differentClass() {
- BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder();
+ public void testEquals() {
+ BipImageDescriptor descriptor = new BipImageDescriptor.Builder().build();
+ BipImageDescriptor descriptorEqual = new BipImageDescriptor.Builder().build();
- BipImageDescriptor descriptor = builder.build();
String notDescriptor = "notDescriptor";
- assertThat(descriptor).isNotEqualTo(notDescriptor);
- }
-
- @Test
- public void testEquals_sameInfo() {
- BipImageDescriptor.Builder builder = new BipImageDescriptor.Builder();
- BipImageDescriptor.Builder builderEqual = new BipImageDescriptor.Builder();
-
- BipImageDescriptor descriptor = builder.build();
- BipImageDescriptor descriptorEqual = builderEqual.build();
-
- assertThat(descriptor).isEqualTo(descriptorEqual);
+ new EqualsTester()
+ .addEqualityGroup(descriptor, descriptor, descriptorEqual)
+ .addEqualityGroup(notDescriptor)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java
index 2f1e60cf34..75d04f6c8b 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/avrcpcontroller/bip/BipImageFormatTest.java
@@ -18,10 +18,10 @@ package com.android.bluetooth.avrcpcontroller;
import static com.google.common.truth.Truth.assertThat;
-import android.annotation.SuppressLint;
-
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -308,37 +308,18 @@ public class BipImageFormatTest {
}
@Test
- public void testEquals_withSameInstance() {
- BipImageFormat format =
- BipImageFormat.createNative(
- new BipEncoding(BipEncoding.JPEG, null),
- BipPixel.createFixed(1280, 1024),
- -1);
-
- assertThat(format).isEqualTo(format);
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void testEquals_withDifferentClass() {
- BipImageFormat format =
- BipImageFormat.createNative(
- new BipEncoding(BipEncoding.JPEG, null),
- BipPixel.createFixed(1280, 1024),
- -1);
- String notFormat = "notFormat";
-
- assertThat(format).isNotEqualTo(notFormat);
- }
-
- @Test
- public void testEquals_withSameInfo() {
+ public void testEquals() {
BipEncoding encoding = new BipEncoding(BipEncoding.JPEG, null);
BipPixel pixel = BipPixel.createFixed(1280, 1024);
BipImageFormat format = BipImageFormat.createNative(encoding, pixel, -1);
BipImageFormat formatEqual = BipImageFormat.createNative(encoding, pixel, -1);
- assertThat(format).isEqualTo(formatEqual);
+ String notFormat = "notFormat";
+
+ new EqualsTester()
+ .addEqualityGroup(format, format, formatEqual)
+ .addEqualityGroup(notFormat)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
index 2b08692043..77017748ba 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BassClientServiceTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.bass_client;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.EXTRA_PREVIOUS_STATE;
import static android.bluetooth.BluetoothProfile.EXTRA_STATE;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
@@ -355,9 +358,9 @@ public class BassClientServiceTest {
mBassClientService.cleanup();
when(mDatabaseManager.getProfileConnectionPolicy(
mCurrentDevice, BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
assertThat(mBassClientService.getConnectionPolicy(mCurrentDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .isEqualTo(CONNECTION_POLICY_UNKNOWN);
}
/**
@@ -369,7 +372,7 @@ public class BassClientServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class),
eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
assertThat(mBassClientService.connect(mCurrentDevice)).isTrue();
verify(mObjectsFactory)
@@ -386,7 +389,7 @@ public class BassClientServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class),
eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
BluetoothDevice nullDevice = null;
assertThat(mBassClientService.connect(nullDevice)).isFalse();
@@ -401,7 +404,7 @@ public class BassClientServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class),
eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
assertThat(mCurrentDevice).isNotNull();
assertThat(mBassClientService.connect(mCurrentDevice)).isFalse();
@@ -451,7 +454,7 @@ public class BassClientServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class),
eq(BluetoothProfile.LE_AUDIO_BROADCAST_ASSISTANT)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
// Mock the CSIP group
List<BluetoothDevice> groupDevices = new ArrayList<>();
@@ -991,7 +994,7 @@ public class BassClientServiceTest {
any(), any(), anyInt(), anyInt(), any(), any());
// Error in syncEstablished causes sourceLost, sourceAddFailed notification
- // and not removing cache because scanning is inactice
+ // and not removing cache because scanning is inactive
onSyncEstablishedFailed(device1, handle1);
TestUtils.waitForLooperToFinishScheduledTask(mBassClientService.getCallbacks().getLooper());
inOrderCallback.verify(mCallback).onSourceLost(eq(broadcastId1));
@@ -1420,7 +1423,7 @@ public class BassClientServiceTest {
// Add broadcast source
mBassClientService.addSource(mCurrentDevice, meta, /* isGroupOp */ true);
- /* In case if device supporth handover, Source stream status needs to be updated */
+ /* In case if device supports handover, Source stream status needs to be updated */
handleHandoverSupport();
// Verify all group members getting ADD_BCAST_SOURCE message
@@ -2024,7 +2027,7 @@ public class BassClientServiceTest {
ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
Optional<Message> msg;
- // Verrify that one device got the message...
+ // Verify that one device got the message...
verify(mStateMachines.get(mCurrentDevice), atLeast(1)).sendMessage(messageCaptor.capture());
msg =
messageCaptor.getAllValues().stream()
@@ -4212,7 +4215,7 @@ public class BassClientServiceTest {
verifyAddSourceForGroup(meta);
prepareRemoteSourceState(metaNoBroadcast, /* isPaSynced */ true, /* isBisSynced */ false);
- // Verify getSyncedBroadcastSinks returns empty device list if no broadcst ID
+ // Verify getSyncedBroadcastSinks returns empty device list if no broadcast ID
assertThat(mBassClientService.getSyncedBroadcastSinks().isEmpty()).isTrue();
assertThat(mBassClientService.getSyncedBroadcastSinks(TEST_BROADCAST_ID).isEmpty())
.isTrue();
@@ -4350,7 +4353,7 @@ public class BassClientServiceTest {
prepareTwoSynchronizedDevicesForLocalBroadcast();
- /* Imitiate scenario when if there would be broadcast - stop would be called */
+ /* Imitate scenario when if there would be broadcast - stop would be called */
mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
@@ -4366,7 +4369,7 @@ public class BassClientServiceTest {
prepareTwoSynchronizedDevicesForLocalBroadcast();
- /* Imitiate scenario when if there would be broadcast - stop would be called */
+ /* Imitate scenario when if there would be broadcast - stop would be called */
mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
@@ -4385,7 +4388,7 @@ public class BassClientServiceTest {
doReturn(false).when(mLeAudioService).isPlaying(TEST_BROADCAST_ID);
- /* Imitiate scenario when if there would be broadcast - stop would be called */
+ /* Imitate scenario when if there would be broadcast - stop would be called */
mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
@@ -4510,7 +4513,7 @@ public class BassClientServiceTest {
mBassClientService.notifyBroadcastStateChanged(
0 /* BROADCAST_STATE_STOPPED */, TEST_BROADCAST_ID);
- /* Imitiate scenario when if there would be broadcast - stop would be called */
+ /* Imitate scenario when if there would be broadcast - stop would be called */
mBassClientService.handleDeviceDisconnection(mCurrentDevice, true);
mBassClientService.handleDeviceDisconnection(mCurrentDevice1, true);
@@ -5377,7 +5380,7 @@ public class BassClientServiceTest {
BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID);
verifyAddSourceForGroup(meta);
- // Bis syned
+ // Bis synced
prepareRemoteSourceState(meta, /* isPaSynced */ true, /* isBisSynced */ true);
verify(mLeAudioService).activeBroadcastAssistantNotification(eq(true));
}
@@ -6072,7 +6075,7 @@ public class BassClientServiceTest {
BassConstants.PENDING_SYNC_HANDLE))
.isEqualTo(BassConstants.INVALID_BROADCAST_ID);
- // Resumue without another register sync is possible
+ // Resume without another register sync is possible
mBassClientService.resumeReceiversSourceSynchronization();
mInOrderMethodProxy
.verify(mMethodProxy, never())
@@ -6602,7 +6605,7 @@ public class BassClientServiceTest {
mBassClientService.suspendAllReceiversSourceSynchronization();
verifyRemoveMessageAndInjectSourceRemoval();
- // Start searching sources sync to paused broadcaser and remain cache
+ // Start searching sources sync to paused broadcaster and remain cache
startSearchingForSources();
mInOrderMethodProxy
.verify(mMethodProxy)
@@ -7034,7 +7037,7 @@ public class BassClientServiceTest {
startSearchingForSources();
checkTimeout(TEST_BROADCAST_ID, BassClientService.MESSAGE_BIG_MONITOR_TIMEOUT);
- // Check sync to another braodcaster during OOR monitoring
+ // Check sync to another broadcaster during OOR monitoring
ArgumentCaptor<ScanResult> resultCaptor = ArgumentCaptor.forClass(ScanResult.class);
checkTimeout(TEST_BROADCAST_ID, BassClientService.MESSAGE_BIG_MONITOR_TIMEOUT);
onScanResult(mSourceDevice2, TEST_BROADCAST_ID + 1);
@@ -7248,7 +7251,7 @@ public class BassClientServiceTest {
}
@Test
- public void testIsLocalBroadacst() {
+ public void testIsLocalBroadcast() {
int broadcastId = 12345;
BluetoothLeBroadcastMetadata metadata = createBroadcastMetadata(broadcastId);
@@ -7373,7 +7376,7 @@ public class BassClientServiceTest {
0 /* STATUS_LOCAL_STREAM_REQUESTED */);
injectRemoteSourceStateChanged(meta, /* isPaSynced */ false, /* isBisSynced */ false);
- // Resume source will force syncing to broadcaser and put pending source to add
+ // Resume source will force syncing to broadcaster and put pending source to add
mBassClientService.resumeReceiversSourceSynchronization();
mInOrderMethodProxy
.verify(mMethodProxy)
@@ -7649,20 +7652,14 @@ public class BassClientServiceTest {
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Connect again first sink
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7675,35 +7672,23 @@ public class BassClientServiceTest {
}
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
- // Disconnect second sink cause remove metada for both devices
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice1))
- .getConnectionState();
+ // Disconnect second sink cause remove metadata for both devices
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice1)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice1,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice1, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice1), TEST_SOURCE_ID + 1);
// Connect again both devices
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice1))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice1)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7739,20 +7724,14 @@ public class BassClientServiceTest {
}
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Connect again first sink
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7773,35 +7752,23 @@ public class BassClientServiceTest {
}
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
- // Disconnect second sink cause remove metada for both devices
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice1))
- .getConnectionState();
+ // Disconnect second sink cause remove metadata for both devices
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice1)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice1,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice1, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice1), TEST_SOURCE_ID + 1);
// Connect again both devices
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice1))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice1)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice1)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7830,14 +7797,10 @@ public class BassClientServiceTest {
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Remove second source should remove metadata for both
@@ -7848,9 +7811,7 @@ public class BassClientServiceTest {
}
// Connect again first sink
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7887,14 +7848,10 @@ public class BassClientServiceTest {
}
// Disconnect first sink not cause removing metadata
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Remove second source should remove metadata for both
@@ -7905,9 +7862,7 @@ public class BassClientServiceTest {
}
// Connect again first sink
- doReturn(BluetoothProfile.STATE_CONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_CONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(true).when(mStateMachines.get(mCurrentDevice)).isConnected();
prepareRemoteSourceState(meta, /* isPaSynced */ false, /* isBisSynced */ false);
@@ -7937,14 +7892,10 @@ public class BassClientServiceTest {
mBassClientService.addSource(mCurrentDevice1, meta, /* isGroupOp */ false);
// Disconnect first sink should remove pendingSourceToAdd for it
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Sync established should add source on only one sink
@@ -7986,14 +7937,10 @@ public class BassClientServiceTest {
mBassClientService.addSource(mCurrentDevice, meta, /* isGroupOp */ true);
// Disconnect first sink should remove pendingSourceToAdd for it
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(mStateMachines.get(mCurrentDevice))
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(mStateMachines.get(mCurrentDevice)).getConnectionState();
doReturn(false).when(mStateMachines.get(mCurrentDevice)).isConnected();
mBassClientService.connectionStateChanged(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
injectRemoteSourceStateRemoval(mStateMachines.get(mCurrentDevice), TEST_SOURCE_ID);
// Sync established should add source on only one sink
@@ -8045,7 +7992,7 @@ public class BassClientServiceTest {
@Test
@EnableFlags(Flags.FLAG_LEAUDIO_BROADCAST_RESYNC_HELPER)
- public void sinkDisconnectionDuringReasuming() {
+ public void sinkDisconnectionDuringResuming() {
prepareSynchronizedPairAndStopSearching();
BluetoothLeBroadcastMetadata meta = createBroadcastMetadata(TEST_BROADCAST_ID);
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 f93ff8eee3..de0641296a 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;
@@ -193,12 +197,12 @@ public class BassClientStateMachineTest {
private static int classTypeToConnectionState(Class type) {
if (type == BassClientStateMachine.Disconnected.class) {
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
} else if (type == BassClientStateMachine.Connecting.class) {
- return BluetoothProfile.STATE_CONNECTING;
+ return STATE_CONNECTING;
} else if (type == BassClientStateMachine.Connected.class
|| type == BassClientStateMachine.ConnectedProcessing.class) {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
} else {
assertWithMessage("Invalid class type given: " + type).fail();
return 0;
@@ -221,8 +225,7 @@ public class BassClientStateMachineTest {
/** Test that default state is disconnected */
@Test
public void testDefaultDisconnectedState() {
- assertThat(mBassClientStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mBassClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
/**
@@ -290,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
@@ -328,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);
@@ -341,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);
@@ -378,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
@@ -388,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
@@ -403,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
@@ -413,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
@@ -547,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());
@@ -561,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());
@@ -583,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());
@@ -1365,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());
@@ -1373,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);
}
@@ -1423,7 +1421,7 @@ public class BassClientStateMachineTest {
initToConnectingState();
Message msg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED);
- msg.obj = BluetoothProfile.STATE_CONNECTING;
+ msg.obj = STATE_CONNECTING;
BassClientStateMachine.BluetoothGattTestableWrapper btGatt =
Mockito.mock(BassClientStateMachine.BluetoothGattTestableWrapper.class);
mBassClientStateMachine.mBluetoothGatt = btGatt;
@@ -1437,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);
}
@@ -1502,7 +1500,7 @@ public class BassClientStateMachineTest {
initToConnectedState();
Message connectedMsg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED);
- connectedMsg.obj = BluetoothProfile.STATE_CONNECTED;
+ connectedMsg.obj = STATE_CONNECTED;
mBassClientStateMachine.sendMessage(connectedMsg);
TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper());
@@ -1512,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();
@@ -1721,7 +1719,7 @@ public class BassClientStateMachineTest {
BaseData data = Mockito.mock(BaseData.class);
when(mBassClientService.getBase(anyInt())).thenReturn(data);
- when(data.getNumberOfSubgroupsofBIG()).thenReturn((byte) 1);
+ when(data.getNumberOfSubGroupsOfBIG()).thenReturn((byte) 1);
Mockito.clearInvocations(callbacks);
mBassClientStateMachine.sendMessage(UPDATE_BCAST_SOURCE, sourceId, paSync, metadata);
@@ -1954,7 +1952,7 @@ public class BassClientStateMachineTest {
Message msgToConnectedState =
mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED);
- msgToConnectedState.obj = BluetoothProfile.STATE_CONNECTED;
+ msgToConnectedState.obj = STATE_CONNECTED;
mBassClientStateMachine.sendMessage(msgToConnectedState);
TestUtils.waitForLooperToFinishScheduledTask(mHandlerThread.getLooper());
@@ -1965,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();
@@ -2635,7 +2633,7 @@ public class BassClientStateMachineTest {
initToConnectingState();
Message msg = mBassClientStateMachine.obtainMessage(CONNECTION_STATE_CHANGED);
- msg.obj = BluetoothProfile.STATE_CONNECTED;
+ msg.obj = STATE_CONNECTED;
sendMessageAndVerifyTransition(msg, BassClientStateMachine.Connected.class);
Mockito.clearInvocations(mBassClientService);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java
index aa3a14ff1e..d51e857efe 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/BleBroadcastAssistantBinderTest.java
@@ -16,6 +16,8 @@
package com.android.bluetooth.bass_client;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
@@ -30,7 +32,6 @@ import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothLeBroadcastAssistantCallback;
import android.bluetooth.le.ScanFilter;
import android.content.AttributionSource;
@@ -109,16 +110,13 @@ public class BleBroadcastAssistantBinderTest {
@Test
public void setConnectionPolicy() {
- mBinder.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, mAttributionSource);
- verify(mService).setConnectionPolicy(mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource);
+ verify(mService).setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED);
mBinder.cleanup();
assertThat(
mBinder.setConnectionPolicy(
- mDevice,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- mAttributionSource))
+ mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource))
.isFalse();
}
@@ -129,7 +127,7 @@ public class BleBroadcastAssistantBinderTest {
mBinder.cleanup();
assertThat(mBinder.getConnectionPolicy(mDevice, mAttributionSource))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .isEqualTo(CONNECTION_POLICY_FORBIDDEN);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java
index c9b4986463..f8d3db6482 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/bass_client/PublicBroadcastDataTest.java
@@ -53,13 +53,13 @@ public class PublicBroadcastDataTest {
byte[] serviceDataInvalid =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
};
assertThat(PublicBroadcastData.parsePublicBroadcastData(serviceDataInvalid)).isNull();
byte[] serviceDataInvalid2 =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
(byte) 0x03, // metaDataLength
(byte) 0x06,
(byte) 0x07, // invalid metaData
@@ -82,7 +82,7 @@ public class PublicBroadcastDataTest {
byte[] serviceDataNoMetaData =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
(byte) 0x00, // metaDataLength
};
PublicBroadcastData dataNoMetaData =
@@ -100,13 +100,13 @@ public class PublicBroadcastDataTest {
int metaDataLength = 142;
byte[] serviceDataInvalid =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
};
assertThat(PublicBroadcastData.parsePublicBroadcastData(serviceDataInvalid)).isNull();
byte[] serviceDataInvalid2 =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
(byte) 0x03, // metaDataLength
(byte) 0x06,
(byte) 0x07, // invalid metaData
@@ -138,7 +138,7 @@ public class PublicBroadcastDataTest {
byte[] serviceDataNoMetaData =
new byte[] {
- (byte) 0x02, // features, non-encrypted, standard quality prsent
+ (byte) 0x02, // features, non-encrypted, standard quality preset
(byte) 0x00, // metaDataLength
};
PublicBroadcastData dataNoMetaData =
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java
index e07cc3780b..abe3891872 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/ActiveDeviceManagerTest.java
@@ -16,6 +16,12 @@
package com.android.bluetooth.btservice;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.android.bluetooth.TestUtils.mockGetSystemService;
@@ -38,7 +44,6 @@ import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothLeBroadcastMetadata;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSinkAudioPolicy;
import android.content.Context;
@@ -394,7 +399,7 @@ public class ActiveDeviceManagerTest {
mTestLooper.dispatchAll();
verify(mHeadsetService).setActiveDevice(mHeadsetDevice);
- // HFP activce device to null. Expect to fallback to LeAudio.
+ // HFP active device to null. Expect to fallback to LeAudio.
headsetActiveDeviceChanged(null);
mTestLooper.dispatchAll();
verify(mLeAudioService, times(2)).setActiveDevice(mLeAudioDevice);
@@ -585,7 +590,7 @@ public class ActiveDeviceManagerTest {
}
@Test
- public void a2dpHeadsetActivated_checkFallbackMeachanismOneA2dpOneHeadset() {
+ public void a2dpHeadsetActivated_checkFallbackMechanismOneA2dpOneHeadset() {
// Active call
when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_IN_CALL);
@@ -606,9 +611,7 @@ public class ActiveDeviceManagerTest {
when(mHeadsetService.getFallbackDevice()).thenReturn(mA2dpHeadsetDevice);
mDatabaseManager.setProfileConnectionPolicy(
- mA2dpHeadsetDevice,
- BluetoothProfile.A2DP,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mA2dpHeadsetDevice, BluetoothProfile.A2DP, CONNECTION_POLICY_FORBIDDEN);
a2dpDisconnected(mA2dpHeadsetDevice);
mTestLooper.dispatchAll();
verify(mHeadsetService, times(2)).setActiveDevice(mA2dpHeadsetDevice);
@@ -637,9 +640,7 @@ public class ActiveDeviceManagerTest {
when(mHeadsetService.getFallbackDevice()).thenReturn(mA2dpHeadsetDevice);
mDatabaseManager.setProfileConnectionPolicy(
- mSecondaryAudioDevice,
- BluetoothProfile.HEADSET,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mSecondaryAudioDevice, BluetoothProfile.HEADSET, CONNECTION_POLICY_FORBIDDEN);
headsetDisconnected(mSecondaryAudioDevice);
mTestLooper.dispatchAll();
verify(mHeadsetService, times(3)).setActiveDevice(mA2dpHeadsetDevice);
@@ -1099,7 +1100,7 @@ public class ActiveDeviceManagerTest {
leAudioDisconnected(mLeAudioDevice2);
mTestLooper.dispatchAll();
- // Should not encrease a number of this call.
+ // Should not increase a number of this call.
order.verify(mLeAudioService, never()).setActiveDevice(any());
leAudioDisconnected(mLeAudioDevice);
@@ -1755,8 +1756,7 @@ public class ActiveDeviceManagerTest {
*/
@Test
public void a2dpConnectedWhenBroadcasting_notSetA2dpActive() {
- final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
- when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
+ when(mLeAudioService.isBroadcastStarted()).thenReturn(true);
a2dpConnected(mA2dpDevice, false);
mTestLooper.dispatchAll();
verify(mA2dpService, never()).setActiveDevice(any());
@@ -1771,8 +1771,7 @@ public class ActiveDeviceManagerTest {
*/
@Test
public void headsetConnectedWhenBroadcasting_notSetHeadsetActive() {
- final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
- when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
+ when(mLeAudioService.isBroadcastStarted()).thenReturn(true);
headsetConnected(mHeadsetDevice, false);
mTestLooper.dispatchAll();
verify(mHeadsetService, never()).setActiveDevice(any());
@@ -1787,8 +1786,7 @@ public class ActiveDeviceManagerTest {
*/
@Test
public void hearingAidConnectedWhenBroadcasting_notSetHearingAidActive() {
- final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
- when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
+ when(mLeAudioService.isBroadcastStarted()).thenReturn(true);
hearingAidConnected(mHearingAidDevice);
mTestLooper.dispatchAll();
verify(mHearingAidService, never()).setActiveDevice(any());
@@ -1800,8 +1798,7 @@ public class ActiveDeviceManagerTest {
*/
@Test
public void leHearingAidConnectedWhenBroadcasting_notSetLeHearingAidActive() {
- final List<BluetoothLeBroadcastMetadata> metadataList = mock(List.class);
- when(mLeAudioService.getAllBroadcastMetadata()).thenReturn(metadataList);
+ when(mLeAudioService.isBroadcastStarted()).thenReturn(true);
leHearingAidConnected(mLeHearingAidDevice);
mTestLooper.dispatchAll();
verify(mLeAudioService, never()).setActiveDevice(any());
@@ -1829,18 +1826,13 @@ public class ActiveDeviceManagerTest {
mDatabaseManager.setProfileConnectionPolicy(
device,
BluetoothProfile.HEADSET,
- supportHfp
- ? BluetoothProfile.CONNECTION_POLICY_ALLOWED
- : BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ supportHfp ? CONNECTION_POLICY_ALLOWED : CONNECTION_POLICY_UNKNOWN);
mDeviceConnectionStack.add(device);
mMostRecentDevice = device;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.A2DP,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.A2DP, device, STATE_DISCONNECTED, STATE_CONNECTED);
}
/** Helper to indicate A2dp disconnected for a device. */
@@ -1852,10 +1844,7 @@ public class ActiveDeviceManagerTest {
: null;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.A2DP,
- device,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ BluetoothProfile.A2DP, device, STATE_CONNECTED, STATE_DISCONNECTED);
}
/** Helper to indicate A2dp active device changed for a device. */
@@ -1872,18 +1861,13 @@ public class ActiveDeviceManagerTest {
mDatabaseManager.setProfileConnectionPolicy(
device,
BluetoothProfile.A2DP,
- supportA2dp
- ? BluetoothProfile.CONNECTION_POLICY_ALLOWED
- : BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ supportA2dp ? CONNECTION_POLICY_ALLOWED : CONNECTION_POLICY_UNKNOWN);
mDeviceConnectionStack.add(device);
mMostRecentDevice = device;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HEADSET,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.HEADSET, device, STATE_DISCONNECTED, STATE_CONNECTED);
}
/** Helper to indicate Headset disconnected for a device. */
@@ -1895,10 +1879,7 @@ public class ActiveDeviceManagerTest {
: null;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HEADSET,
- device,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ BluetoothProfile.HEADSET, device, STATE_CONNECTED, STATE_DISCONNECTED);
}
/** Helper to indicate Headset active device changed for a device. */
@@ -1916,10 +1897,7 @@ public class ActiveDeviceManagerTest {
mMostRecentDevice = device;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HEARING_AID,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.HEARING_AID, device, STATE_DISCONNECTED, STATE_CONNECTED);
}
/** Helper to indicate Hearing Aid disconnected for a device. */
@@ -1931,10 +1909,7 @@ public class ActiveDeviceManagerTest {
: null;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HEARING_AID,
- device,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ BluetoothProfile.HEARING_AID, device, STATE_CONNECTED, STATE_DISCONNECTED);
}
/** Helper to indicate Hearing Aid active device changed for a device. */
@@ -1951,10 +1926,7 @@ public class ActiveDeviceManagerTest {
mMostRecentDevice = device;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.LE_AUDIO,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.LE_AUDIO, device, STATE_DISCONNECTED, STATE_CONNECTED);
}
/** Helper to indicate LE Audio disconnected for a device. */
@@ -1966,10 +1938,7 @@ public class ActiveDeviceManagerTest {
: null;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.LE_AUDIO,
- device,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ BluetoothProfile.LE_AUDIO, device, STATE_CONNECTED, STATE_DISCONNECTED);
}
/** Helper to indicate LE Audio active device changed for a device. */
@@ -1987,10 +1956,7 @@ public class ActiveDeviceManagerTest {
mMostRecentDevice = device;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HAP_CLIENT,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.HAP_CLIENT, device, STATE_DISCONNECTED, STATE_CONNECTED);
}
/** Helper to indicate LE Hearing Aid disconnected for a device. */
@@ -2002,10 +1968,7 @@ public class ActiveDeviceManagerTest {
: null;
mActiveDeviceManager.profileConnectionStateChanged(
- BluetoothProfile.HAP_CLIENT,
- device,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ BluetoothProfile.HAP_CLIENT, device, STATE_CONNECTED, STATE_DISCONNECTED);
}
private class TestDatabaseManager extends DatabaseManager {
@@ -2036,9 +1999,9 @@ public class ActiveDeviceManagerTest {
if (device == null) {
return false;
}
- if (policy != BluetoothProfile.CONNECTION_POLICY_UNKNOWN
- && policy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && policy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (policy != CONNECTION_POLICY_UNKNOWN
+ && policy != CONNECTION_POLICY_FORBIDDEN
+ && policy != CONNECTION_POLICY_ALLOWED) {
return false;
}
SparseIntArray policyMap = mProfileConnectionPolicy.get(device);
@@ -2054,9 +2017,9 @@ public class ActiveDeviceManagerTest {
public int getProfileConnectionPolicy(BluetoothDevice device, int profile) {
SparseIntArray policy = mProfileConnectionPolicy.get(device);
if (policy == null) {
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
- return policy.get(profile, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ return policy.get(profile, CONNECTION_POLICY_FORBIDDEN);
}
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java
index 36541709ff..9fd3d19837 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/AdapterServiceTest.java
@@ -23,6 +23,10 @@ import static android.bluetooth.BluetoothAdapter.STATE_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_ON;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_OFF;
import static android.bluetooth.BluetoothAdapter.STATE_TURNING_ON;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -221,9 +225,7 @@ public class AdapterServiceTest {
doReturn(true).when(mMockLeAudioService).isAvailable();
LeAudioService.setLeAudioService(mMockLeAudioService);
- doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED)
- .when(mMockLeAudioService)
- .getConnectionPolicy(any());
+ doReturn(CONNECTION_POLICY_ALLOWED).when(mMockLeAudioService).getConnectionPolicy(any());
AdapterNativeInterface.setInstance(mNativeInterface);
BluetoothKeystoreNativeInterface.setInstance(mKeystoreNativeInterface);
@@ -393,7 +395,7 @@ public class AdapterServiceTest {
}
private List<ProfileService> listOfMockServices() {
- return Flags.scanManagerRefactor()
+ return Flags.onlyStartScanDuringBleOn()
? List.of(mMockGattService, mMockService, mMockService2)
: List.of(mMockService, mMockService2);
}
@@ -410,7 +412,7 @@ public class AdapterServiceTest {
TestUtils.syncHandler(looper, AdapterState.BLE_TURN_ON);
verifyStateChange(callback, STATE_OFF, STATE_BLE_TURNING_ON);
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
TestUtils.syncHandler(looper, MESSAGE_PROFILE_SERVICE_REGISTERED);
TestUtils.syncHandler(looper, MESSAGE_PROFILE_SERVICE_STATE_CHANGED);
}
@@ -434,7 +436,7 @@ public class AdapterServiceTest {
verifyStateChange(callback, STATE_ON, STATE_TURNING_OFF);
if (!onlyGatt) {
- // Stop (if Flags.scanManagerRefactor GATT), PBAP, and PAN services
+ // Stop (if Flags.onlyStartScanDuringBleOn GATT), PBAP, and PAN services
assertThat(adapter.mSetProfileServiceStateCounter).isEqualTo(services.size() * 2);
for (ProfileService service : services) {
@@ -485,7 +487,7 @@ public class AdapterServiceTest {
verifyStateChange(callback, STATE_BLE_ON, STATE_TURNING_ON);
if (!onlyGatt) {
- // Start Mock (if Flags.scanManagerRefactor GATT), PBAP, and PAN services
+ // Start Mock (if Flags.onlyStartScanDuringBleOn GATT), PBAP, and PAN services
assertThat(adapter.mSetProfileServiceStateCounter).isEqualTo(services.size());
for (ProfileService service : services) {
@@ -538,7 +540,7 @@ public class AdapterServiceTest {
TestUtils.syncHandler(looper, AdapterState.BLE_TURN_OFF);
verifyStateChange(callback, STATE_BLE_ON, STATE_BLE_TURNING_OFF);
- if (!Flags.scanManagerRefactor()) {
+ if (!Flags.onlyStartScanDuringBleOn()) {
TestUtils.syncHandler(looper, MESSAGE_PROFILE_SERVICE_STATE_CHANGED);
TestUtils.syncHandler(looper, MESSAGE_PROFILE_SERVICE_UNREGISTERED);
}
@@ -590,7 +592,7 @@ public class AdapterServiceTest {
* started and stopped.
*/
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
public void testEnableDisableOnlyGatt() {
Context mockContext = mock(Context.class);
Resources mockResources = mock(Resources.class);
@@ -613,7 +615,7 @@ public class AdapterServiceTest {
/** Test: Don't start GATT Check whether the AdapterService quits gracefully */
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
public void testGattStartTimeout() {
assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF);
@@ -645,7 +647,7 @@ public class AdapterServiceTest {
/** Test: Don't stop GATT Check whether the AdapterService quits gracefully */
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
public void testGattStopTimeout() {
doEnable(false);
@@ -678,8 +680,8 @@ public class AdapterServiceTest {
}
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void startBleOnly_whenScanManagerRefactorFlagIsOff_onlyStartGattProfile() {
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void startBleOnly_whenOnlyStartScanDuringBleOnFlagIsOff_onlyStartGattProfile() {
mAdapterService.bringUpBle();
assertThat(mAdapterService.getBluetoothGatt()).isNotNull();
@@ -690,8 +692,8 @@ public class AdapterServiceTest {
}
@Test
- @EnableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void startBleOnly_whenScanManagerRefactorFlagIsOn_onlyStartScanController() {
+ @EnableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void startBleOnly_whenOnlyStartScanDuringBleOnFlagIsOn_onlyStartScanController() {
mAdapterService.bringUpBle();
assertThat(mAdapterService.getBluetoothGatt()).isNull();
@@ -700,8 +702,8 @@ public class AdapterServiceTest {
}
@Test
- @EnableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void startBleOnly_whenScanManagerRefactorFlagIsOn_startAndStopScanController() {
+ @EnableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void startBleOnly_whenOnlyStartScanDuringBleOnFlagIsOn_startAndStopScanController() {
assertThat(mAdapterService.getBluetoothScan()).isNull();
assertThat(mAdapterService.getBluetoothGatt()).isNull();
@@ -742,8 +744,8 @@ public class AdapterServiceTest {
}
@Test
- @EnableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void startBrDr_whenScanManagerRefactorFlagIsOn_startAndStopScanController() {
+ @EnableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void startBrDr_whenOnlyStartScanDuringBleOnFlagIsOn_startAndStopScanController() {
assertThat(mAdapterService.getBluetoothScan()).isNull();
assertThat(mAdapterService.getBluetoothGatt()).isNull();
@@ -811,7 +813,7 @@ public class AdapterServiceTest {
/** Test: Don't start a classic profile Check whether the AdapterService quits gracefully */
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
public void testProfileStartTimeout() {
assertThat(mAdapterService.getState()).isEqualTo(STATE_OFF);
@@ -855,7 +857,7 @@ public class AdapterServiceTest {
/** Test: Don't stop a classic profile Check whether the AdapterService quits gracefully */
@Test
- @DisableFlags(Flags.FLAG_SCAN_MANAGER_REFACTOR)
+ @DisableFlags(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
public void testProfileStopTimeout() {
doEnable(false);
@@ -1053,7 +1055,7 @@ public class AdapterServiceTest {
@EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE)
public void testGattConnectionToLeAudioDevice_whenDeviceIsNotConnected_success() {
int groupId = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1075,7 +1077,7 @@ public class AdapterServiceTest {
@EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE)
public void testGattConnectionToLeAudioDevice_whenDeviceIsConnected_ignore() {
int groupId = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1097,7 +1099,7 @@ public class AdapterServiceTest {
@EnableFlags(Flags.FLAG_ALLOW_GATT_CONNECT_FROM_THE_APPS_WITHOUT_MAKING_LEAUDIO_DEVICE_ACTIVE)
public void testGattConnectionToLeAudioDevice_whenLeAudioIsNotAllowed_ignore() {
int groupId = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_DISCONNECTED;
+ int getConnectionState_LeAudioService = STATE_DISCONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1109,9 +1111,7 @@ public class AdapterServiceTest {
getConnectionState_LeAudioService,
getConnectionState_AdapterService);
- doReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)
- .when(mMockLeAudioService)
- .getConnectionPolicy(any());
+ doReturn(CONNECTION_POLICY_FORBIDDEN).when(mMockLeAudioService).getConnectionPolicy(any());
mAdapterService.notifyDirectLeGattClientConnect(1, mDevice);
order.verify(mMockLeAudioService, never()).setAutoActiveModeState(groupId, false);
@@ -1124,7 +1124,7 @@ public class AdapterServiceTest {
int groupId = 1;
int clientIf = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1152,7 +1152,7 @@ public class AdapterServiceTest {
int groupId = 1;
int clientIf = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_DISCONNECTED;
+ int getConnectionState_LeAudioService = STATE_DISCONNECTED;
int getConnectionState_AdapterService = BluetoothDevice.CONNECTION_STATE_DISCONNECTED;
InOrder order =
prepareLeAudioWithConnectedDevices(
@@ -1179,7 +1179,7 @@ public class AdapterServiceTest {
public void testGattConnectionToLeAudioDevice_triggerDisconnecting() {
int groupId = 1;
int clientIf = 1;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1211,7 +1211,7 @@ public class AdapterServiceTest {
int clientIf = 1;
int clientIfTwo = 2;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1259,7 +1259,7 @@ public class AdapterServiceTest {
int clientIf = 1;
int clientIfTwo = 2;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
@@ -1308,7 +1308,7 @@ public class AdapterServiceTest {
int clientIf = 1;
int clientIfTwo = 2;
- int getConnectionState_LeAudioService = BluetoothProfile.STATE_CONNECTED;
+ int getConnectionState_LeAudioService = STATE_CONNECTED;
int getConnectionState_AdapterService =
BluetoothDevice.CONNECTION_STATE_ENCRYPTED_LE
| BluetoothDevice.CONNECTION_STATE_CONNECTED;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/DataMigrationTest.java
index ce49c79d12..f1b99ccd3c 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
@@ -172,11 +172,11 @@ public class DataMigrationTest {
assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1)).isEqualTo(-1);
for (int i = 0; i < DataMigration.MAX_ATTEMPT; i++) {
- assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)).isTrue();
+ assertThat(DataMigration.incrementMigrationAttempt(mMockContext)).isTrue();
assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1))
.isEqualTo(i + 1);
}
- assertThat(DataMigration.incrementeMigrationAttempt(mMockContext)).isFalse();
+ assertThat(DataMigration.incrementMigrationAttempt(mMockContext)).isFalse();
assertThat(mPrefs.getInt(DataMigration.MIGRATION_ATTEMPT_PROPERTY, -1))
.isEqualTo(DataMigration.MAX_ATTEMPT + 1);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
index 046bd4b75e..906436cfbe 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/PhonePolicyTest.java
@@ -963,7 +963,7 @@ public class PhonePolicyTest {
@Test
@EnableFlags(Flags.FLAG_AUTO_CONNECT_ON_MULTIPLE_HFP_WHEN_NO_A2DP_DEVICE)
- public void autoConnect_whenMultiHfpAndDeconnection_startConnection() {
+ public void autoConnect_whenMultiHfpAndDisconnection_startConnection() {
// Return desired values from the mocked object(s)
doReturn(false).when(mAdapterService).isQuietModeEnabled();
@@ -980,11 +980,11 @@ public class PhonePolicyTest {
db.start(mDatabase);
TestUtils.waitForLooperToFinishScheduledTask(db.getHandlerLooper());
- BluetoothDevice deviceToDeconnect = getTestDevice(0);
- db.setConnection(deviceToDeconnect, BluetoothProfile.HEADSET);
+ BluetoothDevice deviceToDisconnect = getTestDevice(0);
+ db.setConnection(deviceToDisconnect, BluetoothProfile.HEADSET);
doReturn(CONNECTION_POLICY_ALLOWED)
.when(mHeadsetService)
- .getConnectionPolicy(eq(deviceToDeconnect));
+ .getConnectionPolicy(eq(deviceToDisconnect));
List<BluetoothDevice> devices =
List.of(getTestDevice(1), getTestDevice(2), getTestDevice(3));
@@ -996,7 +996,7 @@ public class PhonePolicyTest {
.getConnectionPolicy(eq(device));
}
- db.setDisconnection(deviceToDeconnect, BluetoothProfile.HEADSET);
+ db.setDisconnection(deviceToDisconnect, BluetoothProfile.HEADSET);
// wait for all MSG_UPDATE_DATABASE
TestUtils.waitForLooperToFinishScheduledTask(db.getHandlerLooper());
@@ -1008,7 +1008,7 @@ public class PhonePolicyTest {
verify(mHeadsetService).connect(eq(device));
}
// Except for the device that was manually disconnected
- verify(mHeadsetService, never()).connect(eq(deviceToDeconnect));
+ verify(mHeadsetService, never()).connect(eq(deviceToDisconnect));
}
/**
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java
index f20773d067..4a261c1b06 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/RemoteDevicesTest.java
@@ -1,6 +1,9 @@
package com.android.bluetooth.btservice;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra;
@@ -275,7 +278,7 @@ public class RemoteDevicesTest {
// Verify that resetting battery level changes it back to BluetoothDevice
// .BATTERY_LEVEL_UNKNOWN
mRemoteDevices.onHeadsetConnectionStateChanged(
- mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED);
// Verify BATTERY_LEVEL_CHANGED intent is sent after first reset
verify(mAdapterService, times(2))
.sendBroadcast(
@@ -324,7 +327,7 @@ public class RemoteDevicesTest {
// Verify that battery level is not reset
mRemoteDevices.onHeadsetConnectionStateChanged(
- mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED);
assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull();
assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel())
@@ -590,7 +593,7 @@ public class RemoteDevicesTest {
// Verify that resetting battery level changes it back to BluetoothDevice
// .BATTERY_LEVEL_UNKNOWN
mRemoteDevices.onHeadsetClientConnectionStateChanged(
- mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED);
// Verify BATTERY_LEVEL_CHANGED intent is sent after first reset
verify(mAdapterService, times(2))
@@ -641,7 +644,7 @@ public class RemoteDevicesTest {
// Verify that battery level is not reset.
mRemoteDevices.onHeadsetClientConnectionStateChanged(
- mDevice, BluetoothProfile.STATE_DISCONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ mDevice, STATE_DISCONNECTING, STATE_DISCONNECTED);
assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNotNull();
assertThat(mRemoteDevices.getDeviceProperties(mDevice).getBatteryLevel())
@@ -749,7 +752,7 @@ public class RemoteDevicesTest {
mIntentArgument.capture(), mStringArgument.capture(), any(Bundle.class));
verifyBatteryLevelChangedIntent(
mDevice,
- RemoteDevices.batteryChargeIndicatorToPercentge(batteryLevel),
+ RemoteDevices.batteryChargeIndicatorToPercentage(batteryLevel),
mIntentArgument);
assertThat(mStringArgument.getValue()).isEqualTo(BLUETOOTH_CONNECT);
}
@@ -767,7 +770,7 @@ public class RemoteDevicesTest {
}
@Test
- public void testSetgetHfAudioPolicyForRemoteAg() {
+ public void testSetGetHfAudioPolicyForRemoteAg() {
// Verify that device property is null initially
assertThat(mRemoteDevices.getDeviceProperties(mDevice)).isNull();
@@ -855,7 +858,7 @@ public class RemoteDevicesTest {
private static BatteryService setBatteryServiceForTesting(BluetoothDevice device) {
BatteryService newService = mock(BatteryService.class);
- when(newService.getConnectionState(device)).thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(newService.getConnectionState(device)).thenReturn(STATE_CONNECTED);
when(newService.isAvailable()).thenReturn(true);
BatteryService oldService = BatteryService.getBatteryService();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java
index 1e666f7dd4..2a49540088 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/SilenceDeviceManagerTest.java
@@ -17,6 +17,8 @@
package com.android.bluetooth.btservice;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -26,7 +28,6 @@ import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.*;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Bundle;
import android.os.HandlerThread;
@@ -167,28 +168,28 @@ public class SilenceDeviceManagerTest {
/** Helper to indicate A2dp connected for a device. */
private void a2dpConnected(BluetoothDevice device) {
mSilenceDeviceManager.a2dpConnectionStateChanged(
- device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED);
+ device, STATE_DISCONNECTED, STATE_CONNECTED);
TestUtils.waitForLooperToFinishScheduledTask(mLooper);
}
/** Helper to indicate A2dp disconnected for a device. */
private void a2dpDisconnected(BluetoothDevice device) {
mSilenceDeviceManager.a2dpConnectionStateChanged(
- device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+ device, STATE_CONNECTED, STATE_DISCONNECTED);
TestUtils.waitForLooperToFinishScheduledTask(mLooper);
}
/** Helper to indicate Headset connected for a device. */
private void headsetConnected(BluetoothDevice device) {
mSilenceDeviceManager.hfpConnectionStateChanged(
- device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED);
+ device, STATE_DISCONNECTED, STATE_CONNECTED);
TestUtils.waitForLooperToFinishScheduledTask(mLooper);
}
/** Helper to indicate Headset disconnected for a device. */
private void headsetDisconnected(BluetoothDevice device) {
mSilenceDeviceManager.hfpConnectionStateChanged(
- device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTED);
+ device, STATE_CONNECTED, STATE_DISCONNECTED);
TestUtils.waitForLooperToFinishScheduledTask(mLooper);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/bluetoothKeystore/BluetoothKeystoreServiceTest.java
index 30374d57ae..ba2fe08153 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
@@ -242,7 +242,7 @@ public final class BluetoothKeystoreServiceTest {
@Test
public void testParserFileAfterDisableCommonCriteriaMode() {
// preconfiguration.
- // need to creat encrypted file.
+ // need to create encrypted file.
testParserFile();
// created encrypted file
assertThat(setEncryptKeyOrRemoveKey(CONFIG_FILE_PREFIX, CONFIG_FILE_HASH)).isTrue();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java
index c06dbb5d08..e05c0a0d26 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/DatabaseManagerTest.java
@@ -16,6 +16,10 @@
package com.android.bluetooth.btservice.storage;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -143,7 +147,7 @@ public final class DatabaseManagerTest {
for (int id = 0; id < BluetoothProfile.MAX_PROFILE_ID; id++) {
assertThat(mDatabaseManager.getProfileConnectionPolicy(mDevice, id))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .isEqualTo(CONNECTION_POLICY_UNKNOWN);
}
assertThat(mDatabaseManager.getA2dpSupportsOptionalCodecs(mDevice))
@@ -168,41 +172,23 @@ public final class DatabaseManagerTest {
// Cases of device not in database
testSetGetProfileConnectionPolicyCase(
- false,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- true);
+ false, CONNECTION_POLICY_UNKNOWN, CONNECTION_POLICY_UNKNOWN, true);
testSetGetProfileConnectionPolicyCase(
- false,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- true);
+ false, CONNECTION_POLICY_FORBIDDEN, CONNECTION_POLICY_FORBIDDEN, true);
testSetGetProfileConnectionPolicyCase(
- false,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- true);
+ false, CONNECTION_POLICY_ALLOWED, CONNECTION_POLICY_ALLOWED, true);
testSetGetProfileConnectionPolicyCase(
- false, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
+ false, badConnectionPolicy, CONNECTION_POLICY_UNKNOWN, false);
// Cases of device already in database
testSetGetProfileConnectionPolicyCase(
- true,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- true);
+ true, CONNECTION_POLICY_UNKNOWN, CONNECTION_POLICY_UNKNOWN, true);
testSetGetProfileConnectionPolicyCase(
- true,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- true);
+ true, CONNECTION_POLICY_FORBIDDEN, CONNECTION_POLICY_FORBIDDEN, true);
testSetGetProfileConnectionPolicyCase(
- true,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- true);
+ true, CONNECTION_POLICY_ALLOWED, CONNECTION_POLICY_ALLOWED, true);
testSetGetProfileConnectionPolicyCase(
- true, badConnectionPolicy, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
+ true, badConnectionPolicy, CONNECTION_POLICY_UNKNOWN, false);
}
@Test
@@ -1431,6 +1417,28 @@ public final class DatabaseManagerTest {
}
}
+ @Test
+ public void testDatabaseMigration_121_122() throws IOException {
+ // Create a database with version 121
+ SupportSQLiteDatabase db = testHelper.createDatabase(DB_NAME, 121);
+
+ // insert a device to the database
+ ContentValues device = contentValuesDevice_121();
+ assertThat(db.insert("metadata", SQLiteDatabase.CONFLICT_IGNORE, device)).isNotEqualTo(-1);
+
+ // Migrate database from 121 to 122
+ db.close();
+ db =
+ testHelper.runMigrationsAndValidate(
+ DB_NAME, 122, true, MetadataDatabase.MIGRATION_121_122);
+ Cursor cursor = db.query("SELECT * FROM metadata");
+ assertHasColumn(cursor, "key_missing_count", true);
+ while (cursor.moveToNext()) {
+ // Check the new columns was added with default value
+ assertColumnIntData(cursor, "key_missing_count", 0);
+ }
+ }
+
private ContentValues createContentValuesDeviceCommon() {
ContentValues device = new ContentValues();
device.put("address", mDevice.getAddress());
@@ -1615,6 +1623,12 @@ public final class DatabaseManagerTest {
return device;
}
+ private ContentValues contentValuesDevice_121() {
+ ContentValues device = contentValuesDevice_120();
+ device.put("is_preferred_microphone_for_calls", 1);
+ return device;
+ }
+
/** Helper function to check whether the database has the expected column */
void assertHasColumn(Cursor cursor, String columnName, boolean hasColumn) {
if (hasColumn) {
@@ -1685,8 +1699,8 @@ public final class DatabaseManagerTest {
// Check number of metadata in the database
if (!stored) {
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_FORBIDDEN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
// Database won't be updated
assertThat(list).isEmpty();
return;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json
new file mode 100644
index 0000000000..43a8f11132
--- /dev/null
+++ b/android/app/tests/unit/src/com/android/bluetooth/btservice/storage/schemas/com.android.bluetooth.btservice.storage.MetadataDatabase/122.json
@@ -0,0 +1,357 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 122,
+ "identityHash": "a80cd402e29589764a3e3cf412150d60",
+ "entities": [
+ {
+ "tableName": "metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, `migrated` INTEGER NOT NULL, `a2dpSupportsOptionalCodecs` INTEGER NOT NULL, `a2dpOptionalCodecsEnabled` INTEGER NOT NULL, `last_active_time` INTEGER NOT NULL, `is_active_a2dp_device` INTEGER NOT NULL, `isActiveHfpDevice` INTEGER NOT NULL, `preferred_output_only_profile` INTEGER NOT NULL, `preferred_duplex_profile` INTEGER NOT NULL, `active_audio_device_policy` INTEGER NOT NULL, `is_preferred_microphone_for_calls` INTEGER NOT NULL, `key_missing_count` INTEGER NOT NULL, `a2dp_connection_policy` INTEGER, `a2dp_sink_connection_policy` INTEGER, `hfp_connection_policy` INTEGER, `hfp_client_connection_policy` INTEGER, `hid_host_connection_policy` INTEGER, `pan_connection_policy` INTEGER, `pbap_connection_policy` INTEGER, `pbap_client_connection_policy` INTEGER, `map_connection_policy` INTEGER, `sap_connection_policy` INTEGER, `hearing_aid_connection_policy` INTEGER, `hap_client_connection_policy` INTEGER, `map_client_connection_policy` INTEGER, `le_audio_connection_policy` INTEGER, `volume_control_connection_policy` INTEGER, `csip_set_coordinator_connection_policy` INTEGER, `le_call_control_connection_policy` INTEGER, `bass_client_connection_policy` INTEGER, `battery_connection_policy` INTEGER, `manufacturer_name` BLOB, `model_name` BLOB, `software_version` BLOB, `hardware_version` BLOB, `companion_app` BLOB, `main_icon` BLOB, `is_untethered_headset` BLOB, `untethered_left_icon` BLOB, `untethered_right_icon` BLOB, `untethered_case_icon` BLOB, `untethered_left_battery` BLOB, `untethered_right_battery` BLOB, `untethered_case_battery` BLOB, `untethered_left_charging` BLOB, `untethered_right_charging` BLOB, `untethered_case_charging` BLOB, `enhanced_settings_ui_uri` BLOB, `device_type` BLOB, `main_battery` BLOB, `main_charging` BLOB, `main_low_battery_threshold` BLOB, `untethered_left_low_battery_threshold` BLOB, `untethered_right_low_battery_threshold` BLOB, `untethered_case_low_battery_threshold` BLOB, `spatial_audio` BLOB, `fastpair_customized` BLOB, `le_audio` BLOB, `gmcs_cccd` BLOB, `gtbs_cccd` BLOB, `exclusive_manager` BLOB, `call_establish_audio_policy` INTEGER, `connecting_time_audio_policy` INTEGER, `in_band_ringtone_audio_policy` INTEGER, PRIMARY KEY(`address`))",
+ "fields": [
+ {
+ "fieldPath": "address",
+ "columnName": "address",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "migrated",
+ "columnName": "migrated",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "a2dpSupportsOptionalCodecs",
+ "columnName": "a2dpSupportsOptionalCodecs",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "a2dpOptionalCodecsEnabled",
+ "columnName": "a2dpOptionalCodecsEnabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "last_active_time",
+ "columnName": "last_active_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "is_active_a2dp_device",
+ "columnName": "is_active_a2dp_device",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActiveHfpDevice",
+ "columnName": "isActiveHfpDevice",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "preferred_output_only_profile",
+ "columnName": "preferred_output_only_profile",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "preferred_duplex_profile",
+ "columnName": "preferred_duplex_profile",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "active_audio_device_policy",
+ "columnName": "active_audio_device_policy",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "is_preferred_microphone_for_calls",
+ "columnName": "is_preferred_microphone_for_calls",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "key_missing_count",
+ "columnName": "key_missing_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.a2dp_connection_policy",
+ "columnName": "a2dp_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.a2dp_sink_connection_policy",
+ "columnName": "a2dp_sink_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.hfp_connection_policy",
+ "columnName": "hfp_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.hfp_client_connection_policy",
+ "columnName": "hfp_client_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.hid_host_connection_policy",
+ "columnName": "hid_host_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.pan_connection_policy",
+ "columnName": "pan_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.pbap_connection_policy",
+ "columnName": "pbap_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.pbap_client_connection_policy",
+ "columnName": "pbap_client_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.map_connection_policy",
+ "columnName": "map_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.sap_connection_policy",
+ "columnName": "sap_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.hearing_aid_connection_policy",
+ "columnName": "hearing_aid_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.hap_client_connection_policy",
+ "columnName": "hap_client_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.map_client_connection_policy",
+ "columnName": "map_client_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.le_audio_connection_policy",
+ "columnName": "le_audio_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.volume_control_connection_policy",
+ "columnName": "volume_control_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.csip_set_coordinator_connection_policy",
+ "columnName": "csip_set_coordinator_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.le_call_control_connection_policy",
+ "columnName": "le_call_control_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.bass_client_connection_policy",
+ "columnName": "bass_client_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "profileConnectionPolicies.battery_connection_policy",
+ "columnName": "battery_connection_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "publicMetadata.manufacturer_name",
+ "columnName": "manufacturer_name",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.model_name",
+ "columnName": "model_name",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.software_version",
+ "columnName": "software_version",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.hardware_version",
+ "columnName": "hardware_version",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.companion_app",
+ "columnName": "companion_app",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.main_icon",
+ "columnName": "main_icon",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.is_untethered_headset",
+ "columnName": "is_untethered_headset",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_left_icon",
+ "columnName": "untethered_left_icon",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_right_icon",
+ "columnName": "untethered_right_icon",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_case_icon",
+ "columnName": "untethered_case_icon",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_left_battery",
+ "columnName": "untethered_left_battery",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_right_battery",
+ "columnName": "untethered_right_battery",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_case_battery",
+ "columnName": "untethered_case_battery",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_left_charging",
+ "columnName": "untethered_left_charging",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_right_charging",
+ "columnName": "untethered_right_charging",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_case_charging",
+ "columnName": "untethered_case_charging",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.enhanced_settings_ui_uri",
+ "columnName": "enhanced_settings_ui_uri",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.device_type",
+ "columnName": "device_type",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.main_battery",
+ "columnName": "main_battery",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.main_charging",
+ "columnName": "main_charging",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.main_low_battery_threshold",
+ "columnName": "main_low_battery_threshold",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_left_low_battery_threshold",
+ "columnName": "untethered_left_low_battery_threshold",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_right_low_battery_threshold",
+ "columnName": "untethered_right_low_battery_threshold",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.untethered_case_low_battery_threshold",
+ "columnName": "untethered_case_low_battery_threshold",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.spatial_audio",
+ "columnName": "spatial_audio",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.fastpair_customized",
+ "columnName": "fastpair_customized",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.le_audio",
+ "columnName": "le_audio",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.gmcs_cccd",
+ "columnName": "gmcs_cccd",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.gtbs_cccd",
+ "columnName": "gtbs_cccd",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "publicMetadata.exclusive_manager",
+ "columnName": "exclusive_manager",
+ "affinity": "BLOB"
+ },
+ {
+ "fieldPath": "audioPolicyMetadata.callEstablishAudioPolicy",
+ "columnName": "call_establish_audio_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "audioPolicyMetadata.connectingTimeAudioPolicy",
+ "columnName": "connecting_time_audio_policy",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "audioPolicyMetadata.inBandRingtoneAudioPolicy",
+ "columnName": "in_band_ringtone_audio_policy",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "address"
+ ]
+ }
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a80cd402e29589764a3e3cf412150d60')"
+ ]
+ }
+} \ No newline at end of file
diff --git a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java
index 6ea19c5477..69e8546ac3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/csip/BluetoothCsisBinderTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.csip;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -23,7 +26,6 @@ import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothCsipSetCoordinatorLockCallback;
import android.content.AttributionSource;
import android.os.ParcelUuid;
@@ -56,7 +58,7 @@ public class BluetoothCsisBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource);
verify(mService).getDevicesMatchingConnectionStates(states);
}
@@ -69,7 +71,7 @@ public class BluetoothCsisBinderTest {
@Test
public void setConnectionPolicy() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementBinderTest.java
index 05aff3911c..9db59f4fb1 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementBinderTest.java
@@ -19,6 +19,8 @@ package com.android.bluetooth.gatt;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -65,10 +67,24 @@ public class DistanceMeasurementBinderTest {
private DistanceMeasurementBinder mBinder;
@Before
- public void setUp() {
+ public void setUp() throws Throwable {
mBinder = new DistanceMeasurementBinder(mAdapterService, mDistanceMeasurementManager);
when(mDistanceMeasurementManager.getSupportedDistanceMeasurementMethods())
.thenReturn(Collections.emptyList());
+ when(mDistanceMeasurementManager.runOnDistanceMeasurementThreadAndWaitForResult(any()))
+ .thenAnswer(
+ invocationOnMock -> {
+ DistanceMeasurementManager.GetResultTask task =
+ invocationOnMock.getArgument(0);
+ return task.getResult();
+ });
+ doAnswer(
+ invocation -> {
+ ((Runnable) (invocation.getArgument(0))).run();
+ return null;
+ })
+ .when(mDistanceMeasurementManager)
+ .postOnDistanceMeasurementThread(any());
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java
index 3fafb0678a..2c753134a3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/gatt/DistanceMeasurementManagerTest.java
@@ -35,6 +35,7 @@ import android.bluetooth.le.DistanceMeasurementParams;
import android.bluetooth.le.DistanceMeasurementResult;
import android.bluetooth.le.IDistanceMeasurementCallback;
import android.content.pm.PackageManager;
+import android.os.HandlerThread;
import android.os.RemoteException;
import androidx.test.filters.SmallTest;
@@ -67,6 +68,7 @@ public class DistanceMeasurementManagerTest {
private DistanceMeasurementManager mDistanceMeasurementManager;
private UUID mUuid;
+ private HandlerThread mHandlerThread;
private static final int RSSI_FREQUENCY_LOW = 3000;
private static final int CS_FREQUENCY_LOW = 5000;
@@ -81,7 +83,12 @@ public class DistanceMeasurementManagerTest {
.getIdentityAddress(mDevice.getAddress());
doReturn(true).when(mAdapterService).isConnected(any());
DistanceMeasurementNativeInterface.setInstance(mDistanceMeasurementNativeInterface);
- mDistanceMeasurementManager = new DistanceMeasurementManager(mAdapterService);
+
+ mHandlerThread = new HandlerThread("DistanceMeasurementManagerTest");
+ mHandlerThread.start();
+
+ mDistanceMeasurementManager =
+ new DistanceMeasurementManager(mAdapterService, mHandlerThread.getLooper());
mUuid = UUID.randomUUID();
}
@@ -89,6 +96,7 @@ public class DistanceMeasurementManagerTest {
public void tearDown() throws Exception {
mDistanceMeasurementManager.cleanup();
DistanceMeasurementNativeInterface.setInstance(null);
+ mHandlerThread.quit();
}
@Test
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..f52702a24b 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;
@@ -130,11 +131,11 @@ public class GattServiceTest {
doReturn(mNativeInterface).when(mGattObjectsFactory).getNativeInterface();
doReturn(mDistanceMeasurementManager)
.when(mGattObjectsFactory)
- .createDistanceMeasurementManager(any());
+ .createDistanceMeasurementManager(any(), any());
doReturn(mScanManager)
.when(mScanObjectsFactory)
.createScanManager(any(), any(), any(), any());
- doReturn(mPeriodicScanManager).when(mScanObjectsFactory).createPeriodicScanManager(any());
+ doReturn(mPeriodicScanManager).when(mScanObjectsFactory).createPeriodicScanManager();
doReturn(mContext.getPackageManager()).when(mAdapterService).getPackageManager();
doReturn(mContext.getSharedPreferences("GattServiceTestPrefs", Context.MODE_PRIVATE))
.when(mAdapterService)
@@ -404,7 +405,7 @@ public class GattServiceTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
BluetoothDevice testDevice = getTestDevice(90);
BluetoothDevice[] bluetoothDevices = new BluetoothDevice[] {testDevice};
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java
index a0a123dcd9..7f079c79b7 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientBinderTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.hap;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -27,7 +30,6 @@ import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothHapClientCallback;
import android.content.AttributionSource;
@@ -95,28 +97,20 @@ public class HapClientBinderTest {
public void setConnectionPolicy() {
assertThrows(
NullPointerException.class,
- () ->
- mBinder.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, null));
+ () -> mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, null));
assertThrows(
NullPointerException.class,
() ->
mBinder.setConnectionPolicy(
- null,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- mAttributionSource));
+ null, CONNECTION_POLICY_ALLOWED, mAttributionSource));
assertThrows(
IllegalArgumentException.class,
() ->
mBinder.setConnectionPolicy(
- mDevice,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- mAttributionSource));
-
- mBinder.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED, mAttributionSource);
- verify(mHapClientService)
- .setConnectionPolicy(eq(mDevice), eq(BluetoothProfile.CONNECTION_POLICY_ALLOWED));
+ mDevice, CONNECTION_POLICY_UNKNOWN, mAttributionSource));
+
+ mBinder.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED, mAttributionSource);
+ verify(mHapClientService).setConnectionPolicy(eq(mDevice), eq(CONNECTION_POLICY_ALLOWED));
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java
index 85ba8fdb4e..a67995ffae 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientNativeCallbackTest.java
@@ -16,12 +16,13 @@
package com.android.bluetooth.hap;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothHapPresetInfo;
-import android.bluetooth.BluetoothProfile;
import com.android.bluetooth.btservice.AdapterService;
@@ -51,7 +52,7 @@ public class HapClientNativeCallbackTest {
@Test
public void onConnectionStateChanged() {
- int state = BluetoothProfile.STATE_CONNECTED;
+ int state = STATE_CONNECTED;
mNativeCallback.onConnectionStateChanged(state, null);
verify(mHapClientService).messageFromNative(mEvent.capture());
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hap/HapClientServiceTest.java
index 272e2e0b45..045ed21e09 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
@@ -288,7 +288,7 @@ public class HapClientServiceTest {
/* This one has no coordinated operation support but is part of a coordinated set with
* mDevice, which supports it, thus mDevice will forward the operation to mDevice2.
- * This device should also be rocognised as grouped one.
+ * This device should also be recognized as grouped one.
*/
mNativeCallback.onFeaturesUpdate(getByteAddress(mDevice2), 0);
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 dc6345b039..123b34c178 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
@@ -303,7 +303,7 @@ public class AtPhonebookTest {
}
@Test
- public void processCpbrCommand_withReceivcedCallsAndCharsetGsm() {
+ public void processCpbrCommand_withReceivedCallsAndCharsetGsm() {
Cursor mockCursorOne = mock(Cursor.class);
when(mockCursorOne.getCount()).thenReturn(1);
when(mockCursorOne.getColumnIndexOrThrow(CallLog.Calls.NUMBER)).thenReturn(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..9fadbcb9a7 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/BluetoothHeadsetBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.hfp;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.AttributionSource;
import org.junit.Before;
@@ -65,7 +67,7 @@ public class BluetoothHeadsetBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource);
verify(mService).getDevicesMatchingConnectionStates(states);
}
@@ -78,7 +80,7 @@ public class BluetoothHeadsetBinderTest {
@Test
public void setConnectionPolicy() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
}
@@ -168,18 +170,4 @@ public class BluetoothHeadsetBinderTest {
mBinder.stopScoUsingVirtualVoiceCall(mAttributionSource);
verify(mService).stopScoUsingVirtualVoiceCall();
}
-
- @Test
- public void phoneStateChanged() {
- int numActive = 2;
- int numHeld = 5;
- int callState = HeadsetHalConstants.CALL_STATE_IDLE;
- String number = "000-000-0000";
- int type = 0;
- String name = "Unknown";
- mBinder.phoneStateChanged(
- numActive, numHeld, callState, number, type, name, mAttributionSource);
- verify(mService)
- .phoneStateChanged(numActive, numHeld, callState, number, type, name, false);
- }
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java
index 6c5d267e54..52741b9746 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetPhoneStateTest.java
@@ -136,7 +136,7 @@ public class HeadsetPhoneStateTest {
}
/**
- * Verify that partially turnning off {@link PhoneStateListener#LISTEN_SIGNAL_STRENGTHS} update
+ * Verify that partially turning off {@link PhoneStateListener#LISTEN_SIGNAL_STRENGTHS} update
* should only unsubscribe signal strength update
*/
@Test
@@ -187,7 +187,7 @@ public class HeadsetPhoneStateTest {
/**
* Verify that when multiple devices tries to subscribe to the same indicator, the same
- * subscription is not triggered twice. Also, when one of the device is unsubsidised from an
+ * subscription is not triggered twice. Also, when one of the device is unsubsidized from an
* indicator, the other device still remain subscribed.
*/
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
index 46b8d2539d..0905e185d4 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceAndStateMachineTest.java
@@ -16,6 +16,12 @@
package com.android.bluetooth.hfp;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasData;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra;
@@ -215,8 +221,7 @@ public class HeadsetServiceAndStateMachineTest {
assertThat(HeadsetService.getHeadsetService()).isEqualTo(mHeadsetService);
// Verify default connection and audio states
BluetoothDevice device = getTestDevice(0);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetService.getAudioState(device))
.isEqualTo(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
}
@@ -228,7 +233,7 @@ public class HeadsetServiceAndStateMachineTest {
@Test
public void testConnectFromApi() {
BluetoothDevice device = getTestDevice(0);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET);
mBondedDevices.add(device);
@@ -242,14 +247,10 @@ public class HeadsetServiceAndStateMachineTest {
mAdapterService,
mNativeInterface,
mSystemInterface);
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED);
verify(mNativeInterface).connectHfp(device);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
- assertThat(
- mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTING}))
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING);
+ assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTING}))
.containsExactly(device);
// Get feedback from native to put device into connected state
HeadsetStackEvent connectedEvent =
@@ -259,13 +260,9 @@ public class HeadsetServiceAndStateMachineTest {
device);
mHeadsetService.messageFromNative(connectedEvent);
mTestLooper.dispatchAll();
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
- assertThat(
- mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ verifyConnectionStateIntent(device, STATE_CONNECTED, STATE_CONNECTING);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED);
+ assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}))
.containsExactly(device);
}
@@ -277,7 +274,7 @@ public class HeadsetServiceAndStateMachineTest {
@Test
public void testUnbondDevice_disconnectBeforeUnbond() {
BluetoothDevice device = getTestDevice(0);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET);
mBondedDevices.add(device);
@@ -291,8 +288,7 @@ public class HeadsetServiceAndStateMachineTest {
mAdapterService,
mNativeInterface,
mSystemInterface);
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED);
verify(mNativeInterface).connectHfp(device);
// Get feedback from native layer to go back to disconnected state
HeadsetStackEvent connectedEvent =
@@ -302,8 +298,7 @@ public class HeadsetServiceAndStateMachineTest {
device);
mHeadsetService.messageFromNative(connectedEvent);
mTestLooper.dispatchAll();
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTING);
+ verifyConnectionStateIntent(device, STATE_DISCONNECTED, STATE_CONNECTING);
mHeadsetService.handleBondStateChanged(
device, BluetoothDevice.BOND_BONDED, BluetoothDevice.BOND_NONE);
@@ -323,7 +318,7 @@ public class HeadsetServiceAndStateMachineTest {
@Test
public void testUnbondDevice_disconnectAfterUnbond() {
BluetoothDevice device = getTestDevice(0);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET);
mBondedDevices.add(device);
@@ -338,8 +333,7 @@ public class HeadsetServiceAndStateMachineTest {
mNativeInterface,
mSystemInterface);
verify(mNativeInterface).connectHfp(device);
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ verifyConnectionStateIntent(device, STATE_CONNECTING, STATE_DISCONNECTED);
// Get feedback from native layer to go to connected state
HeadsetStackEvent connectedEvent =
new HeadsetStackEvent(
@@ -348,10 +342,8 @@ public class HeadsetServiceAndStateMachineTest {
device);
mHeadsetService.messageFromNative(connectedEvent);
mTestLooper.dispatchAll();
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ verifyConnectionStateIntent(device, STATE_CONNECTED, STATE_CONNECTING);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).containsExactly(device);
// Check that the state machine is not destroyed
@@ -367,8 +359,7 @@ public class HeadsetServiceAndStateMachineTest {
mHeadsetService.messageFromNative(connectingEvent);
mTestLooper.dispatchAll();
- verifyConnectionStateIntent(
- device, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED);
+ verifyConnectionStateIntent(device, STATE_DISCONNECTED, STATE_CONNECTED);
// Check that the state machine is destroyed after another async call
ArgumentCaptor<HeadsetStateMachine> stateMachineArgument =
@@ -392,7 +383,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -431,7 +422,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -475,7 +466,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -526,7 +517,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -620,7 +611,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -1187,7 +1178,7 @@ public class HeadsetServiceAndStateMachineTest {
.containsExactlyElementsIn(mBondedDevices);
assertThat(
mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ new int[] {STATE_CONNECTED}))
.containsExactlyElementsIn(mBondedDevices);
}
List<BluetoothDevice> connectedDevices = mHeadsetService.getConnectedDevices();
@@ -1580,16 +1571,16 @@ public class HeadsetServiceAndStateMachineTest {
verify(mNativeInterface).sendBsir(eq(device), eq(true));
// this device is a HFP only device
- doReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED)
+ doReturn(CONNECTION_POLICY_ALLOWED)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.A2DP);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEARING_AID);
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO);
@@ -1788,7 +1779,7 @@ public class HeadsetServiceAndStateMachineTest {
}
private void connectTestDevice(BluetoothDevice device) {
- doReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ doReturn(CONNECTION_POLICY_UNKNOWN)
.when(mDatabaseManager)
.getProfileConnectionPolicy(device, BluetoothProfile.HEADSET);
doReturn(BluetoothDevice.BOND_BONDED).when(mAdapterService).getBondState(eq(device));
@@ -1812,20 +1803,11 @@ public class HeadsetServiceAndStateMachineTest {
mSystemInterface);
verify(mActiveDeviceManager)
.profileConnectionStateChanged(
- BluetoothProfile.HEADSET,
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ BluetoothProfile.HEADSET, device, STATE_DISCONNECTED, STATE_CONNECTING);
verify(mSilenceDeviceManager)
- .hfpConnectionStateChanged(
- device,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
- assertThat(
- mHeadsetService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTING}))
+ .hfpConnectionStateChanged(device, STATE_DISCONNECTED, STATE_CONNECTING);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING);
+ assertThat(mHeadsetService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTING}))
.containsExactly(device);
// Get feedback from native to put device into connected state
HeadsetStackEvent slcConnectedEvent =
@@ -1837,17 +1819,10 @@ public class HeadsetServiceAndStateMachineTest {
mTestLooper.dispatchAll();
verify(mActiveDeviceManager)
.profileConnectionStateChanged(
- BluetoothProfile.HEADSET,
- device,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ BluetoothProfile.HEADSET, device, STATE_CONNECTING, STATE_CONNECTED);
verify(mSilenceDeviceManager)
- .hfpConnectionStateChanged(
- device,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .hfpConnectionStateChanged(device, STATE_CONNECTING, STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED);
}
@SafeVarargs
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
index 91d9038a51..18a53db436 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetServiceTest.java
@@ -16,6 +16,13 @@
package com.android.bluetooth.hfp;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -160,9 +167,7 @@ public class HeadsetServiceTest {
assertThat(mCurrentDevice).isNotNull();
final HeadsetStateMachine stateMachine =
mock(HeadsetStateMachine.class);
- doReturn(BluetoothProfile.STATE_DISCONNECTED)
- .when(stateMachine)
- .getConnectionState();
+ doReturn(STATE_DISCONNECTED).when(stateMachine).getConnectionState();
doReturn(BluetoothHeadset.STATE_AUDIO_DISCONNECTED)
.when(stateMachine)
.getAudioState();
@@ -197,7 +202,7 @@ public class HeadsetServiceTest {
// Verify default connection and audio states
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetService.getAudioState(mCurrentDevice))
.isEqualTo(BluetoothHeadset.STATE_AUDIO_DISCONNECTED);
}
@@ -211,65 +216,50 @@ public class HeadsetServiceTest {
testOkToAcceptConnectionCase(
mCurrentDevice,
BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(
- mCurrentDevice,
- BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mCurrentDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false);
testOkToAcceptConnectionCase(
mCurrentDevice,
BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(
mCurrentDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false);
testOkToAcceptConnectionCase(
mCurrentDevice,
BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(
- mCurrentDevice,
- BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mCurrentDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false);
testOkToAcceptConnectionCase(
mCurrentDevice,
BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(
mCurrentDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false);
testOkToAcceptConnectionCase(
- mCurrentDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- true);
+ mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true);
testOkToAcceptConnectionCase(
- mCurrentDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false);
testOkToAcceptConnectionCase(
- mCurrentDevice,
- BluetoothDevice.BOND_BONDED,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
- true);
+ mCurrentDevice, BluetoothDevice.BOND_BONDED, CONNECTION_POLICY_ALLOWED, true);
testOkToAcceptConnectionCase(
mCurrentDevice, BluetoothDevice.BOND_BONDED, badPriorityValue, false);
testOkToAcceptConnectionCase(
mCurrentDevice,
badBondState,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
+ CONNECTION_POLICY_UNKNOWN,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(
- mCurrentDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
+ mCurrentDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false);
testOkToAcceptConnectionCase(
mCurrentDevice,
badBondState,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED,
+ CONNECTION_POLICY_ALLOWED,
Flags.donotValidateBondStateFromProfiles());
testOkToAcceptConnectionCase(mCurrentDevice, badBondState, badPriorityValue, false);
}
@@ -283,7 +273,7 @@ public class HeadsetServiceTest {
public void testConnectDevice_connectDeviceBelowLimit() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
verify(mObjectsFactory)
@@ -297,14 +287,10 @@ public class HeadsetServiceTest {
verify(mStateMachines.get(mCurrentDevice))
.sendMessage(HeadsetStateMachine.CONNECT, mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTING);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTING);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice));
// 2nd connection attempt will fail
assertThat(mHeadsetService.connect(mCurrentDevice)).isFalse();
@@ -340,10 +326,8 @@ public class HeadsetServiceTest {
verify(mStateMachines.get(mCurrentDevice))
.sendMessage(HeadsetStateMachine.STACK_EVENT, connectedEvent);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice));
// Test disconnect from native
HeadsetStackEvent disconnectEvent =
@@ -355,9 +339,9 @@ public class HeadsetServiceTest {
verify(mStateMachines.get(mCurrentDevice))
.sendMessage(HeadsetStateMachine.STACK_EVENT, disconnectEvent);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_DISCONNECTED);
+ .thenReturn(STATE_DISCONNECTED);
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).isEmpty();
}
@@ -413,7 +397,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
@@ -439,16 +423,16 @@ public class HeadsetServiceTest {
.sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class));
// Put device to connecting
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ .thenReturn(STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
}
@@ -465,7 +449,7 @@ public class HeadsetServiceTest {
eq(mNativeInterface),
eq(mSystemInterface));
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
}
@@ -479,7 +463,7 @@ public class HeadsetServiceTest {
public void testConnectAudio_withOneDevice() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
verify(mObjectsFactory)
@@ -493,17 +477,13 @@ public class HeadsetServiceTest {
verify(mStateMachines.get(mCurrentDevice))
.sendMessage(HeadsetStateMachine.CONNECT, mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice));
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED);
// Test connect audio - set the device first as the active device
assertThat(mHeadsetService.setActiveDevice(mCurrentDevice)).isTrue();
assertThat(mHeadsetService.connectAudio(mCurrentDevice))
@@ -541,7 +521,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
@@ -567,26 +547,22 @@ public class HeadsetServiceTest {
.sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class));
// Put device to connecting
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ .thenReturn(STATE_CONNECTING);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Try to connect audio
@@ -637,7 +613,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
@@ -663,26 +639,22 @@ public class HeadsetServiceTest {
.sendMessage(eq(HeadsetStateMachine.CONNECT), any(BluetoothDevice.class));
// Put device to connecting
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ .thenReturn(STATE_CONNECTING);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED);
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
}
@@ -727,7 +699,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
doAnswer(
invocation -> {
BluetoothDevice[] devicesArray =
@@ -763,28 +735,24 @@ public class HeadsetServiceTest {
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ .thenReturn(STATE_CONNECTING);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED);
}
// Try to connect audio
BluetoothDevice firstDevice = connectedDevices.get(0);
@@ -813,7 +781,7 @@ public class HeadsetServiceTest {
public void testConnectAudio_deviceDisconnected() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
verify(mObjectsFactory)
@@ -829,14 +797,12 @@ public class HeadsetServiceTest {
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
// Put device in disconnected state
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_DISCONNECTED);
+ .thenReturn(STATE_DISCONNECTED);
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).isEmpty();
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTED,
- BluetoothProfile.STATE_DISCONNECTED);
+ mCurrentDevice, STATE_CONNECTED, STATE_DISCONNECTED);
// connectAudio should fail
assertThat(mHeadsetService.connectAudio(mCurrentDevice))
.isEqualTo(BluetoothStatusCodes.ERROR_NOT_ACTIVE_DEVICE);
@@ -884,7 +850,7 @@ public class HeadsetServiceTest {
0, 0, HeadsetHalConstants.CALL_STATE_IDLE, TEST_PHONE_NUMBER, 128, "");
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
final ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
// Connect one device
@@ -903,29 +869,22 @@ public class HeadsetServiceTest {
// Put device to connecting
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTING);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED);
// Change phone state
mHeadsetService.phoneStateChanged(
headsetCallState.mNumActive,
@@ -985,7 +944,7 @@ public class HeadsetServiceTest {
final ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 0; i < MAX_HEADSET_CONNECTIONS; ++i) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
@@ -1013,28 +972,24 @@ public class HeadsetServiceTest {
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
+ .thenReturn(STATE_CONNECTING);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTING);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTING);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
// Put device to connected
connectedDevices.add(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices())
.containsExactlyElementsIn(connectedDevices);
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_CONNECTING,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_CONNECTING, STATE_CONNECTED);
assertThat(mHeadsetService.setActiveDevice(mCurrentDevice)).isTrue();
}
// Change phone state
@@ -1064,7 +1019,7 @@ public class HeadsetServiceTest {
public void testClccResponse_withOneDevice() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
verify(mObjectsFactory)
@@ -1076,10 +1031,8 @@ public class HeadsetServiceTest {
mNativeInterface,
mSystemInterface);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
- assertThat(mHeadsetService.getConnectionState(mCurrentDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(mCurrentDevice)).isEqualTo(STATE_CONNECTED);
mHeadsetService.clccResponse(1, 0, 0, 0, false, "8225319000", 0);
// index 0 is the end mark of CLCC response.
mHeadsetService.clccResponse(0, 0, 0, 0, false, "8225319000", 0);
@@ -1097,7 +1050,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 2; i >= 0; i--) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
@@ -1111,7 +1064,7 @@ public class HeadsetServiceTest {
mSystemInterface);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
connectedDevices.add(mCurrentDevice);
// index 0 is the end mark of CLCC response.
mHeadsetService.clccResponse(i, 0, 0, 0, false, "8225319000", 0);
@@ -1129,13 +1082,13 @@ public class HeadsetServiceTest {
public void testSetSilenceMode() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 0; i < 2; i++) {
mCurrentDevice = getTestDevice(i);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ .thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).setSilenceDevice(anyBoolean()))
.thenReturn(true);
}
@@ -1168,14 +1121,13 @@ public class HeadsetServiceTest {
public void testSetActiveDevice_AudioNotAllowed() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
mHeadsetService.setForceScoAudio(false);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
assertThat(mHeadsetService.setActiveDevice(null)).isTrue();
when(mSystemInterface.isInCall()).thenReturn(true);
@@ -1260,19 +1212,16 @@ public class HeadsetServiceTest {
public void testConnectDeviceNotAllowedInbandRingPolicy_InbandRingStatus() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
assertThat(mHeadsetService.connect(mCurrentDevice)).isTrue();
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
when(mStateMachines.get(mCurrentDevice).getConnectingTimestampMs())
.thenReturn(SystemClock.uptimeMillis());
assertThat(mHeadsetService.getConnectedDevices()).isEqualTo(List.of(mCurrentDevice));
mHeadsetService.onConnectionStateChangedFromStateMachine(
- mCurrentDevice,
- BluetoothProfile.STATE_DISCONNECTED,
- BluetoothProfile.STATE_CONNECTED);
+ mCurrentDevice, STATE_DISCONNECTED, STATE_CONNECTED);
mHeadsetService.setActiveDevice(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getHfpCallAudioPolicy())
@@ -1302,13 +1251,12 @@ public class HeadsetServiceTest {
public void testIncomingCallDeviceConnect_InbandRingStatus() {
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
mCurrentDevice = getTestDevice(0);
connectDeviceHelper(mCurrentDevice);
when(mStateMachines.get(mCurrentDevice).getDevice()).thenReturn(mCurrentDevice);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
when(mSystemInterface.isRinging()).thenReturn(true);
mHeadsetService.setActiveDevice(mCurrentDevice);
@@ -1326,7 +1274,7 @@ public class HeadsetServiceTest {
ArrayList<BluetoothDevice> connectedDevices = new ArrayList<>();
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
for (int i = 2; i >= 0; i--) {
mCurrentDevice = getTestDevice(i);
connectDeviceHelper(mCurrentDevice);
@@ -1349,17 +1297,13 @@ public class HeadsetServiceTest {
mCurrentDevice = device;
when(mDatabaseManager.getProfileConnectionPolicy(
any(BluetoothDevice.class), eq(BluetoothProfile.HEADSET)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
assertThat(mHeadsetService.connect(device)).isTrue();
when(mStateMachines.get(device).getDevice()).thenReturn(device);
- when(mStateMachines.get(device).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTING);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
- when(mStateMachines.get(mCurrentDevice).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
- assertThat(mHeadsetService.getConnectionState(device))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(device).getConnectionState()).thenReturn(STATE_CONNECTING);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTING);
+ when(mStateMachines.get(mCurrentDevice).getConnectionState()).thenReturn(STATE_CONNECTED);
+ assertThat(mHeadsetService.getConnectionState(device)).isEqualTo(STATE_CONNECTED);
assertThat(mHeadsetService.getConnectedDevices()).contains(device);
}
@@ -1390,7 +1334,6 @@ public class HeadsetServiceTest {
mNativeInterface,
mSystemInterface);
when(mStateMachines.get(device).getDevice()).thenReturn(device);
- when(mStateMachines.get(device).getConnectionState())
- .thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(mStateMachines.get(device).getConnectionState()).thenReturn(STATE_CONNECTED);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
index 9b96fb9e3c..22e98262e5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfp/HeadsetStateMachineTest.java
@@ -18,6 +18,11 @@ package com.android.bluetooth.hfp;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.media.audio.Flags.FLAG_DEPRECATE_STREAM_BT_SCO;
import static com.android.bluetooth.TestUtils.MockitoRule;
@@ -29,7 +34,6 @@ import static org.mockito.Mockito.*;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothStatusCodes;
import android.content.ContentResolver;
import android.content.Intent;
@@ -152,7 +156,7 @@ public class HeadsetStateMachineTest {
.getContext()
.getPackageManager());
when(mHeadsetService.getConnectionPolicy(any(BluetoothDevice.class)))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
when(mHeadsetService.getForceScoAudio()).thenReturn(true);
when(mHeadsetService.okToAcceptConnection(any(BluetoothDevice.class), anyBoolean()))
.thenReturn(true);
@@ -187,8 +191,7 @@ public class HeadsetStateMachineTest {
/** Test that default state is Disconnected */
@Test
public void testDefaultDisconnectedState() {
- assertThat(mHeadsetStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mHeadsetStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
assertThat(mHeadsetStateMachine.getCurrentState())
.isInstanceOf(HeadsetStateMachine.Disconnected.class);
}
@@ -197,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);
}
@@ -214,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);
}
@@ -240,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);
}
@@ -266,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);
}
@@ -311,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);
}
@@ -332,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);
}
@@ -389,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);
}
@@ -419,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);
}
@@ -442,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);
}
@@ -455,7 +433,7 @@ public class HeadsetStateMachineTest {
* message
*/
@Test
- public void testStateTransition_DisconnectingToConnected_StackSlcCconnected() {
+ public void testStateTransition_DisconnectingToConnected_StackSlcConnected() {
int numBroadcastsSent = setUpDisconnectingState();
// Send StackEvent.SLC_CONNECTED message
numBroadcastsSent++;
@@ -472,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);
}
@@ -494,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);
}
@@ -524,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);
}
@@ -554,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);
}
@@ -589,7 +555,7 @@ public class HeadsetStateMachineTest {
* ScoManagedByAudioEnabled
*/
@Test
- public void testStateTransition_ConnectedToAudioConnecting_ConnectAudio_ScoManagedbyAudio() {
+ public void testStateTransition_ConnectedToAudioConnecting_ConnectAudio_ScoManagedByAudio() {
mSetFlagsRule.enableFlags(Flags.FLAG_IS_SCO_MANAGED_BY_AUDIO);
Utils.setIsScoManagedByAudioEnabled(true);
@@ -742,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);
@@ -777,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);
@@ -912,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);
@@ -944,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);
@@ -1095,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);
@@ -1130,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);
@@ -1512,7 +1478,7 @@ public class HeadsetStateMachineTest {
@Test
public void testProcessAtChld_withProcessChldTrue() {
int chld = 1;
- when(mSystemInterface.processChld(chld)).thenReturn(true);
+ when(mSystemInterface.processChld(mHeadsetService, chld)).thenReturn(true);
mHeadsetStateMachine.processAtChld(chld, mDevice);
@@ -1522,7 +1488,7 @@ public class HeadsetStateMachineTest {
@Test
public void testProcessAtChld_withProcessChldFalse() {
int chld = 1;
- when(mSystemInterface.processChld(chld)).thenReturn(false);
+ when(mSystemInterface.processChld(mHeadsetService, chld)).thenReturn(false);
mHeadsetStateMachine.processAtChld(chld, mDevice);
@@ -2101,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;
@@ -2130,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(
@@ -2149,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;
@@ -2232,10 +2189,7 @@ public class HeadsetStateMachineTest {
eq(BLUETOOTH_CONNECT),
any(Bundle.class));
HeadsetTestUtils.verifyConnectionStateBroadcast(
- mDevice,
- BluetoothProfile.STATE_DISCONNECTING,
- BluetoothProfile.STATE_CONNECTED,
- mIntentArgument.getValue());
+ mDevice, STATE_DISCONNECTING, STATE_CONNECTED, mIntentArgument.getValue());
assertThat(mHeadsetStateMachine.getCurrentState())
.isInstanceOf(HeadsetStateMachine.Disconnecting.class);
return numBroadcastsSent;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java
index 5ae51566b7..e96fc3a9a6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.hfpclient;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -72,7 +74,7 @@ public class HeadsetClientServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -87,7 +89,7 @@ public class HeadsetClientServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/HeadsetClientStateMachineTest.java
index cf9aaecf49..243928ee26 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
@@ -242,7 +242,7 @@ public class HeadsetClientStateMachineTest {
public void testProcessAndroidSlcCommand() {
initToConnectedState();
- // True on correct AT command and BluetothDevice
+ // True on correct AT command and BluetoothDevice
assertThat(processAndroidSlcCommand("+ANDROID: (SINKAUDIOPOLICY)")).isTrue();
assertThat(processAndroidSlcCommand("+ANDROID: ()")).isTrue();
assertThat(processAndroidSlcCommand("+ANDROID: (,,,)")).isTrue();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java
index 455d2d2b76..d6cffe4f20 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionServiceTest.java
@@ -16,6 +16,10 @@
package com.android.bluetooth.hfpclient;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.android.bluetooth.TestUtils.mockGetSystemService;
@@ -30,7 +34,6 @@ import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
-import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
@@ -146,7 +149,7 @@ public class HfpClientConnectionServiceTest {
private void setupDeviceConnection(BluetoothDevice device) throws Exception {
mHfpClientConnectionService.onConnectionStateChanged(
- device, BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_CONNECTING);
+ device, STATE_CONNECTED, STATE_CONNECTING);
HfpClientDeviceBlock block = mHfpClientConnectionService.findBlockForDevice(mDevice);
assertThat(block).isNotNull();
assertThat(block.getDevice()).isEqualTo(mDevice);
@@ -172,7 +175,7 @@ public class HfpClientConnectionServiceTest {
createService();
setupDeviceConnection(mDevice);
HfpClientConnectionService.onConnectionStateChanged(
- mDevice, BluetoothProfile.STATE_DISCONNECTED, BluetoothProfile.STATE_CONNECTED);
+ mDevice, STATE_DISCONNECTED, STATE_CONNECTED);
assertThat(mHfpClientConnectionService.findBlockForDevice(mDevice)).isNull();
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java
index 83d36d8623..5423abf868 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientConnectionTest.java
@@ -21,9 +21,11 @@ import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
@@ -36,7 +38,6 @@ import android.telecom.TelecomManager;
import androidx.test.filters.MediumTest;
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -103,7 +104,7 @@ public class HfpClientConnectionTest {
@Test
public void constructorWithNumber() {
- when(mMockServiceInterface.dial(mDevice, TEST_NUMBER)).thenReturn(mCall);
+ doReturn(mCall).when(mMockServiceInterface).dial(mDevice, TEST_NUMBER);
mHfpClientConnection = initiateHfpClientConnectionWithNumber().build();
@@ -240,18 +241,16 @@ public class HfpClientConnectionTest {
assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_ACTIVE);
}
- // TODO: b/393810023 - re-enable when setConference can be called
- // @Test
- // @Ignore("b/191783947")
- // public void handleCallChanged_activeConference() {
- // mHfpClientConnection = createHfpClientConnectionWithExistingCall().build();
- // HfpClientConference mockConference = mock(HfpClientConference.class);
- // mHfpClientConnection.setConference(mockConference);
- // mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_ACTIVE);
- // mHfpClientConnection.handleCallChanged();
+ @Test
+ public void handleCallChanged_activeConference() {
+ mHfpClientConnection = spy(createHfpClientConnectionWithExistingCall().build());
+ HfpClientConference mockConference = mock(HfpClientConference.class);
+ doReturn(mockConference).when(mHfpClientConnection).getConference();
+ mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_ACTIVE);
+ mHfpClientConnection.handleCallChanged();
- // verify(mockConference).setActive();
- // }
+ verify(mockConference).setActive();
+ }
@Test
public void handleCallChanged_heldByResponseAndHold() {
@@ -262,19 +261,17 @@ public class HfpClientConnectionTest {
assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_HOLDING);
}
- // TODO: b/393810023 - re-enable when setConference can be called
- // @Test
- // @Ignore("b/191783947")
- // public void handleCallChanged_heldByResponseAndHoldConference() {
- // mHfpClientConnection = createHfpClientConnectionWithExistingCall().build();
- // HfpClientConference mockConference = mock(HfpClientConference.class);
- // mHfpClientConnection.setConference(mockConference);
- //
- // mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD);
- // mHfpClientConnection.handleCallChanged();
+ @Test
+ public void handleCallChanged_heldByResponseAndHoldConference() {
+ mHfpClientConnection = spy(createHfpClientConnectionWithExistingCall().build());
+ HfpClientConference mockConference = mock(HfpClientConference.class);
+ doReturn(mockConference).when(mHfpClientConnection).getConference();
+
+ mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD_BY_RESPONSE_AND_HOLD);
+ mHfpClientConnection.handleCallChanged();
- // verify(mockConference).setOnHold();
- // }
+ verify(mockConference).setOnHold();
+ }
@Test
public void handleCallChanged_held() {
@@ -285,18 +282,17 @@ public class HfpClientConnectionTest {
assertThat(mHfpClientConnection.getState()).isEqualTo(Connection.STATE_HOLDING);
}
- // TODO: b/393810023 - re-enable when setConference can be called
- // @Test
- // @Ignore("b/191783947")
- // public void handleCallChanged_heldConference() {
- // mHfpClientConnection = createHfpClientConnectionWithExistingCall().build();
- // HfpClientConference mockConference = mock(HfpClientConference.class);
- // mHfpClientConnection.setConference(mockConference);
- // mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD);
- // mHfpClientConnection.handleCallChanged();
+ @Test
+ public void handleCallChanged_heldConference() {
+ mHfpClientConnection = spy(createHfpClientConnectionWithExistingCall().build());
+ HfpClientConference mockConference = mock(HfpClientConference.class);
+ doReturn(mockConference).when(mHfpClientConnection).getConference();
- // verify(mockConference).setOnHold();
- // }
+ mHfpClientConnection.getCall().setState(HfpClientCall.CALL_STATE_HELD);
+ mHfpClientConnection.handleCallChanged();
+
+ verify(mockConference).setOnHold();
+ }
@Test
public void handleCallChanged_dialing() {
@@ -425,11 +421,11 @@ public class HfpClientConnectionTest {
}
@Test
- @Ignore("b/191783947")
public void onUnhold_connectionServiceHasOneConnection_acceptsHeldCall() {
mHfpClientConnection = createHfpClientConnectionWithExistingCall().build();
- when(mHfpClientConnectionService.getAllConnections())
- .thenReturn(Set.of(mHfpClientConnection));
+ doReturn(Set.of(mHfpClientConnection))
+ .when(mHfpClientConnectionService)
+ .getAllConnections();
mHfpClientConnection.onUnhold();
@@ -438,7 +434,6 @@ public class HfpClientConnectionTest {
}
@Test
- @Ignore("b/191783947")
public void onUnhold_connectionServiceHasMultipleConnections_doesNotAcceptHeldCall() {
mHfpClientConnection = createHfpClientConnectionWithExistingCall().build();
HfpClientConnection secondConnection =
@@ -453,8 +448,9 @@ public class HfpClientConnectionTest {
/* outgoing= */ false,
/* inBandRing= */ true))
.build();
- when(mHfpClientConnectionService.getAllConnections())
- .thenReturn(Set.of(mHfpClientConnection, secondConnection));
+ doReturn(Set.of(mHfpClientConnection, secondConnection))
+ .when(mHfpClientConnectionService)
+ .getAllConnections();
mHfpClientConnection.onUnhold();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java
index 5d6a5a3c9c..09178c30d5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hfpclient/connserv/HfpClientDeviceBlockTest.java
@@ -125,7 +125,6 @@ public class HfpClientDeviceBlockTest {
}
@Test
- @Ignore("b/191783947")
public void testHandleMultiPartyCall_scoStateIsSetOnConference() {
HfpClientCall call =
new HfpClientCall(
@@ -143,7 +142,6 @@ public class HfpClientDeviceBlockTest {
ArgumentCaptor<HfpClientConference> conferenceCaptor =
ArgumentCaptor.forClass(HfpClientConference.class);
- // TODO(b/191783947): addConference is final and cannot be mocked
verify(mConnServ).addConference(conferenceCaptor.capture());
HfpClientConference conference = conferenceCaptor.getValue();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java
index 52c220d86b..4b11bc7b2a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hid/BluetoothHidDeviceBinderTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.hid;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -27,7 +30,6 @@ import static org.mockito.Mockito.when;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHidDeviceAppQosSettings;
import android.bluetooth.BluetoothHidDeviceAppSdpSettings;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothHidDeviceCallback;
import android.content.AttributionSource;
@@ -138,7 +140,7 @@ public class BluetoothHidDeviceBinderTest {
@Test
public void setConnectionPolicy() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, mAttributionSource);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
}
@@ -164,7 +166,7 @@ public class BluetoothHidDeviceBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, mAttributionSource);
verify(mService).getDevicesMatchingConnectionStates(states);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
index 74f80c6fdb..946d9a7c93 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/hid/HidHostServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.hid;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.platform.test.flag.junit.SetFlagsRule;
import androidx.test.filters.SmallTest;
@@ -69,13 +71,12 @@ public class HidHostServiceBinderTest {
public void getConnectedDevices_callsServiceMethod() {
mBinder.getConnectedDevices(null);
- verify(mService)
- .getDevicesMatchingConnectionStates(new int[] {BluetoothProfile.STATE_CONNECTED});
+ verify(mService).getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED});
}
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -90,7 +91,7 @@ public class HidHostServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
index 26a10f68f1..e0093fc003 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBinderTest.java
@@ -16,6 +16,9 @@
package com.android.bluetooth.le_audio;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -27,7 +30,6 @@ import android.bluetooth.BluetoothLeAudioCodecConfig;
import android.bluetooth.BluetoothLeAudioContentMetadata;
import android.bluetooth.BluetoothLeBroadcastSettings;
import android.bluetooth.BluetoothLeBroadcastSubgroupSettings;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.IBluetoothLeAudioCallback;
import android.bluetooth.IBluetoothLeBroadcastCallback;
import android.content.AttributionSource;
@@ -95,7 +97,7 @@ public class LeAudioBinderTest {
@Test
public void getDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_DISCONNECTED};
+ int[] states = new int[] {STATE_DISCONNECTED};
AttributionSource source = new AttributionSource.Builder(0).build();
mBinder.getDevicesMatchingConnectionStates(states, source);
@@ -148,7 +150,7 @@ public class LeAudioBinderTest {
@Test
public void setConnectionPolicy() {
BluetoothDevice device = getTestDevice(0);
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ int connectionPolicy = CONNECTION_POLICY_UNKNOWN;
AttributionSource source = new AttributionSource.Builder(0).build();
mBinder.setConnectionPolicy(device, connectionPolicy, source);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioBroadcastServiceTest.java
index c89dd20667..576f7cdc54 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
@@ -1037,8 +1037,6 @@ public class LeAudioBroadcastServiceTest {
create_event.valueInt1 = broadcastId;
create_event.valueInt2 = LeAudioStackEvent.BROADCAST_STATE_STREAMING;
mService.messageFromNative(create_event);
-
- verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice));
}
@Test
@@ -1049,6 +1047,11 @@ public class LeAudioBroadcastServiceTest {
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* Expect clear of Inband Ringtone Support when device is changing to inactive and there is
+ * no unicast to broadcast fallback device set
+ */
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
/* Imitate setting device in call */
mService.handleAudioModeChange(AudioManager.MODE_IN_CALL);
@@ -1139,6 +1142,11 @@ public class LeAudioBroadcastServiceTest {
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* Expect clear of Inband Ringtone Support when device is changing to inactive and there is
+ * no unicast to broadcast fallback device set
+ */
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
verify(mLeAudioBroadcasterNativeInterface).startBroadcast(eq(broadcastId));
/* Imitate group change request by Bluetooth Sink HAL resume request */
@@ -1228,6 +1236,11 @@ public class LeAudioBroadcastServiceTest {
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* Expect clear of Inband Ringtone Support when device is changing to inactive and there is
+ * no unicast to broadcast fallback device set
+ */
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
/* Internal broadcast paused due to onAudioSuspend */
LeAudioStackEvent state_event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE);
@@ -1315,6 +1328,11 @@ public class LeAudioBroadcastServiceTest {
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* Expect clear of Inband Ringtone Support when device is changing to inactive and there is
+ * no unicast to broadcast fallback device set
+ */
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
/* Internal broadcast paused due to onAudioSuspend */
LeAudioStackEvent state_event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE);
@@ -1390,7 +1408,7 @@ public class LeAudioBroadcastServiceTest {
}
@Test
- public void testCacheAndResmueSuspendingSources() {
+ public void testCacheAndResumeSuspendingSources() {
mSetFlagsRule.enableFlags(Flags.FLAG_LEAUDIO_BIG_DEPENDS_ON_AUDIO_STATE);
int groupId = 1;
int broadcastId = 243;
@@ -1398,6 +1416,11 @@ public class LeAudioBroadcastServiceTest {
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* Expect clear of Inband Ringtone Support when device is changing to inactive and there is
+ * no unicast to broadcast fallback device set
+ */
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
/* Internal broadcast paused due to onAudioSuspend */
LeAudioStackEvent state_event =
new LeAudioStackEvent(LeAudioStackEvent.EVENT_TYPE_BROADCAST_STATE);
@@ -1426,6 +1449,12 @@ public class LeAudioBroadcastServiceTest {
prepareConnectedUnicastDevice(groupId2, mDevice2);
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* group 1 is deactivated due to broadcast and group 2 is set by default as broadcast to
+ * unicast fallback group (first add device)
+ */
+ verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice2));
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
assertThat(mService.mUnicastGroupIdDeactivatedForBroadcastTransition).isEqualTo(groupId);
reset(mAudioManager);
@@ -1473,6 +1502,12 @@ public class LeAudioBroadcastServiceTest {
devices.add(mDevice);
prepareHandoverStreamingBroadcast(groupId1, broadcastId, code);
+ /* group 1 is deactivated due to broadcast and group 2 is set by default as broadcast to
+ * unicast fallback group (first add device)
+ */
+ verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice2));
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
TestUtils.waitForLooperToFinishScheduledTask(Looper.getMainLooper());
assertThat(mService.mUnicastGroupIdDeactivatedForBroadcastTransition).isEqualTo(groupId2);
@@ -1528,11 +1563,18 @@ public class LeAudioBroadcastServiceTest {
devices.add(mDevice2);
prepareConnectedUnicastDevice(groupId2, mDevice2);
+ InOrder tbsOrder = inOrder(mTbsService);
+ tbsOrder.verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice2));
+ tbsOrder.verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice));
+
assertThat(mService.mUnicastGroupIdDeactivatedForBroadcastTransition).isEqualTo(groupId);
+ tbsOrder.verify(mTbsService, times(1)).setInbandRingtoneSupport(eq(mDevice));
reset(mAudioManager);
mService.setBroadcastToUnicastFallbackGroup(groupId2);
+ tbsOrder.verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+ tbsOrder.verify(mTbsService, times(1)).setInbandRingtoneSupport(eq(mDevice2));
/* Update fallback active device (only input is active) */
ArgumentCaptor<BluetoothProfileConnectionInfo> connectionInfoArgumentCaptor =
@@ -1644,6 +1686,12 @@ public class LeAudioBroadcastServiceTest {
devices.add(mDevice);
prepareHandoverStreamingBroadcast(groupId, broadcastId, code);
+ /* group 1 is deactivated due to broadcast and group 2 is set by default as broadcast to
+ * unicast fallback group (first add device)
+ */
+ verify(mTbsService, never()).clearInbandRingtoneSupport(eq(mDevice2));
+ verify(mTbsService, times(1)).clearInbandRingtoneSupport(eq(mDevice));
+
/* Earliest connected group (2) become fallback device */
assertThat(mService.mUnicastGroupIdDeactivatedForBroadcastTransition).isEqualTo(groupId2);
verify(mLeAudioCallbacks).onBroadcastToUnicastFallbackGroupChanged(groupId2);
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 0ec418e49a..7e8820e6bc 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_audio/LeAudioServiceTest.java
@@ -19,6 +19,8 @@ package com.android.bluetooth.le_audio;
import static android.bluetooth.BluetoothDevice.BOND_BONDED;
import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.EXTRA_PREVIOUS_STATE;
import static android.bluetooth.BluetoothProfile.EXTRA_STATE;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
@@ -290,7 +292,7 @@ public class LeAudioServiceTest {
// Make sure the device is known to the service and is not forbidden to connect
mService.createDeviceDescriptor(mSingleDevice, true);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
// Verify the device is enabled in the service when policy is not FORBIDDEN during BT Enable
mService.handleBluetoothEnabled();
@@ -300,7 +302,7 @@ public class LeAudioServiceTest {
when(mDatabaseManager.setProfileConnectionPolicy(
eq(mSingleDevice), eq(BluetoothProfile.LE_AUDIO), anyInt()))
.thenReturn(true);
- mService.setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN);
verify(mNativeInterface).setEnableState(eq(mSingleDevice), eq(false));
}
@@ -315,15 +317,15 @@ public class LeAudioServiceTest {
@Test
public void testGetSetPriority() {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
assertWithMessage("Initial device priority")
- .that(BluetoothProfile.CONNECTION_POLICY_UNKNOWN)
+ .that(CONNECTION_POLICY_UNKNOWN)
.isEqualTo(mService.getConnectionPolicy(mLeftDevice));
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
assertWithMessage("Setting device priority to PRIORITY_OFF")
- .that(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)
+ .that(CONNECTION_POLICY_FORBIDDEN)
.isEqualTo(mService.getConnectionPolicy(mLeftDevice));
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
@@ -355,41 +357,25 @@ public class LeAudioServiceTest {
int badPriorityValue = 1024;
int badBondState = 42;
testOkToConnectCase(
- mSingleDevice,
- BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- false);
+ mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_UNKNOWN, false);
testOkToConnectCase(
- mSingleDevice,
- BluetoothDevice.BOND_NONE,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(
mSingleDevice, BluetoothDevice.BOND_NONE, CONNECTION_POLICY_ALLOWED, false);
testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_NONE, badPriorityValue, false);
testOkToConnectCase(
- mSingleDevice,
- BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_UNKNOWN,
- false);
+ mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_UNKNOWN, false);
testOkToConnectCase(
- mSingleDevice,
- BluetoothDevice.BOND_BONDING,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- false);
+ mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(
mSingleDevice, BluetoothDevice.BOND_BONDING, CONNECTION_POLICY_ALLOWED, false);
testOkToConnectCase(mSingleDevice, BluetoothDevice.BOND_BONDING, badPriorityValue, false);
- testOkToConnectCase(
- mSingleDevice, BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, true);
- testOkToConnectCase(
- mSingleDevice, BOND_BONDED, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
+ testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_UNKNOWN, true);
+ testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(mSingleDevice, BOND_BONDED, CONNECTION_POLICY_ALLOWED, true);
testOkToConnectCase(mSingleDevice, BOND_BONDED, badPriorityValue, false);
- testOkToConnectCase(
- mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_UNKNOWN, false);
- testOkToConnectCase(
- mSingleDevice, badBondState, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN, false);
+ testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_UNKNOWN, false);
+ testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_FORBIDDEN, false);
testOkToConnectCase(mSingleDevice, badBondState, CONNECTION_POLICY_ALLOWED, false);
testOkToConnectCase(mSingleDevice, badBondState, badPriorityValue, false);
}
@@ -401,9 +387,9 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Return No UUID
doReturn(new ParcelUuid[] {})
@@ -419,7 +405,7 @@ public class LeAudioServiceTest {
public void testOutgoingConnectPriorityOff() {
// Set the device priority to PRIORITY_OFF so connect() should fail
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Send a connect request
assertWithMessage("Connect expected to fail").that(mService.connect(mLeftDevice)).isFalse();
@@ -432,9 +418,9 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Send a connect request
assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue();
@@ -509,7 +495,7 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Send a connect request
assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue();
@@ -595,9 +581,9 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Create device descriptor with connect request
assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue();
@@ -650,9 +636,9 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Create device descriptor with connect request
assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue();
@@ -705,9 +691,9 @@ public class LeAudioServiceTest {
when(mDatabaseManager.getProfileConnectionPolicy(mLeftDevice, BluetoothProfile.LE_AUDIO))
.thenReturn(CONNECTION_POLICY_ALLOWED);
when(mDatabaseManager.getProfileConnectionPolicy(mRightDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
// Create device descriptor with connect request
assertWithMessage("Connect failed").that(mService.connect(mLeftDevice)).isTrue();
@@ -827,7 +813,7 @@ public class LeAudioServiceTest {
when(mHapClientService.setConnectionPolicy(any(), anyInt())).thenReturn(true);
when(mBassClientService.setConnectionPolicy(any(), anyInt())).thenReturn(true);
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_ALLOWED)).isTrue();
@@ -857,22 +843,18 @@ public class LeAudioServiceTest {
assertThat(mService.getConnectionState(mSingleDevice)).isEqualTo(STATE_CONNECTED);
// Set connection policy to forbidden
- assertThat(
- mService.setConnectionPolicy(
- mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
// Verify connection policy for CSIP and VCP are also set
verify(mVolumeControlService)
- .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN);
verify(mCsipSetCoordinatorService)
- .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
- verify(mHapClientService)
- .setConnectionPolicy(mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN);
+ verify(mHapClientService).setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN);
if (BluetoothProperties.isProfileBapBroadcastAssistEnabled().orElse(false)) {
verify(mBassClientService)
- .setConnectionPolicy(
- mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN);
}
// Verify the connection state broadcast, and that we are in Connecting state
verifyConnectionStateIntent(mSingleDevice, STATE_DISCONNECTING, STATE_CONNECTED);
@@ -899,7 +881,7 @@ public class LeAudioServiceTest {
List<BluetoothDevice> prevConnectedDevices = mService.getConnectedDevices();
when(mDatabaseManager.getProfileConnectionPolicy(device, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
// Send a connect request
assertWithMessage("Connect failed").that(mService.connect(device)).isTrue();
@@ -1243,9 +1225,11 @@ public class LeAudioServiceTest {
assertThat(connInfo.isSuppressNoisyIntent()).isTrue();
// AudioManager removes audio device
+ // We just ignore it as AudioManager is going to restart and re-add devices
injectAudioDeviceRemoved(
- mSingleDevice, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, true);
- verify(mNativeInterface, times(1)).groupSetActive(-1);
+ mSingleDevice, AudioDeviceInfo.TYPE_BLE_HEADSET, true, false, false);
+
+ verify(mNativeInterface, never()).groupSetActive(-1);
}
/** Test setting active device group without Ringtone context */
@@ -1586,7 +1570,7 @@ public class LeAudioServiceTest {
}
/**
- * Test native interface health base action message handling. It does not much, just chects
+ * Test native interface health base action message handling. It does not much, just checks
* stack even and that service not crash
*/
@Test
@@ -1630,14 +1614,10 @@ public class LeAudioServiceTest {
verify(mDatabaseManager)
.setProfileConnectionPolicy(
- mLeftDevice,
- BluetoothProfile.LE_AUDIO,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mLeftDevice, BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_FORBIDDEN);
verify(mDatabaseManager)
.setProfileConnectionPolicy(
- mRightDevice,
- BluetoothProfile.LE_AUDIO,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ mRightDevice, BluetoothProfile.LE_AUDIO, CONNECTION_POLICY_FORBIDDEN);
}
private void sendEventAndVerifyIntentForGroupStatusChanged(int groupId, int groupStatus) {
@@ -2436,7 +2416,7 @@ public class LeAudioServiceTest {
.when(mDatabaseManager)
.setProfileConnectionPolicy(any(BluetoothDevice.class), anyInt(), anyInt());
when(mDatabaseManager.getProfileConnectionPolicy(mSingleDevice, BluetoothProfile.LE_AUDIO))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
// Ensures GATT server services are not authorized when the device does not have a group
assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_ALLOWED)).isTrue();
@@ -2449,9 +2429,7 @@ public class LeAudioServiceTest {
verify(mTbsService).setDeviceAuthorized(mSingleDevice, true);
// Ensure that disconnecting unauthorizes GATT server services
- assertThat(
- mService.setConnectionPolicy(
- mSingleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ assertThat(mService.setConnectionPolicy(mSingleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
verify(mMcpService).setDeviceAuthorized(mSingleDevice, false);
verify(mTbsService).setDeviceAuthorized(mSingleDevice, false);
@@ -2587,7 +2565,7 @@ public class LeAudioServiceTest {
verify(mNativeInterface, times(0)).groupSetActive(groupId);
reset(mNativeInterface);
- /* Expect device to be incactive */
+ /* Expect device to be inactive */
injectAudioConfChanged(mSingleDevice, groupId, 0, direction);
verify(mNativeInterface).groupSetActive(-1);
@@ -2602,7 +2580,7 @@ public class LeAudioServiceTest {
reset(mNativeInterface);
reset(mAudioManager);
- /* Expect device to be incactive */
+ /* Expect device to be inactive */
injectAudioConfChanged(mSingleDevice, groupId, 1, direction);
verify(mNativeInterface).groupSetActive(groupId);
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..3057a13b55 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);
}
/**
@@ -142,10 +144,9 @@ public class LeAudioStateMachineTest {
connStCh.valueInt1 = LeAudioStackEvent.CONNECTION_STATE_CONNECTING;
mLeAudioStateMachine.sendMessage(LeAudioStateMachine.STACK_EVENT, connStCh);
- // Verify that one connection state change is notifyed
+ // 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())
@@ -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/MsftAdvMonitorMergedPatternListTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorMergedPatternListTest.java
index 62c8545fa2..2e5bb43da1 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorMergedPatternListTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/MsftAdvMonitorMergedPatternListTest.java
@@ -38,7 +38,7 @@ public final class MsftAdvMonitorMergedPatternListTest {
new ParcelUuid(UUID.fromString("12345678-90AB-CDEF-1234-567890ABCDEF"));
@Test
- public void testAddandRemove() {
+ public void testAddAndRemove() {
MsftAdvMonitorMergedPatternList patternList = new MsftAdvMonitorMergedPatternList();
int filterIndex = 0;
int addedFilterIndex = filterIndex;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/PeriodicScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/PeriodicScanManagerTest.java
index e05daddc57..8c8da944de 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/PeriodicScanManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/PeriodicScanManagerTest.java
@@ -40,8 +40,6 @@ import androidx.test.filters.SmallTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
-import com.android.bluetooth.btservice.AdapterService;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
@@ -50,14 +48,13 @@ import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
-/** Test cases for {@link PeriodicScanManagerTest}. */
+/** Test cases for {@link PeriodicScanManager}. */
@SmallTest
@RunWith(AndroidJUnit4.class)
public class PeriodicScanManagerTest {
@Rule public final MockitoRule mMockitoRule = new MockitoRule();
@Mock private PeriodicScanNativeInterface mPeriodicScanNativeInterface;
- @Mock private AdapterService mAdapterService;
@Mock private IPeriodicAdvertisingCallback mCallback;
@Mock private IBinder mBinder;
@@ -73,7 +70,7 @@ public class PeriodicScanManagerTest {
public void setUp() throws Exception {
mTargetContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
PeriodicScanNativeInterface.setInstance(mPeriodicScanNativeInterface);
- mPeriodicScanManager = new PeriodicScanManager(mAdapterService);
+ mPeriodicScanManager = new PeriodicScanManager();
BluetoothManager manager = mTargetContext.getSystemService(BluetoothManager.class);
assertThat(manager).isNotNull();
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 69af019b45..dd8785ccdf 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;
@@ -86,7 +89,6 @@ public class ScanControllerTest {
@Mock private ScannerMap mScannerMap;
@Mock private ScannerMap.ScannerApp mApp;
- @Mock private ScanController.PendingIntentInfo mPiInfo;
@Mock private PeriodicScanManager mPeriodicScanManager;
@Mock private ScanManager mScanManager;
@Mock private Resources mResources;
@@ -117,7 +119,7 @@ public class ScanControllerTest {
doReturn(mScanManager)
.when(mScanObjectsFactory)
.createScanManager(any(), any(), any(), any());
- doReturn(mPeriodicScanManager).when(mScanObjectsFactory).createPeriodicScanManager(any());
+ doReturn(mPeriodicScanManager).when(mScanObjectsFactory).createPeriodicScanManager();
doReturn(mResources).when(mAdapterService).getResources();
doReturn(mContext.getPackageManager()).when(mAdapterService).getPackageManager();
@@ -158,8 +160,10 @@ public class ScanControllerTest {
public void continuePiStartScan() {
int scannerId = 1;
- mPiInfo.settings = new ScanSettings.Builder().build();
- mApp.mInfo = mPiInfo;
+ ScanController.PendingIntentInfo pii =
+ new ScanController.PendingIntentInfo(
+ null, new ScanSettings.Builder().build(), null, null, 0);
+ mApp.mInfo = pii;
AppScanStats appScanStats = mock(AppScanStats.class);
doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scannerId);
@@ -167,7 +171,7 @@ public class ScanControllerTest {
mScanController.continuePiStartScan(scannerId, mApp);
verify(appScanStats)
- .recordScanStart(mPiInfo.settings, mPiInfo.filters, false, false, scannerId, null);
+ .recordScanStart(pii.settings(), pii.filters(), false, false, scannerId, null);
verify(mScanManager).startScan(any());
}
@@ -175,9 +179,10 @@ public class ScanControllerTest {
public void continuePiStartScanCheckUid() {
int scannerId = 1;
- mPiInfo.settings = new ScanSettings.Builder().build();
- mPiInfo.callingUid = 123;
- mApp.mInfo = mPiInfo;
+ ScanController.PendingIntentInfo pii =
+ new ScanController.PendingIntentInfo(
+ null, new ScanSettings.Builder().build(), null, null, 123);
+ mApp.mInfo = pii;
AppScanStats appScanStats = mock(AppScanStats.class);
doReturn(appScanStats).when(mScannerMap).getAppScanStatsById(scannerId);
@@ -185,14 +190,14 @@ public class ScanControllerTest {
mScanController.continuePiStartScan(scannerId, mApp);
verify(appScanStats)
- .recordScanStart(mPiInfo.settings, mPiInfo.filters, false, false, scannerId, null);
+ .recordScanStart(pii.settings(), pii.filters(), false, false, scannerId, null);
verify(mScanManager)
.startScan(
argThat(
new ArgumentMatcher<ScanClient>() {
@Override
public boolean matches(ScanClient client) {
- return mPiInfo.callingUid == client.appUid;
+ return pii.callingUid() == client.mAppUid;
}
}));
}
@@ -211,14 +216,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;
@@ -246,14 +250,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;
@@ -331,9 +334,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)
@@ -344,13 +346,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());
@@ -368,7 +370,7 @@ public class ScanControllerTest {
advData,
address);
- assertThat(scanClient.appDied).isTrue();
+ assertThat(scanClient.mAppDied).isTrue();
verify(appScanStats).recordScanStop(scannerId);
}
@@ -414,14 +416,10 @@ 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
@@ -442,8 +440,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)
@@ -454,7 +452,6 @@ public class ScanControllerTest {
IScannerCallback callback = mock(IScannerCallback.class);
app.mCallback = callback;
- app.mInfo = mock(ScanController.PendingIntentInfo.class);
doReturn(app).when(mScannerMap).getById(scannerId);
doReturn(scanClientSet).when(mScanManager).getRegularScanQueue();
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 3359c2b48a..15dc16bbf3 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
@@ -54,8 +54,6 @@ public class ScanFilterQueueTest {
byte[] irk = new byte[] {0x02};
queue.addDeviceAddress(address, type, irk);
- queue.addServiceChanged();
-
UUID uuid = UUID.randomUUID();
queue.addUuid(uuid);
@@ -87,7 +85,7 @@ public class ScanFilterQueueTest {
queue.addAdvertisingDataType(adType, adData, adDataMask);
ScanFilterQueue.Entry[] entries = queue.toArray();
- int entriesLength = 10;
+ int entriesLength = 9;
assertThat(entries.length).isEqualTo(entriesLength);
for (ScanFilterQueue.Entry entry : entries) {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
index 2312d11787..d19e0c7251 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScanManagerTest.java
@@ -304,8 +304,8 @@ public class ScanManagerTest {
mClientId = mClientId + 1;
ScanClient client = new ScanClient(mClientId, scanSettings, scanFilterList, appUid);
- client.stats = appScanStats;
- client.stats.recordScanStart(
+ client.mStats = appScanStats;
+ client.mStats.recordScanStart(
scanSettings, scanFilterList, isFiltered, false, mClientId, null);
return client;
}
@@ -412,8 +412,8 @@ public class ScanManagerTest {
ScanSettings scanSettings = createScanSettingsWithPhy(scanMode, phy);
ScanClient client = new ScanClient(id, scanSettings, scanFilterList);
- client.stats = mMockAppScanStats;
- client.stats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null);
+ client.mStats = mMockAppScanStats;
+ client.mStats.recordScanStart(scanSettings, scanFilterList, isFiltered, false, id, null);
return client;
}
@@ -479,7 +479,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client);
assertThat(mScanManager.getSuspendedScanQueue()).contains(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -507,7 +507,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
}
}
@@ -530,7 +530,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client);
assertThat(mScanManager.getSuspendedScanQueue()).contains(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -552,7 +552,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -574,7 +574,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -602,12 +602,12 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).doesNotContain(client);
assertThat(mScanManager.getSuspendedScanQueue()).contains(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
}
}
@@ -635,12 +635,12 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
}
}
@@ -661,24 +661,24 @@ public class ScanManagerTest {
ScanClient client = createScanClient(isFiltered, scanMode);
// Start scan
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Wait for scan timeout
advanceTime(DEFAULT_SCAN_TIMEOUT_MILLIS);
mLooper.dispatchAll();
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
- assertThat(client.stats.isScanTimeout(client.scannerId)).isTrue();
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mStats.isScanTimeout(client.mScannerId)).isTrue();
// Turn off screen
sendMessageWaitForProcessed(createScreenOnOffMessage(false));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Set as background app
sendMessageWaitForProcessed(createImportanceMessage(false));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Set as foreground app
sendMessageWaitForProcessed(createImportanceMessage(true));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -699,7 +699,7 @@ public class ScanManagerTest {
ScanClient client = createScanClient(isFiltered, scanMode);
// Start scan, this sends scan timeout message with delay
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Move time forward so scan timeout message can be dispatched
advanceTime(DEFAULT_SCAN_TIMEOUT_MILLIS);
// Since we are using a TestLooper, need to mock AppScanStats.isScanningTooLong
@@ -707,20 +707,20 @@ public class ScanManagerTest {
// return true because no real time is elapsed
doReturn(true).when(mMockAppScanStats).isScanningTooLong();
syncHandler(ScanManager.MSG_SCAN_TIMEOUT);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
- assertThat(client.stats.isScanTimeout(client.scannerId)).isTrue();
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mStats.isScanTimeout(client.mScannerId)).isTrue();
// Turn off screen
sendMessageWaitForProcessed(createScreenOnOffMessage(false));
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF);
// Set as background app
sendMessageWaitForProcessed(createImportanceMessage(false));
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_SCREEN_OFF);
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Set as foreground app
sendMessageWaitForProcessed(createImportanceMessage(true));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -771,17 +771,17 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Set as background app
sendMessageWaitForProcessed(createImportanceMessage(false));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Set as foreground app
sendMessageWaitForProcessed(createImportanceMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
});
}
@@ -804,17 +804,17 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Set as background app
sendMessageWaitForProcessed(createImportanceMessage(false));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Set as foreground app
sendMessageWaitForProcessed(createImportanceMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
});
}
@@ -847,11 +847,11 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Wait for upgrade duration
advanceTime(DEFAULT_SCAN_UPGRADE_DURATION_MILLIS);
mLooper.dispatchAll();
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
}
}
@@ -885,7 +885,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Wait for upgrade and downgrade duration
int max_duration =
DEFAULT_SCAN_UPGRADE_DURATION_MILLIS
@@ -894,7 +894,7 @@ public class ScanManagerTest {
: DEFAULT_SCAN_DOWNGRADE_DURATION_BT_CONNECTING_MILLIS;
advanceTime(max_duration);
mLooper.dispatchAll();
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
});
}
@@ -928,14 +928,14 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Set connecting state
sendMessageWaitForProcessed(createConnectingMessage(true));
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
// Wait for downgrade duration
advanceTime(DEFAULT_SCAN_DOWNGRADE_DURATION_BT_CONNECTING_MILLIS);
mLooper.dispatchAll();
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
}
}
@@ -969,7 +969,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Set connecting state
sendMessageWaitForProcessed(createConnectingMessage(true));
// Turn off screen
@@ -980,7 +980,7 @@ public class ScanManagerTest {
mLooper.dispatchAll();
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
}
}
@@ -1009,7 +1009,7 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
// Set connecting state
sendMessageWaitForProcessed(createConnectingMessage(true));
// Set as background app
@@ -1019,7 +1019,7 @@ public class ScanManagerTest {
mLooper.dispatchAll();
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(expectedScanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(expectedScanMode);
});
}
@@ -1124,7 +1124,7 @@ public class ScanManagerTest {
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
assertThat(mScanManager.getBatchScanQueue()).doesNotContain(client);
assertThat(mScanManager.getBatchScanParams()).isNull();
@@ -1167,7 +1167,7 @@ public class ScanManagerTest {
// Turn on screen
sendMessageWaitForProcessed(createScreenOnOffMessage(true));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
- assertThat(client.settings.getScanMode()).isEqualTo(scanMode);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(scanMode);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
assertThat(mScanManager.getBatchScanQueue()).doesNotContain(client);
assertThat(mScanManager.getBatchScanParams()).isNull();
@@ -1292,7 +1292,7 @@ public class ScanManagerTest {
advanceTime(scanTestDuration);
// Record scan stop
- client.stats.recordScanStop(mClientId);
+ client.mStats.recordScanStop(mClientId);
// Verify that the app scan stop is logged
mInOrder.verify(mMetricsLogger)
.logAppScanStateChanged(
@@ -1494,12 +1494,12 @@ public class ScanManagerTest {
// Verify radio scan stop is logged with the third app when screen turns on
mInOrder.verify(mMetricsLogger)
.logRadioScanStopped(
- eq(new int[] {mostAggressiveClient.appUid}),
- eq(new String[] {TEST_PACKAGE_NAME + mostAggressiveClient.appUid}),
+ eq(new int[] {mostAggressiveClient.mAppUid}),
+ eq(new String[] {TEST_PACKAGE_NAME + mostAggressiveClient.mAppUid}),
eq(
BluetoothStatsLog
.LE_APP_SCAN_STATE_CHANGED__LE_SCAN_TYPE__SCAN_TYPE_REGULAR),
- eq(AppScanStats.convertScanMode(mostAggressiveClient.scanModeApp)),
+ eq(AppScanStats.convertScanMode(mostAggressiveClient.mScanModeApp)),
eq((long) SCAN_MODE_SCREEN_OFF_LOW_POWER_INTERVAL_MS),
eq((long) SCAN_MODE_SCREEN_OFF_LOW_POWER_WINDOW_MS),
eq(false),
@@ -1802,11 +1802,11 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
// Set connecting state
sendMessageWaitForProcessed(createConnectingMessage(true));
// SCAN_MODE_LOW_LATENCY is now downgraded to SCAN_MODE_BALANCED
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_BALANCED);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_BALANCED);
}
@Test
@@ -1826,13 +1826,13 @@ public class ScanManagerTest {
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
assertThat(mScanManager.getRegularScanQueue()).contains(client);
assertThat(mScanManager.getSuspendedScanQueue()).doesNotContain(client);
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
// Set AppScanStats to null
- client.stats = null;
+ client.mStats = null;
// Set connecting state
sendMessageWaitForProcessed(createConnectingMessage(true));
// Since AppScanStats is null, no downgrade takes place for scan mode
- assertThat(client.settings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
+ assertThat(client.mSettings.getScanMode()).isEqualTo(SCAN_MODE_LOW_LATENCY);
}
@Test
@@ -1944,7 +1944,7 @@ public class ScanManagerTest {
// Start scan
sendMessageWaitForProcessed(createStartStopScanMessage(true, client));
- assertThat(client.settings.getPhy()).isEqualTo(phy);
+ assertThat(client.mSettings.getPhy()).isEqualTo(phy);
verify(mScanNativeInterface)
.gattSetScanParameters(
eq(expect1m ? mClientId : 0),
@@ -1976,7 +1976,7 @@ public class ScanManagerTest {
// Start scan on 1m
sendMessageWaitForProcessed(createStartStopScanMessage(true, client1m));
- assertThat(client1m.settings.getPhy()).isEqualTo(PHY_LE_1M);
+ assertThat(client1m.mSettings.getPhy()).isEqualTo(PHY_LE_1M);
verify(mScanNativeInterface)
.gattSetScanParameters(
eq(clientId1m),
@@ -1995,7 +1995,7 @@ public class ScanManagerTest {
// Start scan on coded
sendMessageWaitForProcessed(createStartStopScanMessage(true, clientCoded));
- assertThat(clientCoded.settings.getPhy()).isEqualTo(PHY_LE_CODED);
+ assertThat(clientCoded.mSettings.getPhy()).isEqualTo(PHY_LE_CODED);
verify(mScanNativeInterface)
.gattSetScanParameters(
eq(clientId1m),
diff --git a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScannerMapTest.java b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScannerMapTest.java
index 9bee3680c3..e8d31e0552 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScannerMapTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/le_scan/ScannerMapTest.java
@@ -85,15 +85,14 @@ public class ScannerMapTest {
@Test
public void getByMethodsWithPii() {
ScannerMap scannerMap = new ScannerMap();
- ScanController.PendingIntentInfo info = new ScanController.PendingIntentInfo();
- info.callingUid = UID;
- info.callingPackage = APP_NAME;
- info.intent =
+ PendingIntent intent =
PendingIntent.getBroadcast(
InstrumentationRegistry.getInstrumentation().getTargetContext(),
0,
new Intent(),
PendingIntent.FLAG_IMMUTABLE);
+ ScanController.PendingIntentInfo info =
+ new ScanController.PendingIntentInfo(intent, null, null, APP_NAME, UID);
UUID uuid = UUID.randomUUID();
ScannerMap.ScannerApp app =
scannerMap.add(
@@ -109,7 +108,7 @@ public class ScannerMapTest {
ScannerMap.ScannerApp scannerMapByName = scannerMap.getByName(APP_NAME).get(0);
assertThat(scannerMapByName.mName).isEqualTo(APP_NAME);
- ScannerMap.ScannerApp scannerMapByPii = scannerMap.getByPendingIntentInfo(info);
+ ScannerMap.ScannerApp scannerMapByPii = scannerMap.getByPendingIntentInfo(intent);
assertThat(scannerMapByPii.mName).isEqualTo(APP_NAME);
assertThat(scannerMap.getAppScanStatsById(SCANNER_ID)).isNotNull();
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java
index 72a3c75168..6410ebf3f0 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.map;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -65,7 +67,7 @@ public class BluetoothMapServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -80,7 +82,7 @@ public class BluetoothMapServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
index 85d8ba6f15..2f6604a486 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/BluetoothMapServiceTest.java
@@ -15,6 +15,8 @@
*/
package com.android.bluetooth.map;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.android.bluetooth.TestUtils.mockGetSystemService;
@@ -26,7 +28,6 @@ import static org.mockito.Mockito.when;
import android.app.AlarmManager;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.telephony.TelephonyManager;
@@ -86,9 +87,7 @@ public class BluetoothMapServiceTest {
public void getDevicesMatchingConnectionStates_whenNoDeviceIsConnected_returnsEmptyList() {
when(mAdapterService.getBondedDevices()).thenReturn(new BluetoothDevice[] {mDevice});
- assertThat(
- mService.getDevicesMatchingConnectionStates(
- new int[] {BluetoothProfile.STATE_CONNECTED}))
+ assertThat(mService.getDevicesMatchingConnectionStates(new int[] {STATE_CONNECTED}))
.isEmpty();
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java
index 041a7ff86d..f9f0b50fa1 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/map/MsgTest.java
@@ -18,11 +18,11 @@ package com.android.bluetooth.map;
import static com.google.common.truth.Truth.assertThat;
-import android.annotation.SuppressLint;
-
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
+import com.google.common.testing.EqualsTester;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -53,50 +53,22 @@ public class MsgTest {
}
@Test
- public void equals_withSameInstance() {
- BluetoothMapContentObserver.Msg msg =
- new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG);
-
- assertThat(msg.equals(msg)).isTrue();
- }
-
- @Test
- public void equals_withNull() {
- BluetoothMapContentObserver.Msg msg =
- new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG);
-
- assertThat(msg).isNotNull();
- }
-
- @Test
- @SuppressLint("TruthIncompatibleType") // That the point of this test
- public void equals_withDifferentClass() {
- BluetoothMapContentObserver.Msg msg =
- new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG);
- String msgOfDifferentClass = "msg_of_different_class";
-
- assertThat(msg).isNotEqualTo(msgOfDifferentClass);
- }
-
- @Test
- public void equals_withDifferentId() {
+ public void equals() {
long idOne = 1;
long idTwo = 2;
BluetoothMapContentObserver.Msg msg =
new BluetoothMapContentObserver.Msg(idOne, TEST_FOLDER_ID, TEST_READ_FLAG);
+ BluetoothMapContentObserver.Msg msgWithSameId =
+ new BluetoothMapContentObserver.Msg(idOne, TEST_FOLDER_ID, TEST_READ_FLAG);
BluetoothMapContentObserver.Msg msgWithDifferentId =
new BluetoothMapContentObserver.Msg(idTwo, TEST_FOLDER_ID, TEST_READ_FLAG);
- assertThat(msg).isNotEqualTo(msgWithDifferentId);
- }
-
- @Test
- public void equals_withEqualInstance() {
- BluetoothMapContentObserver.Msg msg =
- new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG);
- BluetoothMapContentObserver.Msg msgWithSameId =
- new BluetoothMapContentObserver.Msg(TEST_ID, TEST_FOLDER_ID, TEST_READ_FLAG);
+ String msgOfDifferentClass = "msg_of_different_class";
- assertThat(msg).isEqualTo(msgWithSameId);
+ new EqualsTester()
+ .addEqualityGroup(msg, msg, msgWithSameId)
+ .addEqualityGroup(msgWithDifferentId, msgWithDifferentId)
+ .addEqualityGroup(msgOfDifferentClass)
+ .testEquals();
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientContentTest.java
index bfabc8081a..886e0ca3a7 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
@@ -448,7 +448,7 @@ public class MapClientContentTest {
/** Test that we gracefully exit when there's a problem with the SMS/MMS DB being available */
@Test
- public void testInsertSmsFails_messageHandleNotInteractable() {
+ public void testInsertSmsFails_messageHandleNotIntractable() {
// Try to store an MMS, but make the content resolver fail to insert and provide a null URI
MissingContentProvider missingContentProvider =
Mockito.spy(new MissingContentProvider(mMockContext));
@@ -470,7 +470,7 @@ public class MapClientContentTest {
/** Test that we gracefully exit when there's a problem with the SMS/MMS DB being available */
@Test
- public void testInsertMmsPartsSkippedWhenMmsInsertFails_messageHandleNotInteractable() {
+ public void testInsertMmsPartsSkippedWhenMmsInsertFails_messageHandleNotIntractable() {
// Try to store an MMS, but make the content resolver fail to insert and provide a null URI
MissingContentProvider missingContentProvider =
Mockito.spy(new MissingContentProvider(mMockContext));
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java
index 431314a7af..d3e98577a6 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceBinderTest.java
@@ -15,13 +15,15 @@
*/
package com.android.bluetooth.mapclient;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.net.Uri;
import androidx.test.filters.MediumTest;
@@ -72,7 +74,7 @@ public class MapClientServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -87,7 +89,7 @@ public class MapClientServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
index ce23a13dce..c75333efcf 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientServiceTest.java
@@ -18,6 +18,9 @@ package com.android.bluetooth.mapclient;
import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -171,7 +174,7 @@ public class MapClientServiceTest {
@Test
public void disconnect_whenConnected_returnsTrue() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
when(sm.getState()).thenReturn(connectionState);
mService.getInstanceMap().put(mRemoteDevice, sm);
@@ -183,13 +186,12 @@ public class MapClientServiceTest {
@Test
public void getConnectionState_whenNotConnected() {
- assertThat(mService.getConnectionState(mRemoteDevice))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mService.getConnectionState(mRemoteDevice)).isEqualTo(STATE_DISCONNECTED);
}
@Test
public void getConnectionState_whenConnected() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
when(sm.getState()).thenReturn(connectionState);
mService.getInstanceMap().put(mRemoteDevice, sm);
@@ -199,7 +201,7 @@ public class MapClientServiceTest {
@Test
public void getConnectedDevices() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
BluetoothDevice[] bondedDevices = new BluetoothDevice[] {mRemoteDevice};
when(mAdapterService.getBondedDevices()).thenReturn(bondedDevices);
@@ -278,7 +280,7 @@ public class MapClientServiceTest {
@Test
public void aclDisconnectedNoTransport_whenConnected_doesNotCallDisconnect() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
mService.getInstanceMap().put(mRemoteDevice, sm);
when(sm.getState()).thenReturn(connectionState);
@@ -291,7 +293,7 @@ public class MapClientServiceTest {
@Test
public void aclDisconnectedLeTransport_whenConnected_doesNotCallDisconnect() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
mService.getInstanceMap().put(mRemoteDevice, sm);
when(sm.getState()).thenReturn(connectionState);
@@ -304,7 +306,7 @@ public class MapClientServiceTest {
@Test
public void aclDisconnectedBrEdrTransport_whenConnected_callsDisconnect() {
- int connectionState = BluetoothProfile.STATE_CONNECTED;
+ int connectionState = STATE_CONNECTED;
MceStateMachine sm = mock(MceStateMachine.class);
mService.getInstanceMap().put(mRemoteDevice, sm);
when(sm.getState()).thenReturn(connectionState);
@@ -375,8 +377,7 @@ public class MapClientServiceTest {
assertThat(mService.getInstanceMap().keySet()).containsExactly(mRemoteDevice);
mTestLooper.dispatchAll();
- assertThat(mService.getConnectionState(mRemoteDevice))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
+ assertThat(mService.getConnectionState(mRemoteDevice)).isEqualTo(STATE_CONNECTING);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java
index 1f8cfb4a5d..fbd9bf4201 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
@@ -125,6 +125,9 @@ public class MapClientStateMachineTest {
private static final boolean MESSAGE_SEEN = true;
private static final boolean MESSAGE_NOT_SEEN = false;
+ private static final String SMS_HANDLE = "0001";
+ private static final String MMS_HANDLE = "0002";
+
private static final String TEST_MESSAGE_HANDLE = "0123456789000032";
private static final String TEST_MESSAGE = "Hello World!";
private static final String SENT_PATH = "telecom/msg/sent";
@@ -143,9 +146,6 @@ public class MapClientStateMachineTest {
private final BluetoothDevice mDevice = getTestDevice(74);
private final Context mTargetContext =
InstrumentationRegistry.getInstrumentation().getTargetContext();
- private final String mTestMessageSmsHandle = "0001";
- private final String mTestMessageMmsHandle = "0002";
- private final String mTestMessageUnknownHandle = "0003";
private Bmessage mTestIncomingSmsBmessage;
private Bmessage mTestIncomingMmsBmessage;
@@ -231,7 +231,7 @@ public class MapClientStateMachineTest {
createTestMessages();
when(mRequestGetMessage.getMessage()).thenReturn(mTestIncomingSmsBmessage);
- when(mRequestGetMessage.getHandle()).thenReturn(mTestMessageSmsHandle);
+ when(mRequestGetMessage.getHandle()).thenReturn(SMS_HANDLE);
when(mService.getSystemService(Context.TELEPHONY_SERVICE)).thenReturn(mTelephonyManager);
when(mTelephonyManager.isSmsCapable()).thenReturn(false);
@@ -369,16 +369,13 @@ public class MapClientStateMachineTest {
public void testSMSMessageSent() {
masConnected_whenConnecting_isConnected(); // transition to the connected state
- when(mRequestPushMessage.getMsgHandle()).thenReturn(mTestMessageSmsHandle);
+ when(mRequestPushMessage.getMsgHandle()).thenReturn(SMS_HANDLE);
when(mRequestPushMessage.getBMsg()).thenReturn(mTestIncomingSmsBmessage);
sendAndDispatchMessage(MceStateMachine.MSG_MAS_REQUEST_COMPLETED, mRequestPushMessage);
verify(mDatabase)
.storeMessage(
- eq(mTestIncomingSmsBmessage),
- eq(mTestMessageSmsHandle),
- any(),
- eq(MESSAGE_SEEN));
+ eq(mTestIncomingSmsBmessage), eq(SMS_HANDLE), any(), eq(MESSAGE_SEEN));
}
/**
@@ -518,12 +515,7 @@ public class MapClientStateMachineTest {
String dateTime = new ObexTime(Instant.now()).toString();
EventReport event =
createNewEventReport(
- "NewMessage",
- dateTime,
- mTestMessageSmsHandle,
- "telecom/msg/inbox",
- null,
- "SMS_GSM");
+ "NewMessage", dateTime, SMS_HANDLE, "telecom/msg/inbox", null, "SMS_GSM");
sendAndDispatchEvent(event);
@@ -533,10 +525,7 @@ public class MapClientStateMachineTest {
verify(mDatabase)
.storeMessage(
- eq(mTestIncomingSmsBmessage),
- eq(mTestMessageSmsHandle),
- any(),
- eq(MESSAGE_NOT_SEEN));
+ eq(mTestIncomingSmsBmessage), eq(SMS_HANDLE), any(), eq(MESSAGE_NOT_SEEN));
}
/** Test seen status set for new MMS */
@@ -547,15 +536,10 @@ public class MapClientStateMachineTest {
String dateTime = new ObexTime(Instant.now()).toString();
EventReport event =
createNewEventReport(
- "NewMessage",
- dateTime,
- mTestMessageMmsHandle,
- "telecom/msg/inbox",
- null,
- "MMS");
+ "NewMessage", dateTime, MMS_HANDLE, "telecom/msg/inbox", null, "MMS");
when(mRequestGetMessage.getMessage()).thenReturn(mTestIncomingMmsBmessage);
- when(mRequestGetMessage.getHandle()).thenReturn(mTestMessageMmsHandle);
+ when(mRequestGetMessage.getHandle()).thenReturn(MMS_HANDLE);
sendAndDispatchEvent(event);
@@ -565,10 +549,7 @@ public class MapClientStateMachineTest {
verify(mDatabase)
.storeMessage(
- eq(mTestIncomingMmsBmessage),
- eq(mTestMessageMmsHandle),
- any(),
- eq(MESSAGE_NOT_SEEN));
+ eq(mTestIncomingMmsBmessage), eq(MMS_HANDLE), any(), eq(MESSAGE_NOT_SEEN));
}
@Test
@@ -579,15 +560,10 @@ public class MapClientStateMachineTest {
String dateTime = new ObexTime(Instant.now()).toString();
EventReport event =
createNewEventReport(
- "NewMessage",
- dateTime,
- mTestMessageMmsHandle,
- "telecom/msg/inbox",
- null,
- "MMS");
+ "NewMessage", dateTime, MMS_HANDLE, "telecom/msg/inbox", null, "MMS");
// Prepare to send back message content, but use handle B
- when(mRequestGetMessage.getHandle()).thenReturn(mTestMessageUnknownHandle);
+ when(mRequestGetMessage.getHandle()).thenReturn("0003"); // unknown handle
when(mRequestGetMessage.getMessage()).thenReturn(mTestIncomingMmsBmessage);
sendAndDispatchEvent(event);
@@ -607,7 +583,7 @@ public class MapClientStateMachineTest {
masConnected_whenConnecting_isConnected(); // transition to the connected state
com.android.bluetooth.mapclient.Message testMessageListingSms =
- createNewMessage("SMS_GSM", mTestMessageSmsHandle);
+ createNewMessage("SMS_GSM", SMS_HANDLE);
ArrayList<com.android.bluetooth.mapclient.Message> messageListSms = new ArrayList<>();
messageListSms.add(testMessageListingSms);
when(mRequestGetMessagesListing.getList()).thenReturn(messageListSms);
@@ -633,12 +609,12 @@ public class MapClientStateMachineTest {
masConnected_whenConnecting_isConnected(); // transition to the connected state
com.android.bluetooth.mapclient.Message testMessageListingMms =
- createNewMessage("MMS", mTestMessageMmsHandle);
+ createNewMessage("MMS", MMS_HANDLE);
ArrayList<com.android.bluetooth.mapclient.Message> messageListMms = new ArrayList<>();
messageListMms.add(testMessageListingMms);
when(mRequestGetMessage.getMessage()).thenReturn(mTestIncomingMmsBmessage);
- when(mRequestGetMessage.getHandle()).thenReturn(mTestMessageMmsHandle);
+ when(mRequestGetMessage.getHandle()).thenReturn(MMS_HANDLE);
when(mRequestGetMessagesListing.getList()).thenReturn(messageListMms);
sendAndDispatchMessage(
@@ -665,20 +641,14 @@ public class MapClientStateMachineTest {
String dateTime = new ObexTime(Instant.now()).toString();
EventReport event =
createNewEventReport(
- "NewMessage",
- dateTime,
- mTestMessageSmsHandle,
- "telecom/msg/inbox",
- null,
- "SMS_GSM");
+ "NewMessage", dateTime, SMS_HANDLE, "telecom/msg/inbox", null, "SMS_GSM");
sendAndDispatchEvent(event);
verify(mMasClient).makeRequest(any(RequestGetMessage.class));
- MceStateMachine.MessageMetadata messageMetadata =
- mStateMachine.mMessages.get(mTestMessageSmsHandle);
- assertThat(messageMetadata.getHandle()).isEqualTo(mTestMessageSmsHandle);
+ MceStateMachine.MessageMetadata messageMetadata = mStateMachine.mMessages.get(SMS_HANDLE);
+ assertThat(messageMetadata.getHandle()).isEqualTo(SMS_HANDLE);
assertThat(new ObexTime(Instant.ofEpochMilli(messageMetadata.getTimestamp())).toString())
.isEqualTo(dateTime);
}
@@ -725,12 +695,7 @@ public class MapClientStateMachineTest {
String dateTime = new ObexTime(Instant.now()).toString();
EventReport event =
createNewEventReport(
- "NewMessage",
- dateTime,
- mTestMessageSmsHandle,
- "telecom/msg/inbox",
- null,
- "SMS_GSM");
+ "NewMessage", dateTime, SMS_HANDLE, "telecom/msg/inbox", null, "SMS_GSM");
sendAndDispatchEvent(event);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
index bb53310b80..6b3df639aa 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/mcp/MediaControlGattServiceTest.java
@@ -1191,7 +1191,7 @@ public class MediaControlGattServiceTest {
public void testCharacteristic_longReadAuthorized() {
BluetoothGattService service = initAllFeaturesGattService();
- /* Twenty three octects long title */
+ /* Twenty three octets long title */
String title = "01234567890123456789012";
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(MediaControlGattService.UUID_TRACK_TITLE);
@@ -1232,7 +1232,7 @@ public class MediaControlGattServiceTest {
public void testCharacteristic_longReadOutsideLenAuthorized() {
BluetoothGattService service = initAllFeaturesGattService();
- /* Twenty three octects long title */
+ /* Twenty three octets long title */
String title = "01234567890123456789012";
BluetoothGattCharacteristic characteristic =
service.getCharacteristic(MediaControlGattService.UUID_TRACK_TITLE);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java
index e858738007..6b757ad437 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppManagerTest.java
@@ -153,8 +153,8 @@ public class BluetoothOppManagerTest {
bluetoothOppManager.addToAcceptlist(address1);
bluetoothOppManager.addToAcceptlist(address2);
- assertThat(bluetoothOppManager.isAcceptlisted(address1)).isTrue();
- assertThat(bluetoothOppManager.isAcceptlisted(address2)).isTrue();
+ assertThat(bluetoothOppManager.isAcceptListed(address1)).isTrue();
+ assertThat(bluetoothOppManager.isAcceptListed(address2)).isTrue();
}
@Test
@@ -162,10 +162,10 @@ public class BluetoothOppManagerTest {
BluetoothOppManager bluetoothOppManager = BluetoothOppManager.getInstance(mContext);
String address = "01:23:45:67:89:AB";
- assertThat(bluetoothOppManager.isAcceptlisted(address)).isFalse();
+ assertThat(bluetoothOppManager.isAcceptListed(address)).isFalse();
bluetoothOppManager.addToAcceptlist(address);
- assertThat(bluetoothOppManager.isAcceptlisted(address)).isTrue();
+ assertThat(bluetoothOppManager.isAcceptListed(address)).isTrue();
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java
index 51aec2c424..2481534d3c 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/opp/BluetoothOppObexClientSessionTest.java
@@ -205,7 +205,7 @@ public class BluetoothOppObexClientSessionTest {
thread.mCs = new ClientSession(mTransport);
thread.addShare(shareInfo);
- // thread.mCs.put() will throw because the obexconnection is not connected
+ // thread.mCs.put() will throw because the obex connection is not connected
assertThat(thread.sendFile(sendFileInfo)).isEqualTo(BluetoothShare.STATUS_OBEX_DATA_ERROR);
}
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 77fb3991a9..5378dc6f41 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
@@ -337,7 +337,7 @@ public class BluetoothOppObexServerSessionTest {
request.setHeader(HeaderSet.TARGET, null);
BluetoothOppManager bluetoothOppManager = mock(BluetoothOppManager.class);
BluetoothOppManager.setInstance(bluetoothOppManager);
- doReturn(true).when(bluetoothOppManager).isAcceptlisted(any());
+ doReturn(true).when(bluetoothOppManager).isAcceptListed(any());
assertThat(mServerSession.onConnect(request, reply)).isEqualTo(ResponseCodes.OBEX_HTTP_OK);
BluetoothOppManager.setInstance(null);
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 80ef0232ec..c122b44579 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
@@ -73,20 +73,6 @@ public class BluetoothOppTransferTest {
@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";
- private final String mFilename = "random.jpg";
- private final String mMimetype = "image/jpeg";
- private final int mDirection = BluetoothShare.DIRECTION_INBOUND;
- private final String mDestination = "01:23:45:67:89:AB";
- private final int mVisibility = BluetoothShare.VISIBILITY_VISIBLE;
- private final int mConfirm = BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED;
- private final int mStatus = BluetoothShare.STATUS_PENDING;
- private final int mTotalBytes = 1023;
- private final int mCurrentBytes = 42;
- private final int mTimestamp = 123456789;
- private final boolean mMediaScanned = false;
-
BluetoothOppBatch mBluetoothOppBatch;
BluetoothOppTransfer mTransfer;
BluetoothOppTransfer.EventHandler mEventHandler;
@@ -116,19 +102,19 @@ public class BluetoothOppTransferTest {
mInitShareInfo =
new BluetoothOppShareInfo(
8765,
- mUri,
- mHintString,
- mFilename,
- mMimetype,
- mDirection,
- mDestination,
- mVisibility,
- mConfirm,
- mStatus,
- mTotalBytes,
- mCurrentBytes,
- mTimestamp,
- mMediaScanned);
+ Uri.parse("file://Idontknow/Justmadeitup"),
+ "this is a object that take 4 bytes",
+ "random.jpg",
+ "image/jpeg",
+ BluetoothShare.DIRECTION_INBOUND,
+ "01:23:45:67:89:AB",
+ BluetoothShare.VISIBILITY_VISIBLE,
+ BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
+ BluetoothShare.STATUS_PENDING,
+ 1023,
+ 42,
+ 123456789,
+ false);
mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo);
mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
@@ -144,19 +130,19 @@ public class BluetoothOppTransferTest {
BluetoothOppShareInfo newShareInfo =
new BluetoothOppShareInfo(
1,
- mUri,
- mHintString,
- mFilename,
- mMimetype,
+ Uri.parse("file://Idontknow/Justmadeitup"),
+ "this is a object that take 4 bytes",
+ "random.jpg",
+ "image/jpeg",
BluetoothShare.DIRECTION_INBOUND,
- mDestination,
- mVisibility,
+ "01:23:45:67:89:AB",
+ BluetoothShare.VISIBILITY_VISIBLE,
BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
- mStatus,
- mTotalBytes,
- mCurrentBytes,
- mTimestamp,
- mMediaScanned);
+ BluetoothShare.STATUS_PENDING,
+ 1023,
+ 42,
+ 123456789,
+ false);
doAnswer(
invocation -> {
@@ -238,19 +224,19 @@ public class BluetoothOppTransferTest {
mInitShareInfo =
new BluetoothOppShareInfo(
123,
- mUri,
- mHintString,
- mFilename,
- mMimetype,
+ Uri.parse("file://Idontknow/Justmadeitup"),
+ "this is a object that take 4 bytes",
+ "random.jpg",
+ "image/jpeg",
BluetoothShare.DIRECTION_OUTBOUND,
- mDestination,
- mVisibility,
- mConfirm,
- mStatus,
- mTotalBytes,
- mCurrentBytes,
- mTimestamp,
- mMediaScanned);
+ "01:23:45:67:89:AB",
+ BluetoothShare.VISIBILITY_VISIBLE,
+ BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
+ BluetoothShare.STATUS_PENDING,
+ 1023,
+ 42,
+ 123456789,
+ false);
mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo);
mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
@@ -286,19 +272,19 @@ public class BluetoothOppTransferTest {
mInitShareInfo =
new BluetoothOppShareInfo(
123,
- mUri,
- mHintString,
- mFilename,
- mMimetype,
+ Uri.parse("file://Idontknow/Justmadeitup"),
+ "this is a object that take 4 bytes",
+ "random.jpg",
+ "image/jpeg",
BluetoothShare.DIRECTION_OUTBOUND,
- mDestination,
- mVisibility,
- mConfirm,
- mStatus,
- mTotalBytes,
- mCurrentBytes,
- mTimestamp,
- mMediaScanned);
+ "01:23:45:67:89:AB",
+ BluetoothShare.VISIBILITY_VISIBLE,
+ BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
+ BluetoothShare.STATUS_PENDING,
+ 1023,
+ 42,
+ 123456789,
+ false);
mBluetoothOppBatch = new BluetoothOppBatch(mContext, mInitShareInfo);
mTransfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch, mSession);
mEventHandler = mTransfer.new EventHandler(Looper.getMainLooper());
@@ -318,19 +304,19 @@ public class BluetoothOppTransferTest {
BluetoothOppShareInfo newInfo =
new BluetoothOppShareInfo(
321,
- mUri,
- mHintString,
- mFilename,
- mMimetype,
- mDirection,
- mDestination,
- mVisibility,
- mConfirm,
- mStatus,
- mTotalBytes,
- mCurrentBytes,
- mTimestamp,
- mMediaScanned);
+ Uri.parse("file://Idontknow/Justmadeitup"),
+ "this is a object that take 4 bytes",
+ "random.jpg",
+ "image/jpeg",
+ BluetoothShare.DIRECTION_INBOUND,
+ "01:23:45:67:89:AB",
+ BluetoothShare.VISIBILITY_VISIBLE,
+ BluetoothShare.USER_CONFIRMATION_AUTO_CONFIRMED,
+ BluetoothShare.STATUS_PENDING,
+ 1023,
+ 42,
+ 123456789,
+ false);
// Adding new info will assign value to mCurrentShare
mBluetoothOppBatch.addShare(newInfo);
mEventHandler.handleMessage(message);
@@ -387,7 +373,7 @@ public class BluetoothOppTransferTest {
.getTargetContext()
.getSystemService(BluetoothManager.class)
.getAdapter()
- .getRemoteDevice(mDestination);
+ .getRemoteDevice("01:23:45:67:89:AB");
BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
transfer.mCurrentShare = mInitShareInfo;
transfer.mCurrentShare.mConfirm = BluetoothShare.USER_CONFIRMATION_PENDING;
@@ -410,7 +396,7 @@ public class BluetoothOppTransferTest {
.getTargetContext()
.getSystemService(BluetoothManager.class)
.getAdapter()
- .getRemoteDevice(mDestination);
+ .getRemoteDevice("01:23:45:67:89:AB");
BluetoothOppTransfer transfer = new BluetoothOppTransfer(mContext, mBluetoothOppBatch);
transfer.mCurrentShare = mInitShareInfo;
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
index 2975803aaf..15763b79c3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.pan;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -72,7 +74,7 @@ public class PanServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -87,7 +89,7 @@ public class PanServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
index 55d11455b7..c9f20f430a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pan/PanServiceTest.java
@@ -16,6 +16,12 @@
package com.android.bluetooth.pan;
import static android.bluetooth.BluetoothPan.PAN_ROLE_NONE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
import static android.net.TetheringManager.TETHERING_BLUETOOTH;
import static android.net.TetheringManager.TETHER_ERROR_SERVICE_UNAVAIL;
@@ -106,8 +112,7 @@ public class PanServiceTest {
when(mMockUserManager.isGuestUser()).thenReturn(false);
mService.mPanDevices.put(
mRemoteDevice,
- new BluetoothPanDevice(
- BluetoothProfile.STATE_CONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
+ new BluetoothPanDevice(STATE_CONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
assertThat(mService.connect(mRemoteDevice)).isFalse();
}
@@ -117,8 +122,7 @@ public class PanServiceTest {
when(mMockUserManager.isGuestUser()).thenReturn(false);
mService.mPanDevices.put(
mRemoteDevice,
- new BluetoothPanDevice(
- BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
+ new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
assertThat(mService.connect(mRemoteDevice)).isTrue();
verify(mNativeInterface, timeout(TIMEOUT_MS)).connect(any());
@@ -133,23 +137,22 @@ public class PanServiceTest {
@Test
public void convertHalState() {
assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_CONNECTED))
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ .isEqualTo(STATE_CONNECTED);
assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_CONNECTING))
- .isEqualTo(BluetoothProfile.STATE_CONNECTING);
+ .isEqualTo(STATE_CONNECTING);
assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_DISCONNECTED))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
assertThat(PanNativeInterface.convertHalState(PanNativeInterface.CONN_STATE_DISCONNECTING))
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTING);
+ .isEqualTo(STATE_DISCONNECTING);
assertThat(PanNativeInterface.convertHalState(-24664)) // illegal value
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .isEqualTo(STATE_DISCONNECTED);
}
@Test
public void dump() {
mService.mPanDevices.put(
mRemoteDevice,
- new BluetoothPanDevice(
- BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
+ new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
mService.dump(new StringBuilder());
}
@@ -172,7 +175,7 @@ public class PanServiceTest {
@Test
public void setConnectionPolicy_whenDatabaseManagerRefuses_returnsFalse() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
when(mDatabaseManager.setProfileConnectionPolicy(
mRemoteDevice, BluetoothProfile.PAN, connectionPolicy))
.thenReturn(false);
@@ -183,24 +186,15 @@ public class PanServiceTest {
@Test
public void setConnectionPolicy_returnsTrue() {
when(mDatabaseManager.setProfileConnectionPolicy(
- mRemoteDevice,
- BluetoothProfile.PAN,
- BluetoothProfile.CONNECTION_POLICY_ALLOWED))
+ mRemoteDevice, BluetoothProfile.PAN, CONNECTION_POLICY_ALLOWED))
.thenReturn(true);
- assertThat(
- mService.setConnectionPolicy(
- mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED))
- .isTrue();
+ assertThat(mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_ALLOWED)).isTrue();
verify(mNativeInterface, timeout(TIMEOUT_MS)).connect(any());
when(mDatabaseManager.setProfileConnectionPolicy(
- mRemoteDevice,
- BluetoothProfile.PAN,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ mRemoteDevice, BluetoothProfile.PAN, CONNECTION_POLICY_FORBIDDEN))
.thenReturn(true);
- assertThat(
- mService.setConnectionPolicy(
- mRemoteDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ assertThat(mService.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
verify(mNativeInterface, timeout(TIMEOUT_MS)).disconnect(any());
}
@@ -228,8 +222,7 @@ public class PanServiceTest {
mService.mIsTethering = true;
mService.mPanDevices.put(
mRemoteDevice,
- new BluetoothPanDevice(
- BluetoothProfile.STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
+ new BluetoothPanDevice(STATE_DISCONNECTED, PAN_ROLE_NONE, PAN_ROLE_NONE));
TetheringInterface iface = new TetheringInterface(TETHERING_BLUETOOTH, "iface");
mService.mTetheringCallback.onError(iface, TETHER_ERROR_SERVICE_UNAVAIL);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapObexServerTest.java
index 0730f6fd40..ed78e3239c 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
@@ -689,13 +689,13 @@ public class BluetoothPbapObexServerTest {
}
@Test
- public void setCallversionCounters() {
+ public void setCallVersionCounters() {
ApplicationParameter param = new ApplicationParameter();
AppParamValue value = new AppParamValue();
value.callHistoryVersionCounter =
new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
- BluetoothPbapObexServer.setCallversionCounters(param, value);
+ BluetoothPbapObexServer.setCallVersionCounters(param, value);
byte[] expectedResult =
new byte[] {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
index ec398bd913..becc52e836 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceBinderTest.java
@@ -16,13 +16,15 @@
package com.android.bluetooth.pbap;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;
@@ -65,7 +67,7 @@ public class BluetoothPbapServiceBinderTest {
@Test
public void getDevicesMatchingConnectionStates_callsServiceMethod() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mBinder.getDevicesMatchingConnectionStates(states, null);
verify(mService).getDevicesMatchingConnectionStates(states);
@@ -80,7 +82,7 @@ public class BluetoothPbapServiceBinderTest {
@Test
public void setConnectionPolicy_callsServiceMethod() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mBinder.setConnectionPolicy(mDevice, connectionPolicy, null);
verify(mService).setConnectionPolicy(mDevice, connectionPolicy);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
index 0b7a0f6da6..d3a4de5fed 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapServiceTest.java
@@ -15,6 +15,8 @@
*/
package com.android.bluetooth.pbap;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -168,9 +170,9 @@ public class BluetoothPbapServiceTest {
public void getDevicesMatchingConnectionStates() {
PbapStateMachine sm = mock(PbapStateMachine.class);
mService.mPbapStateMachineMap.put(mRemoteDevice, sm);
- when(sm.getConnectionState()).thenReturn(BluetoothProfile.STATE_CONNECTED);
+ when(sm.getConnectionState()).thenReturn(STATE_CONNECTED);
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
assertThat(mService.getDevicesMatchingConnectionStates(states)).contains(mRemoteDevice);
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/BluetoothPbapSimVcardManagerTest.java
index 86fd898d2f..a2252796e3 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
@@ -423,7 +423,7 @@ public class BluetoothPbapSimVcardManagerTest {
}
@Test
- public void testComposeAndSendSIMPhonebookVcards_whenEndPointIsLessThanStartpoint() {
+ public void testComposeAndSendSIMPhonebookVcards_whenEndPointIsLessThanStartPoint() {
Operation operation = mock(Operation.class);
final int startPoint = 1;
final int endPoint = 0; // Should be equal or greater than startPoint
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbap/PbapStateMachineTest.java
index 8b4cd83b86..607bf253d4 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,114 +16,112 @@
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;
import static com.google.common.truth.Truth.assertThat;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.doReturn;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
-import android.os.HandlerThread;
import androidx.test.filters.MediumTest;
import androidx.test.runner.AndroidJUnit4;
-import org.junit.After;
+import com.android.bluetooth.TestLooper;
+
import org.junit.Before;
-import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import java.io.IOException;
+import java.io.InputStream;
+
@MediumTest
@RunWith(AndroidJUnit4.class)
public class PbapStateMachineTest {
@Rule public final MockitoRule mMockitoRule = new MockitoRule();
@Mock private BluetoothPbapService mBluetoothPbapService;
+ @Mock private BluetoothSocket mSocket;
+ @Mock private InputStream mInputStream;
private static final int TEST_NOTIFICATION_ID = 1000000;
private final BluetoothDevice mDevice = getTestDevice(36);
- private HandlerThread mHandlerThread;
- private PbapStateMachine mPbapStateMachine;
private Handler mHandler;
- private BluetoothSocket mSocket;
+ private TestLooper mLooper;
+ private PbapStateMachine mStateMachine;
@Before
- public void setUp() {
- mHandlerThread = new HandlerThread("PbapTestHandlerThread");
- mHandlerThread.start();
- mHandler = new Handler(mHandlerThread.getLooper());
+ public void setUp() throws IOException {
+ doReturn(mInputStream).when(mSocket).getInputStream();
+ doReturn(mInputStream).when(mSocket).getInputStream();
+
+ mLooper = new TestLooper();
+ mHandler = new Handler(mLooper.getLooper());
- mPbapStateMachine =
+ mStateMachine =
PbapStateMachine.make(
mBluetoothPbapService,
- mHandlerThread.getLooper(),
+ mLooper.getLooper(),
mDevice,
mSocket,
mHandler,
TEST_NOTIFICATION_ID);
}
- @After
- 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.getCurrentState())
+ public void initialState_isConnecting() {
+ assertThat(mStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTING);
+ assertThat(mStateMachine.getCurrentState())
.isInstanceOf(PbapStateMachine.WaitingForAuth.class);
}
/** Test state transition from WaitingForAuth to Finished when the user rejected */
- @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
@Test
public void testStateTransition_WaitingForAuthToFinished() {
- mPbapStateMachine.sendMessage(PbapStateMachine.REJECTED);
- assertThat(mPbapStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
- assertThat(mPbapStateMachine.getCurrentState())
- .isInstanceOf(PbapStateMachine.Finished.class);
+ sendAndDispatchMessage(PbapStateMachine.REJECTED);
+
+ assertThat(mStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
+ assertThat(mStateMachine.getCurrentState()).isInstanceOf(PbapStateMachine.Finished.class);
}
/** Test state transition from WaitingForAuth to Finished when the user rejected */
- @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
@Test
public void testStateTransition_WaitingForAuthToConnected() {
- mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED);
- assertThat(mPbapStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_CONNECTED);
- assertThat(mPbapStateMachine.getCurrentState())
- .isInstanceOf(PbapStateMachine.Connected.class);
+ sendAndDispatchMessage(PbapStateMachine.AUTHORIZED);
+
+ assertThat(mStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED);
+ assertThat(mStateMachine.getCurrentState()).isInstanceOf(PbapStateMachine.Connected.class);
}
/** Test state transition from Connected to Finished when the OBEX server is done */
- @Ignore("Class BluetoothSocket is final and cannot be mocked. b/71512958: re-enable it.")
@Test
public void testStateTransition_ConnectedToFinished() {
- mPbapStateMachine.sendMessage(PbapStateMachine.AUTHORIZED);
- assertThat(mPbapStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.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.getCurrentState())
- .isInstanceOf(PbapStateMachine.Finished.class);
+ sendAndDispatchMessage(PbapStateMachine.AUTHORIZED);
+
+ assertThat(mStateMachine.getConnectionState()).isEqualTo(STATE_CONNECTED);
+ assertThat(mStateMachine.getCurrentState()).isInstanceOf(PbapStateMachine.Connected.class);
+
+ sendAndDispatchMessage(PbapStateMachine.DISCONNECT);
+
+ assertThat(mStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
+ assertThat(mStateMachine.getCurrentState()).isInstanceOf(PbapStateMachine.Finished.class);
+ }
+
+ private void sendAndDispatchMessage(int what) {
+ mStateMachine.sendMessage(what);
+ mLooper.dispatchAll();
}
}
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 4fc428ebbe..a2b773fc03 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
@@ -146,7 +146,7 @@ public class PbapClientAccountManagerTest {
IllegalArgumentException.class, () -> mAccountManager.getAccountForDevice(null));
}
- // Start/Initialization Proceedures
+ // Start/Initialization Procedures
@Test
public void testStartAccountManager_userUnlockedAccountVisibleNoAccounts_accountsInitialized() {
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java
index 21f4d58849..aff8f250a7 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientBinderTest.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.pbapclient;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -28,7 +33,6 @@ import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothProfile;
import android.content.AttributionSource;
import androidx.test.filters.MediumTest;
@@ -93,7 +97,7 @@ public class PbapClientBinderTest {
@Test
public void testGetDevicesMatchingConnectionStates() {
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
mPbapClientBinder.getDevicesMatchingConnectionStates(states, mAttributionSource);
verify(mMockService).getDevicesMatchingConnectionStates(eq(states));
}
@@ -106,7 +110,7 @@ public class PbapClientBinderTest {
@Test
public void testSetConnectionPolicy() {
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
mPbapClientBinder.setConnectionPolicy(mTestDevice, connectionPolicy, mAttributionSource);
verify(mMockService).setConnectionPolicy(eq(mTestDevice), eq(connectionPolicy));
}
@@ -148,7 +152,7 @@ public class PbapClientBinderTest {
@Test
public void testGetDevicesMatchingConnectionStates_afterCleanup_returnsEmptyList() {
mPbapClientBinder.cleanup();
- int[] states = new int[] {BluetoothProfile.STATE_CONNECTED};
+ int[] states = new int[] {STATE_CONNECTED};
List<BluetoothDevice> devices =
mPbapClientBinder.getDevicesMatchingConnectionStates(states, mAttributionSource);
verify(mMockService, never()).getDevicesMatchingConnectionStates(any(int[].class));
@@ -160,13 +164,13 @@ public class PbapClientBinderTest {
mPbapClientBinder.cleanup();
int state = mPbapClientBinder.getConnectionState(mTestDevice, mAttributionSource);
verify(mMockService, never()).getConnectionState(any(BluetoothDevice.class));
- assertThat(state).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(state).isEqualTo(STATE_DISCONNECTED);
}
@Test
public void testSetConnectionPolicy_afterCleanup_returnsFalse() {
mPbapClientBinder.cleanup();
- int connectionPolicy = BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ int connectionPolicy = CONNECTION_POLICY_ALLOWED;
boolean result =
mPbapClientBinder.setConnectionPolicy(
mTestDevice, connectionPolicy, mAttributionSource);
@@ -179,6 +183,6 @@ public class PbapClientBinderTest {
mPbapClientBinder.cleanup();
int result = mPbapClientBinder.getConnectionPolicy(mTestDevice, mAttributionSource);
verify(mMockService, never()).getConnectionPolicy(any(BluetoothDevice.class));
- assertThat(result).isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ assertThat(result).isEqualTo(CONNECTION_POLICY_UNKNOWN);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java
index 0b0b4b1f91..fef6b763de 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientObexClientTest.java
@@ -16,6 +16,11 @@
package com.android.bluetooth.pbapclient;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -31,7 +36,6 @@ import static org.mockito.Mockito.verify;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
-import android.bluetooth.BluetoothProfile;
import android.util.Log;
import androidx.test.platform.app.InstrumentationRegistry;
@@ -136,7 +140,7 @@ public class PbapClientObexClientTest {
assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM);
assertThat(mObexClient.getRfcommChannelId())
.isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID);
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
assertThat(mObexClient.isConnected()).isFalse();
}
@@ -152,18 +156,13 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback)
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTED),
- eq(BluetoothProfile.STATE_CONNECTING));
- verify(mMockCallback)
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTING),
- eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING));
+ verify(mMockCallback).onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED));
assertThat(mObexClient.getTransportType()).isEqualTo(PbapClientObexClient.TRANSPORT_L2CAP);
assertThat(mObexClient.getL2capPsm()).isEqualTo(TEST_L2CAP_PSM);
assertThat(mObexClient.getRfcommChannelId())
.isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID);
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_CONNECTED);
assertThat(mObexClient.isConnected()).isTrue();
}
@@ -175,17 +174,12 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback)
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTED),
- eq(BluetoothProfile.STATE_CONNECTING));
- verify(mMockCallback)
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTING),
- eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChanged(eq(STATE_DISCONNECTED), eq(STATE_CONNECTING));
+ verify(mMockCallback).onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED));
assertThat(mObexClient.getTransportType()).isEqualTo(PbapClientObexClient.TRANSPORT_RFCOMM);
assertThat(mObexClient.getRfcommChannelId()).isEqualTo(TEST_RFCOMM_CHANNEL_ID);
assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM);
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_CONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_CONNECTED);
assertThat(mObexClient.isConnected()).isTrue();
}
@@ -297,7 +291,7 @@ public class PbapClientObexClientTest {
assertThat(mObexClient.getL2capPsm()).isEqualTo(PbapClientObexClient.L2CAP_INVALID_PSM);
assertThat(mObexClient.getRfcommChannelId())
.isEqualTo(PbapClientObexClient.RFCOMM_INVALID_CHANNEL_ID);
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
assertThat(mObexClient.isConnected()).isFalse();
}
@@ -309,7 +303,7 @@ public class PbapClientObexClientTest {
verify(mMockCallback, never()).onConnectionStateChanged(anyInt(), anyInt());
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
assertThat(mObexClient.isConnected()).isFalse();
}
@@ -321,14 +315,10 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTED),
- eq(BluetoothProfile.STATE_DISCONNECTING));
+ .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING));
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
@Test
@@ -341,14 +331,10 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTED),
- eq(BluetoothProfile.STATE_DISCONNECTING));
+ .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING));
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
@Test
@@ -387,14 +373,10 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTED),
- eq(BluetoothProfile.STATE_DISCONNECTING));
+ .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING));
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
@Test
@@ -425,14 +407,10 @@ public class PbapClientObexClientTest {
mTestLooper.dispatchAll();
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTED),
- eq(BluetoothProfile.STATE_DISCONNECTING));
+ .onConnectionStateChanged(eq(STATE_CONNECTED), eq(STATE_DISCONNECTING));
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
// *********************************************************************************************
@@ -449,7 +427,7 @@ public class PbapClientObexClientTest {
mObexClient.close();
mTestLooper.dispatchAll();
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
assertThat(mObexClient.isConnected()).isFalse();
}
@@ -463,14 +441,12 @@ public class PbapClientObexClientTest {
// Timeout() is desirable, but we can't use test looper without receiving the
// InterruptedExceptions
verify(mMockCallback, timeout(2000))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_CONNECTING),
- eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChanged(eq(STATE_CONNECTING), eq(STATE_CONNECTED));
mObexClient.close();
mTestLooper.dispatchAll();
- assertThat(mObexClient.getConnectionState()).isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mObexClient.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
// *********************************************************************************************
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
index 5b0756dde4..35196f14f2 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientServiceTest.java
@@ -236,7 +236,7 @@ public class PbapClientServiceTest {
@Test
@EnableFlags(Flags.FLAG_PBAP_CLIENT_STORAGE_REFACTOR)
- public void onConnectionStateChanged_ConnectedToDisonnecting_eventIgnored() {
+ public void onConnectionStateChanged_ConnectedToDisconnecting_eventIgnored() {
doReturn(STATE_DISCONNECTING).when(mMockDeviceStateMachine).getConnectionState();
mDeviceCallback.onConnectionStateChanged(STATE_CONNECTED, STATE_DISCONNECTING);
assertThat(mDeviceMap.containsKey(mDevice)).isTrue();
@@ -254,7 +254,7 @@ public class PbapClientServiceTest {
@Test
@DisableFlags(Flags.FLAG_PBAP_CLIENT_STORAGE_REFACTOR)
- public void onAccountsChanged_fromNulltoEmpty_tryDownloadIfConnectedCalled() {
+ public void onAccountsChanged_fromNullToEmpty_tryDownloadIfConnectedCalled() {
PbapClientStateMachineOld sm = mock(PbapClientStateMachineOld.class);
mService.mPbapClientStateMachineOldMap.put(mDevice, sm);
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 968afd4ef6..3518b2d418 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineOldTest.java
@@ -15,6 +15,10 @@
*/
package com.android.bluetooth.pbapclient;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTING;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
import static com.android.bluetooth.TestUtils.mockGetSystemService;
@@ -29,7 +33,6 @@ 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;
@@ -97,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);
}
/**
@@ -107,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);
@@ -124,7 +124,6 @@ public class PbapClientStateMachineOldTest {
mIntentArgument.capture(),
any(String[].class),
any(BroadcastOptions.class));
- assertThat(mPbapClientStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
}
}
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapClientStateMachineTest.java
index b48329a9c3..93c4004647 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));
}
// *********************************************************************************************
@@ -227,7 +227,7 @@ public class PbapClientStateMachineTest {
}
@Test
- public void testConnecting_receivedSdpResultWithFailedStatus_transitiontoDisconnecting() {
+ public void testConnecting_receivedSdpResultWithFailedStatus_transitionToDisconnecting() {
testDisconnected_receivedConnect_connectionStateChangesToConnecting();
mPbapClientStateMachine.onSdpResultReceived(
SDP_FAILED,
@@ -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,
@@ -273,7 +267,7 @@ public class PbapClientStateMachineTest {
}
@Test
- public void testConnecting_receivedSdpResultWithUnknownStatus_transitiontoDisconnecting() {
+ public void testConnecting_receivedSdpResultWithUnknownStatus_transitionToDisconnecting() {
testDisconnected_receivedConnect_connectionStateChangesToConnecting();
mPbapClientStateMachine.onSdpResultReceived(
SDP_UNKNOWN,
@@ -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,47 +401,34 @@ 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
- public void testConnected_receivedDisconnect_transitiontoDisconnecting() {
+ public void testConnected_receivedDisconnect_transitionToDisconnecting() {
testConnecting_receivedObexConnection_transitionToConnected();
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
@@ -750,25 +685,20 @@ public class PbapClientStateMachineTest {
@Test
public void testEnterDisconnecting_clientConnected_disconnectIssued() {
- testConnected_receivedDisconnect_transitiontoDisconnecting();
+ testConnected_receivedDisconnect_transitionToDisconnecting();
verify(mMockObexClient, times(1)).disconnect();
}
@Test
public void testDisconnecting_clientDisconnects_transitionToDisconnected() {
testEnterDisconnecting_clientConnected_disconnectIssued();
- setAndNotifyObexClientStatus(
- BluetoothProfile.STATE_CONNECTED, BluetoothProfile.STATE_DISCONNECTING);
- setAndNotifyObexClientStatus(
- BluetoothProfile.STATE_CONNECTING, BluetoothProfile.STATE_DISCONNECTED);
+ setAndNotifyObexClientStatus(STATE_CONNECTED, STATE_DISCONNECTING);
+ setAndNotifyObexClientStatus(STATE_CONNECTING, STATE_DISCONNECTED);
mTestLooper.dispatchAll();
- assertThat(mPbapClientStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
}
@Test
@@ -777,12 +707,9 @@ public class PbapClientStateMachineTest {
mTestLooper.moveTimeForward(PbapClientStateMachine.DISCONNECT_TIMEOUT_MS);
mTestLooper.dispatchAll();
- assertThat(mPbapClientStateMachine.getConnectionState())
- .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
+ assertThat(mPbapClientStateMachine.getConnectionState()).isEqualTo(STATE_DISCONNECTED);
verify(mMockCallback, times(1))
- .onConnectionStateChanged(
- eq(BluetoothProfile.STATE_DISCONNECTING),
- eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChanged(eq(STATE_DISCONNECTING), eq(STATE_DISCONNECTED));
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java b/android/app/tests/unit/src/com/android/bluetooth/pbapclient/PbapPhonebookTest.java
index 6537f475b5..994dccf85a 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
@@ -42,7 +42,7 @@ public class PbapPhonebookTest {
// *********************************************************************************************
@Test
- public void testCreatePhonebook_forFavorites_emptyFavoritesPhonebookeCreated()
+ public void testCreatePhonebook_forFavorites_emptyFavoritesPhonebookCreated()
throws IOException {
PbapPhonebook phonebook = new PbapPhonebook(PbapPhonebook.FAVORITES_PATH);
assertThat(phonebook.getPhonebook()).isEqualTo(PbapPhonebook.FAVORITES_PATH);
@@ -52,7 +52,7 @@ public class PbapPhonebookTest {
}
@Test
- public void testCreatePhonebook_forLocalPhonebook_emptyLocalPhonebookeCreated()
+ public void testCreatePhonebook_forLocalPhonebook_emptyLocalPhonebookCreated()
throws IOException {
PbapPhonebook phonebook = new PbapPhonebook(PbapPhonebook.LOCAL_PHONEBOOK_PATH);
assertThat(phonebook.getPhonebook()).isEqualTo(PbapPhonebook.LOCAL_PHONEBOOK_PATH);
@@ -112,7 +112,7 @@ public class PbapPhonebookTest {
}
@Test
- public void testCreatePhonebook_forSimMissedCallHistory_emptyMiSimssedCallHistoryCreated()
+ public void testCreatePhonebook_forSimMissedCallHistory_emptySimMissedCallHistoryCreated()
throws IOException {
PbapPhonebook phonebook = new PbapPhonebook(PbapPhonebook.SIM_MCH_PATH);
assertThat(phonebook.getPhonebook()).isEqualTo(PbapPhonebook.SIM_MCH_PATH);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
index e7ef894ffa..eab7b0f84a 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapMessageTest.java
@@ -17,7 +17,7 @@
package com.android.bluetooth.sap;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_OK;
-import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFULL;
+import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFUL;
import static com.android.bluetooth.sap.SapMessage.ID_CONNECT_REQ;
import static com.android.bluetooth.sap.SapMessage.ID_DISCONNECT_REQ;
import static com.android.bluetooth.sap.SapMessage.ID_POWER_SIM_OFF_REQ;
@@ -72,7 +72,7 @@ public class SapMessageTest {
int maxMsgSize = 512;
int connectionStatus = CON_STATUS_OK;
int resultCode = RESULT_OK;
- int disconnectionType = DISC_GRACEFULL;
+ int disconnectionType = DISC_GRACEFUL;
int cardReaderStatus = STATUS_CARD_INSERTED;
int statusChange = 1;
int transportProtocol = TRANS_PROTO_T0;
@@ -143,7 +143,7 @@ public class SapMessageTest {
int maxMsgSize = 512;
int connectionStatus = CON_STATUS_OK;
int resultCode = RESULT_OK;
- int disconnectionType = DISC_GRACEFULL;
+ int disconnectionType = DISC_GRACEFUL;
int cardReaderStatus = STATUS_CARD_INSERTED;
int statusChange = 1;
int transportProtocol = TRANS_PROTO_T0;
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 fc4e44c9fe..04d4238131 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
@@ -18,7 +18,7 @@ package com.android.bluetooth.sap;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_OK;
-import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFULL;
+import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFUL;
import static com.android.bluetooth.sap.SapMessage.ID_CONNECT_RESP;
import static com.android.bluetooth.sap.SapMessage.ID_DISCONNECT_RESP;
import static com.android.bluetooth.sap.SapMessage.ID_POWER_SIM_OFF_REQ;
@@ -192,7 +192,7 @@ public class SapRilReceiverHidlTest {
@Test
public void callback_disconnectIndication() throws Exception {
int token = 1;
- int disconnectType = DISC_GRACEFULL;
+ int disconnectType = DISC_GRACEFUL;
mReceiver.mSapCallback.disconnectIndication(token, disconnectType);
verify(mCallback, timeout(TIMEOUT_MS))
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
index 9df3905124..d2e6ea5d03 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapRilReceiverTest.java
@@ -18,7 +18,7 @@ package com.android.bluetooth.sap;
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_OK;
-import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFULL;
+import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFUL;
import static com.android.bluetooth.sap.SapMessage.ID_CONNECT_RESP;
import static com.android.bluetooth.sap.SapMessage.ID_DISCONNECT_RESP;
import static com.android.bluetooth.sap.SapMessage.ID_POWER_SIM_OFF_REQ;
@@ -198,7 +198,7 @@ public class SapRilReceiverTest {
@Test
public void callback_disconnectIndication() throws Exception {
int token = 1;
- int disconnectType = DISC_GRACEFULL;
+ int disconnectType = DISC_GRACEFUL;
mReceiver.mSapCallback.disconnectIndication(token, disconnectType);
verify(mCallback, timeout(TIMEOUT_MS))
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
index 48f6a4de6d..3bed89bda3 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServerTest.java
@@ -20,7 +20,7 @@ import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_ERROR_CONNECTION;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_OK;
import static com.android.bluetooth.sap.SapMessage.CON_STATUS_OK_ONGOING_CALL;
-import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFULL;
+import static com.android.bluetooth.sap.SapMessage.DISC_GRACEFUL;
import static com.android.bluetooth.sap.SapMessage.ID_CONNECT_REQ;
import static com.android.bluetooth.sap.SapMessage.ID_CONNECT_RESP;
import static com.android.bluetooth.sap.SapMessage.ID_DISCONNECT_IND;
@@ -127,7 +127,7 @@ public class SapServerTest {
.thenReturn(notificationManager);
ArgumentCaptor<Notification> captor = ArgumentCaptor.forClass(Notification.class);
- int type = DISC_GRACEFULL;
+ int type = DISC_GRACEFUL;
int flags = PendingIntent.FLAG_CANCEL_CURRENT;
mSapServer.setNotification(type, flags);
@@ -297,7 +297,7 @@ public class SapServerTest {
@Test
public void handleRilInd_whenStateIsConnected_callsSendClientMessage() {
- int disconnectionType = DISC_GRACEFULL;
+ int disconnectionType = DISC_GRACEFUL;
SapMessage msg = mock(SapMessage.class);
when(msg.getMsgType()).thenReturn(ID_RIL_UNSOL_DISCONNECT_IND);
when(msg.getDisconnectionType()).thenReturn(disconnectionType);
@@ -317,7 +317,7 @@ public class SapServerTest {
@Test
public void handleRilInd_whenStateIsDisconnected_callsSendDisconnectInd() {
- int disconnectionType = DISC_GRACEFULL;
+ int disconnectionType = DISC_GRACEFUL;
NotificationManager notificationManager = mock(NotificationManager.class);
when(mTargetContext.getSystemService(NotificationManager.class))
.thenReturn(notificationManager);
@@ -430,7 +430,7 @@ public class SapServerTest {
}
@Test
- public void handleRfcommReply_statusIndMsg_whenInDisonnectingState_doesNotSendMessage()
+ public void handleRfcommReply_statusIndMsg_whenInDisconnectingState_doesNotSendMessage()
throws Exception {
SapMessage msg = mock(SapMessage.class);
when(msg.getMsgType()).thenReturn(ID_STATUS_IND);
@@ -599,7 +599,7 @@ public class SapServerTest {
public void handleMessage_forRilIndMsg_callsHandleRilInd() throws Exception {
SapMessage sapMsg = mock(SapMessage.class);
when(sapMsg.getMsgType()).thenReturn(ID_RIL_UNSOL_DISCONNECT_IND);
- when(sapMsg.getDisconnectionType()).thenReturn(DISC_GRACEFULL);
+ when(sapMsg.getDisconnectionType()).thenReturn(DISC_GRACEFUL);
mSapServer.changeState(SapServer.SAP_STATE.CONNECTED);
mSapServer.mSapHandler = mHandler;
@@ -682,7 +682,7 @@ public class SapServerTest {
mSapServer.mIntentReceiver = mSapServer.new SapServerBroadcastReceiver();
mSapServer.mSapHandler = mHandler;
- int disconnectType = SapMessage.DISC_GRACEFULL;
+ int disconnectType = SapMessage.DISC_GRACEFUL;
Intent intent = new Intent(SapServer.SAP_DISCONNECT_ACTION);
intent.putExtra(SapServer.SAP_DISCONNECT_TYPE_EXTRA, disconnectType);
mSapServer.changeState(SapServer.SAP_STATE.CONNECTED);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
index a7ea9feafa..d6336bcb34 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/sap/SapServiceTest.java
@@ -16,6 +16,10 @@
package com.android.bluetooth.sap;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.TestUtils.getTestDevice;
@@ -82,20 +86,17 @@ public class SapServiceTest {
@Test
public void testGetConnectionPolicy() {
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
- assertThat(mService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_UNKNOWN);
+ .thenReturn(CONNECTION_POLICY_UNKNOWN);
+ assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_UNKNOWN);
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
- assertThat(mService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ .thenReturn(CONNECTION_POLICY_FORBIDDEN);
+ assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_FORBIDDEN);
when(mDatabaseManager.getProfileConnectionPolicy(mDevice, BluetoothProfile.SAP))
- .thenReturn(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ .thenReturn(CONNECTION_POLICY_ALLOWED);
- assertThat(mService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ assertThat(mService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
}
@Test
diff --git a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
index c791e243b5..81d7bc1bd5 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/tbs/TbsGattTest.java
@@ -645,7 +645,7 @@ public class TbsGattTest {
mFirstDevice,
true);
- // Clear freindly name (should not send any notification)
+ // Clear friendly name (should not send any notification)
verifySetValue(characteristic, null, false, mFirstDevice, true);
// Check with notifications disabled
@@ -780,7 +780,7 @@ public class TbsGattTest {
}
@Test
- public void testSilentModeAndInbandringtonFlagsChanges() {
+ public void testSilentModeAndInbandRingtoneFlagsChanges() {
prepareDefaultService();
BluetoothGattCharacteristic characteristic = getCharacteristic(TbsGatt.UUID_STATUS_FLAGS);
configureNotifications(mFirstDevice, characteristic, true);
@@ -848,7 +848,7 @@ public class TbsGattTest {
public void testCharacteristic_longReadAuthorized() {
prepareDefaultService();
- /* Twenty three octects long friendly name */
+ /* Twenty three octets long friendly name */
String title = "01234567890123456789012";
BluetoothGattCharacteristic characteristic =
getCharacteristic(TbsGatt.UUID_CALL_FRIENDLY_NAME);
@@ -888,7 +888,7 @@ public class TbsGattTest {
public void testCharacteristic_longReadOutsideLenAuthorized() {
prepareDefaultService();
- /* Twenty three octects long friendly name */
+ /* Twenty three octets long friendly name */
String title = "01234567890123456789012";
BluetoothGattCharacteristic characteristic =
getCharacteristic(TbsGatt.UUID_CALL_FRIENDLY_NAME);
diff --git a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java
index 7a727f5d7f..4045cb9bfb 100644
--- a/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java
+++ b/android/app/tests/unit/src/com/android/bluetooth/vc/VolumeControlNativeCallbackTest.java
@@ -16,6 +16,8 @@
package com.android.bluetooth.vc;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.android.bluetooth.TestUtils.MockitoRule;
import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_CONNECTION_STATE_CHANGED;
import static com.android.bluetooth.vc.VolumeControlStackEvent.EVENT_TYPE_DEVICE_AVAILABLE;
@@ -29,8 +31,6 @@ import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.verify;
-import android.bluetooth.BluetoothProfile;
-
import androidx.test.runner.AndroidJUnit4;
import com.android.bluetooth.btservice.AdapterService;
@@ -65,7 +65,7 @@ public class VolumeControlNativeCallbackTest {
@Test
public void onConnectionStateChanged() {
- int state = BluetoothProfile.STATE_CONNECTED;
+ int state = STATE_CONNECTED;
mNativeCallback.onConnectionStateChanged(state, null);
verify(mService).messageFromNative(mEvent.capture());
diff --git a/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java b/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java
index 62d87393bd..4dcb10d96f 100644
--- a/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java
+++ b/android/leaudio/app/src/main/java/com/android/bluetooth/leaudio/BluetoothProxy.java
@@ -17,6 +17,11 @@
package com.android.bluetooth.leaudio;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+
import android.app.Application;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
@@ -551,10 +556,9 @@ public class BluetoothProxy {
final int toState =
intent.getIntExtra(BluetoothProfile.EXTRA_STATE, -1);
- if (toState == BluetoothProfile.STATE_CONNECTED
- || toState == BluetoothProfile.STATE_DISCONNECTED)
+ if (toState == STATE_CONNECTED || toState == STATE_DISCONNECTED)
svc_data.isConnectedMutable.postValue(
- toState == BluetoothProfile.STATE_CONNECTED);
+ toState == STATE_CONNECTED);
}
}
}
@@ -1065,7 +1069,7 @@ public class BluetoothProxy {
if (mBluetoothLeBroadcastAssistant != null) {
boolean is_connected =
mBluetoothLeBroadcastAssistant.getConnectionState(dev)
- == BluetoothProfile.STATE_CONNECTED;
+ == STATE_CONNECTED;
state_wrapper.bassData.isConnectedMutable.setValue(is_connected);
}
}
@@ -1226,10 +1230,10 @@ public class BluetoothProxy {
if (mBluetoothLeBroadcastAssistant != null) {
if (connect) {
mBluetoothLeBroadcastAssistant.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ device, CONNECTION_POLICY_ALLOWED);
} else {
mBluetoothLeBroadcastAssistant.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ device, CONNECTION_POLICY_FORBIDDEN);
}
}
}
@@ -1342,11 +1346,9 @@ public class BluetoothProxy {
public void connectHap(BluetoothDevice device, boolean connect) {
if (bluetoothHapClient != null) {
if (connect) {
- bluetoothHapClient.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED);
} else {
- bluetoothHapClient.setConnectionPolicy(
- device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN);
+ bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN);
}
}
}
@@ -1376,11 +1378,11 @@ public class BluetoothProxy {
}
switch (newState) {
- case BluetoothProfile.STATE_DISCONNECTED:
+ case STATE_DISCONNECTED:
device_wrapper.isGattBrConnectedMutable.postValue(
false);
break;
- case BluetoothProfile.STATE_CONNECTED:
+ case STATE_CONNECTED:
device_wrapper.isGattBrConnectedMutable.postValue(true);
break;
default:
diff --git a/android/pandora/server/src/A2dp.kt b/android/pandora/server/src/A2dp.kt
index 0b5a0d6640..ba7003961f 100644
--- a/android/pandora/server/src/A2dp.kt
+++ b/android/pandora/server/src/A2dp.kt
@@ -23,6 +23,8 @@ import android.bluetooth.BluetoothCodecStatus
import android.bluetooth.BluetoothCodecType
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -98,13 +100,10 @@ class A2dp(val context: Context) : A2DPImplBase(), Closeable {
.map {
it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR)
}
- .filter {
- it == BluetoothProfile.STATE_CONNECTED ||
- it == BluetoothProfile.STATE_DISCONNECTED
- }
+ .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED }
.first()
- if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ if (state == STATE_DISCONNECTED) {
throw RuntimeException("openSource failed, A2DP has been disconnected")
}
}
@@ -131,13 +130,10 @@ class A2dp(val context: Context) : A2DPImplBase(), Closeable {
.map {
it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR)
}
- .filter {
- it == BluetoothProfile.STATE_CONNECTED ||
- it == BluetoothProfile.STATE_DISCONNECTED
- }
+ .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED }
.first()
- if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ if (state == STATE_DISCONNECTED) {
throw RuntimeException("waitSource failed, A2DP has been disconnected")
}
}
diff --git a/android/pandora/server/src/A2dpSink.kt b/android/pandora/server/src/A2dpSink.kt
index 789c9edf72..931997d5a5 100644
--- a/android/pandora/server/src/A2dpSink.kt
+++ b/android/pandora/server/src/A2dpSink.kt
@@ -20,6 +20,9 @@ import android.bluetooth.BluetoothA2dpSink
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -67,13 +70,13 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable {
override fun waitSink(
request: WaitSinkRequest,
- responseObserver: StreamObserver<WaitSinkResponse>
+ responseObserver: StreamObserver<WaitSinkResponse>,
) {
grpcUnary<WaitSinkResponse>(scope, responseObserver) {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.i(TAG, "waitSink: device=$device")
- if (bluetoothA2dpSink.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) {
+ if (bluetoothA2dpSink.getConnectionState(device) != STATE_CONNECTED) {
val state =
flow
.filter {
@@ -83,13 +86,10 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable {
.map {
it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR)
}
- .filter {
- it == BluetoothProfile.STATE_CONNECTED ||
- it == BluetoothProfile.STATE_DISCONNECTED
- }
+ .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED }
.first()
- if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ if (state == STATE_DISCONNECTED) {
throw RuntimeException("waitStream failed, A2DP has been disconnected")
}
}
@@ -104,7 +104,7 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable {
grpcUnary<CloseResponse>(scope, responseObserver) {
val device = bluetoothAdapter.getRemoteDevice(request.sink.cookie.toString("UTF-8"))
Log.i(TAG, "close: device=$device")
- if (bluetoothA2dpSink.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) {
+ if (bluetoothA2dpSink.getConnectionState(device) != STATE_CONNECTED) {
throw RuntimeException("Device is not connected, cannot close")
}
@@ -114,13 +114,8 @@ class A2dpSink(val context: Context) : A2DPImplBase(), Closeable {
.filter { it.getBluetoothDeviceExtra() == device }
.map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) }
- bluetoothA2dpSink.setConnectionPolicy(
- device,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- )
- a2dpConnectionStateChangedFlow
- .filter { it == BluetoothProfile.STATE_DISCONNECTED }
- .first()
+ bluetoothA2dpSink.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN)
+ a2dpConnectionStateChangedFlow.filter { it == STATE_DISCONNECTED }.first()
CloseResponse.getDefaultInstance()
}
diff --git a/android/pandora/server/src/Asha.kt b/android/pandora/server/src/Asha.kt
index 0c2d37ab48..d97b4b8b65 100644
--- a/android/pandora/server/src/Asha.kt
+++ b/android/pandora/server/src/Asha.kt
@@ -20,6 +20,7 @@ import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothHearingAid
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -79,7 +80,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
override fun waitPeripheral(
request: WaitPeripheralRequest,
- responseObserver: StreamObserver<WaitPeripheralResponse>
+ responseObserver: StreamObserver<WaitPeripheralResponse>,
) {
grpcUnary<WaitPeripheralResponse>(scope, responseObserver) {
Log.i(TAG, "waitPeripheral")
@@ -87,9 +88,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.d(TAG, "connection address ${device.getAddress()}")
- if (
- bluetoothHearingAid.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED
- ) {
+ if (bluetoothHearingAid.getConnectionState(device) != STATE_CONNECTED) {
Log.d(TAG, "wait for bluetoothHearingAid profile connection")
flow
.filter {
@@ -97,7 +96,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
}
.filter { it.getBluetoothDeviceExtra() == device }
.map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) }
- .filter { it == BluetoothProfile.STATE_CONNECTED }
+ .filter { it == STATE_CONNECTED }
.first()
}
@@ -113,9 +112,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.d(TAG, "connection address ${device.getAddress()}")
- if (
- bluetoothHearingAid.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED
- ) {
+ if (bluetoothHearingAid.getConnectionState(device) != STATE_CONNECTED) {
throw RuntimeException("Hearing aid device is not connected, cannot start")
}
@@ -141,7 +138,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
) {
Log.d(
TAG,
- "TYPE_HEARING_AID added with address: ${addedDevice.address}"
+ "TYPE_HEARING_AID added with address: ${addedDevice.address}",
)
trySendBlocking(null)
}
@@ -151,7 +148,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
audioManager.registerAudioDeviceCallback(
audioDeviceCallback,
- Handler(Looper.getMainLooper())
+ Handler(Looper.getMainLooper()),
)
awaitClose { audioManager.unregisterAudioDeviceCallback(audioDeviceCallback) }
}
@@ -182,7 +179,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
for (outputDevice in outputDevices) {
Log.d(
TAG,
- "available output device in listener:${outputDevice.type}"
+ "available output device in listener:${outputDevice.type}",
)
if (outputDevice.type == AudioDeviceInfo.TYPE_HEARING_AID) {
val result = router.setPreferredDevice(outputDevice)
@@ -196,7 +193,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
audioTrack!!.addOnRoutingChangedListener(
audioRoutingListener,
- Handler(Looper.getMainLooper())
+ Handler(Looper.getMainLooper()),
)
awaitClose { audioTrack!!.removeOnRoutingChangedListener(audioRoutingListener) }
}
@@ -206,7 +203,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC,
minVolume,
- AudioManager.FLAG_SHOW_UI
+ AudioManager.FLAG_SHOW_UI,
)
StartResponse.getDefaultInstance()
@@ -244,7 +241,7 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC,
maxVolume,
- AudioManager.FLAG_SHOW_UI
+ AudioManager.FLAG_SHOW_UI,
)
}
}
@@ -261,10 +258,12 @@ class Asha(val context: Context) : AshaImplBase(), Closeable {
)
}
}
+
override fun onError(t: Throwable?) {
Log.e(TAG, t.toString())
responseObserver.onError(t)
}
+
override fun onCompleted() {
Log.i(TAG, "onCompleted")
responseObserver.onNext(PlaybackAudioResponse.getDefaultInstance())
diff --git a/android/pandora/server/src/GattInstance.kt b/android/pandora/server/src/GattInstance.kt
index 655668c9a8..770f63c940 100644
--- a/android/pandora/server/src/GattInstance.kt
+++ b/android/pandora/server/src/GattInstance.kt
@@ -22,7 +22,8 @@ import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.bluetooth.BluetoothGattService
-import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.bluetooth.BluetoothStatusCodes
import android.content.Context
import android.util.Log
@@ -39,7 +40,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
public val mGatt: BluetoothGatt
private var mServiceDiscovered = MutableStateFlow(false)
- private var mConnectionState = MutableStateFlow(BluetoothProfile.STATE_DISCONNECTED)
+ private var mConnectionState = MutableStateFlow(STATE_DISCONNECTED)
private var mValuesRead = MutableStateFlow(0)
private var mValueWrote = MutableStateFlow(false)
private var mOnCharacteristicChanged = MutableStateFlow(false)
@@ -55,26 +56,31 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
var uuid: UUID?,
var handle: Int,
var value: ByteString?,
- var status: AttStatusCode
+ var status: AttStatusCode,
) {}
+
private var mGattInstanceValuesRead = arrayListOf<GattInstanceValueRead>()
class GattInstanceValueWrote(var uuid: UUID?, var handle: Int, var status: AttStatusCode) {}
+
private var mGattInstanceValueWrote =
GattInstanceValueWrote(null, 0, AttStatusCode.UNKNOWN_ERROR)
companion object GattManager {
val gattInstances: MutableMap<String, GattInstance> = mutableMapOf<String, GattInstance>()
+
fun get(address: String): GattInstance {
val instance = gattInstances.get(address)
requireNotNull(instance) { "Unable to find GATT instance for $address" }
return instance
}
+
fun get(address: ByteString): GattInstance {
val instance = gattInstances.get(address.toByteArray().decodeToString())
requireNotNull(instance) { "Unable to find GATT instance for $address" }
return instance
}
+
fun clearAllInstances() {
gattInstances.clear()
}
@@ -85,11 +91,11 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
override fun onConnectionStateChange(
bluetoothGatt: BluetoothGatt,
status: Int,
- newState: Int
+ newState: Int,
) {
Log.i(TAG, "$mDevice connection state changed to $newState")
mConnectionState.value = newState
- if (newState == BluetoothProfile.STATE_DISCONNECTED) {
+ if (newState == STATE_DISCONNECTED) {
gattInstances.remove(mDevice.address)
}
}
@@ -105,7 +111,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
bluetoothGatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
value: ByteArray,
- status: Int
+ status: Int,
) {
Log.i(TAG, "onCharacteristicRead, status: $status")
for (gattInstanceValueRead: GattInstanceValueRead in mGattInstanceValuesRead) {
@@ -124,7 +130,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
bluetoothGatt: BluetoothGatt,
descriptor: BluetoothGattDescriptor,
status: Int,
- value: ByteArray
+ value: ByteArray,
) {
Log.i(TAG, "onDescriptorRead, status: $status")
for (gattInstanceValueRead: GattInstanceValueRead in mGattInstanceValuesRead) {
@@ -142,7 +148,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
override fun onCharacteristicWrite(
bluetoothGatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
- status: Int
+ status: Int,
) {
Log.i(TAG, "onCharacteristicWrite, status: $status")
mGattInstanceValueWrote.status = AttStatusCode.forNumber(status)
@@ -152,7 +158,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
override fun onDescriptorWrite(
bluetoothGatt: BluetoothGatt,
descriptor: BluetoothGattDescriptor,
- status: Int
+ status: Int,
) {
Log.i(TAG, "onDescriptorWrite, status: $status")
mGattInstanceValueWrote.status = AttStatusCode.forNumber(status)
@@ -162,12 +168,12 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
override fun onCharacteristicChanged(
bluetoothGatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic,
- value: ByteArray
+ value: ByteArray,
) {
Log.i(
TAG,
"onCharacteristicChanged, characteristic: " +
- characteristic.getUuid().toString().uppercase()
+ characteristic.getUuid().toString().uppercase(),
)
mCharacteristicChangedMap[characteristic] = true
mOnCharacteristicChanged.value = true
@@ -189,11 +195,11 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
}
public fun isConnected(): Boolean {
- return mConnectionState.value == BluetoothProfile.STATE_CONNECTED
+ return mConnectionState.value == STATE_CONNECTED
}
public fun isDisconnected(): Boolean {
- return mConnectionState.value == BluetoothProfile.STATE_DISCONNECTED
+ return mConnectionState.value == STATE_DISCONNECTED
}
public fun isBonded(): Boolean {
@@ -259,7 +265,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
characteristic.getUuid(),
characteristic.getInstanceId(),
ByteString.EMPTY,
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
)
if (mGatt.readCharacteristic(characteristic)) {
@@ -272,7 +278,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
public suspend fun readCharacteristicUuidBlocking(
uuid: UUID,
startHandle: Int,
- endHandle: Int
+ endHandle: Int,
): ArrayList<GattInstanceValueRead> {
mGattInstanceValuesRead = arrayListOf()
// Init mGattInstanceValuesRead with characteristics values.
@@ -288,14 +294,14 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
uuid,
characteristic.getInstanceId(),
ByteString.EMPTY,
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
)
check(
mGatt.readUsingCharacteristicUuid(
uuid,
characteristic.getInstanceId(),
- characteristic.getInstanceId()
+ characteristic.getInstanceId(),
)
)
waitForValuesRead()
@@ -314,7 +320,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
uuid,
startHandle,
ByteString.EMPTY,
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
)
mGatt.readUsingCharacteristicUuid(uuid, startHandle, endHandle)
@@ -332,7 +338,7 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
descriptor.getUuid(),
descriptor.getInstanceId(),
ByteString.EMPTY,
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
)
if (mGatt.readDescriptor(descriptor)) {
@@ -344,18 +350,18 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
public suspend fun writeCharacteristicBlocking(
characteristic: BluetoothGattCharacteristic,
- value: ByteArray
+ value: ByteArray,
): GattInstanceValueWrote {
GattInstanceValueWrote(
characteristic.getUuid(),
characteristic.getInstanceId(),
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
if (
mGatt.writeCharacteristic(
characteristic,
value,
- BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT
+ BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT,
) == BluetoothStatusCodes.SUCCESS
) {
waitForWriteEnd()
@@ -365,12 +371,12 @@ class GattInstance(val mDevice: BluetoothDevice, val mTransport: Int, val mConte
public suspend fun writeDescriptorBlocking(
descriptor: BluetoothGattDescriptor,
- value: ByteArray
+ value: ByteArray,
): GattInstanceValueWrote {
GattInstanceValueWrote(
descriptor.getUuid(),
descriptor.getInstanceId(),
- AttStatusCode.UNKNOWN_ERROR
+ AttStatusCode.UNKNOWN_ERROR,
)
if (mGatt.writeDescriptor(descriptor, value) == BluetoothStatusCodes.SUCCESS) {
waitForWriteEnd()
diff --git a/android/pandora/server/src/Hap.kt b/android/pandora/server/src/Hap.kt
index 416879b46c..ddecaeb773 100644
--- a/android/pandora/server/src/Hap.kt
+++ b/android/pandora/server/src/Hap.kt
@@ -26,6 +26,7 @@ import android.bluetooth.BluetoothLeAudio
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
import android.content.Context
import android.content.IntentFilter
import android.media.AudioManager
@@ -381,14 +382,14 @@ class Hap(val context: Context) : HAPImplBase(), Closeable {
grpcUnary<Empty>(scope, responseObserver) {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.i(TAG, "waitPeripheral(${device}")
- if (bluetoothHapClient.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) {
+ if (bluetoothHapClient.getConnectionState(device) != STATE_CONNECTED) {
Log.d(TAG, "Manual call to setConnectionPolicy")
bluetoothHapClient.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED)
Log.d(TAG, "now waiting for bluetoothHapClient profile connection")
flow
.filter { it.getBluetoothDeviceExtra() == device }
.map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) }
- .filter { it == BluetoothProfile.STATE_CONNECTED }
+ .filter { it == STATE_CONNECTED }
.first()
}
diff --git a/android/pandora/server/src/Hfp.kt b/android/pandora/server/src/Hfp.kt
index 65f552463b..850d650256 100644
--- a/android/pandora/server/src/Hfp.kt
+++ b/android/pandora/server/src/Hfp.kt
@@ -21,6 +21,8 @@ import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothHeadset
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -92,7 +94,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
grpcUnary<Empty>(scope, responseObserver) {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
- bluetoothHfp.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED)
+ bluetoothHfp.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED)
Empty.getDefaultInstance()
}
@@ -102,7 +104,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
grpcUnary<Empty>(scope, responseObserver) {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
- bluetoothHfp.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN)
+ bluetoothHfp.setConnectionPolicy(device, CONNECTION_POLICY_FORBIDDEN)
Empty.getDefaultInstance()
}
@@ -136,7 +138,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
grpcUnary(scope, responseObserver) {
when (request.audioPath!!) {
AudioPath.AUDIO_PATH_UNKNOWN,
- AudioPath.UNRECOGNIZED, -> {}
+ AudioPath.UNRECOGNIZED -> {}
AudioPath.AUDIO_PATH_HANDSFREE -> {
check(bluetoothHfp.getActiveDevice() != null)
inCallService.setAudioRoute(CallAudioState.ROUTE_BLUETOOTH)
@@ -195,7 +197,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
override fun makeCall(
request: MakeCallRequest,
- responseObserver: StreamObserver<MakeCallResponse>
+ responseObserver: StreamObserver<MakeCallResponse>,
) {
grpcUnary(scope, responseObserver) {
telecomManager.placeCall(Uri.fromParts("tel", request.number, null), Bundle())
@@ -205,7 +207,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
override fun setVoiceRecognition(
request: SetVoiceRecognitionRequest,
- responseObserver: StreamObserver<SetVoiceRecognitionResponse>
+ responseObserver: StreamObserver<SetVoiceRecognitionResponse>,
) {
grpcUnary(scope, responseObserver) {
if (request.enabled) {
@@ -223,7 +225,7 @@ class Hfp(val context: Context) : HFPImplBase(), Closeable {
override fun clearCallHistory(
request: ClearCallHistoryRequest,
- responseObserver: StreamObserver<ClearCallHistoryResponse>
+ responseObserver: StreamObserver<ClearCallHistoryResponse>,
) {
grpcUnary(scope, responseObserver) {
context.contentResolver.delete(CallLog.Calls.CONTENT_URI, null, null)
diff --git a/android/pandora/server/src/HfpHandsfree.kt b/android/pandora/server/src/HfpHandsfree.kt
index 5571407dd4..77b0c957da 100644
--- a/android/pandora/server/src/HfpHandsfree.kt
+++ b/android/pandora/server/src/HfpHandsfree.kt
@@ -21,6 +21,8 @@ import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothHeadsetClient
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -68,12 +70,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun answerCallAsHandsfree(
request: AnswerCallAsHandsfreeRequest,
- responseObserver: StreamObserver<AnswerCallAsHandsfreeResponse>
+ responseObserver: StreamObserver<AnswerCallAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.acceptCall(
request.connection.toBluetoothDevice(bluetoothAdapter),
- BluetoothHeadsetClient.CALL_ACCEPT_NONE
+ BluetoothHeadsetClient.CALL_ACCEPT_NONE,
)
AnswerCallAsHandsfreeResponse.getDefaultInstance()
}
@@ -81,7 +83,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun endCallAsHandsfree(
request: EndCallAsHandsfreeRequest,
- responseObserver: StreamObserver<EndCallAsHandsfreeResponse>
+ responseObserver: StreamObserver<EndCallAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
for (call in
@@ -90,7 +92,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
)) {
bluetoothHfpClient.terminateCall(
request.connection.toBluetoothDevice(bluetoothAdapter),
- call
+ call,
)
}
EndCallAsHandsfreeResponse.getDefaultInstance()
@@ -99,7 +101,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun declineCallAsHandsfree(
request: DeclineCallAsHandsfreeRequest,
- responseObserver: StreamObserver<DeclineCallAsHandsfreeResponse>
+ responseObserver: StreamObserver<DeclineCallAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.rejectCall(request.connection.toBluetoothDevice(bluetoothAdapter))
@@ -109,7 +111,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun connectToAudioAsHandsfree(
request: ConnectToAudioAsHandsfreeRequest,
- responseObserver: StreamObserver<ConnectToAudioAsHandsfreeResponse>
+ responseObserver: StreamObserver<ConnectToAudioAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.connectAudio(request.connection.toBluetoothDevice(bluetoothAdapter))
@@ -119,7 +121,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun disconnectFromAudioAsHandsfree(
request: DisconnectFromAudioAsHandsfreeRequest,
- responseObserver: StreamObserver<DisconnectFromAudioAsHandsfreeResponse>
+ responseObserver: StreamObserver<DisconnectFromAudioAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.disconnectAudio(
@@ -131,12 +133,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun makeCallAsHandsfree(
request: MakeCallAsHandsfreeRequest,
- responseObserver: StreamObserver<MakeCallAsHandsfreeResponse>
+ responseObserver: StreamObserver<MakeCallAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.dial(
request.connection.toBluetoothDevice(bluetoothAdapter),
- request.number
+ request.number,
)
MakeCallAsHandsfreeResponse.getDefaultInstance()
}
@@ -144,7 +146,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun callTransferAsHandsfree(
request: CallTransferAsHandsfreeRequest,
- responseObserver: StreamObserver<CallTransferAsHandsfreeResponse>
+ responseObserver: StreamObserver<CallTransferAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.explicitCallTransfer(
@@ -156,12 +158,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun enableSlcAsHandsfree(
request: EnableSlcAsHandsfreeRequest,
- responseObserver: StreamObserver<Empty>
+ responseObserver: StreamObserver<Empty>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.setConnectionPolicy(
request.connection.toBluetoothDevice(bluetoothAdapter),
- BluetoothProfile.CONNECTION_POLICY_ALLOWED
+ CONNECTION_POLICY_ALLOWED,
)
Empty.getDefaultInstance()
}
@@ -169,12 +171,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun disableSlcAsHandsfree(
request: DisableSlcAsHandsfreeRequest,
- responseObserver: StreamObserver<Empty>
+ responseObserver: StreamObserver<Empty>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.setConnectionPolicy(
request.connection.toBluetoothDevice(bluetoothAdapter),
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
+ CONNECTION_POLICY_FORBIDDEN,
)
Empty.getDefaultInstance()
}
@@ -182,7 +184,7 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun setVoiceRecognitionAsHandsfree(
request: SetVoiceRecognitionAsHandsfreeRequest,
- responseObserver: StreamObserver<SetVoiceRecognitionAsHandsfreeResponse>
+ responseObserver: StreamObserver<SetVoiceRecognitionAsHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
if (request.enabled) {
@@ -200,12 +202,12 @@ class HfpHandsfree(val context: Context) : HFPImplBase(), Closeable {
override fun sendDtmfFromHandsfree(
request: SendDtmfFromHandsfreeRequest,
- responseObserver: StreamObserver<SendDtmfFromHandsfreeResponse>
+ responseObserver: StreamObserver<SendDtmfFromHandsfreeResponse>,
) {
grpcUnary(scope, responseObserver) {
bluetoothHfpClient.sendDTMF(
request.connection.toBluetoothDevice(bluetoothAdapter),
- request.code.toByte()
+ request.code.toByte(),
)
SendDtmfFromHandsfreeResponse.getDefaultInstance()
}
diff --git a/android/pandora/server/src/Host.kt b/android/pandora/server/src/Host.kt
index 196d87952a..c4243015f6 100644
--- a/android/pandora/server/src/Host.kt
+++ b/android/pandora/server/src/Host.kt
@@ -25,7 +25,7 @@ import android.bluetooth.BluetoothDevice.BOND_NONE
import android.bluetooth.BluetoothDevice.TRANSPORT_BREDR
import android.bluetooth.BluetoothDevice.TRANSPORT_LE
import android.bluetooth.BluetoothManager
-import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
import android.bluetooth.BluetoothUuid
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
@@ -400,7 +400,7 @@ class Host(
} catch (e: Exception) {
Log.w(TAG, "Gatt instance doesn't exist. Android might be peripheral")
val instance = GattInstance(bluetoothDevice, TRANSPORT_LE, context)
- instance.waitForState(BluetoothProfile.STATE_CONNECTED)
+ instance.waitForState(STATE_CONNECTED)
instance
}
if (gattInstance.isDisconnected()) {
@@ -452,8 +452,7 @@ class Host(
val bluetoothDevice =
bluetoothAdapter.getRemoteLeDevice(address.decodeAsMacAddressToString(), type)
initiatedConnection.add(bluetoothDevice)
- GattInstance(bluetoothDevice, TRANSPORT_LE, context)
- .waitForState(BluetoothProfile.STATE_CONNECTED)
+ GattInstance(bluetoothDevice, TRANSPORT_LE, context).waitForState(STATE_CONNECTED)
ConnectLEResponse.newBuilder()
.setConnection(bluetoothDevice.toConnection(TRANSPORT_LE))
.build()
diff --git a/android/pandora/server/src/LeAudio.kt b/android/pandora/server/src/LeAudio.kt
index 4abbb993fb..7e7e7e6147 100644
--- a/android/pandora/server/src/LeAudio.kt
+++ b/android/pandora/server/src/LeAudio.kt
@@ -20,6 +20,8 @@ import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothLeAudio
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
@@ -73,7 +75,7 @@ class LeAudio(val context: Context) : LeAudioImplBase(), Closeable {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.i(TAG, "open: device=$device")
- if (bluetoothLeAudio.getConnectionState(device) != BluetoothProfile.STATE_CONNECTED) {
+ if (bluetoothLeAudio.getConnectionState(device) != STATE_CONNECTED) {
bluetoothLeAudio.connect(device)
val state =
flow
@@ -85,13 +87,10 @@ class LeAudio(val context: Context) : LeAudioImplBase(), Closeable {
.map {
it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR)
}
- .filter {
- it == BluetoothProfile.STATE_CONNECTED ||
- it == BluetoothProfile.STATE_DISCONNECTED
- }
+ .filter { it == STATE_CONNECTED || it == STATE_DISCONNECTED }
.first()
- if (state == BluetoothProfile.STATE_DISCONNECTED) {
+ if (state == STATE_DISCONNECTED) {
throw RuntimeException("open failed, LE_AUDIO has been disconnected")
}
}
diff --git a/android/pandora/server/src/Pan.kt b/android/pandora/server/src/Pan.kt
index b24287fa15..62334af83b 100644
--- a/android/pandora/server/src/Pan.kt
+++ b/android/pandora/server/src/Pan.kt
@@ -20,6 +20,7 @@ import android.bluetooth.BluetoothDevice.TRANSPORT_BREDR
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothPan
import android.bluetooth.BluetoothProfile
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED
import android.content.Context
import android.net.TetheringManager
import android.net.TetheringManager.TETHERING_BLUETOOTH
@@ -72,7 +73,7 @@ class Pan(private val context: Context) : PANImplBase(), Closeable {
override fun enableTethering(
request: EnableTetheringRequest,
- responseObserver: StreamObserver<EnableTetheringResponse>
+ responseObserver: StreamObserver<EnableTetheringResponse>,
) {
grpcUnary<EnableTetheringResponse>(mScope, responseObserver) {
Log.i(TAG, "enableTethering")
@@ -80,7 +81,7 @@ class Pan(private val context: Context) : PANImplBase(), Closeable {
mTetheringManager.startTethering(
TETHERING_BLUETOOTH,
Executors.newSingleThreadExecutor(),
- mStartTetheringCallback
+ mStartTetheringCallback,
)
mTetheringEnabled.first { it == true }
}
@@ -90,12 +91,12 @@ class Pan(private val context: Context) : PANImplBase(), Closeable {
override fun connectPan(
request: ConnectPanRequest,
- responseObserver: StreamObserver<ConnectPanResponse>
+ responseObserver: StreamObserver<ConnectPanResponse>,
) {
grpcUnary<ConnectPanResponse>(mScope, responseObserver) {
Log.i(TAG, "connectPan")
val device = request.address.toBluetoothDevice(bluetoothAdapter)
- bluetoothPan.setConnectionPolicy(device, BluetoothProfile.CONNECTION_POLICY_ALLOWED)
+ bluetoothPan.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED)
bluetoothPan.connect(device)
ConnectPanResponse.newBuilder()
.setConnection(device.toConnection(TRANSPORT_BREDR))
diff --git a/android/pandora/server/src/Vcp.kt b/android/pandora/server/src/Vcp.kt
index e1b6aa2b1c..6f19685bec 100644
--- a/android/pandora/server/src/Vcp.kt
+++ b/android/pandora/server/src/Vcp.kt
@@ -20,6 +20,7 @@ import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
import android.bluetooth.BluetoothVolumeControl
import android.content.Context
import android.content.IntentFilter
@@ -99,17 +100,14 @@ class Vcp(val context: Context) : VCPImplBase(), Closeable {
grpcUnary<Empty>(scope, responseObserver) {
val device = request.connection.toBluetoothDevice(bluetoothAdapter)
Log.i(TAG, "waitPeripheral(${device}")
- if (
- bluetoothVolumeControl.getConnectionState(device) !=
- BluetoothProfile.STATE_CONNECTED
- ) {
+ if (bluetoothVolumeControl.getConnectionState(device) != STATE_CONNECTED) {
Log.d(TAG, "Manual call to setConnectionPolicy")
bluetoothVolumeControl.setConnectionPolicy(device, CONNECTION_POLICY_ALLOWED)
Log.d(TAG, "wait for bluetoothVolumeControl profile connection")
flow
.filter { it.getBluetoothDeviceExtra() == device }
.map { it.getIntExtra(BluetoothProfile.EXTRA_STATE, BluetoothAdapter.ERROR) }
- .filter { it == BluetoothProfile.STATE_CONNECTED }
+ .filter { it == STATE_CONNECTED }
.first()
}
diff --git a/android/pandora/test/Android.bp b/android/pandora/test/Android.bp
index a271fb7345..794b75ff61 100644
--- a/android/pandora/test/Android.bp
+++ b/android/pandora/test/Android.bp
@@ -22,11 +22,7 @@ python_test_host {
srcs: [
"**/*.py",
],
- version: {
- py3: {
- embedded_launcher: false,
- },
- },
+ embedded_launcher: false,
libs: [
"bumble_services_experimental-python",
"libavatar",
@@ -56,11 +52,7 @@ python_test_host {
"**/*.py",
],
test_config: "AndroidPhyTest.xml",
- version: {
- py3: {
- embedded_launcher: false,
- },
- },
+ embedded_launcher: false,
libs: [
"bumble_services_experimental-python",
"libavatar",
diff --git a/android/pandora/test/a2dp_test.py b/android/pandora/test/a2dp_test.py
index 1c2c4c9e84..d8380bb748 100644
--- a/android/pandora/test/a2dp_test.py
+++ b/android/pandora/test/a2dp_test.py
@@ -337,7 +337,7 @@ class A2dpTest(base_test.BaseTestClass): # type: ignore[misc]
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())
+ await asyncio.gather(self.dut.a2dp.Suspend(source=dut_ref1_source), channel.accept_suspend(timeout=8.0))
@avatar.asynchronous
async def test_avdtp_autoconnect_when_only_avctp_connected(self) -> None:
@@ -533,7 +533,7 @@ class A2dpTest(base_test.BaseTestClass): # type: ignore[misc]
# Stop streaming to RD1.
_, cmd = await asyncio.gather(
self.dut.a2dp.Suspend(source=dut_ref1_source),
- channel.expect_signal(SuspendCommand(transaction_label=self.any, acp_seid=self.any)))
+ channel.expect_signal(SuspendCommand(transaction_label=self.any, acp_seid=self.any), timeout=8.0))
# Simulate AVDTP_BAD_STATE response.
channel.send_signal(SuspendReject(transaction_label=cmd.transaction_label,
diff --git a/flags/bta_dm.aconfig b/flags/bta_dm.aconfig
index 0e424d440c..19e8418785 100644
--- a/flags/bta_dm.aconfig
+++ b/flags/bta_dm.aconfig
@@ -27,3 +27,13 @@ flag {
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "bta_dm_disc_close_proper_conn_id"
+ namespace: "bluetooth"
+ description: "Make sure proper connection is closed when timeout happens"
+ bug: "399687217"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/flags/gap.aconfig b/flags/gap.aconfig
index 1f2241ab6d..ecbc2aadb2 100644
--- a/flags/gap.aconfig
+++ b/flags/gap.aconfig
@@ -9,9 +9,9 @@ flag {
}
flag {
- name: "scan_manager_refactor"
+ name: "only_start_scan_during_ble_on"
namespace: "bluetooth"
- description: "Refactor scan manager as described in go/scan-manager-refactor"
+ description: "Instead of starting scan and gatt in ble_on, only start scan"
bug: "313335632"
}
diff --git a/flags/pairing.aconfig b/flags/pairing.aconfig
index 22f5d2b3d0..19573b99bb 100644
--- a/flags/pairing.aconfig
+++ b/flags/pairing.aconfig
@@ -280,3 +280,13 @@ flag {
purpose: PURPOSE_BUGFIX
}
}
+
+flag {
+ name: "reset_security_flags_on_pairing_failure"
+ namespace: "bluetooth"
+ description: "Reset security flags on pairing failure"
+ bug: "400586238"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+} \ No newline at end of file
diff --git a/flags/rfcomm.aconfig b/flags/rfcomm.aconfig
index f6ad45ef68..fcd640695e 100644
--- a/flags/rfcomm.aconfig
+++ b/flags/rfcomm.aconfig
@@ -39,4 +39,14 @@ flag {
metadata {
purpose: PURPOSE_BUGFIX
}
-} \ No newline at end of file
+}
+
+flag {
+ name: "rfcomm_fix_mux_collision_handling"
+ namespace: "bluetooth"
+ description: "Properly handle incoming connections while connecting"
+ bug: "399420482"
+ metadata {
+ purpose: PURPOSE_BUGFIX
+ }
+}
diff --git a/framework/java/android/bluetooth/BluetoothA2dp.java b/framework/java/android/bluetooth/BluetoothA2dp.java
index 06e98105cd..207167a053 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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -446,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;
}
/**
@@ -562,8 +566,8 @@ public final class BluetoothA2dp implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -618,7 +622,7 @@ public final class BluetoothA2dp implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -1093,53 +1097,18 @@ public final class BluetoothA2dp implements BluetoothProfile {
return false;
}
- /**
- * Helper for converting a state to a string.
- *
- * <p>For debug use only - strings are not internationalized.
- *
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- public static String stateToString(int state) {
- switch (state) {
- case STATE_DISCONNECTED:
- return "disconnected";
- case STATE_CONNECTING:
- return "connecting";
- case STATE_CONNECTED:
- return "connected";
- case STATE_DISCONNECTING:
- return "disconnecting";
- case STATE_PLAYING:
- return "playing";
- case STATE_NOT_PLAYING:
- return "not playing";
- default:
- return "<unknown state " + state + ">";
- }
- }
-
private boolean isEnabled() {
if (mAdapter.getState() == BluetoothAdapter.STATE_ON) return true;
return false;
}
- @SuppressWarnings("MethodCanBeStatic")
- private void verifyDeviceNotNull(BluetoothDevice device, String methodName) {
+ 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 static boolean isValidDevice(BluetoothDevice device) {
- if (device == null) return false;
-
- if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
- return false;
- }
-
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothA2dpSink.java b/framework/java/android/bluetooth/BluetoothA2dpSink.java
index 1cd9c6a5cb..ac45bcf46e 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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.RequiresNoPermission;
@@ -266,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;
}
/**
@@ -338,8 +342,8 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -392,7 +396,7 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -421,40 +425,10 @@ public final class BluetoothA2dpSink implements BluetoothProfile {
return false;
}
- /**
- * Helper for converting a state to a string.
- *
- * <p>For debug use only - strings are not internationalized.
- *
- * @hide
- */
- public static String stateToString(int state) {
- switch (state) {
- case STATE_DISCONNECTED:
- return "disconnected";
- case STATE_CONNECTING:
- return "connecting";
- case STATE_CONNECTED:
- return "connected";
- case STATE_DISCONNECTING:
- return "disconnecting";
- case BluetoothA2dp.STATE_PLAYING:
- return "playing";
- case BluetoothA2dp.STATE_NOT_PLAYING:
- return "not playing";
- default:
- return "<unknown state " + state + ">";
- }
- }
-
private boolean isEnabled() {
return mAdapter.getState() == BluetoothAdapter.STATE_ON;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothAdapter.java b/framework/java/android/bluetooth/BluetoothAdapter.java
index bf5ec5ae21..8f2edc546d 100644
--- a/framework/java/android/bluetooth/BluetoothAdapter.java
+++ b/framework/java/android/bluetooth/BluetoothAdapter.java
@@ -24,6 +24,9 @@ import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.BLUETOOTH_SCAN;
import static android.Manifest.permission.LOCAL_MAC_ADDRESS;
import static android.Manifest.permission.MODIFY_PHONE_STATE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
import static android.bluetooth.BluetoothProfile.getProfileName;
import static android.bluetooth.BluetoothStatusCodes.FEATURE_NOT_SUPPORTED;
import static android.bluetooth.BluetoothUtils.executeFromBinder;
@@ -5560,16 +5563,16 @@ public final class BluetoothAdapter {
public static @ConnectionPolicy int priorityToConnectionPolicy(int priority) {
switch (priority) {
case BluetoothProfile.PRIORITY_AUTO_CONNECT:
- return BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ return CONNECTION_POLICY_ALLOWED;
case BluetoothProfile.PRIORITY_ON:
- return BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+ return CONNECTION_POLICY_ALLOWED;
case BluetoothProfile.PRIORITY_OFF:
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
case BluetoothProfile.PRIORITY_UNDEFINED:
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
default:
Log.e(TAG, "setPriority: Invalid priority: " + priority);
- return BluetoothProfile.CONNECTION_POLICY_UNKNOWN;
+ return CONNECTION_POLICY_UNKNOWN;
}
}
@@ -5582,11 +5585,11 @@ public final class BluetoothAdapter {
*/
public static int connectionPolicyToPriority(@ConnectionPolicy int connectionPolicy) {
switch (connectionPolicy) {
- case BluetoothProfile.CONNECTION_POLICY_ALLOWED:
+ case CONNECTION_POLICY_ALLOWED:
return BluetoothProfile.PRIORITY_ON;
- case BluetoothProfile.CONNECTION_POLICY_FORBIDDEN:
+ case CONNECTION_POLICY_FORBIDDEN:
return BluetoothProfile.PRIORITY_OFF;
- case BluetoothProfile.CONNECTION_POLICY_UNKNOWN:
+ case CONNECTION_POLICY_UNKNOWN:
return BluetoothProfile.PRIORITY_UNDEFINED;
}
return BluetoothProfile.PRIORITY_UNDEFINED;
diff --git a/framework/java/android/bluetooth/BluetoothAvrcpController.java b/framework/java/android/bluetooth/BluetoothAvrcpController.java
index 8ced189723..2d39b89925 100644
--- a/framework/java/android/bluetooth/BluetoothAvrcpController.java
+++ b/framework/java/android/bluetooth/BluetoothAvrcpController.java
@@ -17,6 +17,8 @@
package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.RequiresNoPermission;
import android.annotation.RequiresPermission;
@@ -194,7 +196,7 @@ public final class BluetoothAvrcpController implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -274,10 +276,6 @@ public final class BluetoothAvrcpController implements BluetoothProfile {
return mAdapter.getState() == BluetoothAdapter.STATE_ON;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java
index 059e791bea..abec916a24 100644
--- a/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java
+++ b/framework/java/android/bluetooth/BluetoothCsipSetCoordinator.java
@@ -19,6 +19,9 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothUtils.executeFromBinder;
import static java.util.Objects.requireNonNull;
@@ -444,7 +447,7 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -471,8 +474,8 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -508,7 +511,7 @@ public final class BluetoothCsipSetCoordinator implements BluetoothProfile, Auto
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
private boolean isEnabled() {
diff --git a/framework/java/android/bluetooth/BluetoothDevice.java b/framework/java/android/bluetooth/BluetoothDevice.java
index 0c3f4288e6..8c053201e9 100644
--- a/framework/java/android/bluetooth/BluetoothDevice.java
+++ b/framework/java/android/bluetooth/BluetoothDevice.java
@@ -896,8 +896,7 @@ public final class BluetoothDevice implements Parcelable, Attributable {
*
* @hide
*/
- @SystemApi
- public static final int METADATA_EXCLUSIVE_MANAGER = 29;
+ @SystemApi public static final int METADATA_EXCLUSIVE_MANAGER = 29;
private static final int METADATA_MAX_KEY = METADATA_EXCLUSIVE_MANAGER;
@@ -1727,8 +1726,8 @@ public final class BluetoothDevice implements Parcelable, Attributable {
/**
* Returns the identity address and identity address type of this BluetoothDevice. An identity
- * address is a public or static random Bluetooth LE device address that serves as a
- * unique identifier.
+ * address is a public or static random Bluetooth LE device address that serves as a unique
+ * identifier.
*
* @return a {@link BluetoothAddress} containing identity address and identity address type. If
* Bluetooth is not enabled or identity address type is not available, it will return a
@@ -3791,6 +3790,31 @@ public final class BluetoothDevice implements Parcelable, Attributable {
return true;
}
+ /**
+ * Get the number of times {@link ACTION_KEY_MISSING} intent is thrown for this device since
+ * last successful encrypted connection
+ *
+ * @return number of times {@link ACTION_KEY_MISSING} intent is thrown for this device since
+ * last successful encrypted connection
+ *
+ * @hide
+ */
+ @RequiresPermission(BLUETOOTH_CONNECT)
+ public int getKeyMissingCount() {
+ final IBluetooth service = getService();
+ if (service == null || !isBluetoothEnabled()) {
+ Log.e(TAG, "Bluetooth is not enabled. Cannot get key missing counter.");
+ if (DBG) log(Log.getStackTraceString(new Throwable()));
+ } else {
+ try {
+ return service.getKeyMissingCount(this, mAttributionSource);
+ } catch (RemoteException e) {
+ Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
+ }
+ }
+ return -1;
+ }
+
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothGatt.java b/framework/java/android/bluetooth/BluetoothGatt.java
index 3e3f3a207c..1ef8d2add6 100644
--- a/framework/java/android/bluetooth/BluetoothGatt.java
+++ b/framework/java/android/bluetooth/BluetoothGatt.java
@@ -18,6 +18,8 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothUtils.logRemoteException;
import android.annotation.IntDef;
@@ -268,7 +270,7 @@ public final class BluetoothGatt implements BluetoothProfile {
callback.onConnectionStateChange(
BluetoothGatt.this,
GATT_FAILURE,
- BluetoothProfile.STATE_DISCONNECTED);
+ STATE_DISCONNECTED);
}
}
});
@@ -385,10 +387,7 @@ public final class BluetoothGatt implements BluetoothProfile {
if (!address.equals(mDevice.getAddress())) {
return;
}
- int profileState =
- connected
- ? BluetoothProfile.STATE_CONNECTED
- : BluetoothProfile.STATE_DISCONNECTED;
+ int profileState = connected ? STATE_CONNECTED : STATE_DISCONNECTED;
if (Flags.unregisterGattClientDisconnected() && !connected && !mAutoConnect) {
unregisterApp();
diff --git a/framework/java/android/bluetooth/BluetoothGattServer.java b/framework/java/android/bluetooth/BluetoothGattServer.java
index 34002052b4..3a86c1d7b3 100644
--- a/framework/java/android/bluetooth/BluetoothGattServer.java
+++ b/framework/java/android/bluetooth/BluetoothGattServer.java
@@ -17,6 +17,8 @@
package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -122,9 +124,7 @@ public final class BluetoothGattServer implements BluetoothProfile {
mCallback.onConnectionStateChange(
mAdapter.getRemoteDevice(address),
status,
- connected
- ? BluetoothProfile.STATE_CONNECTED
- : BluetoothProfile.STATE_DISCONNECTED);
+ connected ? STATE_CONNECTED : STATE_DISCONNECTED);
} catch (Exception ex) {
Log.w(TAG, "Unhandled exception in callback", ex);
}
diff --git a/framework/java/android/bluetooth/BluetoothHapClient.java b/framework/java/android/bluetooth/BluetoothHapClient.java
index 08642c3800..e551cca8f5 100644
--- a/framework/java/android/bluetooth/BluetoothHapClient.java
+++ b/framework/java/android/bluetooth/BluetoothHapClient.java
@@ -19,7 +19,11 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothUtils.callServiceIfEnabled;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -576,8 +580,8 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable
requireNonNull(device);
boolean defaultValue = false;
if (!isValidDevice(device)
- || (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ || (connectionPolicy != CONNECTION_POLICY_FORBIDDEN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED)) {
return defaultValue;
}
return callServiceIfEnabled(
@@ -599,7 +603,7 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable
@RequiresBluetoothConnectPermission
@RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
public @ConnectionPolicy int getConnectionPolicy(@Nullable BluetoothDevice device) {
- int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ int defaultValue = CONNECTION_POLICY_FORBIDDEN;
if (!isValidDevice(device)) {
return defaultValue;
}
@@ -661,7 +665,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;
}
@@ -1084,11 +1088,4 @@ public final class BluetoothHapClient implements BluetoothProfile, AutoCloseable
this::getService,
s -> s.setPresetNameForGroup(groupId, presetIndex, name, mAttributionSource));
}
-
- private static boolean isValidDevice(BluetoothDevice device) {
- if (device == null) return false;
-
- if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
- return false;
- }
}
diff --git a/framework/java/android/bluetooth/BluetoothHeadset.java b/framework/java/android/bluetooth/BluetoothHeadset.java
index dc99736bbf..3e33b42980 100644
--- a/framework/java/android/bluetooth/BluetoothHeadset.java
+++ b/framework/java/android/bluetooth/BluetoothHeadset.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.MODIFY_PHONE_STATE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -547,7 +551,7 @@ public final class BluetoothHeadset implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -579,8 +583,8 @@ public final class BluetoothHeadset implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -635,7 +639,7 @@ public final class BluetoothHeadset implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -1127,36 +1131,6 @@ public final class BluetoothHeadset implements BluetoothProfile {
}
/**
- * Notify Headset of phone state change. This is a backdoor for phone app to call
- * BluetoothHeadset since there is currently not a good way to get precise call state change
- * outside of phone app.
- *
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- @RequiresBluetoothConnectPermission
- @RequiresPermission(
- allOf = {
- BLUETOOTH_CONNECT,
- MODIFY_PHONE_STATE,
- })
- public void phoneStateChanged(
- int numActive, int numHeld, int callState, String number, int type, String name) {
- final IBluetoothHeadset service = getService();
- if (service == null) {
- Log.w(TAG, "Proxy not attached to service");
- if (DBG) log(Log.getStackTraceString(new Throwable()));
- } else if (isEnabled()) {
- try {
- service.phoneStateChanged(
- numActive, numHeld, callState, number, type, name, mAttributionSource);
- } catch (RemoteException e) {
- Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
- }
- }
- }
-
- /**
* Sends a vendor-specific unsolicited result code to the headset.
*
* <p>The actual string to be sent is <code>command + ": " + arg</code>. For example, if {@code
@@ -1308,10 +1282,6 @@ public final class BluetoothHeadset implements BluetoothProfile {
return mAdapter.getState() == BluetoothAdapter.STATE_OFF;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothHeadsetClient.java b/framework/java/android/bluetooth/BluetoothHeadsetClient.java
index 3ef33cb845..fea8f81c5f 100644
--- a/framework/java/android/bluetooth/BluetoothHeadsetClient.java
+++ b/framework/java/android/bluetooth/BluetoothHeadsetClient.java
@@ -17,6 +17,10 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -795,7 +799,7 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -822,8 +826,8 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -860,7 +864,7 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -1642,10 +1646,6 @@ public final class BluetoothHeadsetClient implements BluetoothProfile, AutoClose
return mAdapter.getState() == BluetoothAdapter.STATE_ON;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothHearingAid.java b/framework/java/android/bluetooth/BluetoothHearingAid.java
index 0a4e829216..7e14057546 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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.IntDef;
import android.annotation.NonNull;
@@ -470,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;
}
/**
@@ -563,8 +567,8 @@ public final class BluetoothHearingAid implements BluetoothProfile {
if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -601,29 +605,7 @@ public final class BluetoothHearingAid implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
- }
-
- /**
- * Helper for converting a state to a string.
- *
- * <p>For debug use only - strings are not internationalized.
- *
- * @hide
- */
- public static String stateToString(int state) {
- switch (state) {
- case STATE_DISCONNECTED:
- return "disconnected";
- case STATE_CONNECTING:
- return "connecting";
- case STATE_CONNECTED:
- return "connected";
- case STATE_DISCONNECTING:
- return "disconnecting";
- default:
- return "<unknown state " + state + ">";
- }
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -781,11 +763,4 @@ public final class BluetoothHearingAid implements BluetoothProfile {
throw new IllegalArgumentException("Device cannot be null");
}
}
-
- private static boolean isValidDevice(BluetoothDevice device) {
- if (device == null) return false;
-
- if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
- return false;
- }
}
diff --git a/framework/java/android/bluetooth/BluetoothHidDevice.java b/framework/java/android/bluetooth/BluetoothHidDevice.java
index 8fd7dee6f7..92ee4f5fb3 100644
--- a/framework/java/android/bluetooth/BluetoothHidDevice.java
+++ b/framework/java/android/bluetooth/BluetoothHidDevice.java
@@ -18,7 +18,10 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothUtils.executeFromBinder;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.RequiresNoPermission;
@@ -770,8 +773,8 @@ public final class BluetoothHidDevice implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -786,13 +789,6 @@ public final class BluetoothHidDevice implements BluetoothProfile {
return false;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- if (device == null) return false;
-
- if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
- return false;
- }
-
private static void log(String msg) {
if (DBG) {
Log.d(TAG, msg);
diff --git a/framework/java/android/bluetooth/BluetoothHidHost.java b/framework/java/android/bluetooth/BluetoothHidHost.java
index 6e9759b1e5..5eb6895746 100644
--- a/framework/java/android/bluetooth/BluetoothHidHost.java
+++ b/framework/java/android/bluetooth/BluetoothHidHost.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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -386,7 +390,7 @@ public final class BluetoothHidHost implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -441,8 +445,8 @@ public final class BluetoothHidHost implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -556,7 +560,7 @@ public final class BluetoothHidHost implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -601,10 +605,6 @@ public final class BluetoothHidHost implements BluetoothProfile {
return mAdapter.getState() == BluetoothAdapter.STATE_ON;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
/**
* Initiate virtual unplug for a HID input device.
*
diff --git a/framework/java/android/bluetooth/BluetoothLeAudio.java b/framework/java/android/bluetooth/BluetoothLeAudio.java
index 09683a912a..4cc3b604fb 100644
--- a/framework/java/android/bluetooth/BluetoothLeAudio.java
+++ b/framework/java/android/bluetooth/BluetoothLeAudio.java
@@ -19,6 +19,9 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -972,7 +975,7 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -1291,8 +1294,8 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (mAdapter.isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -1328,29 +1331,7 @@ public final class BluetoothLeAudio implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
- }
-
- /**
- * Helper for converting a state to a string.
- *
- * <p>For debug use only - strings are not internationalized.
- *
- * @hide
- */
- public static String stateToString(int state) {
- switch (state) {
- case STATE_DISCONNECTED:
- return "disconnected";
- case STATE_CONNECTING:
- return "connecting";
- case STATE_CONNECTED:
- return "connected";
- case STATE_DISCONNECTING:
- return "disconnecting";
- default:
- return "<unknown state " + state + ">";
- }
+ return CONNECTION_POLICY_FORBIDDEN;
}
private static boolean isValidDevice(@Nullable BluetoothDevice device) {
diff --git a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java
index a0ce14ade0..63ddb8a03a 100644
--- a/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java
+++ b/framework/java/android/bluetooth/BluetoothLeBroadcastAssistant.java
@@ -19,6 +19,9 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.BLUETOOTH_SCAN;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static java.util.Objects.requireNonNull;
@@ -582,7 +585,7 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au
log("getConnectionState(" + sink + ")");
requireNonNull(sink);
final IBluetoothLeBroadcastAssistant service = getService();
- final int defaultValue = BluetoothProfile.STATE_DISCONNECTED;
+ final int defaultValue = STATE_DISCONNECTED;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
@@ -677,8 +680,8 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (mBluetoothAdapter.isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -706,7 +709,7 @@ public final class BluetoothLeBroadcastAssistant implements BluetoothProfile, Au
log("getConnectionPolicy()");
requireNonNull(device);
final IBluetoothLeBroadcastAssistant service = getService();
- final int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ final int defaultValue = CONNECTION_POLICY_FORBIDDEN;
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
if (DBG) log(Log.getStackTraceString(new Throwable()));
diff --git a/framework/java/android/bluetooth/BluetoothManager.java b/framework/java/android/bluetooth/BluetoothManager.java
index 00522d4f89..4dce4c790b 100644
--- a/framework/java/android/bluetooth/BluetoothManager.java
+++ b/framework/java/android/bluetooth/BluetoothManager.java
@@ -17,6 +17,8 @@
package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.android.modules.utils.build.SdkLevel.isAtLeastU;
@@ -100,11 +102,11 @@ public final class BluetoothManager {
List<BluetoothDevice> connectedDevices = getConnectedDevices(profile);
for (BluetoothDevice connectedDevice : connectedDevices) {
if (device.equals(connectedDevice)) {
- return BluetoothProfile.STATE_CONNECTED;
+ return STATE_CONNECTED;
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -123,8 +125,7 @@ public final class BluetoothManager {
@RequiresBluetoothConnectPermission
@RequiresPermission(BLUETOOTH_CONNECT)
public List<BluetoothDevice> getConnectedDevices(int profile) {
- return getDevicesMatchingConnectionStates(
- profile, new int[] {BluetoothProfile.STATE_CONNECTED});
+ return getDevicesMatchingConnectionStates(profile, new int[] {STATE_CONNECTED});
}
/**
diff --git a/framework/java/android/bluetooth/BluetoothMap.java b/framework/java/android/bluetooth/BluetoothMap.java
index 2f079d1a90..4c44995921 100644
--- a/framework/java/android/bluetooth/BluetoothMap.java
+++ b/framework/java/android/bluetooth/BluetoothMap.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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.RequiresNoPermission;
@@ -426,7 +430,7 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -478,8 +482,8 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -540,7 +544,7 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
private static void log(String msg) {
@@ -550,8 +554,4 @@ public final class BluetoothMap implements BluetoothProfile, AutoCloseable {
private boolean isEnabled() {
return mAdapter.isEnabled();
}
-
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
}
diff --git a/framework/java/android/bluetooth/BluetoothMapClient.java b/framework/java/android/bluetooth/BluetoothMapClient.java
index 0f6700df80..a018669858 100644
--- a/framework/java/android/bluetooth/BluetoothMapClient.java
+++ b/framework/java/android/bluetooth/BluetoothMapClient.java
@@ -20,6 +20,10 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.RECEIVE_SMS;
import static android.Manifest.permission.SEND_SMS;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -395,7 +399,7 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -439,8 +443,8 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable
if (DBG) Log.d(TAG, Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -493,7 +497,7 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
/**
@@ -571,8 +575,4 @@ public final class BluetoothMapClient implements BluetoothProfile, AutoCloseable
private boolean isEnabled() {
return mAdapter.isEnabled();
}
-
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
}
diff --git a/framework/java/android/bluetooth/BluetoothPan.java b/framework/java/android/bluetooth/BluetoothPan.java
index 6ecdc6fa2a..ded188821e 100644
--- a/framework/java/android/bluetooth/BluetoothPan.java
+++ b/framework/java/android/bluetooth/BluetoothPan.java
@@ -20,7 +20,11 @@ import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
import static android.Manifest.permission.TETHER_PRIVILEGED;
import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothUtils.executeFromBinder;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -380,8 +384,8 @@ public final class BluetoothPan implements BluetoothProfile {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -478,7 +482,7 @@ public final class BluetoothPan implements BluetoothProfile {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -607,11 +611,6 @@ public final class BluetoothPan implements BluetoothProfile {
}
@UnsupportedAppUsage
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
- @UnsupportedAppUsage
private static void log(String msg) {
Log.d(TAG, msg);
}
diff --git a/framework/java/android/bluetooth/BluetoothPbap.java b/framework/java/android/bluetooth/BluetoothPbap.java
index afa796b85e..8da64ddb96 100644
--- a/framework/java/android/bluetooth/BluetoothPbap.java
+++ b/framework/java/android/bluetooth/BluetoothPbap.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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.RequiresNoPermission;
@@ -193,11 +197,11 @@ public class BluetoothPbap implements BluetoothProfile {
if (service == null) {
Log.w(TAG, "Proxy not attached to service");
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
} catch (RemoteException e) {
Log.e(TAG, e.toString());
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -252,8 +256,8 @@ public class BluetoothPbap implements BluetoothProfile {
try {
final IBluetoothPbap service = getService();
if (service != null && isEnabled() && isValidDevice(device)) {
- if (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
+ if (connectionPolicy != CONNECTION_POLICY_FORBIDDEN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED) {
return false;
}
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
@@ -297,13 +301,6 @@ public class BluetoothPbap implements BluetoothProfile {
return false;
}
- private static boolean isValidDevice(BluetoothDevice device) {
- if (device == null) return false;
-
- if (BluetoothAdapter.checkBluetoothAddress(device.getAddress())) return true;
- return false;
- }
-
private static void log(String msg) {
if (DBG) {
Log.d(TAG, msg);
diff --git a/framework/java/android/bluetooth/BluetoothPbapClient.java b/framework/java/android/bluetooth/BluetoothPbapClient.java
index 0969c688f7..391c46da63 100644
--- a/framework/java/android/bluetooth/BluetoothPbapClient.java
+++ b/framework/java/android/bluetooth/BluetoothPbapClient.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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import android.annotation.NonNull;
import android.annotation.RequiresNoPermission;
@@ -298,7 +302,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) {
@@ -309,10 +313,6 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl
return mAdapter.isEnabled();
}
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
-
/**
* Set priority of the profile
*
@@ -356,8 +356,8 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -412,6 +412,6 @@ public final class BluetoothPbapClient implements BluetoothProfile, AutoCloseabl
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
}
diff --git a/framework/java/android/bluetooth/BluetoothSap.java b/framework/java/android/bluetooth/BluetoothSap.java
index 843b369be0..5ec412cb39 100644
--- a/framework/java/android/bluetooth/BluetoothSap.java
+++ b/framework/java/android/bluetooth/BluetoothSap.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.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
+import static android.bluetooth.BluetoothUtils.isValidDevice;
import static java.util.Objects.requireNonNull;
@@ -424,7 +428,7 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.STATE_DISCONNECTED;
+ return STATE_DISCONNECTED;
}
/**
@@ -470,8 +474,8 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable {
if (DBG) log(Log.getStackTraceString(new Throwable()));
} else if (isEnabled()
&& isValidDevice(device)
- && (connectionPolicy == BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- || connectionPolicy == BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ && (connectionPolicy == CONNECTION_POLICY_FORBIDDEN
+ || connectionPolicy == CONNECTION_POLICY_ALLOWED)) {
try {
return service.setConnectionPolicy(device, connectionPolicy, mAttributionSource);
} catch (RemoteException e) {
@@ -526,7 +530,7 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable {
Log.e(TAG, e.toString() + "\n" + Log.getStackTraceString(new Throwable()));
}
}
- return BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ return CONNECTION_POLICY_FORBIDDEN;
}
private static void log(String msg) {
@@ -536,8 +540,4 @@ public final class BluetoothSap implements BluetoothProfile, AutoCloseable {
private boolean isEnabled() {
return mAdapter.isEnabled();
}
-
- private static boolean isValidDevice(BluetoothDevice device) {
- return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
- }
}
diff --git a/framework/java/android/bluetooth/BluetoothSocket.java b/framework/java/android/bluetooth/BluetoothSocket.java
index 7c2f524fa0..824dda69d4 100644
--- a/framework/java/android/bluetooth/BluetoothSocket.java
+++ b/framework/java/android/bluetooth/BluetoothSocket.java
@@ -671,7 +671,7 @@ public final class BluetoothSocket implements Closeable {
mDevice, mType, mUuid, mPort, getSecurityFlags());
} else {
mPfd =
- socketManager.connectSocketwithOffload(
+ socketManager.connectSocketWithOffload(
mDevice,
mType,
mUuid,
diff --git a/framework/java/android/bluetooth/BluetoothUtils.java b/framework/java/android/bluetooth/BluetoothUtils.java
index 67004ca889..2665af1bac 100644
--- a/framework/java/android/bluetooth/BluetoothUtils.java
+++ b/framework/java/android/bluetooth/BluetoothUtils.java
@@ -65,8 +65,8 @@ public final class BluetoothUtils {
}
}
- // Helper method to extract bytes from byte array.
- private static byte[] extractBytes(byte[] rawBytes, int start, int length) {
+ /** Helper method to extract bytes from byte array. */
+ public static byte[] extractBytes(byte[] rawBytes, int start, int length) {
int remainingLength = rawBytes.length - start;
if (remainingLength < length) {
Log.w(
@@ -429,4 +429,8 @@ public final class BluetoothUtils {
public static void logRemoteException(String tag, RemoteException ex) {
Log.w(tag, ex.toString() + ": " + inlineStackTrace());
}
+
+ static boolean isValidDevice(BluetoothDevice device) {
+ return device != null && BluetoothAdapter.checkBluetoothAddress(device.getAddress());
+ }
}
diff --git a/framework/java/android/bluetooth/BluetoothVolumeControl.java b/framework/java/android/bluetooth/BluetoothVolumeControl.java
index c5e89749e7..1cf3cedeba 100644
--- a/framework/java/android/bluetooth/BluetoothVolumeControl.java
+++ b/framework/java/android/bluetooth/BluetoothVolumeControl.java
@@ -19,6 +19,9 @@ package android.bluetooth;
import static android.Manifest.permission.BLUETOOTH_CONNECT;
import static android.Manifest.permission.BLUETOOTH_PRIVILEGED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static android.bluetooth.BluetoothUtils.callServiceIfEnabled;
import static android.bluetooth.BluetoothUtils.executeFromBinder;
@@ -376,7 +379,7 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose
@RequiresPermission(BLUETOOTH_CONNECT)
public int getConnectionState(BluetoothDevice device) {
Log.d(TAG, "getConnectionState(" + device + ")");
- int defaultValue = BluetoothProfile.STATE_DISCONNECTED;
+ int defaultValue = STATE_DISCONNECTED;
if (!isValidDevice(device)) {
return defaultValue;
@@ -634,8 +637,8 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose
Log.d(TAG, "setConnectionPolicy(" + device + ", " + connectionPolicy + ")");
boolean defaultValue = false;
if (!isValidDevice(device)
- || (connectionPolicy != BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
- && connectionPolicy != BluetoothProfile.CONNECTION_POLICY_ALLOWED)) {
+ || (connectionPolicy != CONNECTION_POLICY_FORBIDDEN
+ && connectionPolicy != CONNECTION_POLICY_ALLOWED)) {
return defaultValue;
}
return callServiceIfEnabled(
@@ -657,7 +660,7 @@ public final class BluetoothVolumeControl implements BluetoothProfile, AutoClose
@RequiresPermission(allOf = {BLUETOOTH_CONNECT, BLUETOOTH_PRIVILEGED})
public @ConnectionPolicy int getConnectionPolicy(@NonNull BluetoothDevice device) {
Log.v(TAG, "getConnectionPolicy(" + device + ")");
- int defaultValue = BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+ int defaultValue = CONNECTION_POLICY_FORBIDDEN;
if (!isValidDevice(device)) {
return defaultValue;
}
diff --git a/framework/java/android/bluetooth/le/BluetoothLeScanner.java b/framework/java/android/bluetooth/le/BluetoothLeScanner.java
index cd94688f2b..01e3f6b545 100644
--- a/framework/java/android/bluetooth/le/BluetoothLeScanner.java
+++ b/framework/java/android/bluetooth/le/BluetoothLeScanner.java
@@ -87,7 +87,6 @@ public final class BluetoothLeScanner {
private final BluetoothAdapter mBluetoothAdapter;
private final AttributionSource mAttributionSource;
-
private final Handler mHandler;
private final Map<ScanCallback, BleScanCallbackWrapper> mLeScanClients;
@@ -380,14 +379,14 @@ public final class BluetoothLeScanner {
/** Bluetooth GATT interface callbacks */
@SuppressLint("AndroidFrameworkRequiresPermission")
- private class BleScanCallbackWrapper extends IScannerCallback.Stub {
+ private final class BleScanCallbackWrapper extends IScannerCallback.Stub {
private static final int REGISTRATION_CALLBACK_TIMEOUT_MILLIS = 2000;
private final ScanCallback mScanCallback;
private final List<ScanFilter> mFilters;
private final WorkSource mWorkSource;
- private ScanSettings mSettings;
- private IBluetoothScan mBluetoothScan;
+ private final ScanSettings mSettings;
+ private final IBluetoothScan mBluetoothScan;
// mLeHandle 0: not registered
// -2: registration failed because app is scanning to frequently
@@ -395,7 +394,7 @@ public final class BluetoothLeScanner {
// > 0: registered and scan started
private int mScannerId;
- public BleScanCallbackWrapper(
+ BleScanCallbackWrapper(
IBluetoothScan bluetoothScan,
List<ScanFilter> filters,
ScanSettings settings,
@@ -410,7 +409,7 @@ public final class BluetoothLeScanner {
}
@SuppressWarnings("WaitNotInLoop") // TODO(b/314811467)
- public void startRegistration() {
+ void startRegistration() {
synchronized (this) {
// Scan stopped.
if (mScannerId == -1 || mScannerId == -2) return;
@@ -442,7 +441,7 @@ public final class BluetoothLeScanner {
}
@RequiresPermission(BLUETOOTH_SCAN)
- public void stopLeScan() {
+ void stopLeScan() {
synchronized (this) {
if (mScannerId <= 0) {
Log.e(TAG, "Error state, mLeHandle: " + mScannerId);
@@ -533,31 +532,20 @@ public final class BluetoothLeScanner {
}
;
}
- Handler handler = new Handler(Looper.getMainLooper());
- handler.post(
- new Runnable() {
- @Override
- public void run() {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "onScanResult() - handler run");
- }
- mScanCallback.onScanResult(
- ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult);
+ mHandler.post(
+ () -> {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "onScanResult() - handler run");
}
+ mScanCallback.onScanResult(
+ ScanSettings.CALLBACK_TYPE_ALL_MATCHES, scanResult);
});
}
@Override
public void onBatchScanResults(final List<ScanResult> results) {
Attributable.setAttributionSource(results, mAttributionSource);
- Handler handler = new Handler(Looper.getMainLooper());
- handler.post(
- new Runnable() {
- @Override
- public void run() {
- mScanCallback.onBatchScanResults(results);
- }
- });
+ mHandler.post(() -> mScanCallback.onBatchScanResults(results));
}
@Override
@@ -573,20 +561,11 @@ public final class BluetoothLeScanner {
return;
}
}
- Handler handler = new Handler(Looper.getMainLooper());
- handler.post(
- new Runnable() {
- @Override
- public void run() {
- if (onFound) {
- mScanCallback.onScanResult(
- ScanSettings.CALLBACK_TYPE_FIRST_MATCH, scanResult);
- } else {
- mScanCallback.onScanResult(
- ScanSettings.CALLBACK_TYPE_MATCH_LOST, scanResult);
- }
- }
- });
+ int callbackType =
+ onFound
+ ? ScanSettings.CALLBACK_TYPE_FIRST_MATCH
+ : ScanSettings.CALLBACK_TYPE_MATCH_LOST;
+ mHandler.post(() -> mScanCallback.onScanResult(callbackType, scanResult));
}
@Override
@@ -614,13 +593,7 @@ public final class BluetoothLeScanner {
@SuppressLint("AndroidFrameworkBluetoothPermission")
private void postCallbackError(final ScanCallback callback, final int errorCode) {
- mHandler.post(
- new Runnable() {
- @Override
- public void run() {
- callback.onScanFailed(errorCode);
- }
- });
+ mHandler.post(() -> callback.onScanFailed(errorCode));
}
private boolean isSettingsConfigAllowedForScan(ScanSettings settings) {
diff --git a/framework/tests/bumble/Android.bp b/framework/tests/bumble/Android.bp
index 8728910405..af28a67db2 100644
--- a/framework/tests/bumble/Android.bp
+++ b/framework/tests/bumble/Android.bp
@@ -105,11 +105,7 @@ python_binary_host {
srcs: [
"src/bumble_server.py",
],
- version: {
- py3: {
- embedded_launcher: false,
- },
- },
+ embedded_launcher: false,
libs: [
"bumble-pandora",
"bumble_services_experimental-python",
diff --git a/framework/tests/bumble/AndroidManifest.xml b/framework/tests/bumble/AndroidManifest.xml
index 93580dc27f..6f644b2d23 100644
--- a/framework/tests/bumble/AndroidManifest.xml
+++ b/framework/tests/bumble/AndroidManifest.xml
@@ -8,6 +8,7 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.LOCAL_MAC_ADDRESS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
+ <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application>
<uses-library android:name="android.test.runner" />
diff --git a/framework/tests/bumble/AndroidTest.xml b/framework/tests/bumble/AndroidTest.xml
index 482d8d3586..fca6e5463c 100644
--- a/framework/tests/bumble/AndroidTest.xml
+++ b/framework/tests/bumble/AndroidTest.xml
@@ -24,7 +24,7 @@
<option name="host-setup-command" value="adb -s $SERIAL reverse tcp:7999 tcp:7999" />
<option name="host-background-command"
- value="$EXTRA_FILE(host_testcases)/BumbleBluetoothTests/bumble_pandora_server --rootcanal-port 6211 --config $EXTRA_FILE(host_testcases)/BumbleBluetoothTests/bumble_config.json"/>
+ value="$EXTRA_FILE(host_testcases:testsdir)/BumbleBluetoothTests/bumble_pandora_server --rootcanal-port 6211 --config $EXTRA_FILE(host_testcases:testsdir)/BumbleBluetoothTests/bumble_config.json"/>
<option name="host-teardown-command" value="adb -s $SERIAL reverse --remove tcp:7999" />
</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 63acc8ded0..77dbfd3e95 100644
--- a/framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/BleOnStateTest.java
@@ -109,7 +109,7 @@ public class BleOnStateTest {
}
@Test
- public void whenScanManagerRefactorOffOrOn_scanWorks() {
+ public void whenOnlyStartScanDuringBleOnOffOrOn_scanWorks() {
advertiseWithBumble(TEST_UUID_STRING, HostProto.OwnAddressType.PUBLIC);
ScanFilter scanFilter =
@@ -129,8 +129,8 @@ public class BleOnStateTest {
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void whenScanManagerRefactorOff_canAdvertise() throws Exception {
+ @RequiresFlagsDisabled(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void whenOnlyStartScanDuringBleOnOff_canAdvertise() throws Exception {
final BluetoothLeAdvertiser bluetoothLeAdvertiser = mAdapter.getBluetoothLeAdvertiser();
AdvertiseSettings settings = new AdvertiseSettings.Builder().build();
@@ -164,8 +164,8 @@ public class BleOnStateTest {
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void whenScanManagerRefactorOn_cantAdvertise() throws Exception {
+ @RequiresFlagsEnabled(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void whenOnlyStartScanDuringBleOnOn_cantAdvertise() throws Exception {
final BluetoothLeAdvertiser bluetoothLeAdvertiser = mAdapter.getBluetoothLeAdvertiser();
AdvertiseSettings settings = new AdvertiseSettings.Builder().build();
@@ -200,8 +200,8 @@ public class BleOnStateTest {
}
@Test
- @RequiresFlagsDisabled(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void whenScanManagerRefactorOff_gattCanConnect() {
+ @RequiresFlagsDisabled(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void whenOnlyStartScanDuringBleOnOff_gattCanConnect() {
advertiseWithBumble();
BluetoothDevice device =
@@ -215,8 +215,8 @@ public class BleOnStateTest {
}
@Test
- @RequiresFlagsEnabled(Flags.FLAG_SCAN_MANAGER_REFACTOR)
- public void whenScanManagerRefactorOn_gattCantConnect() {
+ @RequiresFlagsEnabled(Flags.FLAG_ONLY_START_SCAN_DURING_BLE_ON)
+ public void whenOnlyStartScanDuringBleOnOn_gattCantConnect() {
advertiseWithBumble();
BluetoothDevice device =
diff --git a/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt b/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt
index 13ce995741..8efa65ba4e 100644
--- a/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt
+++ b/framework/tests/bumble/src/android/bluetooth/DckGattTest.kt
@@ -16,6 +16,8 @@
package android.bluetooth
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
@@ -98,14 +100,14 @@ public class DckGattTest() {
val device =
bluetoothAdapter.getRemoteLeDevice(
Utils.BUMBLE_RANDOM_ADDRESS,
- BluetoothDevice.ADDRESS_TYPE_RANDOM
+ BluetoothDevice.ADDRESS_TYPE_RANDOM,
)
val gatt = device.connectGatt(context, false, gattCallbackMock)
verify(gattCallbackMock, timeout(TIMEOUT))
.onConnectionStateChange(
eq(gatt),
eq(BluetoothGatt.GATT_SUCCESS),
- eq(BluetoothProfile.STATE_CONNECTED)
+ eq(STATE_CONNECTED),
)
advertiseContext.cancel(null)
@@ -182,7 +184,7 @@ public class DckGattTest() {
// Advertising data.
Utils.BUMBLE_RANDOM_ADDRESS,
BluetoothDevice
- .ADDRESS_TYPE_RANDOM // Specify address type as RANDOM because the device
+ .ADDRESS_TYPE_RANDOM, // Specify address type as RANDOM because the device
// advertises with this address type.
)
@@ -193,11 +195,7 @@ public class DckGattTest() {
// 5. Connect to the Bumble device and expect a successful connection callback.
var bumbleGatt = bumbleDevice.connectGatt(context, false, gattCallback)
verify(gattCallback, timeout(TIMEOUT))
- .onConnectionStateChange(
- any(),
- eq(BluetoothGatt.GATT_SUCCESS),
- eq(BluetoothProfile.STATE_CONNECTED)
- )
+ .onConnectionStateChange(any(), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED))
// 6. Discover GATT services offered by Bumble and expect successful service discovery.
bumbleGatt.discoverServices()
@@ -210,11 +208,7 @@ public class DckGattTest() {
// 8. Disconnect from the Bumble device and expect a successful disconnection callback.
bumbleGatt.disconnect()
verify(gattCallback, timeout(TIMEOUT))
- .onConnectionStateChange(
- any(),
- eq(BluetoothGatt.GATT_SUCCESS),
- eq(BluetoothProfile.STATE_DISCONNECTED)
- )
+ .onConnectionStateChange(any(), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_DISCONNECTED))
}
/*
@@ -241,7 +235,7 @@ public class DckGattTest() {
.setDeviceAddress(
TEST_ADDRESS_RANDOM_STATIC,
BluetoothDevice.ADDRESS_TYPE_RANDOM,
- Utils.BUMBLE_IRK
+ Utils.BUMBLE_IRK,
)
.build()
leScanner.startScan(listOf(scanFilter), scanSettings, scanCallbackMock)
@@ -259,11 +253,7 @@ public class DckGattTest() {
val device = scanResult.device
val gatt = device.connectGatt(context, false, gattCallbackMock)
verify(gattCallbackMock, timeout(TIMEOUT))
- .onConnectionStateChange(
- eq(gatt),
- eq(BluetoothGatt.GATT_SUCCESS),
- eq(BluetoothProfile.STATE_CONNECTED)
- )
+ .onConnectionStateChange(eq(gatt), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED))
// Stop scan on DUT after GATT connect
leScanner.stopScan(scanCallbackMock)
@@ -305,11 +295,7 @@ public class DckGattTest() {
val device = scanResult.device
val gatt = device.connectGatt(context, false, gattCallbackMock)
verify(gattCallbackMock, timeout(TIMEOUT))
- .onConnectionStateChange(
- eq(gatt),
- eq(BluetoothGatt.GATT_SUCCESS),
- eq(BluetoothProfile.STATE_CONNECTED)
- )
+ .onConnectionStateChange(eq(gatt), eq(BluetoothGatt.GATT_SUCCESS), eq(STATE_CONNECTED))
}
private fun advertiseWithBumble(withUuid: Boolean = false): GrpcContext.CancellableContext {
diff --git a/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt b/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt
index 32e09b9de7..909894612b 100644
--- a/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt
+++ b/framework/tests/bumble/src/android/bluetooth/DckTestRule.kt
@@ -17,6 +17,7 @@
package android.bluetooth
import android.app.PendingIntent
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
@@ -93,7 +94,7 @@ class DckTestRule(
fun scanWithCallback(
scanFilter: ScanFilter,
scanSettings: ScanSettings,
- coroutine: CoroutineScope = scope
+ coroutine: CoroutineScope = scope,
) =
callbackFlow {
val callback =
@@ -128,7 +129,7 @@ class DckTestRule(
fun scanWithPendingIntent(
scanFilter: ScanFilter,
scanSettings: ScanSettings,
- coroutine: CoroutineScope = scope
+ coroutine: CoroutineScope = scope,
) =
callbackFlow {
val intentFilter = IntentFilter(ACTION_DYNAMIC_RECEIVER_SCAN_RESULT)
@@ -161,7 +162,7 @@ class DckTestRule(
scanIntent,
PendingIntent.FLAG_MUTABLE or
PendingIntent.FLAG_UPDATE_CURRENT or
- PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT
+ PendingIntent.FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT,
)
leScanner.startScan(listOf(scanFilter), scanSettings, pendingIntent)
@@ -189,7 +190,7 @@ class DckTestRule(
override fun onConnectionStateChange(
gatt: BluetoothGatt,
status: Int,
- newState: Int
+ newState: Int,
) {
trySend(GattState(gatt, status, newState))
}
@@ -294,7 +295,7 @@ class DckTestRule(
trySend(
intent.getIntExtra(
BluetoothAdapter.EXTRA_STATE,
- BluetoothAdapter.ERROR
+ BluetoothAdapter.ERROR,
)
)
}
@@ -313,12 +314,10 @@ class DckTestRule(
val bumbleDevice =
bluetoothAdapter.getRemoteLeDevice(
Utils.BUMBLE_RANDOM_ADDRESS,
- BluetoothDevice.ADDRESS_TYPE_RANDOM
+ BluetoothDevice.ADDRESS_TYPE_RANDOM,
)
- withTimeout(TIMEOUT_MS) {
- connectGatt(bumbleDevice).first { it.state == BluetoothProfile.STATE_CONNECTED }
- }
+ withTimeout(TIMEOUT_MS) { connectGatt(bumbleDevice).first { it.state == STATE_CONNECTED } }
}
private fun reset() {
diff --git a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
index a6abad4e48..fa52d8c607 100644
--- a/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/GattClientTest.java
@@ -18,6 +18,7 @@ package android.bluetooth;
import static android.bluetooth.BluetoothGatt.GATT_SUCCESS;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
import static com.google.common.truth.Truth.assertThat;
@@ -225,7 +226,7 @@ public class GattClientTest {
gatt.disconnect();
inOrder.verify(gattCallback, timeout(1000))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED));
gatt.connect();
inOrder.verify(gattCallback, timeout(1000))
@@ -235,7 +236,7 @@ public class GattClientTest {
// be necessary.
gatt.disconnect();
inOrder.verify(gattCallback, timeout(1000))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED));
gatt.close();
}
@@ -362,9 +363,7 @@ public class GattClientTest {
verify(gattCallback, timeout(35000))
.onConnectionStateChange(
- any(),
- eq(BluetoothGatt.GATT_CONNECTION_TIMEOUT),
- eq(BluetoothProfile.STATE_DISCONNECTED));
+ any(), eq(BluetoothGatt.GATT_CONNECTION_TIMEOUT), eq(STATE_DISCONNECTED));
}
@Test
@@ -562,7 +561,7 @@ public class GattClientTest {
private void disconnectAndWaitDisconnection(
BluetoothGatt gatt, BluetoothGattCallback callback) {
- final int state = BluetoothProfile.STATE_DISCONNECTED;
+ final int state = STATE_DISCONNECTED;
gatt.disconnect();
verify(callback, timeout(1000)).onConnectionStateChange(eq(gatt), anyInt(), eq(state));
@@ -741,8 +740,7 @@ public class GattClientTest {
gatt.disconnect();
inOrder.verify(gattCallback, timeout(1000))
- .onConnectionStateChange(
- any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED));
gatt.connect();
inOrder.verify(gattCallback, timeout(1000))
@@ -750,8 +748,7 @@ public class GattClientTest {
gatt.disconnect();
inOrder.verify(gattCallback, timeout(1000))
- .onConnectionStateChange(
- any(), anyInt(), eq(BluetoothProfile.STATE_DISCONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_DISCONNECTED));
}
} finally {
for (BluetoothGatt gatt : gatts) {
diff --git a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java
index 8991637b2a..be7e41609a 100644
--- a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithScanTest.java
@@ -16,6 +16,8 @@
package android.bluetooth;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
@@ -91,7 +93,7 @@ public class GattServerConnectWithScanTest {
gattServer.connect(device, false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -118,7 +120,7 @@ public class GattServerConnectWithScanTest {
gattServer.connect(device, false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -142,7 +144,7 @@ public class GattServerConnectWithScanTest {
try {
gattServer.connect(mBumble.getRemoteDevice(), false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -166,7 +168,7 @@ public class GattServerConnectWithScanTest {
try {
gattServer.connect(mBumble.getRemoteDevice(), false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
diff --git a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java
index 902f3c59f5..739c026333 100644
--- a/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/GattServerConnectWithoutScanTest.java
@@ -16,6 +16,8 @@
package android.bluetooth;
+import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
+
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.any;
@@ -78,7 +80,7 @@ public class GattServerConnectWithoutScanTest {
gattServer.connect(device, false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -104,7 +106,7 @@ public class GattServerConnectWithoutScanTest {
gattServer.connect(device, false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -126,7 +128,7 @@ public class GattServerConnectWithoutScanTest {
try {
gattServer.connect(mBumble.getRemoteDevice(), false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
@@ -148,7 +150,7 @@ public class GattServerConnectWithoutScanTest {
try {
gattServer.connect(mBumble.getRemoteDevice(), false);
verify(mockGattServerCallback, timeout(TIMEOUT_GATT_CONNECTION_MS))
- .onConnectionStateChange(any(), anyInt(), eq(BluetoothProfile.STATE_CONNECTED));
+ .onConnectionStateChange(any(), anyInt(), eq(STATE_CONNECTED));
} finally {
gattServer.close();
}
diff --git a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt
index 2c165d9d53..bf382ba159 100644
--- a/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt
+++ b/framework/tests/bumble/src/android/bluetooth/RfcommTest.kt
@@ -17,6 +17,7 @@ package android.bluetooth
import android.Manifest
import android.annotation.SuppressLint
+import android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN
import android.bluetooth.test_utils.EnableBluetoothRule
import android.content.BroadcastReceiver
import android.content.Context
@@ -25,6 +26,7 @@ import android.content.IntentFilter
import android.platform.test.annotations.RequiresFlagsEnabled
import android.platform.test.flag.junit.CheckFlagsRule
import android.platform.test.flag.junit.DeviceFlagsValueProvider
+import android.provider.Settings
import android.util.Log
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
@@ -48,6 +50,7 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.withTimeout
import org.junit.After
+import org.junit.Assert.assertThrows
import org.junit.Before
import org.junit.Ignore
import org.junit.Rule
@@ -105,8 +108,14 @@ class RfcommTest {
private val mLocalAddress: ByteString =
ByteString.copyFrom("DA:4C:10:DE:17:00".hexToByteArray(bdAddrFormat))
+ private val BLE_SCAN_ALWAYS_AVAILABLE = "ble_scan_always_enabled"
+
init {
- val intentFilter = IntentFilter(BluetoothDevice.ACTION_PAIRING_REQUEST)
+ val intentFilter =
+ IntentFilter().apply {
+ addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
+ addAction(BluetoothAdapter.ACTION_BLE_STATE_CHANGED)
+ }
mFlow = intentFlow(mContext, intentFilter, mScope).shareIn(mScope, SharingStarted.Eagerly)
}
@@ -123,21 +132,12 @@ class RfcommTest {
mHost = Host(mContext)
val bluetoothA2dp = getProfileProxy(mContext, BluetoothProfile.A2DP) as BluetoothA2dp
- bluetoothA2dp.setConnectionPolicy(
- mRemoteDevice,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- )
+ bluetoothA2dp.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN)
val bluetoothHfp = getProfileProxy(mContext, BluetoothProfile.HEADSET) as BluetoothHeadset
- bluetoothHfp.setConnectionPolicy(
- mRemoteDevice,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- )
+ bluetoothHfp.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN)
val bluetoothHidHost =
getProfileProxy(mContext, BluetoothProfile.HID_HOST) as BluetoothHidHost
- bluetoothHidHost.setConnectionPolicy(
- mRemoteDevice,
- BluetoothProfile.CONNECTION_POLICY_FORBIDDEN,
- )
+ bluetoothHidHost.setConnectionPolicy(mRemoteDevice, CONNECTION_POLICY_FORBIDDEN)
if (mRemoteDevice.isConnected) {
mHost.disconnectAndVerify(mRemoteDevice)
}
@@ -150,6 +150,10 @@ class RfcommTest {
*/
@After
fun tearDown() {
+ if (Settings.Global.getInt(mContext.contentResolver, BLE_SCAN_ALWAYS_AVAILABLE, 0) == 1) {
+ // Recover BLE Scan always available setting
+ Settings.Global.putInt(mContext.contentResolver, BLE_SCAN_ALWAYS_AVAILABLE, 0)
+ }
if (mAdapter.bondedDevices.contains(mRemoteDevice)) {
mHost.removeBondAndVerify(mRemoteDevice)
}
@@ -615,6 +619,73 @@ class RfcommTest {
}
}
+ /*
+ Test Steps:
+ 1. Create an Rfcomm insecure socket
+ 2. Verify that Rfcomm socket is connected
+ 3. Disable Bluetooth to BLE_ON mode
+ 4. Verify remote devices disconnected based on successful data transmission
+ */
+ @Test
+ @RequiresFlagsEnabled(Flags.FLAG_DISCONNECT_ACLS_BY_BREDR_DISABLED)
+ fun clientRfcommDeviceDisconnectedOnBleOnMode() {
+ // Enable BLE_ON mode if disable Bluetooth
+ Settings.Global.putInt(mContext.contentResolver, BLE_SCAN_ALWAYS_AVAILABLE, 1)
+ // Must wait for BLE_SCAN_ALWAYS_AVAILABLE to be enabled and then enable BLE_ON mode
+ for (i in 1..10) {
+ if (mAdapter.isBleScanAlwaysAvailable()) {
+ // Enable BLE_ON mode
+ mAdapter.enableBLE()
+ break
+ }
+ Log.d(TAG, "Ble scan not yet available... Sleeping 50 ms $i/10")
+ Thread.sleep(50)
+ }
+
+ updateSecurityConfig()
+
+ startServer { serverId ->
+ val (insecureSocket, connection) = createConnectAcceptSocketUsingSettings(serverId)
+
+ // Verify that Rfcomm Socket is connected
+ Truth.assertThat(insecureSocket.isConnected).isTrue()
+
+ // disable Bluetooth to BLE_ON mode
+ mAdapter.disable()
+ waitingBluetoothLeStates(BluetoothAdapter.STATE_BLE_ON)
+
+ // 1. In Bluetooth disabled state, under BLE_ON mode, it's impossible to determine the
+ // device's connection status.
+ // 2. Determine whether the Rfcomm Socket or ACL link has been disconnected based on
+ // successful data transmission.
+ val data: ByteArray =
+ "Test data for clientRfcommDeviceDisconnectedOnBleOnMode".toByteArray()
+ val socketOs = insecureSocket.outputStream
+
+ // Verify that Rfcomm Socket is disconnected
+ assertThrows(IOException::class.java) { socketOs.write(data) }
+
+ // Validate that the test run while Bluetooth stayed in BLE_ON all along
+ Truth.assertThat(mAdapter.leState).isEqualTo(BluetoothAdapter.STATE_BLE_ON)
+ }
+ }
+
+ // helper to wait for Bluetooth BLE state change
+ private fun waitingBluetoothLeStates(state: Int) {
+ runBlocking(mScope.coroutineContext) {
+ withTimeout(STATE_CHANGE_TIMEOUT.toMillis()) {
+ // wait for Bluetooth states
+ launch {
+ Log.i(TAG, "Waiting for waitingBluetoothLeStates: " + state)
+ mFlow
+ .filter { it.action == BluetoothAdapter.ACTION_BLE_STATE_CHANGED }
+ .filter { it.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == state }
+ .first()
+ }
+ }
+ }
+ }
+
// helper to update the security config for remote bumble device
private fun updateSecurityConfig(
isEncrypted: Boolean = false,
@@ -828,6 +899,7 @@ class RfcommTest {
private val TAG = RfcommTest::class.java.getSimpleName()
private val GRPC_TIMEOUT = Duration.ofSeconds(10)
private val CONNECT_TIMEOUT = Duration.ofSeconds(7)
+ private val STATE_CHANGE_TIMEOUT = Duration.ofSeconds(5)
private const val TEST_UUID = "2ac5d8f1-f58d-48ac-a16b-cdeba0892d65"
private const val SERIAL_PORT_UUID = "00001101-0000-1000-8000-00805F9B34FB"
private const val TEST_SERVER_NAME = "RFCOMM Server"
diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java
index 26deb09327..38527362ba 100644
--- a/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHeadTrackerTest.java
@@ -18,6 +18,8 @@ package android.bluetooth.hid;
import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR;
import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -275,7 +277,7 @@ public class HidHeadTrackerTest {
* <ol>
* <li>Bumble has Android Headtracker Service
* <li>Bumble does not support HID and HOGP
- * <li>Bummble is connectable over LE
+ * <li>Bumble is connectable over LE
* </ol>
*
* <p>Steps:
@@ -315,20 +317,14 @@ public class HidHeadTrackerTest {
verifyConnectionState(mBumbleDevice, equalTo(TRANSPORT_LE), equalTo(STATE_CONNECTING));
verifyConnectionState(mBumbleDevice, equalTo(TRANSPORT_LE), equalTo(STATE_CONNECTED));
- // Disable a2dp and HFP connetcion policy
+ // Disable a2dp and HFP connection policy
- if (mA2dpService.getConnectionPolicy(mBumbleDevice)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- mA2dpService.setConnectionPolicy(
- mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (mA2dpService.getConnectionPolicy(mBumbleDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(mA2dpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
- if (mHfpService.getConnectionPolicy(mBumbleDevice)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- mHfpService.setConnectionPolicy(
- mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (mHfpService.getConnectionPolicy(mBumbleDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(mHfpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
@@ -368,7 +364,7 @@ public class HidHeadTrackerTest {
* <ol>
* <li>Bumble has Android Headtracker Service
* <li>Bumble supports only HID but not HOGP
- * <li>Bummble is connectable over LE
+ * <li>Bumble is connectable over LE
* </ol>
*
* <p>Steps:
diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java
index be8ca125cd..fb89c738ad 100644
--- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostDualModeTest.java
@@ -18,6 +18,8 @@ package android.bluetooth.hid;
import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR;
import static android.bluetooth.BluetoothDevice.TRANSPORT_LE;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -310,17 +312,12 @@ public class HidHostDualModeTest {
hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice),
hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED));
- if (a2dpService.getConnectionPolicy(mDevice)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- a2dpService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (a2dpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(a2dpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
- if (hfpService.getConnectionPolicy(mDevice) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- hfpService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (hfpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(hfpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
diff --git a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java
index 6a94d6a3de..b92a8d17ba 100644
--- a/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/hid/HidHostTest.java
@@ -17,6 +17,8 @@
package android.bluetooth.hid;
import static android.bluetooth.BluetoothDevice.TRANSPORT_BREDR;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_ALLOWED;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTED;
import static android.bluetooth.BluetoothProfile.STATE_CONNECTING;
import static android.bluetooth.BluetoothProfile.STATE_DISCONNECTED;
@@ -313,17 +315,12 @@ public class HidHostTest {
hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice),
hasExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.BOND_BONDED));
- if (a2dpService.getConnectionPolicy(mDevice)
- == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- a2dpService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (a2dpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(a2dpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
- if (hfpService.getConnectionPolicy(mDevice) == BluetoothProfile.CONNECTION_POLICY_ALLOWED) {
- assertThat(
- hfpService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ if (hfpService.getConnectionPolicy(mDevice) == CONNECTION_POLICY_ALLOWED) {
+ assertThat(hfpService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
}
verifyConnectionState(mDevice, equalTo(TRANSPORT_BREDR), equalTo(STATE_CONNECTING));
@@ -380,8 +377,7 @@ public class HidHostTest {
@Test
public void hidReconnectionWhenConnectionPolicyChangeTest() throws Exception {
- assertThat(mHidService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
mHidBlockingStub.disconnectHost(Empty.getDefaultInstance());
verifyProfileDisconnectionState();
@@ -392,17 +388,11 @@ public class HidHostTest {
mHidBlockingStub.disconnectHost(Empty.getDefaultInstance());
verifyProfileDisconnectionState();
- assertThat(
- mHidService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
- .isTrue();
+ assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)).isTrue();
reconnectionFromRemoteAndVerifyDisconnectedState();
- assertThat(
- mHidService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_ALLOWED))
- .isTrue();
+ assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_ALLOWED)).isTrue();
verifyIntentReceived(
hasAction(BluetoothHidHost.ACTION_CONNECTION_STATE_CHANGED),
hasExtra(BluetoothDevice.EXTRA_DEVICE, mDevice),
@@ -435,8 +425,7 @@ public class HidHostTest {
@Test
public void hidReconnectionAfterBTrestartWithConnectionPolicyAllowedTest() throws Exception {
- assertThat(mHidService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
bluetoothRestart();
@@ -460,13 +449,9 @@ public class HidHostTest {
public void hidReconnectionAfterBTrestartWithConnectionPolicyiDisallowedTest()
throws Exception {
- assertThat(mHidService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
- assertThat(
- mHidService.setConnectionPolicy(
- mDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
- .isTrue();
+ assertThat(mHidService.setConnectionPolicy(mDevice, CONNECTION_POLICY_FORBIDDEN)).isTrue();
bluetoothRestart();
reconnectionFromRemoteAndVerifyDisconnectedState();
@@ -486,8 +471,7 @@ public class HidHostTest {
@Test
public void hidReconnectionAfterDeviceRemovedTest() throws Exception {
- assertThat(mHidService.getConnectionPolicy(mDevice))
- .isEqualTo(BluetoothProfile.CONNECTION_POLICY_ALLOWED);
+ assertThat(mHidService.getConnectionPolicy(mDevice)).isEqualTo(CONNECTION_POLICY_ALLOWED);
mHidBlockingStub.disconnectHost(Empty.getDefaultInstance());
verifyProfileDisconnectionState();
diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java
index ee8e54df36..bdfa42dd65 100644
--- a/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/pairing/OobPairingTest.java
@@ -275,7 +275,7 @@ public class OobPairingTest {
* </ol>
*/
@Test
- public void createBondByRemoteDevicWithLocalOob() throws Exception {
+ public void createBondByRemoteDeviceWithLocalOob() throws Exception {
IntentReceiver intentReceiver =
new IntentReceiver.Builder(mContext, BluetoothDevice.ACTION_BOND_STATE_CHANGED)
.setIntentListener(intentListener)
diff --git a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java
index c2fb973fba..c8f9388da0 100644
--- a/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java
+++ b/framework/tests/bumble/src/android/bluetooth/pairing/PairingTest.java
@@ -16,6 +16,8 @@
package android.bluetooth.pairing;
+import static android.bluetooth.BluetoothProfile.CONNECTION_POLICY_FORBIDDEN;
+
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra;
@@ -786,13 +788,9 @@ public class PairingTest {
.build();
// Disable all profiles other than A2DP as profile connections take too long
- assertThat(
- mHfpService.setConnectionPolicy(
- mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ assertThat(mHfpService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
- assertThat(
- mHidService.setConnectionPolicy(
- mBumbleDevice, BluetoothProfile.CONNECTION_POLICY_FORBIDDEN))
+ assertThat(mHidService.setConnectionPolicy(mBumbleDevice, CONNECTION_POLICY_FORBIDDEN))
.isTrue();
testStep_BondBredr(intentReceiver);
diff --git a/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt b/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt
index c3e90213f3..145993ec1a 100644
--- a/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt
+++ b/framework/tests/bumble/src/android/bluetooth/sockets/lecoc/DckL2capTest.kt
@@ -17,6 +17,8 @@
package android.bluetooth
import android.Manifest
+import android.bluetooth.BluetoothProfile.STATE_CONNECTED
+import android.bluetooth.BluetoothProfile.STATE_DISCONNECTED
import android.bluetooth.test_utils.EnableBluetoothRule
import android.content.Context
import android.platform.test.annotations.RequiresFlagsEnabled
@@ -53,6 +55,7 @@ import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import pandora.HostProto.Connection
+import pandora.l2cap.L2CAPProto.Channel
import pandora.l2cap.L2CAPProto.ConnectRequest
import pandora.l2cap.L2CAPProto.ConnectResponse
import pandora.l2cap.L2CAPProto.CreditBasedChannelRequest
@@ -75,7 +78,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
@@ -103,6 +106,12 @@ public class DckL2capTest() : Closeable {
/** Wrapper for [BluetoothGatt] along with its [state] and [status] */
data class GattState(val gatt: BluetoothGatt, val status: Int, val state: Int)
+ data class SocketServerDetails(
+ val listenSocket: BluetoothServerSocket,
+ val bluetoothSocket: BluetoothSocket,
+ val channel: Channel,
+ )
+
override fun close() {
scope.cancel("Cancelling test scope")
}
@@ -140,112 +149,207 @@ public class DckL2capTest() : Closeable {
gatt.close()
}
openedGatts.clear()
+ host.close()
}
@Test
@VirtualOnly
- fun testSend() {
- Log.d(TAG, "testSend")
- val remoteDevice =
- bluetoothAdapter.getRemoteLeDevice(
- Utils.BUMBLE_RANDOM_ADDRESS,
- BluetoothDevice.ADDRESS_TYPE_RANDOM,
- )
+ /**
+ * Test:
+ * - Create L2CAP server on Bumble (DCK L2cap Server)
+ * - create Insecure Client Bluetooth Socket & initiate connection
+ * - Ensure socket is connected
+ */
+ fun testConnectInsecure() {
+ Log.d(TAG, "testConnectInsecure")
+ val (socket, channel) = clientSocketConnectUtil(false)
+ Log.d(TAG, "testConnectInsecure: done")
+ }
- Log.d(TAG, "testSend: Connect L2CAP")
- val bluetoothSocket = createSocket(dckSpsm, remoteDevice)
- runBlocking {
- val waitFlow = flow { emit(waitConnection(dckSpsm, remoteDevice)) }
- val connectJob =
- scope.launch {
- // give some time for Bumble to host the socket server
- Thread.sleep(200)
- bluetoothSocket.connect()
- Log.d(TAG, "testSend: Bluetooth socket connected")
- }
- connectionResponse = waitFlow.first()
- // Wait for the connection to complete
- connectJob.join()
- }
- assertThat(connectionResponse).isNotNull()
- assertThat(connectionResponse.hasChannel()).isTrue()
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create L2CAP server on Bumble (DCK L2cap Server)
+ * - create insecure Client Bluetooth Socket & initiate connection on phone
+ * - Ensure socket is connected
+ * - Initiate disconnection from phone side
+ */
+ fun testConnectInsecureClientLocalDisconnect() {
+ Log.d(TAG, "testConnectInsecureClientLocalDisconnect")
+ val (bluetoothSocket, channel) = clientSocketConnectUtil(false)
+
+ assertThat((bluetoothSocket).isConnected()).isTrue()
+ Log.d(TAG, "testConnectInsecureClientLocalDisconnect: close/disconnect")
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
+ Log.d(TAG, "testConnectInsecureClientLocalDisconnect: done")
+ }
- val channel = connectionResponse.channel
- val sampleData = "cafe-baguette".toByteArray()
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create insecure L2CAP Socket server on Phone
+ * - Use Bumble as client and trigger connection to L2cap server on Phone
+ * - Ensure connection is established
+ */
+ fun testAcceptInsecure() {
+ Log.d(TAG, "testAcceptInsecure: Connect L2CAP")
+ val (l2capServer, bluetoothSocket, channel) =
+ l2capServerOnPhoneAndConnectionFromBumbleUtil(false)
+ assertThat((bluetoothSocket)?.isConnected()).isTrue()
- val receiveObserver = StreamObserverSpliterator<ReceiveResponse>()
- mBumble
- .l2cap()
- .receive(ReceiveRequest.newBuilder().setChannel(channel).build(), receiveObserver)
+ bluetoothSocket.close()
+ l2capServer.close()
+ Log.d(TAG, "testAcceptInsecure: done")
+ }
- Log.d(TAG, "testSend: Send data from Android to Bumble")
- val outputStream = bluetoothSocket.outputStream
- outputStream.write(sampleData)
- outputStream.flush()
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create insecure L2CAP Socket server on Phone
+ * - Use Bumble as client and trigger connection to L2cap server on Phone
+ * - Ensure connection is established
+ * - trigger disconnection by closing the socket handle from Phone side
+ * - Ensure L2cap connection is disconnected
+ */
+ fun testAcceptInsecureLocalDisconnect() {
+ Log.d(TAG, "testAcceptInsecureLocalDisconnect: Connect L2CAP")
+ val (l2capServer, bluetoothSocket, channel) =
+ l2capServerOnPhoneAndConnectionFromBumbleUtil(false)
+ Log.d(TAG, "testAcceptInsecureLocalDisconnect: close/disconnect")
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket)?.isConnected()).isFalse()
+ Log.d(TAG, "testAcceptInsecureLocalDisconnect: done")
+ }
- Log.d(TAG, "testSend: waitReceive data on Bumble")
- val receiveData = receiveObserver.iterator().next()
- assertThat(receiveData.data.toByteArray()).isEqualTo(sampleData)
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create L2CAP Socket server on Bumble (DCK server)
+ * - create insecure l2cap client and connect to l2cap on Bumble server
+ * - Ensure connection is established
+ * - Send sample data from Phone to bumble
+ * - ensure the Data received on Bumble side as expected
+ * - disconnect the socket by invoking close
+ * - Ensure L2cap connection is disconnected
+ */
+ fun testSendOverInsecureSocketAsClient() {
+ Log.d(TAG, "testSendOverInsecureSocketAsClient")
+ val (bluetoothSocket, channel) = clientSocketConnectUtil(false)
+
+ assertThat((bluetoothSocket).isConnected()).isTrue()
+ Log.d(TAG, "testSendOverInsecureSocketAsClient: close/disconnect")
+
+ sendDataFromPhoneToBumbleAndVerifyUtil(bluetoothSocket, channel)
+ // disconnect socket from local
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
- bluetoothSocket.close()
- Log.d(TAG, "testSend: waitDisconnection")
- val waitDisconnectionRequest =
- WaitDisconnectionRequest.newBuilder().setChannel(channel).build()
- val disconnectionResponse =
- mBumble.l2capBlocking().waitDisconnection(waitDisconnectionRequest)
- assertThat(disconnectionResponse.hasSuccess()).isTrue()
- Log.d(TAG, "testSend: done")
+ bluetoothSocket?.close()
+ Log.d(TAG, "testSendOverInsecureSocketAsClient: done")
}
@Test
@VirtualOnly
- fun testReceive() {
- Log.d(TAG, "testReceive: Connect L2CAP")
- var bluetoothSocket: BluetoothSocket?
- val l2capServer = bluetoothAdapter.listenUsingInsecureL2capChannel()
- val socketFlow = flow { emit(l2capServer.accept()) }
- val connectResponse = createAndConnectL2capChannelWithBumble(l2capServer.psm)
- runBlocking {
- bluetoothSocket = socketFlow.first()
- assertThat(connectResponse.hasChannel()).isTrue()
- }
+ /**
+ * Test:
+ * - Create L2CAP Socket server on Bumble (DCK server)
+ * - create insecure l2cap client and connect to l2cap on Bumble server
+ * - Ensure connection is established
+ * - Send sample data from Bumble to Phone
+ * - ensure the Data received on Phone side as expected
+ * - disconnect the socket by invoking close
+ * - Ensure L2cap connection is disconnected
+ */
+ fun testReceiveOverInsecureSocketAsClient() {
+ Log.d(TAG, "testReceiveOverInsecureSocketAsClient")
+ val (bluetoothSocket, channel) = clientSocketConnectUtil(false)
+
+ assertThat((bluetoothSocket).isConnected()).isTrue()
+ Log.d(TAG, "testReceiveOverInsecureSocketAsClient: close/disconnect")
+
+ sendDataFromBumbleToPhoneAndVerifyUtil(bluetoothSocket, channel)
+ // disconnect socket from local
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
- val inputStream = bluetoothSocket!!.inputStream
- val sampleData: ByteString = ByteString.copyFromUtf8("cafe-baguette")
- val buffer = ByteArray(sampleData.size())
+ bluetoothSocket?.close()
+ Log.d(TAG, "testReceiveOverInsecureSocketAsClient: done")
+ }
- val sendRequest =
- SendRequest.newBuilder().setChannel(connectResponse.channel).setData(sampleData).build()
- Log.d(TAG, "testReceive: Send data from Bumble to Android")
- mBumble.l2capBlocking().send(sendRequest)
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create insecure L2CAP Socket server on Phone
+ * - Use Bumble as client nd trigger connection to L2cap server on Phone
+ * - Ensure connection is established
+ * - Send sample data from Phone to Bumble
+ * - Ensure data is received on Bumble side as expected
+ * - close the socket connection from phone
+ * - Ensure L2cap connection is disconnected
+ */
+ fun testSendOverInsecureSocketAsServer() {
+ Log.d(TAG, "testReceiveOverInsecureSocketAsServer: Connect L2CAP")
+ val (l2capServer, bluetoothSocket, channel) =
+ l2capServerOnPhoneAndConnectionFromBumbleUtil(false)
+
+ sendDataFromPhoneToBumbleAndVerifyUtil(bluetoothSocket, channel)
+ // disconnect from local
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
- Log.d(TAG, "testReceive: Receive data on Android")
- val read = inputStream.read(buffer)
- assertThat(ByteString.copyFrom(buffer).substring(0, read)).isEqualTo(sampleData)
+ bluetoothSocket?.close()
+ Log.d(TAG, "testReceiveOverInsecureSocketAsServer: done")
+ }
+
+ @Test
+ @VirtualOnly
+ /**
+ * Test:
+ * - Create insecure L2CAP Socket server on Phone
+ * - Use Bumble as client nd trigger connection to L2cap server on Phone
+ * - Ensure connection is established
+ * - Send sample data from Bumble to phone
+ * - Ensure data is received on phone side as expected
+ * - close the socket connection from phone
+ * - Ensure L2cap connection is disconnected
+ */
+ fun testReceiveOverInsecureSocketAsServer() {
+ Log.d(TAG, "testReceiveOverInsecureSocketAsServer: Connect L2CAP")
+ val (l2capServer, bluetoothSocket, channel) =
+ l2capServerOnPhoneAndConnectionFromBumbleUtil(false)
+
+ sendDataFromBumbleToPhoneAndVerifyUtil(bluetoothSocket, channel)
+ // disconnect from local
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
- Log.d(TAG, "testReceive: disconnect")
- val disconnectRequest =
- DisconnectRequest.newBuilder().setChannel(connectResponse.channel).build()
- val disconnectResponse = mBumble.l2capBlocking().disconnect(disconnectRequest)
- assertThat(disconnectResponse.hasSuccess()).isTrue()
- inputStream.close()
bluetoothSocket?.close()
- l2capServer.close()
- Log.d(TAG, "testReceive: done")
+ Log.d(TAG, "testReceiveOverInsecureSocketAsServer: done")
}
@Test
@VirtualOnly
+ /**
+ * Test:
+ * - Create insecure L2CAP Socket server on Phone
+ * - Use Bumble as client nd trigger connection to L2cap server on Phone
+ * - Ensure connection is established
+ * - Start reading on phone side
+ * - Trigger disconnect from Bumble side
+ * - Ensure read() on returns -1
+ * - close the socket connection from phone
+ * - Ensure L2cap connection is disconnected and Socket state is disconnected
+ */
fun testReadReturnOnRemoteSocketDisconnect() {
- Log.d(TAG, "testReadReturnonSocketDisconnect: Connect L2CAP")
- var bluetoothSocket: BluetoothSocket?
- val l2capServer = bluetoothAdapter.listenUsingInsecureL2capChannel()
- val socketFlow = flow { emit(l2capServer.accept()) }
- val connectResponse = createAndConnectL2capChannelWithBumble(l2capServer.psm)
- runBlocking {
- bluetoothSocket = socketFlow.first()
- assertThat(connectResponse.hasChannel()).isTrue()
- }
+ Log.d(TAG, "testReadReturnOnRemoteSocketDisconnect: Connect L2CAP")
+ val (l2capServer, bluetoothSocket, channel) =
+ l2capServerOnPhoneAndConnectionFromBumbleUtil(false)
val inputStream = bluetoothSocket!!.inputStream
@@ -267,12 +371,10 @@ public class DckL2capTest() : Closeable {
assertThat(bluetoothSocket!!.isConnected()).isTrue()
// read() would be blocking till underlying l2cap is disconnected
- Thread.sleep(1000 * 10)
+ Thread.sleep(1000 * 2)
Log.d(TAG, "testReadReturnOnRemoteSocketDisconnect: disconnect after 10 secs")
- val disconnectRequest =
- DisconnectRequest.newBuilder().setChannel(connectResponse.channel).build()
- val disconnectResponse = mBumble.l2capBlocking().disconnect(disconnectRequest)
- assertThat(disconnectResponse.hasSuccess()).isTrue()
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel, true)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
inputStream.close()
bluetoothSocket?.close()
l2capServer.close()
@@ -281,8 +383,20 @@ public class DckL2capTest() : Closeable {
@Test
@RequiresFlagsEnabled(Flags.FLAG_SOCKET_SETTINGS_API)
- fun testSendOverEncryptedOnlySocket() {
- Log.d(TAG, "testSendOverEncryptedOnlySocket")
+ /**
+ * Test:
+ * - Create Bond between Phone and Bumble (Just works)
+ * - Create L2cap Server on Bumble side (DCK server) and wait for connection
+ * - Create Encrypt Only socket using BluetoothSocketSettings interface
+ * - trigger connection from client socket on phone to l2cap server on Bumble
+ * - Ensure connection is established
+ * - Send sample data from phone to bumble & ensure It is received on bumble side as expected
+ * - close the connection
+ * - Ensure L2cap connection is disconnected and Socket state is disconnected
+ * - remote bonding
+ */
+ fun testSendOverEncryptedOnlySocketAsClient() {
+ Log.d(TAG, "testSendOverEncryptedOnlySocketAsClient")
val remoteDevice =
bluetoothAdapter.getRemoteLeDevice(
Utils.BUMBLE_RANDOM_ADDRESS,
@@ -292,8 +406,66 @@ public class DckL2capTest() : Closeable {
host.createBondAndVerify(remoteDevice)
Log.d(TAG, "testSendOverEncryptedOnlySocket: Connect L2CAP")
+ val (bluetoothSocket, channel) = clientSocketConnectUtilUsingSocketSettings(false, true)
+
+ Log.d(TAG, "testSendOverEncryptedOnlySocket: send data from phone to bumble")
+ sendDataFromPhoneToBumbleAndVerifyUtil(bluetoothSocket, channel)
+
+ // disconnect from local
+ disconnectSocketAndWaitForDisconnectUtil(bluetoothSocket, channel)
+ assertThat((bluetoothSocket).isConnected()).isFalse()
+
+ host.removeBondAndVerify(remoteDevice)
+ Log.d(TAG, "testSendOverEncryptedOnlySocket: done")
+ }
+
+ // Utility functions
+ private fun clientSocketConnectUtil(isSecure: Boolean = false): Pair<BluetoothSocket, Channel> {
+ val remoteDevice =
+ bluetoothAdapter.getRemoteLeDevice(
+ Utils.BUMBLE_RANDOM_ADDRESS,
+ BluetoothDevice.ADDRESS_TYPE_RANDOM,
+ )
+ Log.d(TAG, "clientConnect: Connect L2CAP")
+ val bluetoothSocket = createSocket(dckSpsm, remoteDevice, isSecure)
+ runBlocking {
+ val waitFlow = flow { emit(waitConnection(dckSpsm, remoteDevice)) }
+ val connectJob =
+ scope.launch {
+ // give some time for Bumble to host the socket server
+ Thread.sleep(200)
+ bluetoothSocket.connect()
+ Log.d(TAG, "clientConnect: Bluetooth socket connected")
+ }
+ connectionResponse = waitFlow.first()
+ // Wait for the connection to complete
+ connectJob.join()
+ }
+ assertThat(connectionResponse).isNotNull()
+ assertThat(connectionResponse.hasChannel()).isTrue()
+ assertThat((bluetoothSocket).isConnected()).isTrue()
+
+ val channel = connectionResponse.channel
+ return Pair(bluetoothSocket, channel)
+ }
+
+ private fun clientSocketConnectUtilUsingSocketSettings(
+ isAuthenticated: Boolean = false,
+ isEncrypted: Boolean = false,
+ ): Pair<BluetoothSocket, Channel> {
+ val remoteDevice =
+ bluetoothAdapter.getRemoteLeDevice(
+ Utils.BUMBLE_RANDOM_ADDRESS,
+ BluetoothDevice.ADDRESS_TYPE_RANDOM,
+ )
+ Log.d(TAG, "clientConnect: Connect L2CAP")
val bluetoothSocket =
- createClientSocketUsingSocketSettings(dckSpsm, remoteDevice, true, false)
+ createClientSocketUsingSocketSettings(
+ dckSpsm,
+ remoteDevice,
+ isEncrypted,
+ isAuthenticated,
+ )
runBlocking {
val waitFlow = flow { emit(waitConnection(dckSpsm, remoteDevice)) }
val connectJob =
@@ -301,7 +473,7 @@ public class DckL2capTest() : Closeable {
// give some time for Bumble to host the socket server
Thread.sleep(200)
bluetoothSocket.connect()
- Log.d(TAG, "testSendOverEncryptedOnlySocket: Bluetooth socket connected")
+ Log.d(TAG, "clientConnect: Bluetooth socket connected")
}
connectionResponse = waitFlow.first()
// Wait for the connection to complete
@@ -309,8 +481,65 @@ public class DckL2capTest() : Closeable {
}
assertThat(connectionResponse).isNotNull()
assertThat(connectionResponse.hasChannel()).isTrue()
+ assertThat((bluetoothSocket).isConnected()).isTrue()
val channel = connectionResponse.channel
+ return Pair(bluetoothSocket, channel)
+ }
+
+ private fun disconnectSocketAndWaitForDisconnectUtil(
+ bluetoothSocket: BluetoothSocket,
+ channel: Channel,
+ isRemote: Boolean = false,
+ ) {
+ if (isRemote == false) {
+ bluetoothSocket.close()
+ } else {
+ val disconnectRequest = DisconnectRequest.newBuilder().setChannel(channel).build()
+ val disconnectResponse = mBumble.l2capBlocking().disconnect(disconnectRequest)
+ assertThat(disconnectResponse.hasSuccess()).isTrue()
+ }
+ Log.d(TAG, "disconnectSocketAndWaitForDisconnectUtil: waitDisconnection")
+ val waitDisconnectionRequest =
+ WaitDisconnectionRequest.newBuilder().setChannel(channel).build()
+ val disconnectionResponse =
+ mBumble.l2capBlocking().waitDisconnection(waitDisconnectionRequest)
+ assertThat(disconnectionResponse.hasSuccess()).isTrue()
+ }
+
+ private fun tearDownServerSocketAndWaitForDisconnectUtil(
+ l2capServer: BluetoothServerSocket,
+ channel: Channel,
+ ) {
+ l2capServer.close()
+ Log.d(TAG, "tearDownServerSocketAndWaitForDisconnectUtil: waitDisconnection")
+ val waitDisconnectionRequest =
+ WaitDisconnectionRequest.newBuilder().setChannel(channel).build()
+ val disconnectionResponse =
+ mBumble.l2capBlocking().waitDisconnection(waitDisconnectionRequest)
+ assertThat(disconnectionResponse.hasSuccess()).isTrue()
+ }
+
+ private fun l2capServerOnPhoneAndConnectionFromBumbleUtil(
+ isSecure: Boolean = false
+ ): SocketServerDetails {
+ var bluetoothSocket: BluetoothSocket
+ val channel: Channel
+ val l2capServer = bluetoothAdapter.listenUsingInsecureL2capChannel()
+ val socketFlow = flow { emit(l2capServer.accept()) }
+ val connectResponse = createAndConnectL2capChannelWithBumble(l2capServer.psm)
+ runBlocking {
+ bluetoothSocket = socketFlow.first()
+ assertThat(connectResponse.hasChannel()).isTrue()
+ }
+
+ return SocketServerDetails(l2capServer, bluetoothSocket, connectResponse.channel)
+ }
+
+ private fun sendDataFromPhoneToBumbleAndVerifyUtil(
+ bluetoothSocket: BluetoothSocket,
+ channel: Channel,
+ ) {
val sampleData = "cafe-baguette".toByteArray()
val receiveObserver = StreamObserverSpliterator<ReceiveResponse>()
@@ -318,24 +547,33 @@ public class DckL2capTest() : Closeable {
.l2cap()
.receive(ReceiveRequest.newBuilder().setChannel(channel).build(), receiveObserver)
- Log.d(TAG, "testSendOverEncryptedOnlySocket: Send data from Android to Bumble")
+ Log.d(TAG, "sendDataFromPhoneToBumbleAndVerify: Send data from Android to Bumble")
val outputStream = bluetoothSocket.outputStream
outputStream.write(sampleData)
outputStream.flush()
- Log.d(TAG, "testSendOverEncryptedOnlySocket: waitReceive data on Bumble")
+ Log.d(TAG, "sendDataFromPhoneToBumbleAndVerify: waitReceive data on Bumble")
val receiveData = receiveObserver.iterator().next()
assertThat(receiveData.data.toByteArray()).isEqualTo(sampleData)
+ outputStream.close()
+ }
- bluetoothSocket.close()
- Log.d(TAG, "testSendOverEncryptedOnlySocket: waitDisconnection")
- val waitDisconnectionRequest =
- WaitDisconnectionRequest.newBuilder().setChannel(channel).build()
- val disconnectionResponse =
- mBumble.l2capBlocking().waitDisconnection(waitDisconnectionRequest)
- assertThat(disconnectionResponse.hasSuccess()).isTrue()
- host.removeBondAndVerify(remoteDevice)
- Log.d(TAG, "testSendOverEncryptedOnlySocket: done")
+ private fun sendDataFromBumbleToPhoneAndVerifyUtil(
+ bluetoothSocket: BluetoothSocket,
+ channel: Channel,
+ ) {
+ val inputStream = bluetoothSocket!!.inputStream
+ val sampleData: ByteString = ByteString.copyFromUtf8("cafe-baguette")
+ val buffer = ByteArray(sampleData.size())
+
+ val sendRequest = SendRequest.newBuilder().setChannel(channel).setData(sampleData).build()
+ Log.d(TAG, "sendDataFromBumbleToPhoneAndVerifyUtil: Send data from Bumble to Android")
+ mBumble.l2capBlocking().send(sendRequest)
+
+ Log.d(TAG, "sendDataFromBumbleToPhoneAndVerifyUtil: Receive data on Android")
+ val read = inputStream.read(buffer)
+ assertThat(ByteString.copyFrom(buffer).substring(0, read)).isEqualTo(sampleData)
+ inputStream.close()
}
private fun createAndConnectL2capChannelWithBumble(psm: Int): ConnectResponse {
@@ -367,9 +605,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 } }
@@ -531,7 +767,7 @@ public class DckL2capTest() : Closeable {
// CCC DK Specification R3 1.2.0 r14 section 19.2.1.2 Bluetooth Le Pairing
private val CCC_DK_UUID = UUID.fromString("0000FFF5-0000-1000-8000-00805f9b34fb")
- // Vehicule SPSM
+ // Vehicle SPSM
private val SPSM_UUID = UUID.fromString("D3B5A130-9E23-4B3A-8BE4-6B1EE5F980A3")
}
}
diff --git a/framework/tests/unit/src/android/bluetooth/BluetoothCodecStatusTest.java b/framework/tests/unit/src/android/bluetooth/BluetoothCodecStatusTest.java
index d2124ce265..85422f568a 100644
--- a/framework/tests/unit/src/android/bluetooth/BluetoothCodecStatusTest.java
+++ b/framework/tests/unit/src/android/bluetooth/BluetoothCodecStatusTest.java
@@ -276,7 +276,7 @@ public class BluetoothCodecStatusTest {
4000);
// Selectable capabilities: A and B are same; C is different
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_1_A =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_1_A =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -289,7 +289,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_1_B =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_1_B =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -302,7 +302,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_1_C =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_1_C =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -314,7 +314,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_2_A =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_2_A =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -327,7 +327,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_2_B =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_2_B =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -340,7 +340,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_2_C =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_2_C =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -352,7 +352,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_3_A =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_3_A =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -365,7 +365,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_3_B =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_3_B =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -378,7 +378,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_3_C =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_3_C =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -390,7 +390,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_4_A =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_4_A =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -403,7 +403,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_4_B =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_4_B =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -416,7 +416,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_4_C =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_4_C =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -428,7 +428,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_5_A =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_5_A =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -446,7 +446,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_5_B =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_5_B =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -464,7 +464,7 @@ public class BluetoothCodecStatusTest {
3000,
4000);
- private static final BluetoothCodecConfig SELECTABE_CAPABILITY_5_C =
+ private static final BluetoothCodecConfig SELECTABLE_CAPABILITY_5_C =
buildBluetoothCodecConfig(
BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC,
BluetoothCodecConfig.CODEC_PRIORITY_DEFAULT,
@@ -515,35 +515,35 @@ public class BluetoothCodecStatusTest {
private static final List<BluetoothCodecConfig> SELECTABLE_CAPABILITY_A =
List.of(
- SELECTABE_CAPABILITY_1_A,
- SELECTABE_CAPABILITY_2_A,
- SELECTABE_CAPABILITY_3_A,
- SELECTABE_CAPABILITY_4_A,
- SELECTABE_CAPABILITY_5_A);
+ SELECTABLE_CAPABILITY_1_A,
+ SELECTABLE_CAPABILITY_2_A,
+ SELECTABLE_CAPABILITY_3_A,
+ SELECTABLE_CAPABILITY_4_A,
+ SELECTABLE_CAPABILITY_5_A);
private static final List<BluetoothCodecConfig> SELECTABLE_CAPABILITY_B =
List.of(
- SELECTABE_CAPABILITY_1_B,
- SELECTABE_CAPABILITY_2_B,
- SELECTABE_CAPABILITY_3_B,
- SELECTABE_CAPABILITY_4_B,
- SELECTABE_CAPABILITY_5_B);
+ SELECTABLE_CAPABILITY_1_B,
+ SELECTABLE_CAPABILITY_2_B,
+ SELECTABLE_CAPABILITY_3_B,
+ SELECTABLE_CAPABILITY_4_B,
+ SELECTABLE_CAPABILITY_5_B);
private static final List<BluetoothCodecConfig> SELECTABLE_CAPABILITY_B_REORDERED =
List.of(
- SELECTABE_CAPABILITY_5_B,
- SELECTABE_CAPABILITY_4_B,
- SELECTABE_CAPABILITY_2_B,
- SELECTABE_CAPABILITY_3_B,
- SELECTABE_CAPABILITY_1_B);
+ SELECTABLE_CAPABILITY_5_B,
+ SELECTABLE_CAPABILITY_4_B,
+ SELECTABLE_CAPABILITY_2_B,
+ SELECTABLE_CAPABILITY_3_B,
+ SELECTABLE_CAPABILITY_1_B);
private static final List<BluetoothCodecConfig> SELECTABLE_CAPABILITY_C =
List.of(
- SELECTABE_CAPABILITY_1_C,
- SELECTABE_CAPABILITY_2_C,
- SELECTABE_CAPABILITY_3_C,
- SELECTABE_CAPABILITY_4_C,
- SELECTABE_CAPABILITY_5_C);
+ SELECTABLE_CAPABILITY_1_C,
+ SELECTABLE_CAPABILITY_2_C,
+ SELECTABLE_CAPABILITY_3_C,
+ SELECTABLE_CAPABILITY_4_C,
+ SELECTABLE_CAPABILITY_5_C);
private static final BluetoothCodecStatus BCS_A =
new BluetoothCodecStatus(CONFIG_A, LOCAL_CAPABILITY_A, SELECTABLE_CAPABILITY_A);
diff --git a/offload/hal/Android.bp b/offload/hal/Android.bp
index 87058f085f..8937b611ef 100644
--- a/offload/hal/Android.bp
+++ b/offload/hal/Android.bp
@@ -16,30 +16,20 @@ package {
default_applicable_licenses: ["Android-Apache-2.0"],
}
-rust_library {
+rust_ffi {
name: "libbluetooth_offload_hal",
- vendor_available: true,
crate_name: "bluetooth_offload_hal",
crate_root: "lib.rs",
edition: "2021",
+ vendor_available: true,
rustlibs: [
"android.hardware.bluetooth-V1-rust",
"libbinder_rs",
"libbluetooth_offload_hci",
+ "libbluetooth_offload_leaudio_hci",
"liblog_rust",
"liblogger",
],
- visibility: [
- "//hardware/interfaces/bluetooth:__subpackages__",
- "//packages/modules/Bluetooth/offload:__subpackages__",
- "//vendor:__subpackages__",
- ],
-}
-
-cc_library_headers {
- name: "libbluetooth_offload_hal_headers",
- vendor_available: true,
- host_supported: true,
export_include_dirs: [
"include",
],
diff --git a/offload/hal/include/hal/ffi.h b/offload/hal/include/hal/ffi.h
index f4d9b5ff4d..49fa20b3c4 100644
--- a/offload/hal/include/hal/ffi.h
+++ b/offload/hal/include/hal/ffi.h
@@ -14,10 +14,13 @@
* limitations under the License.
*/
-extern "C" {
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+namespace aidl::android::hardware::bluetooth::hal {
-#include <stddef.h>
-#include <stdint.h>
+extern "C" {
/**
* Callabcks from C to Rust
@@ -26,17 +29,17 @@ extern "C" {
* `hal_interface.close()` call.
*/
-enum HalStatus {
- STATUS_SUCCESS,
- STATUS_ALREADY_INITIALIZED,
- STATUS_UNABLE_TO_OPEN_INTERFACE,
- STATUS_HARDWARE_INITIALIZATION_ERROR,
- STATUS_UNKNOWN,
+enum Status {
+ SUCCESS,
+ ALREADY_INITIALIZED,
+ UNABLE_TO_OPEN_INTERFACE,
+ HARDWARE_INITIALIZATION_ERROR,
+ UNKNOWN,
};
-struct hal_callbacks {
+struct CCallbacks {
void *handle;
- void (*initialization_complete)(const void *handle, enum HalStatus);
+ void (*initialization_complete)(const void *handle, Status);
void (*event_received)(const void *handle, const uint8_t *data, size_t len);
void (*acl_received)(const void *handle, const uint8_t *data, size_t len);
void (*sco_received)(const void *handle, const uint8_t *data, size_t len);
@@ -50,9 +53,9 @@ struct hal_callbacks {
* Locking over `handle` is not necessary.
*/
-struct hal_interface {
+struct CInterface {
void *handle;
- void (*initialize)(void *handle, const struct hal_callbacks *);
+ void (*initialize)(void *handle, const CCallbacks *);
void (*close)(void *handle);
void (*send_command)(void *handle, const uint8_t *data, size_t len);
void (*send_acl)(void *handle, const uint8_t *data, size_t len);
@@ -60,4 +63,86 @@ struct hal_interface {
void (*send_iso)(void *handle, const uint8_t *data, size_t len);
void (*client_died)(void *handle);
};
+
+/**
+ * Add binder service
+ */
+
+void __add_bluetooth_hci_service(CInterface intf);
+
+} // extern "C"
+
+class IBluetoothHciCallbacks {
+public:
+ IBluetoothHciCallbacks(const CCallbacks *callbacks) : callbacks_(*callbacks) {}
+
+ void initializationComplete(Status status) {
+ callbacks_.initialization_complete(callbacks_.handle, status);
+ }
+
+ void hciEventReceived(std::vector<uint8_t> data) {
+ callbacks_.event_received(callbacks_.handle, data.data(), data.size());
+ }
+
+ void aclDataReceived(std::vector<uint8_t> data) {
+ callbacks_.acl_received(callbacks_.handle, data.data(), data.size());
+ }
+
+ void scoDataReceived(std::vector<uint8_t> data) {
+ callbacks_.sco_received(callbacks_.handle, data.data(), data.size());
+ }
+
+ void isoDataReceived(std::vector<uint8_t> data) {
+ callbacks_.iso_received(callbacks_.handle, data.data(), data.size());
+ }
+
+private:
+ CCallbacks callbacks_;
+};
+
+class IBluetoothHci {
+public:
+ virtual ~IBluetoothHci() = default;
+ virtual void initialize(const std::shared_ptr<IBluetoothHciCallbacks> &callbacks);
+ virtual void close();
+ virtual void sendHciCommand(const std::vector<uint8_t> &data);
+ virtual void sendAclData(const std::vector<uint8_t> &data);
+ virtual void sendScoData(const std::vector<uint8_t> &data);
+ virtual void sendIsoData(const std::vector<uint8_t> &data);
+ virtual void clientDied();
+};
+
+static inline void IBluetoothHci_addService(IBluetoothHci *hci) {
+ __add_bluetooth_hci_service((CInterface){
+ .handle = hci,
+ .initialize =
+ [](void *instance, const CCallbacks *callbacks) {
+ static_cast<IBluetoothHci *>(instance)->initialize(
+ std::make_shared<IBluetoothHciCallbacks>(callbacks));
+ },
+ .close = [](void *instance) { static_cast<IBluetoothHci *>(instance)->close(); },
+ .send_command =
+ [](void *instance, const uint8_t *data, size_t len) {
+ static_cast<IBluetoothHci *>(instance)->sendHciCommand(
+ std::vector<uint8_t>(data, data + len));
+ },
+ .send_acl =
+ [](void *instance, const uint8_t *data, size_t len) {
+ static_cast<IBluetoothHci *>(instance)->sendAclData(
+ std::vector<uint8_t>(data, data + len));
+ },
+ .send_sco =
+ [](void *instance, const uint8_t *data, size_t len) {
+ static_cast<IBluetoothHci *>(instance)->sendScoData(
+ std::vector<uint8_t>(data, data + len));
+ },
+ .send_iso =
+ [](void *instance, const uint8_t *data, size_t len) {
+ static_cast<IBluetoothHci *>(instance)->sendIsoData(
+ std::vector<uint8_t>(data, data + len));
+ },
+ .client_died =
+ [](void *instance) { static_cast<IBluetoothHci *>(instance)->clientDied(); }});
}
+
+} // namespace aidl::android::hardware::bluetooth::hal
diff --git a/offload/hal/service.rs b/offload/hal/service.rs
index a72eea9200..2b171d2e9c 100644
--- a/offload/hal/service.rs
+++ b/offload/hal/service.rs
@@ -13,11 +13,14 @@
// limitations under the License.
use crate::ffi::{CInterface, CStatus, Callbacks, DataCallbacks, Ffi};
-use android_hardware_bluetooth::aidl::android::hardware::bluetooth::IBluetoothHci::IBluetoothHci;
+use android_hardware_bluetooth::aidl::android::hardware::bluetooth::IBluetoothHci::{
+ BnBluetoothHci, BpBluetoothHci, 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 bluetooth_offload_leaudio_hci::LeAudioModuleBuilder;
use std::sync::{Arc, RwLock};
/// Service Implementation of AIDL interface `hardware/interface/bluetoot/aidl`,
@@ -236,3 +239,16 @@ impl From<CStatus> for Status {
}
}
}
+
+#[no_mangle]
+pub extern "C" fn __add_bluetooth_hci_service(cintf: CInterface) {
+ binder::add_service(
+ &format!("{}/default", BpBluetoothHci::get_descriptor()),
+ BnBluetoothHci::new_binder(
+ HciHalProxy::new(vec![Box::new(LeAudioModuleBuilder {})], cintf),
+ binder::BinderFeatures::default(),
+ )
+ .as_binder(),
+ )
+ .expect("Failed to register service");
+}
diff --git a/system/Android.bp b/system/Android.bp
deleted file mode 100644
index 9d47e06596..0000000000
--- a/system/Android.bp
+++ /dev/null
@@ -1,34 +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
- // SPDX-license-identifier-BSD
- // SPDX-license-identifier-MIT
- // legacy_unencumbered
- default_applicable_licenses: ["system_bt_license"],
-}
-
-filegroup {
- name: "TestMockCodecManager",
- srcs: [
- "bta/le_audio/mock_codec_manager.cc",
- ],
-}
-
-// Export system headers for rules that can't simply use `include_dirs`
-cc_library_headers {
- name: "libbluetooth_system_headers",
- visibility: [
- "//packages/modules/Bluetooth/system:__subpackages__",
- ],
- export_include_dirs: ["./"],
- vendor_available: true,
- host_supported: true,
- apex_available: [
- "//apex_available:platform",
- "com.android.bt",
- ],
- min_sdk_version: "30",
-}
diff --git a/system/TEST_MAPPING b/system/TEST_MAPPING
index 8b04c16b05..3e370f753b 100644
--- a/system/TEST_MAPPING
+++ b/system/TEST_MAPPING
@@ -1,4 +1,9 @@
{
+ "bt-mainline-presubmit": [
+ {
+ "name": "bluetooth_test_gd_unit"
+ }
+ ],
"presubmit": [
{
"name": "bluetooth_test_gd_unit"
diff --git a/system/audio/asrc/asrc_resampler.cc b/system/audio/asrc/asrc_resampler.cc
index 7e44d9ade6..a0dc25995c 100644
--- a/system/audio/asrc/asrc_resampler.cc
+++ b/system/audio/asrc/asrc_resampler.cc
@@ -170,7 +170,7 @@ public:
: state_{.id = StateId::RESET}, reference_timing_{0, 0, 0} {
if (com::android::bluetooth::flags::run_clock_recovery_in_worker_thread()) {
read_clock_timer_.SchedulePeriodic(
- thread->GetWeakPtr(), FROM_HERE,
+ thread->GetWeakPtr(),
base::BindRepeating(
[](void*) {
bluetooth::shim::GetHciLayer()->EnqueueCommand(
@@ -183,7 +183,7 @@ public:
std::chrono::milliseconds(100));
} else {
read_clock_timer_.SchedulePeriodic(
- get_main_thread()->GetWeakPtr(), FROM_HERE,
+ get_main_thread()->GetWeakPtr(),
base::BindRepeating(
[](void*) {
bluetooth::shim::GetHciLayer()->EnqueueCommand(
diff --git a/system/audio/asrc/asrc_resampler_test.cc b/system/audio/asrc/asrc_resampler_test.cc
index 19ea04df0f..d2e109ef33 100644
--- a/system/audio/asrc/asrc_resampler_test.cc
+++ b/system/audio/asrc/asrc_resampler_test.cc
@@ -19,7 +19,6 @@
#include <cstdio>
#include <iostream>
-// TODO(b/369381361) Enfore -Wmissing-prototypes
#pragma GCC diagnostic ignored "-Wmissing-prototypes"
bluetooth::common::MessageLoopThread message_loop_thread("main message loop");
diff --git a/system/audio_hal_interface/Android.bp b/system/audio_hal_interface/Android.bp
index 4f3b25563a..a171e79fa5 100644
--- a/system/audio_hal_interface/Android.bp
+++ b/system/audio_hal_interface/Android.bp
@@ -235,12 +235,10 @@ cc_defaults {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libcutils",
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 8437732184..be7cf3a6b2 100644
--- a/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
+++ b/system/audio_hal_interface/aidl/le_audio_software_aidl.cc
@@ -539,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() ||
@@ -568,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;
}
diff --git a/system/audio_hal_interface/aidl/le_audio_utils.cc b/system/audio_hal_interface/aidl/le_audio_utils.cc
index 571a967384..588308f7cc 100644
--- a/system/audio_hal_interface/aidl/le_audio_utils.cc
+++ b/system/audio_hal_interface/aidl/le_audio_utils.cc
@@ -194,13 +194,15 @@ GetAidlMetadataFromStackFormat(const ::bluetooth::le_audio::types::LeAudioLtvMap
out_ltvs.push_back(
::aidl::android::hardware::bluetooth::audio::MetadataLtv::PreferredAudioContexts{
.values = ::aidl::android::hardware::bluetooth::audio::AudioContext{
- .bitmask = stackMetadata.preferred_audio_context.value()}});
+ .bitmask = static_cast<uint16_t>(
+ stackMetadata.preferred_audio_context.value().value())}});
}
if (stackMetadata.streaming_audio_context) {
out_ltvs.push_back(
::aidl::android::hardware::bluetooth::audio::MetadataLtv::StreamingAudioContexts{
.values = ::aidl::android::hardware::bluetooth::audio::AudioContext{
- .bitmask = stackMetadata.streaming_audio_context.value()}});
+ .bitmask = static_cast<uint16_t>(
+ stackMetadata.streaming_audio_context.value().value())}});
}
if (stackMetadata.vendor_specific) {
if (stackMetadata.vendor_specific->size() >= 2) {
diff --git a/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc b/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc
index c04305ec57..7d6e75ece4 100644
--- a/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc
+++ b/system/audio_hal_interface/aidl/le_audio_utils_unittest.cc
@@ -924,7 +924,7 @@ static void verifyMetadata(
->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv::
preferredAudioContexts>()
.values.bitmask,
- stack_meta.preferred_audio_context.value());
+ stack_meta.preferred_audio_context.value().value());
matched_preferredAudioContexts = true;
} else if (aidl_meta->getTag() ==
@@ -933,7 +933,7 @@ static void verifyMetadata(
->get<::aidl::android::hardware::bluetooth::audio::MetadataLtv::
streamingAudioContexts>()
.values.bitmask,
- stack_meta.streaming_audio_context.value());
+ stack_meta.streaming_audio_context.value().value());
matched_streamingAudioContexts = true;
} else if (aidl_meta->getTag() ==
diff --git a/system/audio_hal_interface/fuzzer/Android.bp b/system/audio_hal_interface/fuzzer/Android.bp
index 422eadd711..faf52cb3b9 100644
--- a/system/audio_hal_interface/fuzzer/Android.bp
+++ b/system/audio_hal_interface/fuzzer/Android.bp
@@ -67,7 +67,6 @@ cc_defaults {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -75,12 +74,10 @@ cc_defaults {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libcutils",
diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp
index 64a85ddfe4..da0f17c726 100644
--- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp
+++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_a2dp_encoding_fuzzer.cpp
@@ -92,7 +92,7 @@ void A2dpEncodingFuzzer::process(const uint8_t* data, size_t size) {
bluetooth::common::MessageLoopThread messageLoopThread(name);
messageLoopThread.StartUp();
- messageLoopThread.DoInThread(FROM_HERE, base::BindOnce(&source_init_delayed));
+ messageLoopThread.DoInThread(base::BindOnce(&source_init_delayed));
uint16_t delayReport = fdp.ConsumeIntegral<uint16_t>();
bluetooth::audio::a2dp::set_remote_delay(delayReport);
diff --git a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp
index e382dbeb62..82f8b224a7 100644
--- a/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp
+++ b/system/audio_hal_interface/fuzzer/libbt_audio_hal_le_audio_software_fuzzer.cpp
@@ -51,7 +51,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
std::string name = fdp.ConsumeRandomLengthString(kRandomStringLength);
bluetooth::common::MessageLoopThread messageLoopThread(name);
messageLoopThread.StartUp();
- messageLoopThread.DoInThread(FROM_HERE, base::BindOnce(&source_init_delayed));
+ messageLoopThread.DoInThread(base::BindOnce(&source_init_delayed));
LeAudioClientInterface* interface = LeAudioClientInterface::Get();
diff --git a/system/audio_hal_interface/hidl/client_interface_hidl.cc b/system/audio_hal_interface/hidl/client_interface_hidl.cc
index 4bea626d5b..4a633a47f1 100644
--- a/system/audio_hal_interface/hidl/client_interface_hidl.cc
+++ b/system/audio_hal_interface/hidl/client_interface_hidl.cc
@@ -163,7 +163,6 @@ public:
if (bluetooth_audio_clientif_ != nullptr && message_loop_ != nullptr) {
// restart the session on the correct thread
message_loop_->DoInThread(
- FROM_HERE,
base::BindOnce(&BluetoothAudioClientInterface::RenewAudioProviderAndSession,
base::Unretained(bluetooth_audio_clientif_)));
} else {
diff --git a/system/audio_hal_interface/le_audio_software.cc b/system/audio_hal_interface/le_audio_software.cc
index d3e65d63b8..2352981e76 100644
--- a/system/audio_hal_interface/le_audio_software.cc
+++ b/system/audio_hal_interface/le_audio_software.cc
@@ -280,6 +280,17 @@ void LeAudioClientInterface::Sink::StopSession() {
get_aidl_client_interface(is_broadcaster_)->EndSession();
}
+static inline void dumpOffloadConfig(
+ const char* msg, const ::bluetooth::audio::aidl::AudioConfiguration& offload_hal_config) {
+ const auto offload_cfg_str = offload_hal_config.toString();
+
+ constexpr size_t linelimit = 940;
+ std::string_view str_view(offload_cfg_str);
+ for (size_t offset = 0; offset < offload_cfg_str.length(); offset += linelimit) {
+ log::debug("{} {}", offset ? " > " : msg, str_view.substr(offset, linelimit));
+ }
+}
+
void LeAudioClientInterface::Sink::UpdateAudioConfigToHal(
const ::bluetooth::le_audio::stream_config& offload_config) {
if (HalVersionManager::GetHalTransport() == BluetoothAudioHalTransport::HIDL) {
@@ -290,8 +301,10 @@ void LeAudioClientInterface::Sink::UpdateAudioConfigToHal(
return;
}
- get_aidl_client_interface(is_broadcaster_)
- ->UpdateAudioConfig(aidl::le_audio::stream_config_to_hal_audio_config(offload_config));
+ auto offload_hal_config = aidl::le_audio::stream_config_to_hal_audio_config(offload_config);
+ dumpOffloadConfig("Encoding config:", offload_hal_config);
+
+ get_aidl_client_interface(is_broadcaster_)->UpdateAudioConfig(offload_hal_config);
}
std::optional<::bluetooth::le_audio::broadcaster::BroadcastConfiguration>
@@ -591,8 +604,11 @@ void LeAudioClientInterface::Source::UpdateAudioConfigToHal(
aidl::SessionType::LE_AUDIO_HARDWARE_OFFLOAD_DECODING_DATAPATH) {
return;
}
- aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig(
- aidl::le_audio::stream_config_to_hal_audio_config(offload_config));
+
+ auto offload_hal_config = aidl::le_audio::stream_config_to_hal_audio_config(offload_config);
+ dumpOffloadConfig("Decoding config:", offload_hal_config);
+
+ aidl::le_audio::LeAudioSourceTransport::interface->UpdateAudioConfig(offload_hal_config);
}
size_t LeAudioClientInterface::Source::Write(const uint8_t* p_buf, uint32_t len) {
diff --git a/system/bta/Android.bp b/system/bta/Android.bp
index 9eaf7c84b2..bfdea63d54 100644
--- a/system/bta/Android.bp
+++ b/system/bta/Android.bp
@@ -47,11 +47,18 @@ filegroup {
],
}
-// BTA static library for target
+filegroup {
+ name: "TestMockCodecManager",
+ srcs: [
+ "le_audio/mock_codec_manager.cc",
+ ],
+}
+
cc_library_static {
name: "libbt-bta",
defaults: ["fluoride_bta_defaults"],
srcs: [
+ ":BtaDmSources",
"ag/bta_ag_act.cc",
"ag/bta_ag_api.cc",
"ag/bta_ag_at.cc",
@@ -71,6 +78,20 @@ cc_library_static {
"av/bta_av_main.cc",
"av/bta_av_ssm.cc",
"csis/csis_client.cc",
+ "gatt/bta_gattc_act.cc",
+ "gatt/bta_gattc_api.cc",
+ "gatt/bta_gattc_cache.cc",
+ "gatt/bta_gattc_db_storage.cc",
+ "gatt/bta_gattc_main.cc",
+ "gatt/bta_gattc_queue.cc",
+ "gatt/bta_gattc_utils.cc",
+ "gatt/bta_gatts_act.cc",
+ "gatt/bta_gatts_api.cc",
+ "gatt/bta_gatts_main.cc",
+ "gatt/bta_gatts_queue.cc",
+ "gatt/bta_gatts_utils.cc",
+ "gatt/database.cc",
+ "gatt/database_builder.cc",
"gmap/gmap_client.cc",
"gmap/gmap_server.cc",
"groups/groups.cc",
@@ -99,6 +120,8 @@ cc_library_static {
"hh/bta_hh_le.cc",
"hh/bta_hh_main.cc",
"hh/bta_hh_utils.cc",
+ "jv/bta_jv_act.cc",
+ "jv/bta_jv_api.cc",
"le_audio/audio_hal_client/audio_sink_hal_client.cc",
"le_audio/audio_hal_client/audio_source_hal_client.cc",
"le_audio/broadcaster/broadcast_configuration_provider.cc",
@@ -128,6 +151,15 @@ cc_library_static {
"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",
+ "sdp/bta_sdp_api.cc",
+ "sdp/bta_sdp_cfg.cc",
+ "sys/bta_sys_conn.cc",
+ "sys/bta_sys_main.cc",
+ "sys/utl.cc",
"vc/device.cc",
"vc/vc.cc",
],
@@ -142,14 +174,19 @@ cc_library_static {
"avrcp-target-service",
"bluetooth_flags_c_lib",
"lib-bt-packets",
+ "libaconfig_storage_read_api_cc",
+ "libbase",
"libbluetooth_crypto_toolbox",
"libbluetooth_gd",
+ "libbluetooth_hci_pdl",
"libbluetooth_log",
"libbt-audio-asrc",
- "libbt-bta-core",
+ "libbt-audio-hal-interface",
"libbt-platform-protos-lite",
"libcom.android.sysprop.bluetooth.wrapped",
+ "libflatbuffers-cpp",
"liblc3",
+ "server_configurable_flags",
],
aidl: {
libs: ["bluetooth_constants"],
@@ -173,62 +210,6 @@ cc_library_static {
min_sdk_version: "Tiramisu",
}
-cc_library_static {
- name: "libbt-bta-core",
- defaults: ["fluoride_bta_defaults"],
- srcs: [
- ":BtaDmSources",
- "gatt/bta_gattc_act.cc",
- "gatt/bta_gattc_api.cc",
- "gatt/bta_gattc_cache.cc",
- "gatt/bta_gattc_db_storage.cc",
- "gatt/bta_gattc_main.cc",
- "gatt/bta_gattc_queue.cc",
- "gatt/bta_gattc_utils.cc",
- "gatt/bta_gatts_act.cc",
- "gatt/bta_gatts_api.cc",
- "gatt/bta_gatts_main.cc",
- "gatt/bta_gatts_queue.cc",
- "gatt/bta_gatts_utils.cc",
- "gatt/database.cc",
- "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",
- "sdp/bta_sdp_api.cc",
- "sdp/bta_sdp_cfg.cc",
- "sys/bta_sys_conn.cc",
- "sys/bta_sys_main.cc",
- "sys/utl.cc",
- ],
- cflags: [
- /* we export all classes, so change default visibility, instead of having EXPORT_SYMBOL on each class*/
- "-fvisibility=default",
- ],
- static_libs: [
- "bluetooth_flags_c_lib",
- "lib-bt-packets",
- "libaconfig_storage_read_api_cc",
- "libbase",
- "libbluetooth_hci_pdl",
- "libbluetooth_log",
- "libbt-audio-hal-interface",
- "libbt-platform-protos-lite",
- "libcom.android.sysprop.bluetooth.wrapped",
- "libflatbuffers-cpp",
- "server_configurable_flags",
- ],
- shared_libs: [
- "libcrypto",
- ],
- apex_available: ["com.android.bt"],
- host_supported: true,
- min_sdk_version: "Tiramisu",
-}
-
cc_test {
name: "net_test_bta",
defaults: [
@@ -306,7 +287,6 @@ cc_test {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-platform-protos-lite",
@@ -383,7 +363,6 @@ cc_test {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-common",
"libbt-platform-protos-lite",
"libbtcore",
@@ -432,7 +411,6 @@ cc_test {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-platform-protos-lite",
diff --git a/system/bta/ag/bta_ag_sco.cc b/system/bta/ag/bta_ag_sco.cc
index 34102d1dd6..cdb960b716 100644
--- a/system/bta/ag/bta_ag_sco.cc
+++ b/system/bta/ag/bta_ag_sco.cc
@@ -75,6 +75,9 @@ using namespace bluetooth;
((uint16_t)(HCI_INP_CODING_LINEAR | HCI_INP_DATA_FMT_2S_COMPLEMENT | HCI_INP_SAMPLE_SIZE_16BIT | \
HCI_AIR_CODING_FORMAT_TRANSPNT))
+static void updateCodecParametersFromProviderInfo(tBTA_AG_UUID_CODEC esco_codec,
+ enh_esco_params_t& params);
+
static bool sco_allowed = true;
static bool hfp_software_datapath_enabled = false;
static RawAddress active_device_addr = {};
@@ -149,9 +152,6 @@ bool bta_ag_sco_is_active_device(const RawAddress& bd_addr) {
return !active_device_addr.IsEmpty() && active_device_addr == bd_addr;
}
-void updateCodecParametersFromProviderInfo(tBTA_AG_UUID_CODEC esco_codec,
- enh_esco_params_t& params);
-
/*******************************************************************************
*
* Function bta_ag_sco_conn_cback
@@ -585,8 +585,8 @@ void bta_ag_create_sco(tBTA_AG_SCB* p_scb, bool is_orig) {
log::debug("AFTER {}", p_scb->ToString());
}
-void updateCodecParametersFromProviderInfo(tBTA_AG_UUID_CODEC esco_codec,
- enh_esco_params_t& params) {
+static void updateCodecParametersFromProviderInfo(tBTA_AG_UUID_CODEC esco_codec,
+ enh_esco_params_t& params) {
if (bta_ag_is_sco_managed_by_audio() && !sco_config_map.empty()) {
auto sco_config_it = sco_config_map.find(esco_codec);
if (sco_config_it == sco_config_map.end()) {
diff --git a/system/bta/csis/csis_client.cc b/system/bta/csis/csis_client.cc
index 1abf97356e..de8559e835 100644
--- a/system/bta/csis/csis_client.cc
+++ b/system/bta/csis/csis_client.cc
@@ -271,7 +271,7 @@ public:
auto device = FindDeviceByAddress(address);
if (device == nullptr) {
- if (!BTM_IsLinkKeyKnown(address, BT_TRANSPORT_LE)) {
+ if (!BTM_IsBonded(address, BT_TRANSPORT_LE)) {
log::error("Connecting {} when not bonded", address);
callbacks_->OnConnectionState(address, ConnectionState::DISCONNECTED);
return;
@@ -1339,7 +1339,7 @@ private:
/* Make sure device is not already bonded which could
* be a case for dual mode devices where
*/
- if (BTM_BleIsLinkKeyKnown(result->bd_addr)) {
+ if (BTM_IsBonded(result->bd_addr, BT_TRANSPORT_LE)) {
log::verbose("Device {} already bonded. Identity address: {}", result->bd_addr,
*BTM_BleGetIdentityAddress(result->bd_addr));
return;
@@ -1480,7 +1480,7 @@ private:
/* Make sure device is not already bonded which could
* be a case for dual mode devices where
*/
- if (BTM_BleIsLinkKeyKnown(result->bd_addr)) {
+ if (BTM_IsBonded(result->bd_addr, BT_TRANSPORT_LE)) {
log::verbose("Device {} already bonded. Identity address: {}", result->bd_addr,
*BTM_BleGetIdentityAddress(result->bd_addr));
return;
diff --git a/system/bta/csis/csis_client_test.cc b/system/bta/csis/csis_client_test.cc
index a9a2480849..016dbb05bd 100644
--- a/system/bta/csis/csis_client_test.cc
+++ b/system/bta/csis/csis_client_test.cc
@@ -23,6 +23,7 @@
#include <vector>
#include "bind_helpers.h"
+#include "bt_transport.h"
#include "bta_csis_api.h"
#include "bta_dm_api_mock.h"
#include "bta_gatt_api_mock.h"
@@ -369,7 +370,7 @@ protected:
SetMockCsisLockCallback(&csis_lock_cb);
callbacks.reset(new MockCsisCallbacks());
- ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(true)));
ON_CALL(btm_interface, BTM_IsEncrypted(_, _)).WillByDefault(DoAll(Return(true)));
@@ -724,7 +725,7 @@ TEST_F(CsisClientTest, test_connect_after_remove) {
CsisClient::Get()->RemoveDevice(test_address);
EXPECT_CALL(*callbacks, OnConnectionState(test_address, ConnectionState::DISCONNECTED));
- ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(Return(false));
+ ON_CALL(btm_interface, IsDeviceBonded(_, _)).WillByDefault(Return(false));
CsisClient::Get()->Connect(test_address);
Mock::VerifyAndClearExpectations(callbacks.get());
@@ -1090,6 +1091,7 @@ TEST_F(CsisClientTest, test_not_open_duplicate_active_scan_while_bonding_set_mem
result.inq_res.eir_len = 8;
result.inq_res.bd_addr = test_address2;
+ ON_CALL(btm_interface, IsDeviceBonded(test_address2, BT_TRANSPORT_LE)).WillByDefault(Return(false));
// CSIS client should process set member event to JNI
EXPECT_CALL(*callbacks, OnSetMemberAvailable(test_address2, 1));
diff --git a/system/bta/dm/bta_dm_disc.cc b/system/bta/dm/bta_dm_disc.cc
index fdda5102af..b3f010e86e 100644
--- a/system/bta/dm/bta_dm_disc.cc
+++ b/system/bta/dm/bta_dm_disc.cc
@@ -37,6 +37,7 @@
#include "internal_include/bt_target.h"
#include "main/shim/dumpsys.h"
#include "osi/include/allocator.h"
+#include "osi/include/osi.h"
#include "stack/btm/btm_dev.h"
#include "stack/include/bt_name.h"
#include "stack/include/bt_uuid16.h"
@@ -94,7 +95,7 @@ static void post_disc_evt(tBTA_DM_DISC_EVT event, std::unique_ptr<tBTA_DM_MSG> m
static void bta_dm_gatt_disc_complete(tCONN_ID conn_id, tGATT_STATUS status);
static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data);
static void bta_dm_execute_queued_discovery_request();
-static void bta_dm_close_gatt_conn();
+static void bta_dm_close_gatt_conn(uint16_t conn_id);
namespace {
@@ -481,8 +482,10 @@ void bta_dm_disc_gattc_register(void) {
false);
}
-static void gatt_close_timer_cb(void*) {
- bta_dm_disc_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr);
+static void gatt_close_timer_cb(void* data) {
+ uint16_t conn_id = PTR_TO_UINT(data);
+ bta_dm_disc_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT,
+ std::make_unique<tBTA_DM_MSG>(tBTA_DM_TOUT{.conn_id = conn_id}));
}
void bta_dm_gatt_finished(RawAddress bda, tBTA_STATUS result,
@@ -548,15 +551,16 @@ static void bta_dm_gatt_disc_complete(tCONN_ID conn_id, tGATT_STATUS status) {
if (bta_dm_discovery_cb.gatt_close_timer != nullptr) {
/* start a GATT channel close delay timer */
alarm_set_on_mloop(bta_dm_discovery_cb.gatt_close_timer, BTA_DM_GATT_CLOSE_DELAY_TOUT,
- gatt_close_timer_cb, 0);
+ gatt_close_timer_cb, UINT_TO_PTR(conn_id));
} else {
- bta_dm_disc_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT, nullptr);
+ bta_dm_disc_sm_execute(BTA_DM_DISC_CLOSE_TOUT_EVT,
+ std::make_unique<tBTA_DM_MSG>(tBTA_DM_TOUT{.conn_id = conn_id}));
}
} else {
log::info("Discovery complete for invalid conn ID. Will pick up next job");
if (com::android::bluetooth::flags::cancel_open_discovery_client()) {
- bta_dm_close_gatt_conn();
+ bta_dm_close_gatt_conn(bta_dm_discovery_cb.conn_id);
} else {
bta_dm_discovery_cb.conn_id = GATT_INVALID_CONN_ID;
}
@@ -569,23 +573,24 @@ static void bta_dm_gatt_disc_complete(tCONN_ID conn_id, tGATT_STATUS status) {
}
}
-/*******************************************************************************
- *
- * Function bta_dm_close_gatt_conn
- *
- * Description This function close the GATT connection after delay
- *timeout.
- *
- * Parameters:
- *
- ******************************************************************************/
-static void bta_dm_close_gatt_conn() {
- if (bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID) {
- BTA_GATTC_Close(bta_dm_discovery_cb.conn_id);
+/* This function close the GATT connection after delay timeout */
+static void bta_dm_close_gatt_conn(uint16_t conn_id) {
+ if (com::android::bluetooth::flags::bta_dm_disc_close_proper_conn_id()) {
+ if (conn_id != GATT_INVALID_CONN_ID) {
+ BTA_GATTC_Close(conn_id);
+ }
+ } else {
+ if (bta_dm_discovery_cb.conn_id != GATT_INVALID_CONN_ID) {
+ BTA_GATTC_Close(bta_dm_discovery_cb.conn_id);
+ }
}
bta_dm_discovery_cb.pending_close_bda = RawAddress::kEmpty;
- bta_dm_discovery_cb.conn_id = GATT_INVALID_CONN_ID;
+
+ if (!com::android::bluetooth::flags::bta_dm_disc_close_proper_conn_id() ||
+ bta_dm_discovery_cb.conn_id == conn_id) {
+ bta_dm_discovery_cb.conn_id = GATT_INVALID_CONN_ID;
+ }
}
/*******************************************************************************
*
@@ -761,7 +766,9 @@ static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, std::unique_ptr<tBTA_
bta_dm_discover_services(std::get<tBTA_DM_API_DISCOVER>(*msg));
break;
case BTA_DM_DISC_CLOSE_TOUT_EVT:
- bta_dm_close_gatt_conn();
+ log::assert_that(std::holds_alternative<tBTA_DM_TOUT>(*msg), "bad message type: {}",
+ msg->index());
+ bta_dm_close_gatt_conn(std::get<tBTA_DM_TOUT>(*msg).conn_id);
break;
default:
log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event),
@@ -789,7 +796,9 @@ static void bta_dm_disc_sm_execute(tBTA_DM_DISC_EVT event, std::unique_ptr<tBTA_
}
} break;
case BTA_DM_DISC_CLOSE_TOUT_EVT:
- bta_dm_close_gatt_conn();
+ log::assert_that(std::holds_alternative<tBTA_DM_TOUT>(*msg), "bad message type: {}",
+ msg->index());
+ bta_dm_close_gatt_conn(std::get<tBTA_DM_TOUT>(*msg).conn_id);
break;
default:
log::info("Received unexpected event {}[0x{:x}] in state {}", bta_dm_event_text(event),
diff --git a/system/bta/dm/bta_dm_disc_int.h b/system/bta/dm/bta_dm_disc_int.h
index adfe3b3f5c..f0feb35d1b 100644
--- a/system/bta/dm/bta_dm_disc_int.h
+++ b/system/bta/dm/bta_dm_disc_int.h
@@ -65,7 +65,12 @@ typedef struct {
tHCI_STATUS hci_status;
} tBTA_DM_SVC_RES;
-using tBTA_DM_MSG = std::variant<tBTA_DM_API_DISCOVER, tBTA_DM_SVC_RES>;
+/* data type for BTA_DM_API_DISCOVER_EVT */
+typedef struct {
+ uint16_t conn_id;
+} tBTA_DM_TOUT;
+
+using tBTA_DM_MSG = std::variant<tBTA_DM_API_DISCOVER, tBTA_DM_SVC_RES, tBTA_DM_TOUT>;
typedef enum { BTA_DM_DISCOVER_IDLE, BTA_DM_DISCOVER_ACTIVE } tBTA_DM_SERVICE_DISCOVERY_STATE;
diff --git a/system/bta/gmap/gmap_client_test.cc b/system/bta/gmap/gmap_client_test.cc
index bc497da0a9..9554a8e310 100644
--- a/system/bta/gmap/gmap_client_test.cc
+++ b/system/bta/gmap/gmap_client_test.cc
@@ -24,6 +24,7 @@
#include "bta/le_audio/le_audio_types.h"
#include "fake_osi.h"
+#include "osi/include/properties.h"
#include "test/mock/mock_osi_properties.h"
using bluetooth::le_audio::GmapClient;
@@ -31,8 +32,6 @@ using ::testing::_;
static constexpr char kGmapEnabledSysProp[] = "bluetooth.profile.gmap.enabled";
-void osi_property_set_bool(const char* key, bool value);
-
class GmapClientTest : public ::testing::Test {
public:
RawAddress addr = RawAddress({0x11, 0x22, 0x33, 0x44, 0x55, 0x66});
diff --git a/system/bta/has/has_client.cc b/system/bta/has/has_client.cc
index 15bdfc5bfc..cb99045b41 100644
--- a/system/bta/has/has_client.cc
+++ b/system/bta/has/has_client.cc
@@ -164,7 +164,7 @@ public:
void Connect(const RawAddress& address) override {
log::info("{}", address);
- if (!BTM_IsLinkKeyKnown(address, BT_TRANSPORT_LE)) {
+ if (!BTM_IsBonded(address, BT_TRANSPORT_LE)) {
log::error("Connecting {} when not bonded", address);
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
return;
diff --git a/system/bta/has/has_client_test.cc b/system/bta/has/has_client_test.cc
index cf0e63f1cc..1f68488f84 100644
--- a/system/bta/has/has_client_test.cc
+++ b/system/bta/has/has_client_test.cc
@@ -39,6 +39,7 @@
#include "hardware/bt_gatt_types.h"
#include "has_types.h"
#include "mock_csis_client.h"
+#include "osi/include/properties.h"
#include "stack/gatt/gatt_int.h"
#include "stack/include/bt_uuid16.h"
#include "stack/include/btm_status.h"
@@ -46,7 +47,6 @@
#include "types/bt_transport.h"
bool gatt_profile_get_eatt_support(const RawAddress& /*addr*/) { return true; }
-void osi_property_set_bool(const char* key, bool value);
namespace bluetooth {
namespace has {
@@ -633,7 +633,7 @@ protected:
encryption_result = true;
- ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(true)));
ON_CALL(btm_interface, SetEncryption(_, _, _, _, _))
.WillByDefault(Invoke([this](const RawAddress& bd_addr, tBT_TRANSPORT /*transport*/,
@@ -861,7 +861,7 @@ protected:
ON_CALL(btm_interface, BTM_IsEncrypted(address, _))
.WillByDefault(DoAll(Return(encryption_result)));
- ON_CALL(btm_interface, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(address, _)).WillByDefault(DoAll(Return(true)));
}
void InjectNotifyReadPresetResponse(uint16_t conn_id, RawAddress const& address, uint16_t handle,
@@ -1127,11 +1127,11 @@ protected:
class HasClientTest : public HasClientTestBase {
void SetUp(void) override {
+ com::android::bluetooth::flags::provider_->reset_flags();
HasClientTestBase::SetUp();
TestAppRegister();
}
void TearDown(void) override {
- com::android::bluetooth::flags::provider_->reset_flags();
TestAppUnregister();
HasClientTestBase::TearDown();
}
@@ -1189,7 +1189,7 @@ TEST_F(HasClientTest, test_connect_after_remove) {
EXPECT_CALL(*callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address));
// Device has no Link Key
- ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(test_address, _)).WillByDefault(DoAll(Return(true)));
HasClient::Get()->Connect(test_address);
Mock::VerifyAndClearExpectations(&callbacks);
}
diff --git a/system/bta/hearing_aid/hearing_aid.cc b/system/bta/hearing_aid/hearing_aid.cc
index 58a4313638..d19ac8070c 100644
--- a/system/bta/hearing_aid/hearing_aid.cc
+++ b/system/bta/hearing_aid/hearing_aid.cc
@@ -572,7 +572,7 @@ public:
return;
}
- if (BTM_IsLinkKeyKnown(address, BT_TRANSPORT_LE)) {
+ if (BTM_IsBonded(address, BT_TRANSPORT_LE)) {
/* if bonded and link not encrypted */
BTM_SetEncryption(address, BT_TRANSPORT_LE, encryption_callback, nullptr,
BTM_BLE_SEC_ENCRYPT);
diff --git a/system/bta/hearing_aid/hearing_aid_audio_source.cc b/system/bta/hearing_aid/hearing_aid_audio_source.cc
index 1f4c68e516..51714a5f70 100644
--- a/system/bta/hearing_aid/hearing_aid_audio_source.cc
+++ b/system/bta/hearing_aid/hearing_aid_audio_source.cc
@@ -100,7 +100,7 @@ void start_audio_ticks() {
}
wakelock_acquire();
- audio_timer.SchedulePeriodic(get_main_thread()->GetWeakPtr(), FROM_HERE,
+ audio_timer.SchedulePeriodic(get_main_thread()->GetWeakPtr(),
base::BindRepeating(&send_audio_data),
std::chrono::milliseconds(data_interval_ms));
log::info("running with data interval: {}", data_interval_ms);
diff --git a/system/bta/hh/bta_hh_le.cc b/system/bta/hh/bta_hh_le.cc
index 5a5c261f98..031462aedc 100644
--- a/system/bta/hh/bta_hh_le.cc
+++ b/system/bta/hh/bta_hh_le.cc
@@ -280,7 +280,7 @@ void bta_hh_le_open_conn(tBTA_HH_DEV_CB* p_cb, bool direct) {
bta_hh_cb.le_cb_index[BTA_HH_GET_LE_CB_IDX(p_cb->hid_handle)] = p_cb->index; // Update index map
if (!direct) {
// don't reconnect unbonded device
- if (!BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
+ if (!BTM_IsBonded(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
return;
}
log::debug("Add {} to background connection list", p_cb->link_spec);
@@ -1108,7 +1108,7 @@ void bta_hh_start_security(tBTA_HH_DEV_CB* p_cb, const tBTA_HH_DATA* /* p_buf */
log::debug("addr:{} already encrypted", p_cb->link_spec.addrt.bda);
p_cb->status = BTA_HH_OK;
bta_hh_sm_execute(p_cb, BTA_HH_ENC_CMPL_EVT, NULL);
- } else if (BTM_IsLinkKeyKnown(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
+ } else if (BTM_IsBonded(p_cb->link_spec.addrt.bda, BT_TRANSPORT_LE)) {
/* if bonded and link not encrypted */
log::debug("addr:{} bonded, not encrypted", p_cb->link_spec.addrt.bda);
p_cb->status = BTA_HH_ERR_AUTH_FAILED;
diff --git a/system/bta/include/bta_le_audio_api.h b/system/bta/include/bta_le_audio_api.h
index 52a3f7d83c..db541799c7 100644
--- a/system/bta/include/bta_le_audio_api.h
+++ b/system/bta/include/bta_le_audio_api.h
@@ -80,9 +80,10 @@ public:
static bool RegisterIsoDataConsumer(LeAudioIsoDataCallback callback);
- static void AddFromStorage(const RawAddress& addr, bool autoconnect, int sink_audio_location,
- int source_audio_location, int sink_supported_context_types,
- int source_supported_context_types,
+ static void AddFromStorage(const RawAddress& addr, bool autoconnect,
+ std::optional<int> sink_audio_location,
+ std::optional<int> source_audio_location,
+ int sink_supported_context_types, int source_supported_context_types,
const std::vector<uint8_t>& handles,
const std::vector<uint8_t>& sink_pacs,
const std::vector<uint8_t>& source_pacs,
diff --git a/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc b/system/bta/le_audio/audio_hal_client/audio_hal_client_test.cc
index cabdee4a64..606ddc69d9 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
@@ -55,7 +55,7 @@ using namespace bluetooth;
bluetooth::common::MessageLoopThread message_loop_thread("test message loop");
bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_thread; }
bt_status_t do_in_main_thread(base::OnceClosure task) {
- if (!message_loop_thread.DoInThread(FROM_HERE, std::move(task))) {
+ if (!message_loop_thread.DoInThread(std::move(task))) {
log::error("failed to post task to task runner!");
return BT_STATUS_FAIL;
}
@@ -230,6 +230,8 @@ public:
class LeAudioClientAudioTest : public ::testing::Test {
protected:
void SetUp(void) override {
+ com::android::bluetooth::flags::provider_->reset_flags();
+
init_message_loop_thread();
bluetooth::audio::le_audio::interface_mock = &mock_client_interface_;
bluetooth::audio::le_audio::sink_mock = &mock_hal_interface_audio_sink_;
@@ -279,8 +281,6 @@ protected:
}
void TearDown(void) override {
- com::android::bluetooth::flags::provider_->reset_flags();
-
/* We have to call Cleanup to tidy up some static variables.
* If on the HAL end Source is running it means we are running the Sink
* on our end, and vice versa.
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 7ff5196256..33af17284b 100644
--- a/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc
+++ b/system/bta/le_audio/audio_hal_client/audio_source_hal_client.cc
@@ -264,7 +264,7 @@ void SourceImpl::StartAudioTicks() {
worker_thread_, source_codec_config_.num_channels, source_codec_config_.sample_rate,
source_codec_config_.bits_per_sample, source_codec_config_.data_interval_us);
audio_timer_.SchedulePeriodic(
- worker_thread_->GetWeakPtr(), FROM_HERE,
+ worker_thread_->GetWeakPtr(),
base::BindRepeating(&SourceImpl::SendAudioData, weak_factory_.GetWeakPtr()),
std::chrono::microseconds(source_codec_config_.data_interval_us));
}
@@ -280,7 +280,7 @@ bool SourceImpl::OnSuspendReq() {
if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) {
if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) {
worker_thread_->DoInThread(
- FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr()));
} else {
StopAudioTicks();
}
@@ -382,7 +382,7 @@ void SourceImpl::Stop() {
if (CodecManager::GetInstance()->GetCodecLocation() == types::CodecLocation::HOST) {
if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) {
worker_thread_->DoInThread(
- FROM_HERE, base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&SourceImpl::StopAudioTicks, weak_factory_.GetWeakPtr()));
} else {
StopAudioTicks();
}
@@ -407,7 +407,7 @@ void SourceImpl::ConfirmStreamingRequest() {
if (com::android::bluetooth::flags::run_ble_audio_ticks_in_worker_thread()) {
worker_thread_->DoInThread(
- FROM_HERE, base::BindOnce(&SourceImpl::StartAudioTicks, weak_factory_.GetWeakPtr()));
+ base::BindOnce(&SourceImpl::StartAudioTicks, weak_factory_.GetWeakPtr()));
} else {
StartAudioTicks();
}
diff --git a/system/bta/le_audio/audio_set_scenarios.json b/system/bta/le_audio/audio_set_scenarios.json
index 52857f3356..93cd811a61 100644
--- a/system/bta/le_audio/audio_set_scenarios.json
+++ b/system/bta/le_audio/audio_set_scenarios.json
@@ -161,7 +161,25 @@
"One-TwoChan-SnkAse-Lc3_24_2_Low_Latency",
"One-TwoChan-SnkAse-Lc3_24_1_Low_Latency",
"One-TwoChan-SnkAse-Lc3_16_2_Low_Latency",
- "One-TwoChan-SnkAse-Lc3_16_1_Low_Latency"
+ "One-TwoChan-SnkAse-Lc3_16_1_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_32_2_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_32_1_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_24_2_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_24_1_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_16_2_Low_Latency",
+ "Two-OneChan-SrcAse-Lc3_16_1_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_32_2_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_32_1_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_24_2_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_24_1_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_16_2_Low_Latency",
+ "One-TwoChan-SrcAse-Lc3_16_1_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_32_2_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_32_1_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_24_2_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_24_1_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_16_2_Low_Latency",
+ "One-OneChan-SrcAse-Lc3_16_1_Low_Latency"
]
},
{
diff --git a/system/bta/le_audio/broadcaster/broadcaster_test.cc b/system/bta/le_audio/broadcaster/broadcaster_test.cc
index 44e6bf7815..a211a810ad 100644
--- a/system/bta/le_audio/broadcaster/broadcaster_test.cc
+++ b/system/bta/le_audio/broadcaster/broadcaster_test.cc
@@ -96,13 +96,12 @@ void invoke_switch_buffer_size_cb(bool /*is_low_latency_buffer_size*/) {}
bt_status_t do_in_main_thread(base::OnceClosure task) {
// Wrap the task with task counter so we could later know if there are
// any callbacks scheduled and we should wait before performing some actions
- if (!message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(
- [](base::OnceClosure task, std::atomic<int>& num_async_tasks) {
- std::move(task).Run();
- num_async_tasks--;
- },
- std::move(task), std::ref(num_async_tasks)))) {
+ if (!message_loop_thread.DoInThread(base::BindOnce(
+ [](base::OnceClosure task, std::atomic<int>& num_async_tasks) {
+ std::move(task).Run();
+ num_async_tasks--;
+ },
+ std::move(task), std::ref(num_async_tasks)))) {
log::error("failed to post task to task runner!");
return BT_STATUS_FAIL;
}
@@ -252,6 +251,8 @@ public:
class BroadcasterTest : public Test {
protected:
void SetUp() override {
+ com::android::bluetooth::flags::provider_->reset_flags();
+
test::mock::osi_alarm::alarm_free.body = [](alarm_t* alarm) {
if (alarm) {
delete alarm;
@@ -349,7 +350,6 @@ protected:
}
void TearDown() override {
- com::android::bluetooth::flags::provider_->reset_flags();
// Message loop cleanup should wait for all the 'till now' scheduled calls
// so it should be called right at the very begginning of teardown.
cleanup_message_loop_thread();
diff --git a/system/bta/le_audio/broadcaster/state_machine.cc b/system/bta/le_audio/broadcaster/state_machine.cc
index da03674a86..65b16086ff 100644
--- a/system/bta/le_audio/broadcaster/state_machine.cc
+++ b/system/bta/le_audio/broadcaster/state_machine.cc
@@ -281,7 +281,10 @@ private:
DisableAnnouncement();
},
/* in ENABLING state */
- [](const void*) { /* Do nothing */ },
+ [this](const void*) {
+ SetState(State::STOPPING);
+ callbacks_->OnStateMachineEvent(GetBroadcastId(), GetState());
+ },
/* in DISABLING state */
[](const void*) { /* Do nothing */ },
/* in STOPPING state */
@@ -456,6 +459,13 @@ private:
handle_it = std::next(handle_it);
if (handle_it == active_config_->connection_handles.end()) {
+ if (GetState() == BroadcastStateMachine::State::STOPPING) {
+ // All ISO setup completed, but we're in stopping state, we need to tear down all ISO
+ log::warn("ISO setup in stopping state. Tearing down ISO data path.");
+ // Remain in STOPPING, BIG will be terminated in OnRemoveIsoDataPath
+ TriggerIsoDatapathTeardown(active_config_->connection_handles[0]);
+ return;
+ }
/* It was the last BIS to set up - change state to streaming */
SetState(State::STREAMING);
callbacks_->OnStateMachineEvent(GetBroadcastId(), GetState(), nullptr);
@@ -563,8 +573,9 @@ private:
.connection_handles = evt->conn_handles,
};
- if (GetState() == BroadcastStateMachine::State::DISABLING) {
- log::info("Terminating BIG due to stream suspending, big_id={}", evt->big_id);
+ if (GetState() == BroadcastStateMachine::State::DISABLING ||
+ GetState() == BroadcastStateMachine::State::STOPPING) {
+ log::info("Terminating BIG in state={}, big_id={}", ToString(GetState()), evt->big_id);
TerminateBig();
} else {
callbacks_->OnBigCreated(evt->conn_handles);
@@ -578,7 +589,8 @@ private:
case HCI_BLE_TERM_BIG_CPL_EVT: {
auto* evt = static_cast<big_terminate_cmpl_evt*>(data);
- log::info("BIG terminate BIG cmpl, reason={} big_id={}", evt->reason, evt->big_id);
+ log::info("BIG terminate BIG cmpl in state={}, reason={} big_id={}", ToString(GetState()),
+ evt->reason, evt->big_id);
if (evt->big_id != GetAdvertisingSid()) {
log::error("State={} Event={}, unknown adv.sid={}", ToString(GetState()), event,
@@ -589,8 +601,11 @@ private:
active_config_ = std::nullopt;
bool disabling = GetState() == BroadcastStateMachine::State::DISABLING;
- /* Go back to configured if BIG is inactive (we are still announcing) */
- SetState(State::CONFIGURED);
+ /* Go back to configured if BIG is inactive (we are still announcing) and state is not
+ * stopping*/
+ if (GetState() != BroadcastStateMachine::State::STOPPING) {
+ SetState(State::CONFIGURED);
+ }
/* Check if we got this HCI event due to STOP or SUSPEND message. */
if (disabling) {
diff --git a/system/bta/le_audio/broadcaster/state_machine_test.cc b/system/bta/le_audio/broadcaster/state_machine_test.cc
index 70a74ea510..7011d6fdbb 100644
--- a/system/bta/le_audio/broadcaster/state_machine_test.cc
+++ b/system/bta/le_audio/broadcaster/state_machine_test.cc
@@ -28,7 +28,6 @@
#include "broadcast_configuration_provider.h"
#include "btm_iso_api.h"
#include "stack/include/btm_ble_api_types.h"
-#include "state_machine.h"
#include "test/common/mock_functions.h"
#include "test/mock/mock_main_shim_le_advertising_manager.h"
#include "test/mock/mock_stack_btm_iso.h"
@@ -674,6 +673,61 @@ TEST_F(StateMachineTest, ProcessMessageSuspendWhenConfiguredLateBigCreateComplet
ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED);
}
+TEST_F(StateMachineTest, ProcessMessageStopWhenEnablingLateBigCreateCompleteEvent) {
+ EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1);
+
+ auto broadcast_id =
+ InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA);
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED);
+
+ /* Hold start process on BIG create */
+ EXPECT_CALL(*mock_iso_manager_, CreateBig(_, _)).WillOnce(Return());
+ broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START);
+
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::ENABLING);
+ EXPECT_CALL(*(sm_callbacks_.get()),
+ OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPING, _))
+ .Times(1);
+ broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP);
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPING);
+
+ /* Inject late BIG create complete event */
+ big_create_cmpl_evt evt;
+ evt.big_id = broadcasts_[broadcast_id]->GetAdvertisingSid();
+ EXPECT_CALL(*mock_iso_manager_, TerminateBig(_, _)).WillOnce(Return());
+ broadcasts_[broadcast_id]->HandleHciEvent(HCI_BLE_CREATE_BIG_CPL_EVT, &evt);
+
+ // There shall be no change in state
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPING);
+}
+
+TEST_F(StateMachineTest, ProcessMessageStopWhenEnablingLateIsoSetupEvent) {
+ EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1);
+
+ auto broadcast_id =
+ InstantiateStateMachine(bluetooth::le_audio::types::LeAudioContextType::MEDIA);
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::CONFIGURED);
+
+ /* Hold start process on Setup Iso Data Path BIG create */
+ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).WillOnce(Return());
+ broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::START);
+
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::ENABLING);
+
+ EXPECT_CALL(*(sm_callbacks_.get()),
+ OnStateMachineEvent(broadcast_id, BroadcastStateMachine::State::STOPPING, _))
+ .Times(1);
+ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).WillOnce(Return());
+ broadcasts_[broadcast_id]->ProcessMessage(BroadcastStateMachine::Message::STOP);
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPING);
+
+ std::optional<BigConfig> const& big_cfg = broadcasts_[broadcast_id]->GetBigConfig();
+ broadcasts_[broadcast_id]->OnSetupIsoDataPath(0, big_cfg->connection_handles[0]);
+
+ // There shall be no change in state
+ ASSERT_EQ(broadcasts_[broadcast_id]->GetState(), BroadcastStateMachine::State::STOPPING);
+}
+
TEST_F(StateMachineTest, ProcessMessageSuspendWhenConfiguredLateIsoDataPathSetUp) {
EXPECT_CALL(*(sm_callbacks_.get()), OnStateMachineCreateStatus(_, true)).Times(1);
diff --git a/system/bta/le_audio/client.cc b/system/bta/le_audio/client.cc
index 6000f0a871..43c5100b02 100644
--- a/system/bta/le_audio/client.cc
+++ b/system/bta/le_audio/client.cc
@@ -145,6 +145,7 @@ using bluetooth::le_audio::types::AudioLocations;
using bluetooth::le_audio::types::BidirectionalPair;
using bluetooth::le_audio::types::DataPathState;
using bluetooth::le_audio::types::hdl_pair;
+using bluetooth::le_audio::types::hdl_pair_wrapper;
using bluetooth::le_audio::types::kLeAudioContextAllRemoteSource;
using bluetooth::le_audio::types::kLeAudioContextAllTypesArray;
using bluetooth::le_audio::types::LeAudioContextType;
@@ -837,17 +838,20 @@ public:
}
}
- void UpdateLocationsAndContextsAvailability(LeAudioDeviceGroup* group, bool force = false) {
+ void UpdateLocationsAndContextsAvailability(LeAudioDeviceGroup* group,
+ bool available_contexts_changed = false) {
bool group_conf_changed = group->ReloadAudioLocations();
group_conf_changed |= group->ReloadAudioDirections();
- group_conf_changed |= group->UpdateAudioContextAvailability();
- if (group_conf_changed || force) {
+
+ log::verbose("group_id: {}, group_conf_changed: {} available_contexts_changed: {}",
+ group->group_id_, group_conf_changed, available_contexts_changed);
+ if (group_conf_changed || available_contexts_changed) {
/* All the configurations should be recalculated for the new conditions */
group->InvalidateCachedConfigurations();
group->InvalidateGroupStrategy();
- callbacks_->OnAudioConf(
- group->audio_directions_, group->group_id_, group->snk_audio_locations_.to_ulong(),
- group->src_audio_locations_.to_ulong(), group->GetAvailableContexts().value());
+ callbacks_->OnAudioConf(group->audio_directions_, group->group_id_,
+ group->audio_locations_.sink, group->audio_locations_.source,
+ group->GetAvailableContexts().value());
}
}
@@ -1881,7 +1885,7 @@ public:
LeAudioDevice* leAudioDevice = leAudioDevices_.FindByAddress(address);
if (!leAudioDevice) {
- if (!BTM_IsLinkKeyKnown(address, BT_TRANSPORT_LE)) {
+ if (!BTM_IsBonded(address, BT_TRANSPORT_LE)) {
log::error("Connecting {} when not bonded", address);
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
return;
@@ -1933,8 +1937,9 @@ public:
}
/* Restore paired device from storage to recreate groups */
- void AddFromStorage(const RawAddress& address, bool autoconnect, int sink_audio_location,
- int source_audio_location, int sink_supported_context_types,
+ void AddFromStorage(const RawAddress& address, bool autoconnect,
+ std::optional<int> sink_audio_location,
+ std::optional<int> source_audio_location, int sink_supported_context_types,
int source_supported_context_types, const std::vector<uint8_t>& handles,
const std::vector<uint8_t>& sink_pacs,
const std::vector<uint8_t>& source_pacs, const std::vector<uint8_t>& ases,
@@ -1950,7 +1955,9 @@ public:
"restoring: {}, autoconnect {}, sink_audio_location: {}, "
"source_audio_location: {}, sink_supported_context_types : 0x{:04x}, "
"source_supported_context_types 0x{:04x}",
- address, autoconnect, sink_audio_location, source_audio_location,
+ address, autoconnect,
+ sink_audio_location ? std::to_string(sink_audio_location.value()) : "none",
+ source_audio_location ? std::to_string(source_audio_location.value()) : "none",
sink_supported_context_types, source_supported_context_types);
leAudioDevices_.Add(address, DeviceConnectState::DISCONNECTED);
@@ -1962,11 +1969,6 @@ public:
group_add_node(group_id, address);
}
- leAudioDevice->src_audio_locations_ = source_audio_location;
- leAudioDevice->snk_audio_locations_ = sink_audio_location;
- callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_.to_ulong());
-
BidirectionalPair<AudioContexts> supported_contexts = {
.sink = AudioContexts(sink_supported_context_types),
.source = AudioContexts(source_supported_context_types),
@@ -1981,12 +1983,22 @@ public:
log::warn("Could not load Handles");
}
+ if (sink_audio_location) {
+ leAudioDevice->audio_locations_.sink->value = sink_audio_location.value();
+ }
+
+ if (source_audio_location) {
+ leAudioDevice->audio_locations_.source->value = source_audio_location.value();
+ }
+
/* Presence of PAC characteristic for a direction means support for that direction */
- if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.source) {
leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource;
}
- if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.sink) {
leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink;
+ callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_,
+ leAudioDevice->audio_locations_.sink->value);
}
if (!DeserializeSinkPacs(leAudioDevice, sink_pacs)) {
@@ -2198,13 +2210,13 @@ public:
std::get<0>(pac_tuple).val_hdl);
}
- if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.sink) {
BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_hdls_.val_hdl);
+ leAudioDevice->audio_locations_.sink->handles.val_hdl);
}
- if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.source) {
BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_,
- leAudioDevice->src_audio_locations_hdls_.val_hdl);
+ leAudioDevice->audio_locations_.source->handles.val_hdl);
}
if (leAudioDevice->audio_avail_hdls_.val_hdl != 0) {
BTA_GATTC_DeregisterForNotifications(gatt_if_, leAudioDevice->address_,
@@ -2326,15 +2338,15 @@ public:
return;
}
- if (hdl == leAudioDevice->snk_audio_locations_hdls_.val_hdl) {
+ if (leAudioDevice->audio_locations_.sink &&
+ hdl == leAudioDevice->audio_locations_.sink->handles.val_hdl) {
AudioLocations snk_audio_locations;
-
bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(snk_audio_locations, len,
value);
/* Value may not change */
- if ((leAudioDevice->audio_directions_ & bluetooth::le_audio::types::kLeAudioDirectionSink) &&
- (leAudioDevice->snk_audio_locations_ ^ snk_audio_locations).none()) {
+ if (!leAudioDevice->audio_locations_.sink ||
+ (leAudioDevice->audio_locations_.sink->value ^ snk_audio_locations).none()) {
return;
}
@@ -2342,29 +2354,26 @@ public:
* audio location. Value of 0x00000000 means mono/unspecified
*/
leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSink;
- leAudioDevice->snk_audio_locations_ = snk_audio_locations;
+ leAudioDevice->audio_locations_.sink->value = snk_audio_locations;
- callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_,
- snk_audio_locations.to_ulong());
+ callbacks_->OnSinkAudioLocationAvailable(leAudioDevice->address_, snk_audio_locations);
if (notify) {
- btif_storage_set_leaudio_audio_location(leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_.to_ulong(),
- leAudioDevice->src_audio_locations_.to_ulong());
+ btif_storage_set_leaudio_sink_audio_location(
+ leAudioDevice->address_, leAudioDevice->audio_locations_.sink->value.to_ulong());
if (group && group->IsReleasingOrIdle()) {
UpdateLocationsAndContextsAvailability(group);
}
}
- } else if (hdl == leAudioDevice->src_audio_locations_hdls_.val_hdl) {
+ } else if (leAudioDevice->audio_locations_.source &&
+ hdl == leAudioDevice->audio_locations_.source->handles.val_hdl) {
AudioLocations src_audio_locations;
-
bluetooth::le_audio::client_parser::pacs::ParseAudioLocations(src_audio_locations, len,
value);
/* Value may not change */
- if ((leAudioDevice->audio_directions_ &
- bluetooth::le_audio::types::kLeAudioDirectionSource) &&
- (leAudioDevice->src_audio_locations_ ^ src_audio_locations).none()) {
+ if (!leAudioDevice->audio_locations_.source ||
+ (leAudioDevice->audio_locations_.source->value ^ src_audio_locations).none()) {
return;
}
@@ -2372,12 +2381,11 @@ public:
* audio location. Value of 0x00000000 means mono/unspecified
*/
leAudioDevice->audio_directions_ |= bluetooth::le_audio::types::kLeAudioDirectionSource;
- leAudioDevice->src_audio_locations_ = src_audio_locations;
+ leAudioDevice->audio_locations_.source->value = src_audio_locations;
if (notify) {
- btif_storage_set_leaudio_audio_location(leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_.to_ulong(),
- leAudioDevice->src_audio_locations_.to_ulong());
+ btif_storage_set_leaudio_source_audio_location(
+ leAudioDevice->address_, leAudioDevice->audio_locations_.source->value.to_ulong());
if (group && group->IsReleasingOrIdle()) {
UpdateLocationsAndContextsAvailability(group);
}
@@ -2389,6 +2397,12 @@ public:
return;
}
+ AudioContexts current_group_contexts;
+
+ if (group) {
+ current_group_contexts = group->GetAvailableContexts();
+ }
+
leAudioDevice->SetAvailableContexts(contexts);
if (!group) {
@@ -2407,11 +2421,13 @@ public:
return;
}
+ /* Whenever context type change, notify user about that.
+ * Note: GetAvailableContexts() add streaming context as well
+ */
+ UpdateLocationsAndContextsAvailability(
+ group, current_group_contexts != group->GetAvailableContexts());
+
if (!group->IsStreaming()) {
- /* Group is not streaming. Device does not have to be attach to the
- * stream, and we can update context availability for the group
- */
- UpdateLocationsAndContextsAvailability(group);
return;
}
@@ -2429,7 +2445,7 @@ public:
supp_audio_contexts.source.value());
}
} else if (hdl == leAudioDevice->ctp_hdls_.val_hdl) {
- groupStateMachine_->ProcessGattCtpNotification(group, value, len);
+ groupStateMachine_->ProcessGattCtpNotification(group, leAudioDevice, value, len);
} else if (hdl == leAudioDevice->tmap_role_hdl_) {
bluetooth::le_audio::client_parser::tmap::ParseTmapRole(leAudioDevice->tmap_role_, len,
value);
@@ -2624,14 +2640,14 @@ public:
std::get<0>(pac_tuple), gatt_register, write_ccc);
}
- if (leAudioDevice->snk_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.sink) {
subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_hdls_, gatt_register,
+ leAudioDevice->audio_locations_.sink->handles, gatt_register,
write_ccc);
}
- if (leAudioDevice->src_audio_locations_hdls_.val_hdl != 0) {
+ if (leAudioDevice->audio_locations_.source) {
subscribe_for_notification(leAudioDevice->conn_id_, leAudioDevice->address_,
- leAudioDevice->src_audio_locations_hdls_, gatt_register,
+ leAudioDevice->audio_locations_.source->handles, gatt_register,
write_ccc);
}
@@ -2972,7 +2988,7 @@ public:
}
bool subscribe_for_notification(tCONN_ID conn_id, const RawAddress& address,
- struct bluetooth::le_audio::types::hdl_pair handle_pair,
+ const struct bluetooth::le_audio::types::hdl_pair& handle_pair,
bool gatt_register = true, bool write_ccc = true) {
std::vector<uint8_t> value(2);
uint8_t* ptr = value.data();
@@ -3282,55 +3298,51 @@ public:
"Found Source PAC characteristic, handle: 0x{:04x}, ccc handle: 0x{:04x}, addr: {}",
charac.value_handle, hdl_pair.ccc_hdl, leAudioDevice->address_);
} else if (charac.uuid == bluetooth::le_audio::uuid::kSinkAudioLocationCharacteristicUuid) {
- leAudioDevice->snk_audio_locations_hdls_.val_hdl = charac.value_handle;
- leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac);
+ auto ccc_hdl = find_ccc_handle(charac);
+ leAudioDevice->audio_locations_.sink.emplace(hdl_pair(charac.value_handle, ccc_hdl),
+ AudioLocations(0));
- if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl == 0) {
+ if (ccc_hdl == 0) {
log::info(", snk audio locations char doesn't have ccc");
- }
-
- if (leAudioDevice->snk_audio_locations_hdls_.ccc_hdl != 0 &&
- !subscribe_for_notification(conn_id, leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_hdls_)) {
+ } else if (!subscribe_for_notification(conn_id, leAudioDevice->address_,
+ leAudioDevice->audio_locations_.sink->handles)) {
disconnectInvalidDevice(leAudioDevice, ", could not subscribe for snk locations char",
LeAudioHealthDeviceStatType::INVALID_DB);
return;
}
/* Obtain initial state of sink audio locations */
- BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->snk_audio_locations_hdls_.val_hdl,
+ BtaGattQueue::ReadCharacteristic(conn_id,
+ leAudioDevice->audio_locations_.sink->handles.val_hdl,
OnGattReadRspStatic, NULL);
log::info(
- "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc "
- "handle: 0x{:04x}, addr: {}",
- charac.value_handle, leAudioDevice->snk_audio_locations_hdls_.ccc_hdl,
- leAudioDevice->address_);
+ "Found Sink audio locations characteristic, handle: 0x{:04x}, ccc handle: "
+ "0x{:04x}, addr: {}",
+ charac.value_handle, ccc_hdl, leAudioDevice->address_);
} else if (charac.uuid == bluetooth::le_audio::uuid::kSourceAudioLocationCharacteristicUuid) {
- leAudioDevice->src_audio_locations_hdls_.val_hdl = charac.value_handle;
- leAudioDevice->src_audio_locations_hdls_.ccc_hdl = find_ccc_handle(charac);
+ auto ccc_hdl = find_ccc_handle(charac);
+ leAudioDevice->audio_locations_.source.emplace(hdl_pair(charac.value_handle, ccc_hdl),
+ AudioLocations(0));
- if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl == 0) {
+ if (ccc_hdl == 0) {
log::info(", src audio locations char doesn't have ccc");
- }
-
- if (leAudioDevice->src_audio_locations_hdls_.ccc_hdl != 0 &&
- !subscribe_for_notification(conn_id, leAudioDevice->address_,
- leAudioDevice->src_audio_locations_hdls_)) {
+ } else if (!subscribe_for_notification(conn_id, leAudioDevice->address_,
+ leAudioDevice->audio_locations_.source->handles)) {
disconnectInvalidDevice(leAudioDevice, ", could not subscribe for src locations char",
LeAudioHealthDeviceStatType::INVALID_DB);
return;
}
/* Obtain initial state of source audio locations */
- BtaGattQueue::ReadCharacteristic(conn_id, leAudioDevice->src_audio_locations_hdls_.val_hdl,
+ BtaGattQueue::ReadCharacteristic(conn_id,
+ leAudioDevice->audio_locations_.source->handles.val_hdl,
OnGattReadRspStatic, NULL);
log::info(
- "Found Source audio locations characteristic, handle: 0x{:04x}, "
- "ccc handle: 0x{:04x}, addr: {}",
- charac.value_handle, leAudioDevice->src_audio_locations_hdls_.ccc_hdl,
- leAudioDevice->address_);
+ "Found Source audio locations characteristic, handle: 0x{:04x}, ccc handle: "
+ "0x{:04x}, addr: {}",
+ charac.value_handle, ccc_hdl, leAudioDevice->address_);
} else if (charac.uuid ==
bluetooth::le_audio::uuid::kAudioContextAvailabilityCharacteristicUuid) {
leAudioDevice->audio_avail_hdls_.val_hdl = charac.value_handle;
@@ -3948,8 +3960,11 @@ public:
uint16_t left_cis_handle = 0;
uint16_t right_cis_handle = 0;
for (auto const& info : group->stream_conf.stream_params.source.stream_config.stream_map) {
- if (info.audio_channel_allocation &
- bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft) {
+ // Use the left channel decoder for the Mono Audio microphone
+ auto is_mono = info.audio_channel_allocation ==
+ bluetooth::le_audio::codec_spec_conf::kLeAudioLocationMonoAudio;
+ if (is_mono || (info.audio_channel_allocation &
+ bluetooth::le_audio::codec_spec_conf::kLeAudioLocationAnyLeft)) {
left_cis_handle = info.stream_handle;
}
if (info.audio_channel_allocation &
@@ -5407,6 +5422,24 @@ public:
auto all_bidirectional_contexts = group->GetAllSupportedBidirectionalContextTypes();
log::debug("all_bidirectional_contexts {}", ToString(all_bidirectional_contexts));
+ /*
+ * Detect the gaming scenario and mirror the context to the other direction.
+ * Thanks to this, we will be able to configure even Microphone only devices, for the GAME
+ * audio context detected on the local audio source, which never gets resumed for such devices.
+ */
+ if (remote_metadata.sink.test(LeAudioContextType::GAME)) {
+ auto ctxs = group->GetSupportedContexts(bluetooth::le_audio::types::kLeAudioDirectionSource) &
+ AudioContexts(LeAudioContextType::GAME) &
+ bluetooth::le_audio::types::kLeAudioContextAllBidir;
+ if (ctxs.any()) {
+ log::debug(
+ "Gaming scenario detected. Use this audio context for the other direction if "
+ "supported");
+ remote_metadata.source.clear();
+ remote_metadata.source.set_all(ctxs);
+ }
+ }
+
/* Make sure we have CONVERSATIONAL when in a call and it is not mixed
* with any other bidirectional context
*/
@@ -5446,10 +5479,26 @@ public:
log::debug("is_ongoing_call_on_other_direction={}",
is_ongoing_call_on_other_direction ? "True" : "False");
- if (remote_metadata.get(remote_other_direction).test_any(all_bidirectional_contexts) &&
- !(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction)) {
- log::debug("The other direction is not streaming bidirectional, ignore that context.");
- remote_metadata.get(remote_other_direction).clear();
+ /* If the other direction is a bidir scenario we might want to take it into the account, but
+ * not always. Look below for details.
+ */
+ auto is_other_direction_bidir =
+ remote_metadata.get(remote_other_direction).test_any(all_bidirectional_contexts);
+
+ /* If the not-resumed direction is local source, we might need to take it's metadata,
+ * (this way we detect GAME scenario), but local sink metadata is unreliable.
+ */
+ bool take_unresumed_local_source_metadata_for_mic_only_devices =
+ (group->audio_locations_.sink == std::nullopt) &&
+ (local_other_direction == bluetooth::le_audio::types::kLeAudioDirectionSource);
+ if (is_other_direction_bidir) {
+ if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction) &&
+ !take_unresumed_local_source_metadata_for_mic_only_devices) {
+ log::debug(
+ "The other direction is not streaming bidirectional or is not a reliable source of "
+ "metadata, ignore that context.");
+ remote_metadata.get(remote_other_direction).clear();
+ }
}
auto single_direction_only_context_types =
@@ -5474,7 +5523,8 @@ public:
remote_metadata.get(remote_direction).unset_all(all_bidirectional_contexts);
remote_metadata.get(remote_direction).set(LeAudioContextType::CONVERSATIONAL);
} else {
- if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction)) {
+ if (!(is_streaming_other_direction || is_releasing_for_reconfiguration_other_direction) &&
+ !take_unresumed_local_source_metadata_for_mic_only_devices) {
// Do not take the obsolete metadata
remote_metadata.get(remote_other_direction).clear();
} else {
@@ -5729,9 +5779,14 @@ public:
btif_storage_leaudio_update_pacs_bin(leAudioDevice->address_);
btif_storage_leaudio_update_ase_bin(leAudioDevice->address_);
- btif_storage_set_leaudio_audio_location(leAudioDevice->address_,
- leAudioDevice->snk_audio_locations_.to_ulong(),
- leAudioDevice->src_audio_locations_.to_ulong());
+ if (leAudioDevice->audio_locations_.sink) {
+ btif_storage_set_leaudio_sink_audio_location(
+ leAudioDevice->address_, leAudioDevice->audio_locations_.sink->value.to_ulong());
+ }
+ if (leAudioDevice->audio_locations_.source) {
+ btif_storage_set_leaudio_source_audio_location(
+ leAudioDevice->address_, leAudioDevice->audio_locations_.source->value.to_ulong());
+ }
instance->connectionReady(leAudioDevice);
}
@@ -6794,8 +6849,8 @@ DeviceGroupsCallbacksImpl deviceGroupsCallbacksImpl;
} // namespace
void LeAudioClient::AddFromStorage(
- const RawAddress& addr, bool autoconnect, int sink_audio_location,
- int source_audio_location, int sink_supported_context_types,
+ const RawAddress& addr, bool autoconnect, std::optional<int> sink_audio_location,
+ std::optional<int> source_audio_location, int sink_supported_context_types,
int source_supported_context_types, const std::vector<uint8_t>& handles,
const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs,
const std::vector<uint8_t>& ases, const std::vector<uint8_t>& gmap) {
@@ -6909,15 +6964,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);
}
}
diff --git a/system/bta/le_audio/client_linux.cc b/system/bta/le_audio/client_linux.cc
index 9908ef0a61..abf6a8faad 100644
--- a/system/bta/le_audio/client_linux.cc
+++ b/system/bta/le_audio/client_linux.cc
@@ -49,8 +49,8 @@ void LeAudioClient::Cleanup(void) {}
LeAudioClient* LeAudioClient::Get(void) { return nullptr; }
void LeAudioClient::DebugDump(int fd) {}
void LeAudioClient::AddFromStorage(
- const RawAddress& addr, bool autoconnect, int sink_audio_location,
- int source_audio_location, int sink_supported_context_types,
+ const RawAddress& addr, bool autoconnect, std::optional<int> sink_audio_location,
+ std::optional<int> source_audio_location, int sink_supported_context_types,
int source_supported_context_types, const std::vector<uint8_t>& handles,
const std::vector<uint8_t>& sink_pacs, const std::vector<uint8_t>& source_pacs,
const std::vector<uint8_t>& ases, const std::vector<uint8_t>& gmap) {}
diff --git a/system/bta/le_audio/codec_manager.cc b/system/bta/le_audio/codec_manager.cc
index ab3da44849..9452218c5d 100644
--- a/system/bta/le_audio/codec_manager.cc
+++ b/system/bta/le_audio/codec_manager.cc
@@ -1059,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:");
@@ -1088,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
@@ -1312,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;
diff --git a/system/bta/le_audio/codec_manager_test.cc b/system/bta/le_audio/codec_manager_test.cc
index 54ba7ac195..b8f79a609b 100644
--- a/system/bta/le_audio/codec_manager_test.cc
+++ b/system/bta/le_audio/codec_manager_test.cc
@@ -29,6 +29,7 @@
#include "le_audio/gmap_server.h"
#include "le_audio/le_audio_types.h"
#include "le_audio_set_configuration_provider.h"
+#include "osi/include/properties.h"
#include "test/mock/mock_legacy_hci_interface.h"
#include "test/mock/mock_main_shim_entry.h"
@@ -46,8 +47,6 @@ using bluetooth::le_audio::types::CodecLocation;
using bluetooth::le_audio::types::kLeAudioDirectionSink;
using bluetooth::le_audio::types::kLeAudioDirectionSource;
-void osi_property_set_bool(const char* key, bool value);
-
static const std::vector<AudioSetConfiguration> offload_capabilities_none(0);
const std::vector<AudioSetConfiguration>* offload_capabilities = &offload_capabilities_none;
@@ -726,6 +725,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 27cfd9e5e3..43f27c0a31 100644
--- a/system/bta/le_audio/device_groups.cc
+++ b/system/bta/le_audio/device_groups.cc
@@ -41,6 +41,7 @@
#include "btm_ble_api_types.h"
#include "btm_iso_api.h"
#include "btm_iso_api_types.h"
+#include "client_parser.h"
#include "com_android_bluetooth_flags.h"
#include "common/strings.h"
#include "gatt_api.h"
@@ -457,6 +458,14 @@ LeAudioDevice* LeAudioDeviceGroup::GetNextActiveDevice(LeAudioDevice* leAudioDev
return (iter == leAudioDevices_.end()) ? nullptr : (iter->lock()).get();
}
+int LeAudioDeviceGroup::GetNumOfActiveDevices(void) const {
+ int result = 0;
+ for (auto dev = GetFirstActiveDevice(); dev; dev = GetNextActiveDevice(dev)) {
+ result++;
+ }
+ return result;
+}
+
LeAudioDevice* LeAudioDeviceGroup::GetFirstActiveDeviceByCisAndDataPathState(
CisState cis_state, DataPathState data_path_state) const {
auto iter = std::find_if(
@@ -815,13 +824,6 @@ uint16_t LeAudioDeviceGroup::GetRemoteDelay(uint8_t direction) const {
return remote_delay_ms;
}
-bool LeAudioDeviceGroup::UpdateAudioContextAvailability(void) {
- log::debug("{}", group_id_);
- auto old_contexts = GetAvailableContexts();
- SetAvailableContexts(GetLatestAvailableContexts());
- return old_contexts != GetAvailableContexts();
-}
-
CodecManager::UnicastConfigurationRequirements
LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextType ctx_type) const {
auto new_req = CodecManager::UnicastConfigurationRequirements{
@@ -839,6 +841,12 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy
BidirectionalPair<bool> has_location = {false, false};
for (auto direction : {types::kLeAudioDirectionSink, types::kLeAudioDirectionSource}) {
+ if (!device->audio_locations_.get(direction)) {
+ log::debug("Device {} has no audio allocation for direction: {}", device->address_,
+ (int)direction);
+ continue;
+ }
+
// Do not put any requirements on the Source if Sink only scenario is used
// Note: With the RINGTONE we should already prepare for a call.
if ((direction == types::kLeAudioDirectionSource) &&
@@ -870,10 +878,8 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy
}
}
- auto& dev_locations = (direction == types::kLeAudioDirectionSink)
- ? device->snk_audio_locations_
- : device->src_audio_locations_;
- if (dev_locations.none()) {
+ auto const& dev_locations = device->audio_locations_.get(direction);
+ if (dev_locations == std::nullopt) {
log::warn("Device {} has no specified locations for direction: {}", device->address_,
(int)direction);
}
@@ -888,8 +894,9 @@ LeAudioDeviceGroup::GetAudioSetConfigurationRequirements(types::LeAudioContextTy
}
// Pass the audio channel allocation requirement according to TMAP
- auto locations = dev_locations.to_ulong() & (codec_spec_conf::kLeAudioLocationFrontLeft |
- codec_spec_conf::kLeAudioLocationFrontRight);
+ auto locations =
+ dev_locations->value.to_ulong() & (codec_spec_conf::kLeAudioLocationFrontLeft |
+ codec_spec_conf::kLeAudioLocationFrontRight);
CodecManager::UnicastConfigurationRequirements::DeviceDirectionRequirements config_req;
config_req.params.Add(codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation,
(uint32_t)locations);
@@ -1040,7 +1047,7 @@ void LeAudioDeviceGroup::ResetPreferredAudioSetConfiguration(void) const {
void LeAudioDeviceGroup::InvalidateCachedConfigurations(void) {
log::info("Group id: {}", group_id_);
context_to_configuration_cache_map_.clear();
- ResetPreferredAudioSetConfiguration();
+ context_to_preferred_configuration_cache_map_.clear();
}
types::BidirectionalPair<AudioContexts> LeAudioDeviceGroup::GetLatestAvailableContexts() const {
@@ -1056,27 +1063,29 @@ types::BidirectionalPair<AudioContexts> LeAudioDeviceGroup::GetLatestAvailableCo
}
bool LeAudioDeviceGroup::ReloadAudioLocations(void) {
- AudioLocations updated_snk_audio_locations_ = codec_spec_conf::kLeAudioLocationMonoAudio;
- AudioLocations updated_src_audio_locations_ = codec_spec_conf::kLeAudioLocationMonoAudio;
-
- for (const auto& device : leAudioDevices_) {
- if (device.expired() ||
- (device.lock().get()->GetConnectionState() != DeviceConnectState::CONNECTED)) {
- continue;
+ types::BidirectionalPair<std::optional<AudioLocations>> updated_audio_locations = {
+ .sink = std::nullopt, .source = std::nullopt};
+
+ for (const auto& device_locked : leAudioDevices_) {
+ auto device = device_locked.lock();
+ if (device && device->GetConnectionState() == DeviceConnectState::CONNECTED) {
+ if (device->audio_locations_.sink) {
+ updated_audio_locations.sink =
+ updated_audio_locations.sink.value_or(0) | device->audio_locations_.sink->value;
+ }
+ if (device->audio_locations_.source) {
+ updated_audio_locations.source =
+ updated_audio_locations.source.value_or(0) | device->audio_locations_.source->value;
+ }
}
- updated_snk_audio_locations_ |= device.lock().get()->snk_audio_locations_;
- updated_src_audio_locations_ |= device.lock().get()->src_audio_locations_;
}
/* Nothing has changed */
- if ((updated_snk_audio_locations_ == snk_audio_locations_) &&
- (updated_src_audio_locations_ == src_audio_locations_)) {
+ if (updated_audio_locations == audio_locations_) {
return false;
}
- snk_audio_locations_ = updated_snk_audio_locations_;
- src_audio_locations_ = updated_src_audio_locations_;
-
+ audio_locations_ = updated_audio_locations;
return true;
}
@@ -1215,16 +1224,23 @@ types::LeAudioConfigurationStrategy LeAudioDeviceGroup::GetGroupSinkStrategy() c
auto strategy_selector = [&, this](uint8_t direction) {
int expected_group_size = Size();
+ if (!audio_locations_.get(direction)) {
+ log::error("No audio locations for direction: {} available in the group", +direction);
+ return types::LeAudioConfigurationStrategy::RFU;
+ }
+
/* Simple strategy picker */
log::debug("Group {} size {}", group_id_, expected_group_size);
if (expected_group_size > 1) {
return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE;
}
- log::debug("audio location 0x{:04x}", snk_audio_locations_.to_ulong());
- if (!(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) ||
- !(snk_audio_locations_.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight) ||
- snk_audio_locations_.none()) {
+ /* Check supported audio locations */
+ auto const& locations = audio_locations_.get(direction).value();
+
+ log::verbose("audio location 0x{:04x}", locations.to_ulong());
+ if (!(locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyLeft) ||
+ !(locations.to_ulong() & codec_spec_conf::kLeAudioLocationAnyRight) || locations.none()) {
return types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE;
}
@@ -1596,14 +1612,23 @@ void LeAudioDeviceGroup::CigConfiguration::UnassignCis(LeAudioDevice* leAudioDev
static bool CheckIfStrategySupported(types::LeAudioConfigurationStrategy strategy,
const types::AseConfiguration& conf, uint8_t direction,
const LeAudioDevice& device) {
+ if (strategy == types::LeAudioConfigurationStrategy::RFU) {
+ log::error("Device {}: No valid strategy for direction: {}", device.address_, +direction);
+ return false;
+ }
+
+ if (!device.audio_locations_.get(direction)) {
+ log::error("Device {}: No valid audio locations for direction: {}", device.address_,
+ +direction);
+ return false;
+ }
+
/* Check direction and if audio location allows to create more cises to a
* single device.
*/
- types::AudioLocations audio_locations = (direction == types::kLeAudioDirectionSink)
- ? device.snk_audio_locations_
- : device.src_audio_locations_;
-
- log::debug("strategy: {}, locations: {}", (int)strategy, audio_locations.to_ulong());
+ auto const& audio_locations = device.audio_locations_.get(direction)->value;
+ log::debug("Device {}: strategy: {}, locations: {}", device.address_, (int)strategy,
+ audio_locations.to_ulong());
switch (strategy) {
case types::LeAudioConfigurationStrategy::MONO_ONE_CIS_PER_DEVICE:
@@ -2267,10 +2292,8 @@ bool LeAudioDeviceGroup::Configure(
types::BidirectionalPair<std::vector<uint8_t>> ccid_lists) {
auto conf = GetConfiguration(context_type);
if (!conf) {
- log::error(
- ", requested context type: {} , is in mismatch with cached available "
- "contexts",
- bluetooth::common::ToString(context_type));
+ log::error("Requested context type: {} , is in mismatch with cached available contexts",
+ bluetooth::common::ToString(context_type));
return false;
}
diff --git a/system/bta/le_audio/device_groups.h b/system/bta/le_audio/device_groups.h
index a9114525d4..a05145581e 100644
--- a/system/bta/le_audio/device_groups.h
+++ b/system/bta/le_audio/device_groups.h
@@ -94,8 +94,7 @@ public:
bool notify_streaming_when_cises_are_ready_;
uint8_t audio_directions_;
- types::AudioLocations snk_audio_locations_;
- types::AudioLocations src_audio_locations_;
+ types::BidirectionalPair<std::optional<types::AudioLocations>> audio_locations_;
/* Whether LE Audio is preferred for OUTPUT_ONLY and DUPLEX cases */
bool is_output_preference_le_audio;
@@ -122,10 +121,9 @@ public:
metadata_context_type_(
{.sink = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED),
.source = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED)}),
- group_available_contexts_(
+ streaming_metadata_context_type_(
{.sink = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED),
.source = types::AudioContexts(types::LeAudioContextType::UNINITIALIZED)}),
- pending_group_available_contexts_change_(types::LeAudioContextType::UNINITIALIZED),
group_user_allowed_context_mask_(
{.sink = types::AudioContexts(types::kLeAudioContextAllTypes),
.source = types::AudioContexts(types::kLeAudioContextAllTypes)}),
@@ -178,6 +176,7 @@ public:
LeAudioDevice* GetNextActiveDeviceByCisAndDataPathState(
LeAudioDevice* leAudioDevice, types::CisState cis_state,
types::DataPathState data_path_state) const;
+ int GetNumOfActiveDevices(void) const;
bool IsDeviceInTheGroup(LeAudioDevice* leAudioDevice) const;
bool HaveAllActiveDevicesAsesTheSameState(types::AseState state) const;
bool HaveAnyActiveDeviceInStreamingState() const;
@@ -207,7 +206,6 @@ public:
uint8_t GetTargetPhy(uint8_t direction) const;
bool GetPresentationDelay(uint32_t* delay, uint8_t direction) const;
uint16_t GetRemoteDelay(uint8_t direction) const;
- bool UpdateAudioContextAvailability(void);
bool UpdateAudioSetConfigurationCache(types::LeAudioContextType ctx_type,
bool use_preferred = false) const;
CodecManager::UnicastConfigurationRequirements GetAudioSetConfigurationRequirements(
@@ -287,20 +285,6 @@ public:
log::info("In transition flag = {}", in_transition_);
}
- /* Returns context types for which support was recently added or removed */
- inline types::AudioContexts GetPendingAvailableContextsChange() const {
- return pending_group_available_contexts_change_;
- }
-
- /* Set which context types were recently added or removed */
- inline void SetPendingAvailableContextsChange(types::AudioContexts audio_contexts) {
- pending_group_available_contexts_change_ = audio_contexts;
- }
-
- inline void ClearPendingAvailableContextsChange() {
- pending_group_available_contexts_change_.clear();
- }
-
inline void SetConfigurationContextType(types::LeAudioContextType context_type) {
configuration_context_type_ = context_type;
}
@@ -319,22 +303,46 @@ public:
return metadata_context_type_;
}
- inline void SetAvailableContexts(types::BidirectionalPair<types::AudioContexts> new_contexts) {
- group_available_contexts_ = new_contexts;
- log::debug("group id: {}, available contexts sink: {}, available contexts source: {}",
- group_id_, group_available_contexts_.sink.to_string(),
- group_available_contexts_.source.to_string());
+ inline void SetStreamingMetadataContexts(types::AudioContexts& metadata, int remote_direction) {
+ log::debug("group_id: {}, direction: {}, metadata: {}", group_id_,
+ remote_direction == types::kLeAudioDirectionSink ? "sink" : "source",
+ common::ToString(metadata));
+ streaming_metadata_context_type_.get(remote_direction) = metadata;
+ }
+
+ inline types::BidirectionalPair<types::AudioContexts> GetStreamingMetadataContexts() const {
+ log::debug("group_id: {}, sink: {}, source: {}", group_id_,
+ common::ToString(streaming_metadata_context_type_.sink),
+ common::ToString(streaming_metadata_context_type_.source));
+ return streaming_metadata_context_type_;
+ }
+
+ inline void ClearStreamingMetadataContexts() {
+ log::debug("group_id: {}", group_id_);
+ streaming_metadata_context_type_.sink.clear();
+ streaming_metadata_context_type_.source.clear();
}
types::AudioContexts GetAvailableContexts(int direction = types::kLeAudioDirectionBoth) const {
log::assert_that(direction <= (types::kLeAudioDirectionBoth), "Invalid direction used.");
+
+ auto streaming_metadata = GetStreamingMetadataContexts();
+ types::BidirectionalPair<types::AudioContexts> available_contexts =
+ GetLatestAvailableContexts();
+
+ log::debug(
+ "group id: {}, streaming contexts sink: {}, streaming contexts source: {}, available "
+ "contexts sink: {}, available contexts source: {}",
+ group_id_, streaming_metadata.sink.to_string(), streaming_metadata.source.to_string(),
+ available_contexts.sink.to_string(), available_contexts.source.to_string());
+
+ available_contexts.sink |= streaming_metadata.sink;
+ available_contexts.source |= streaming_metadata.source;
+
if (direction < types::kLeAudioDirectionBoth) {
- log::debug("group id: {}, available contexts sink: {}, available contexts source: {}",
- group_id_, group_available_contexts_.sink.to_string(),
- group_available_contexts_.source.to_string());
- return group_available_contexts_.get(direction);
+ return available_contexts.get(direction);
} else {
- return types::get_bidirectional(group_available_contexts_);
+ return types::get_bidirectional(available_contexts);
}
}
@@ -445,18 +453,7 @@ private:
/* Current configuration and metadata context types */
types::LeAudioContextType configuration_context_type_;
types::BidirectionalPair<types::AudioContexts> metadata_context_type_;
-
- /* Mask of contexts that the whole group can handle at its current state
- * It's being updated each time group members connect, disconnect or their
- * individual available audio contexts are changed.
- */
- types::BidirectionalPair<types::AudioContexts> group_available_contexts_;
-
- /* A temporary mask for bits which were either added or removed when the
- * group available context type changes. It usually means we should refresh
- * our group configuration capabilities to clear this.
- */
- types::AudioContexts pending_group_available_contexts_change_;
+ types::BidirectionalPair<types::AudioContexts> streaming_metadata_context_type_;
/* Mask of currently allowed context types. Not set a value not set will
* result in streaming rejection.
diff --git a/system/bta/le_audio/devices.cc b/system/bta/le_audio/devices.cc
index ec856c8c42..1d23d93d5e 100644
--- a/system/bta/le_audio/devices.cc
+++ b/system/bta/le_audio/devices.cc
@@ -202,9 +202,18 @@ static uint32_t GetFirstRight(const AudioLocations& audio_locations) {
return 0;
}
-static uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy,
- const AudioLocations& device_locations,
- AudioLocations& group_locations) {
+static uint32_t PickAudioLocation(
+ types::LeAudioConfigurationStrategy strategy, uint8_t direction,
+ const types::BidirectionalPair<
+ std::optional<types::hdl_pair_wrapper<types::AudioLocations>>>&
+ device_audio_locations,
+ AudioLocations& group_locations) {
+ if (!device_audio_locations.get(direction)) {
+ log::error("No valid location is available for direction {}", +direction);
+ return 0;
+ }
+ auto const device_locations = device_audio_locations.get(direction)->value;
+
log::debug("strategy: {}, locations: 0x{:x}, input group locations: 0x{:x}", (int)strategy,
device_locations.to_ulong(), group_locations.to_ulong());
@@ -215,7 +224,9 @@ static uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy,
uint32_t left_device_loc = GetFirstLeft(device_locations);
uint32_t right_device_loc = GetFirstRight(device_locations);
- if (left_device_loc == 0 && right_device_loc == 0) {
+ /* Sink locations should be either Left or Right - TMAP 1.0 Sec. 3.5.1.2.1 */
+ if (direction == le_audio::types::kLeAudioDirectionSink && left_device_loc == 0 &&
+ right_device_loc == 0) {
log::warn("Can't find device able to render left and right audio channel");
}
@@ -244,15 +255,23 @@ static uint32_t PickAudioLocation(types::LeAudioConfigurationStrategy strategy,
return 0;
}
- log::error(
- "Can't find device for left/right channel. Strategy: {}, "
- "device_locations: {:x}, output group_locations: {:x}.",
- strategy, device_locations.to_ulong(), group_locations.to_ulong());
-
/* Return either any left or any right audio location. It might result with
* multiple devices within the group having the same location.
*/
- return left_device_loc ? left_device_loc : right_device_loc;
+ auto location = left_device_loc ? left_device_loc : right_device_loc;
+
+ if (direction == le_audio::types::kLeAudioDirectionSink) {
+ log::error(
+ "Can't find device for left/right channel. Strategy: {}, device_locations: {:x}, "
+ "output group_locations: {:x}, chosen location: {}.",
+ strategy, device_locations.to_ulong(), group_locations.to_ulong(), location);
+ } else {
+ log::debug(
+ "No left or right audio location available. Strategy: {}, device_locations: {:x}, "
+ "output group_locations: {:x}, chosen location: {}.",
+ strategy, device_locations.to_ulong(), group_locations.to_ulong(), location);
+ }
+ return location;
}
bool LeAudioDevice::IsAudioSetConfigurationSupported(
@@ -287,6 +306,11 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_
AudioLocations& group_audio_locations_memo,
const AudioContexts& metadata_context_types,
const std::vector<uint8_t>& ccid_lists, bool reuse_cis_id) {
+ if (num_of_devices == 0) {
+ log::error("No devices available for configuration.");
+ return false;
+ }
+
auto direction_str = (direction == types::kLeAudioDirectionSink ? "Sink" : "Source");
/* First try to use the already configured ASE */
auto ase = GetFirstActiveAseByDirection(direction);
@@ -302,9 +326,12 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_
return false;
}
- auto audio_locations =
- (direction == types::kLeAudioDirectionSink) ? snk_audio_locations_ : src_audio_locations_;
+ if (!audio_locations_.get(direction)) {
+ log::error("{}, unable to find a {} audio allocation", address_, direction_str);
+ return false;
+ }
+ auto const& audio_locations = audio_locations_.get(direction)->value;
auto const& group_ase_configs = audio_set_conf->confs.get(direction);
std::vector<types::AseConfiguration> ase_configs;
std::copy_if(group_ase_configs.cbegin(), group_ase_configs.cend(),
@@ -406,7 +433,7 @@ bool LeAudioDevice::ConfigureAses(const types::AudioSetConfiguration* audio_set_
/* Let's choose audio channel allocation if not set */
ase->codec_config.params.Add(
codec_spec_conf::kLeAudioLtvTypeAudioChannelAllocation,
- PickAudioLocation(strategy, audio_locations, group_audio_locations_memo));
+ PickAudioLocation(strategy, direction, audio_locations_, group_audio_locations_memo));
/* Get default value if no requirement for specific frame blocks per sdu
*/
@@ -1043,8 +1070,12 @@ static std::string locationToString(uint32_t location) {
void LeAudioDevice::Dump(std::stringstream& stream) {
uint16_t acl_handle =
get_btm_client_interface().peer.BTM_GetHCIConnHandle(address_, BT_TRANSPORT_LE);
- std::string snk_location = locationToString(snk_audio_locations_.to_ulong());
- std::string src_location = locationToString(src_audio_locations_.to_ulong());
+ std::string snk_location = audio_locations_.sink
+ ? locationToString(audio_locations_.sink->value.to_ulong())
+ : "None";
+ std::string src_location = audio_locations_.source
+ ? locationToString(audio_locations_.source->value.to_ulong())
+ : "None";
stream << " ● Device address: " << address_.ToRedactedStringForLogging() << ", "
<< connection_state_
diff --git a/system/bta/le_audio/devices.h b/system/bta/le_audio/devices.h
index a176caaf4a..c934681ef2 100644
--- a/system/bta/le_audio/devices.h
+++ b/system/bta/le_audio/devices.h
@@ -93,14 +93,12 @@ public:
std::bitset<16> tmap_role_;
uint8_t audio_directions_;
- types::AudioLocations snk_audio_locations_;
- types::AudioLocations src_audio_locations_;
+ types::BidirectionalPair<std::optional<types::hdl_pair_wrapper<types::AudioLocations>>>
+ audio_locations_;
types::PublishedAudioCapabilities snk_pacs_;
types::PublishedAudioCapabilities src_pacs_;
- struct types::hdl_pair snk_audio_locations_hdls_;
- struct types::hdl_pair src_audio_locations_hdls_;
struct types::hdl_pair audio_avail_hdls_;
struct types::hdl_pair audio_supp_cont_hdls_;
std::vector<struct types::ase> ases_;
@@ -115,6 +113,8 @@ public:
alarm_t* link_quality_timer;
uint16_t link_quality_timer_data;
+ uint8_t last_ase_ctp_command_sent;
+
LeAudioDevice(const RawAddress& address, DeviceConnectState state,
int group_id = bluetooth::groups::kGroupUnknown)
: address_(address),
@@ -135,6 +135,7 @@ public:
acl_asymmetric_(false),
acl_phy_update_done_(false),
link_quality_timer(nullptr),
+ last_ase_ctp_command_sent(0x00),
dsa_({{DsaMode::DISABLED},
types::DataPathState::IDLE,
LE_AUDIO_INVALID_CIS_HANDLE,
diff --git a/system/bta/le_audio/devices_test.cc b/system/bta/le_audio/devices_test.cc
index bc53a5b18c..adc90e5213 100644
--- a/system/bta/le_audio/devices_test.cc
+++ b/system/bta/le_audio/devices_test.cc
@@ -101,6 +101,7 @@ class LeAudioDevicesTest : public Test {
protected:
void SetUp() override {
__android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
+ com::android::bluetooth::flags::provider_->reset_flags();
devices_ = new LeAudioDevices();
bluetooth::manager::SetMockBtmInterface(&btm_interface);
bluetooth::storage::SetMockBtifStorageInterface(&mock_btif_storage_);
@@ -310,19 +311,19 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) {
switch (id) {
case Lc3SettingId::LC3_8_1:
case Lc3SettingId::LC3_8_2:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq8000Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq8000Hz;
case Lc3SettingId::LC3_16_1:
case Lc3SettingId::LC3_16_2:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq16000Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq16000Hz;
case Lc3SettingId::LC3_24_1:
case Lc3SettingId::LC3_24_2:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq24000Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq24000Hz;
case Lc3SettingId::LC3_32_1:
case Lc3SettingId::LC3_32_2:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq32000Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq32000Hz;
case Lc3SettingId::LC3_441_1:
case Lc3SettingId::LC3_441_2:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq44100Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq44100Hz;
case Lc3SettingId::LC3_48_1:
case Lc3SettingId::LC3_48_2:
case Lc3SettingId::LC3_48_3:
@@ -330,7 +331,7 @@ uint8_t GetSamplingFrequency(Lc3SettingId id) {
case Lc3SettingId::LC3_48_5:
case Lc3SettingId::LC3_48_6:
case Lc3SettingId::LC3_VND_1:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioSamplingFreq48000Hz;
+ return codec_spec_conf::kLeAudioSamplingFreq48000Hz;
case Lc3SettingId::UNSUPPORTED:
return kLeAudioSamplingFreqRfu;
}
@@ -347,7 +348,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) {
case Lc3SettingId::LC3_48_1:
case Lc3SettingId::LC3_48_3:
case Lc3SettingId::LC3_48_5:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur7500us;
+ return codec_spec_conf::kLeAudioCodecFrameDur7500us;
case Lc3SettingId::LC3_8_2:
case Lc3SettingId::LC3_16_2:
case Lc3SettingId::LC3_24_2:
@@ -357,7 +358,7 @@ uint8_t GetFrameDuration(Lc3SettingId id) {
case Lc3SettingId::LC3_48_4:
case Lc3SettingId::LC3_48_6:
case Lc3SettingId::LC3_VND_1:
- return ::bluetooth::le_audio::codec_spec_conf::kLeAudioCodecFrameDur10000us;
+ return codec_spec_conf::kLeAudioCodecFrameDur10000us;
case Lc3SettingId::UNSUPPORTED:
return kLeAudioCodecFrameDurRfu;
}
@@ -655,8 +656,8 @@ protected:
kLeAudioDirectionSource);
}
- log::debug("snk confs size: {}", cfg.confs.sink.size());
- log::debug("src confs size: {}", cfg.confs.source.size());
+ log::debug("{}: snk confs size: {}", cfg.name, cfg.confs.sink.size());
+ log::debug("{}: src confs size: {}", cfg.name, cfg.confs.source.size());
return (!cfg.confs.sink.empty() || !cfg.confs.source.empty())
? std::make_unique<AudioSetConfiguration>(cfg)
: nullptr;
@@ -741,13 +742,11 @@ protected:
}
}
- LeAudioDevice* AddTestDevice(
- int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0, int src_ase_num_cached = 0,
- bool invert_ases_emplacement = false, bool out_of_range_device = false,
- uint8_t snk_allocation = codec_spec_conf::kLeAudioLocationFrontLeft |
- codec_spec_conf::kLeAudioLocationFrontRight,
- uint8_t src_allocation = codec_spec_conf::kLeAudioLocationFrontLeft |
- codec_spec_conf::kLeAudioLocationFrontRight) {
+ LeAudioDevice* AddTestDevice(int snk_ase_num, int src_ase_num, int snk_ase_num_cached = 0,
+ int src_ase_num_cached = 0, bool invert_ases_emplacement = false,
+ bool out_of_range_device = false,
+ std::optional<uint32_t> snk_allocation = kChannelAllocationStereo,
+ std::optional<uint32_t> src_allocation = kChannelAllocationStereo) {
int index = group_->Size() + 1;
auto device = (std::make_shared<LeAudioDevice>(GetTestAddress(index),
DeviceConnectState::DISCONNECTED));
@@ -792,8 +791,16 @@ protected:
.source = AudioContexts(kLeAudioContextAllTypes)});
device->SetAvailableContexts({.sink = AudioContexts(kLeAudioContextAllTypes),
.source = AudioContexts(kLeAudioContextAllTypes)});
- device->snk_audio_locations_ = snk_allocation;
- device->src_audio_locations_ = src_allocation;
+
+ if (snk_allocation) {
+ device->audio_locations_.sink.emplace(hdl_pair(0x00ea, 0x0eb),
+ types::AudioLocations(snk_allocation.value()));
+ }
+
+ if (src_allocation) {
+ device->audio_locations_.source.emplace(hdl_pair(0x00fa, 0x00fb),
+ types::AudioLocations(src_allocation.value()));
+ }
device->conn_id_ = index;
device->SetConnectionState(out_of_range_device ? DeviceConnectState::DISCONNECTED
@@ -803,6 +810,12 @@ protected:
return device.get();
}
+ LeAudioDevice* AddTestDevice(std::optional<std::pair<int, uint32_t>> sink,
+ std::optional<std::pair<int, uint32_t>> source = std::nullopt) {
+ return AddTestDevice(sink ? sink->first : 0, source ? source->first : 0, 0, 0, false, false,
+ sink ? sink->second : 0, source ? source->second : 0);
+ }
+
bool TestGroupAseConfigurationVerdict(const TestGroupAseConfigurationData& data,
uint8_t directions_to_verify) {
BidirectionalPair<uint8_t> active_channel_num = {0, 0};
@@ -895,9 +908,6 @@ protected:
BidirectionalPair<AudioContexts> group_audio_locations = {
.sink = AudioContexts(context_type), .source = AudioContexts(context_type)};
- /* Stimulate update of available context map */
- group_->UpdateAudioContextAvailability();
-
ASSERT_EQ(success_expected, group_->Configure(context_type, group_audio_locations));
bool result = true;
@@ -968,16 +978,11 @@ protected:
::bluetooth::le_audio::AudioSetConfigurationProvider::Get()->GetConfigurations(
context_type);
- bool success_expected = directions_to_verify != 0;
+ bool is_expected_to_match_config = directions_to_verify != 0;
int num_of_matching_configurations = 0;
for (const auto& audio_set_conf : *configurations) {
bool interesting_configuration = true;
- uint8_t configuration_directions = 0;
-
- // the configuration should fail if there are no active ases expected
- PublishedAudioCapabilitiesBuilder snk_pac_builder, src_pac_builder;
- snk_pac_builder.Reset();
- src_pac_builder.Reset();
+ uint8_t expected_configuration_directions = 0;
/* Let's go thru devices in the group and configure them*/
for (int i = 0; i < data_size; i++) {
@@ -986,43 +991,46 @@ protected:
/* Prepare PAC's for each device. Also make sure configuration is in our
* interest to test */
for (auto direction : {kLeAudioDirectionSink, kLeAudioDirectionSource}) {
- auto const& ase_confs = audio_set_conf->confs.get(direction);
- auto strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig(ase_confs, data_size);
- auto const ase_cnt = ase_confs.size();
-
- if (ase_cnt == 0) {
+ auto const& ase_confs = audio_set_conf->confs;
+ if (ase_confs.get(direction).size() == 0) {
// Skip the direction if not available
continue;
}
/* Make sure the strategy is the expected one */
- if (direction == kLeAudioDirectionSink && group_->GetGroupSinkStrategy() != strategy) {
+ auto ase_config_strategy = bluetooth::le_audio::utils::GetStrategyForAseConfig(
+ ase_confs.get(direction), data_size);
+ if (group_->GetGroupSinkStrategy() != ase_config_strategy) {
log::debug("Sink strategy mismatch group!=cfg.entry ({}!={})",
static_cast<int>(group_->GetGroupSinkStrategy()),
- static_cast<int>(strategy));
+ static_cast<int>(ase_config_strategy));
interesting_configuration = false;
}
- configuration_directions |= direction;
-
- auto& pac_builder =
- (direction == kLeAudioDirectionSink) ? snk_pac_builder : src_pac_builder;
auto& dest_pacs = (direction == kLeAudioDirectionSink) ? data[i].device->snk_pacs_
: data[i].device->src_pacs_;
- auto const& data_channel_counts = (direction == kLeAudioDirectionSink)
- ? data[i].audio_channel_counts_snk
- : data[i].audio_channel_counts_src;
+ auto const& pacs_data_channel_counts = (direction == kLeAudioDirectionSink)
+ ? data[i].audio_channel_counts_snk
+ : data[i].audio_channel_counts_src;
+
+ if (((direction == kLeAudioDirectionSink)
+ ? data[i].expected_active_channel_num_snk
+ : data[i].expected_active_channel_num_src) > 0) {
+ expected_configuration_directions |= direction;
+ }
- for (const auto& entry : ase_confs) {
- num_of_ase.get(direction)++;
- pac_builder.Add(entry.codec, data_channel_counts);
+ /* Add PAC records */
+ PublishedAudioCapabilitiesBuilder pac_builder;
+ for (const auto& entry : ase_confs.get(direction)) {
+ pac_builder.Add(entry.codec, pacs_data_channel_counts);
if (preferred_codec_config && should_use_preferred_codec) {
const auto customized_codec_config =
PreparePreferredCodecConfig(entry.codec, *preferred_codec_config);
- pac_builder.Add(customized_codec_config, data_channel_counts);
+ pac_builder.Add(customized_codec_config, pacs_data_channel_counts);
}
dest_pacs = pac_builder.Get();
}
+ num_of_ase.get(direction) += ase_confs.get(direction).size();
num_of_ase.get(direction) /= data_size;
}
@@ -1036,23 +1044,25 @@ protected:
}
}
- BidirectionalPair<AudioContexts> group_audio_locations = {
- .sink = AudioContexts(context_type), .source = AudioContexts(context_type)};
-
/* Set preferred codec*/
if (preferred_codec_config) {
group_->SetPreferredAudioSetConfiguration(*preferred_codec_config, *preferred_codec_config);
}
- /* Stimulate update of available context map */
- group_->UpdateAudioContextAvailability();
group_->UpdateAudioSetConfigurationCache(context_type);
+ BidirectionalPair<AudioContexts> group_audio_locations = {
+ .sink = AudioContexts(context_type), .source = AudioContexts(context_type)};
auto configuration_result = group_->Configure(context_type, group_audio_locations);
/* In case of configuration #ase is same as the one we expected to be
* activated verify, ASEs are actually active */
- if (interesting_configuration && (directions_to_verify == configuration_directions)) {
+ uint8_t configuration_directions =
+ (audio_set_conf->confs.sink.size() ? kLeAudioDirectionSink : 0) |
+ (audio_set_conf->confs.source.size() ? kLeAudioDirectionSource : 0);
+
+ if (interesting_configuration &&
+ (expected_configuration_directions == configuration_directions)) {
ASSERT_TRUE(configuration_result);
ASSERT_EQ(group_->GetPreferredConfiguration(context_type) != nullptr,
should_use_preferred_codec);
@@ -1073,13 +1083,23 @@ protected:
TestAsesInactive();
}
- if (success_expected) {
+ if (is_expected_to_match_config) {
ASSERT_GT(num_of_matching_configurations, 0);
} else {
ASSERT_EQ(0, num_of_matching_configurations);
}
}
+ auto TestGroupAseConfiguration(LeAudioContextType context_type,
+ std::vector<TestGroupAseConfigurationData> data,
+ uint8_t directions_to_verify = kLeAudioDirectionSink |
+ kLeAudioDirectionSource,
+ btle_audio_codec_config_t* preferred_codec_config = nullptr,
+ bool should_use_preferred_codec = false) {
+ return TestGroupAseConfiguration(context_type, data.data(), data.size(), directions_to_verify,
+ preferred_codec_config, should_use_preferred_codec);
+ }
+
void TestAsesActive(LeAudioCodecId codec_id, uint8_t sampling_frequency, uint8_t frame_duration,
uint16_t octets_per_frame, uint8_t codec_frame_blocks_per_sdu = 1) {
bool active_ase = false;
@@ -1174,8 +1194,6 @@ protected:
success_expected = false;
}
- /* Stimulate update of available context map */
- group_->UpdateAudioContextAvailability();
group_->UpdateAudioSetConfigurationCache(context_type);
BidirectionalPair<AudioContexts> group_audio_locations = {
.sink = AudioContexts(context_type), .source = AudioContexts(context_type)};
@@ -1362,12 +1380,10 @@ protected:
}
/* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
+ left->audio_locations_.sink->value = codec_spec_conf::kLeAudioLocationFrontLeft;
+ left->audio_locations_.source->value = codec_spec_conf::kLeAudioLocationFrontLeft;
+ right->audio_locations_.sink->value = codec_spec_conf::kLeAudioLocationFrontRight;
+ right->audio_locations_.source->value = codec_spec_conf::kLeAudioLocationFrontRight;
group_->ReloadAudioLocations();
ASSERT_TRUE(group_->Configure(context_type, {.sink = AudioContexts(context_type),
@@ -1408,16 +1424,12 @@ protected:
};
TEST_P(LeAudioAseConfigurationTest, test_context_update) {
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
- ASSERT_EQ(2, group_->Size());
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
- /* Change locations */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
+ ASSERT_EQ(2, group_->Size());
/* Put the PACS */
auto conversational_configuration = getSpecificConfiguration(
@@ -1473,7 +1485,6 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) {
remote_snk_avail_contexts | remote_src_avail_contexts | right_bud_only_context);
/* Now add the right earbud contexts - mind the extra context on that bud */
- group_->UpdateAudioContextAvailability();
ASSERT_NE(group_->GetAvailableContexts(), left->GetAvailableContexts());
ASSERT_EQ(group_->GetAvailableContexts(),
left->GetAvailableContexts() | right->GetAvailableContexts());
@@ -1481,7 +1492,6 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) {
/* Since no device is being added or removed from the group this should not
* change the configuration set.
*/
- group_->UpdateAudioContextAvailability();
ASSERT_EQ(group_->GetAvailableContexts(),
left->GetAvailableContexts() | right->GetAvailableContexts());
@@ -1543,7 +1553,6 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) {
::bluetooth::le_audio::types::kLeAudioDirectionSource)});
/* Right one was changed but the config exist, just not available */
- group_->UpdateAudioContextAvailability();
ASSERT_EQ(group_->GetAvailableContexts(),
left->GetAvailableContexts() | right->GetAvailableContexts());
ASSERT_FALSE(group_->GetAvailableContexts().test(LeAudioContextType::ALERTS));
@@ -1553,45 +1562,65 @@ TEST_P(LeAudioAseConfigurationTest, test_context_update) {
ASSERT_TRUE(group_->IsAudioSetConfigurationAvailable(LeAudioContextType::ALERTS));
}
-TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone) {
- LeAudioDevice* mono_speaker = AddTestDevice(1, 0);
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone_loc0) {
+ /* mono location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}});
TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0});
- /* mono, change location as by default it is stereo */
- mono_speaker->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
+ uint8_t direction_to_verify = kLeAudioDirectionSink;
+
+ TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify);
+}
+
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_ringtone) {
+ /* left only location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
+ kLeAudioCodecChannelCountSingleChannel, 1, 0});
uint8_t direction_to_verify = kLeAudioDirectionSink;
TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1, direction_to_verify);
}
-TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational) {
- LeAudioDevice* mono_speaker = AddTestDevice(1, 0);
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational_loc0) {
+ /* mono location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}});
TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountNone, 1, 0});
- /* mono, change location as by default it is stereo */
- mono_speaker->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
+ /* Microphone should be used on the phone */
+ uint8_t direction_to_verify = kLeAudioDirectionSink;
+ TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify);
+}
+
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_conversational) {
+ /* left only location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
+ kLeAudioCodecChannelCountNone, 1, 0});
/* Microphone should be used on the phone */
uint8_t direction_to_verify = kLeAudioDirectionSink;
TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1, direction_to_verify);
}
-TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media) {
- LeAudioDevice* mono_speaker = AddTestDevice(1, 0);
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media_loc0) {
+ /* mono location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationMonoAudio}});
TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountNone, 1, 0});
- /* mono, change location as by default it is stereo */
- mono_speaker->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
+ uint8_t direction_to_verify = kLeAudioDirectionSink;
+ TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify);
+}
+
+TEST_P(LeAudioAseConfigurationTest, test_mono_speaker_media) {
+ /* left only location */
+ LeAudioDevice* mono_speaker = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ TestGroupAseConfigurationData data({mono_speaker, kLeAudioCodecChannelCountSingleChannel,
+ kLeAudioCodecChannelCountNone, 1, 0});
uint8_t direction_to_verify = kLeAudioDirectionSink;
TestGroupAseConfiguration(LeAudioContextType::MEDIA, &data, 1, direction_to_verify);
@@ -1625,24 +1654,19 @@ TEST_P(LeAudioAseConfigurationTest, test_banded_headphones_media) {
}
TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_mono_microphone) {
- LeAudioDevice* banded_headset =
- AddTestDevice(2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo,
- codec_spec_conf::kLeAudioLocationFrontLeft);
+ /* mono source */
+ LeAudioDevice* banded_headset = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationStereo}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel,
kLeAudioCodecChannelCountSingleChannel, 2, 1});
- /* mono, change location as by default it is stereo */
- banded_headset->src_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
-
TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1);
}
TEST_P(LeAudioAseConfigurationTest, test_banded_headset_ringtone_mono_microphone_loc0) {
- LeAudioDevice* banded_headset =
- AddTestDevice(2, 1, 0, 0, false, false, codec_spec_conf::kLeAudioLocationStereo,
- codec_spec_conf::kLeAudioLocationMonoAudio);
+ /* mono source */
+ LeAudioDevice* banded_headset = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationStereo}},
+ {{1, codec_spec_conf::kLeAudioLocationMonoAudio}});
TestGroupAseConfigurationData data({banded_headset, kLeAudioCodecChannelCountTwoChannel,
kLeAudioCodecChannelCountSingleChannel, 2, 1});
@@ -1753,79 +1777,59 @@ TEST_P(LeAudioAseConfigurationTest, test_banded_headset_media) {
}
TEST_P(LeAudioAseConfigurationTest, test_earbuds_ringtone) {
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
TestGroupAseConfiguration(LeAudioContextType::RINGTONE, data, 2);
}
TEST_P(LeAudioAseConfigurationTest, test_earbuds_conversational) {
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
group_->ReloadAudioLocations();
TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, data, 2);
}
TEST_P(LeAudioAseConfigurationTest, test_earbuds_media) {
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
uint8_t directions_to_verify = kLeAudioDirectionSink;
TestGroupAseConfiguration(LeAudioContextType::MEDIA, data, 2, directions_to_verify);
}
TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_ringtone) {
- LeAudioDevice* handsfree = AddTestDevice(1, 1);
+ LeAudioDevice* handsfree = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1});
- handsfree->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- handsfree->src_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
-
TestGroupAseConfiguration(LeAudioContextType::RINGTONE, &data, 1);
}
TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_ringtone) {
- LeAudioDevice* handsfree = AddTestDevice(
- 1, 1, 0, 0, false, false,
- codec_spec_conf::kLeAudioLocationFrontLeft | codec_spec_conf::kLeAudioLocationFrontRight,
- codec_spec_conf::kLeAudioLocationFrontLeft);
+ LeAudioDevice* handsfree = AddTestDevice({{1, kChannelAllocationStereo}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
TestGroupAseConfigurationData data(
{handsfree, kLeAudioCodecChannelCountSingleChannel | kLeAudioCodecChannelCountTwoChannel,
kLeAudioCodecChannelCountSingleChannel, 2, 1});
@@ -1834,16 +1838,11 @@ TEST_P(LeAudioAseConfigurationTest, test_handsfree_stereo_ringtone) {
}
TEST_P(LeAudioAseConfigurationTest, test_handsfree_mono_conversational) {
- LeAudioDevice* handsfree = AddTestDevice(1, 1);
+ LeAudioDevice* handsfree = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
TestGroupAseConfigurationData data({handsfree, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1});
- handsfree->snk_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- handsfree->src_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
-
TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, &data, 1);
}
@@ -1917,20 +1916,15 @@ TEST_P(LeAudioAseConfigurationTest, test_lc3_config_media) {
TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_media) {
com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true);
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
// this would be also built into pac record
btle_audio_codec_config_t preferred_codec_config = {
.codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3,
@@ -1950,20 +1944,15 @@ TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_media) {
TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_media) {
com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true);
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
// this would be also built into pac record
btle_audio_codec_config_t preferred_codec_config = {
.codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3,
@@ -1983,20 +1972,15 @@ TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_media)
TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_conv) {
com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true);
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
// this would be also built into pac record
btle_audio_codec_config_t preferred_codec_config = {
.codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3,
@@ -2016,20 +2000,15 @@ TEST_P(LeAudioAseConfigurationTest, test_use_codec_preference_earbuds_conv) {
TEST_P(LeAudioAseConfigurationTest, test_not_use_codec_preference_earbuds_conv) {
com::android::bluetooth::flags::provider_->leaudio_set_codec_config_preference(true);
- LeAudioDevice* left = AddTestDevice(1, 1);
- LeAudioDevice* right = AddTestDevice(1, 1);
+ LeAudioDevice* left = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{1, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1},
{right, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 1}};
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
// this would be also built into pac record
btle_audio_codec_config_t preferred_codec_config = {
.codec_type = LE_AUDIO_CODEC_INDEX_SOURCE_LC3,
@@ -2163,16 +2142,10 @@ static auto PrepareStackMetadataLtvBase() {
}
TEST_P(LeAudioAseConfigurationTest, test_reconnection_media) {
- LeAudioDevice* left = AddTestDevice(2, 1);
- LeAudioDevice* right = AddTestDevice(2, 1);
-
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
-
+ LeAudioDevice* left = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
TestGroupAseConfigurationData data[] = {{left, kLeAudioCodecChannelCountSingleChannel,
kLeAudioCodecChannelCountSingleChannel, 1, 0},
{right, kLeAudioCodecChannelCountSingleChannel,
@@ -2260,10 +2233,6 @@ TEST_P(LeAudioAseConfigurationTest, test_ase_metadata) {
LeAudioDevice* headphones = AddTestDevice(2, 1);
- /* Change location as by default it is stereo */
- headphones->snk_audio_locations_ = kChannelAllocationStereo;
- group_->ReloadAudioLocations();
-
AudioSetConfiguration media_configuration = *getSpecificConfiguration(
"One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA);
@@ -2323,8 +2292,9 @@ TEST_P(LeAudioAseConfigurationTest, test_ase_metadata) {
(std::vector<uint8_t>{1, 2, 3}));
/* The adidtional metadata appended by the host stack */
- ASSERT_EQ(ase->metadata.GetAsLeAudioMetadata().streaming_audio_context,
- (uint16_t)LeAudioContextType::MEDIA);
+ uint16_t streaming_context =
+ ase->metadata.GetAsLeAudioMetadata().streaming_audio_context.value().value();
+ ASSERT_EQ(streaming_context, (uint16_t)LeAudioContextType::MEDIA);
ASSERT_EQ(ase->metadata.GetAsLeAudioMetadata().ccid_list, (std::vector<uint8_t>{0xC0}));
}
}
@@ -2348,13 +2318,8 @@ TEST_P(LeAudioAseConfigurationTest, test_ase_metadata) {
* not assigned) or assigned to the same CIS ID as the opposite direction.
*/
TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) {
- LeAudioDevice* tws_headset = AddTestDevice(0, 0, 2, 1, true);
-
- /* Change location as by default it is stereo */
- tws_headset->snk_audio_locations_ = kChannelAllocationStereo;
- tws_headset->src_audio_locations_ =
- ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- group_->ReloadAudioLocations();
+ LeAudioDevice* tws_headset = AddTestDevice(0, 0, 2, 1, true, false, kChannelAllocationStereo,
+ codec_spec_conf::kLeAudioLocationFrontLeft);
auto conversational_configuration = getSpecificConfiguration(
"Two-OneChan-SnkAse-Lc3_16_2-One-OneChan-SrcAse-Lc3_16_2_Low_Latency",
@@ -2429,10 +2394,14 @@ TEST_P(LeAudioAseConfigurationTest, test_reactivation_conversational) {
group_->Activate(LeAudioContextType::CONVERSATIONAL, audio_contexts, ccid_lists);
TestActiveAses();
+ ASSERT_NE(this->group_->cig.cises.size(), 0lu);
/* Verify ASEs assigned CISes by counting assigned to bi-directional CISes */
int bi_dir_ases_count =
std::count_if(tws_headset->ases_.begin(), tws_headset->ases_.end(), [this](auto& ase) {
+ if (ase.cis_id == kInvalidCisId) {
+ return false;
+ }
return this->group_->cig.cises[ase.cis_id].type == CisType::CIS_TYPE_BIDIRECTIONAL;
});
@@ -2469,14 +2438,10 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) {
/* Set desired size to 2 */
desired_group_size_ = 2;
- LeAudioDevice* left = AddTestDevice(2, 1);
+ LeAudioDevice* left =
+ AddTestDevice({{2, kChannelAllocationStereo}}, {{1, kChannelAllocationStereo}});
LeAudioDevice* right = AddTestDevice(0, 0, 0, 0, false, true);
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = kChannelAllocationStereo;
- right->snk_audio_locations_ = kChannelAllocationStereo;
- group_->ReloadAudioLocations();
-
auto media_configuration = getSpecificConfiguration(
"One-TwoChan-SnkAse-Lc3_48_4_High_Reliability", LeAudioContextType::MEDIA);
ASSERT_NE(nullptr, media_configuration);
@@ -2528,14 +2493,10 @@ TEST_P(LeAudioAseConfigurationTest, test_getting_cis_count) {
}
TEST_P(LeAudioAseConfigurationTest, test_config_support) {
- LeAudioDevice* left = AddTestDevice(2, 1);
+ LeAudioDevice* left =
+ AddTestDevice({{2, kChannelAllocationStereo}}, {{1, kChannelAllocationStereo}});
LeAudioDevice* right = AddTestDevice(0, 0, 0, 0, false, true);
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = kChannelAllocationStereo;
- right->snk_audio_locations_ = kChannelAllocationStereo;
- group_->ReloadAudioLocations();
-
auto test_config = getSpecificConfiguration(
"One-OneChan-SnkAse-Lc3_48_4-One-OneChan-SrcAse-Lc3_16_2_Balanced_Reliability",
LeAudioContextType::VOICEASSISTANTS);
@@ -2568,15 +2529,10 @@ TEST_P(LeAudioAseConfigurationTest, test_config_support) {
TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group) {
// A group of two earbuds
- LeAudioDevice* left = AddTestDevice(2, 1);
- LeAudioDevice* right = AddTestDevice(2, 1);
-
- /* Change location as by default it is stereo */
- left->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- left->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontLeft;
- right->snk_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- right->src_audio_locations_ = ::bluetooth::le_audio::codec_spec_conf::kLeAudioLocationFrontRight;
- group_->ReloadAudioLocations();
+ LeAudioDevice* left = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontLeft}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ LeAudioDevice* right = AddTestDevice({{2, codec_spec_conf::kLeAudioLocationFrontRight}},
+ {{1, codec_spec_conf::kLeAudioLocationFrontRight}});
// The Right earbud is currently disconnected
right->SetConnectionState(DeviceConnectState::DISCONNECTED);
@@ -2592,6 +2548,32 @@ TEST_P(LeAudioAseConfigurationTest, test_vendor_codec_configure_incomplete_group
direction_to_verify);
}
+TEST_P(LeAudioAseConfigurationTest, test_mono_microphone_conversational_loc0) {
+ /* Mono microphone - Speaker should be used on the phone */
+ auto mono_microphone =
+ AddTestDevice(std::nullopt, {{1, codec_spec_conf::kLeAudioLocationMonoAudio}});
+ TestGroupAseConfigurationData data(
+ {.device = mono_microphone,
+ .audio_channel_counts_snk = kLeAudioCodecChannelCountNone,
+ .audio_channel_counts_src = kLeAudioCodecChannelCountSingleChannel,
+ .expected_active_channel_num_snk = 0,
+ .expected_active_channel_num_src = 1});
+ TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, {data});
+}
+
+TEST_P(LeAudioAseConfigurationTest, test_mono_microphone_conversational) {
+ /* Mono microphone - Speaker should be used on the phone */
+ auto mono_microphone =
+ AddTestDevice(std::nullopt, {{1, codec_spec_conf::kLeAudioLocationFrontLeft}});
+ TestGroupAseConfigurationData data(
+ {.device = mono_microphone,
+ .audio_channel_counts_snk = kLeAudioCodecChannelCountNone,
+ .audio_channel_counts_src = kLeAudioCodecChannelCountSingleChannel,
+ .expected_active_channel_num_snk = 0,
+ .expected_active_channel_num_src = 1});
+ TestGroupAseConfiguration(LeAudioContextType::CONVERSATIONAL, {data});
+}
+
TEST_P(LeAudioAseConfigurationTest, test_get_metadata_no_ccid) {
auto mono_microphone = AddTestDevice(1, 0);
auto metadata = mono_microphone->GetMetadata(
diff --git a/system/bta/le_audio/le_audio_client_test.cc b/system/bta/le_audio/le_audio_client_test.cc
index e749c574ba..a3c52dc9e6 100644
--- a/system/bta/le_audio/le_audio_client_test.cc
+++ b/system/bta/le_audio/le_audio_client_test.cc
@@ -51,6 +51,7 @@
#include "mock_csis_client.h"
#include "mock_device_groups.h"
#include "mock_state_machine.h"
+#include "osi/include/properties.h"
#include "stack/include/btm_status.h"
#include "stack/include/main_thread.h"
#include "test/common/mock_functions.h"
@@ -103,8 +104,6 @@ constexpr bluetooth::le_audio::types::LeAudioContextType kLeAudioDefaultConfigur
static constexpr char kNotifyUpperLayerAboutGroupBeingInIdleDuringCall[] =
"persist.bluetooth.leaudio.notify.idle.during.call";
-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"; }
@@ -116,13 +115,12 @@ bluetooth::common::MessageLoopThread* get_main_thread() { return &message_loop_t
bt_status_t do_in_main_thread(base::OnceClosure task) {
// Wrap the task with task counter so we could later know if there are
// any callbacks scheduled and we should wait before performing some actions
- if (!message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(
- [](base::OnceClosure task, std::atomic<int>& num_async_tasks) {
- std::move(task).Run();
- num_async_tasks--;
- },
- std::move(task), std::ref(num_async_tasks)))) {
+ if (!message_loop_thread.DoInThread(base::BindOnce(
+ [](base::OnceClosure task, std::atomic<int>& num_async_tasks) {
+ std::move(task).Run();
+ num_async_tasks--;
+ },
+ std::move(task), std::ref(num_async_tasks)))) {
bluetooth::log::error("failed to post task to task runner!");
return BT_STATUS_FAIL;
}
@@ -242,11 +240,12 @@ public:
MOCK_METHOD((void), OnGroupNodeStatus,
(const RawAddress& bd_addr, int group_id, GroupNodeStatus node_status), (override));
MOCK_METHOD((void), OnAudioConf,
- (uint8_t direction, int group_id, uint32_t snk_audio_location,
- uint32_t src_audio_location, uint16_t avail_cont),
+ (uint8_t direction, int group_id, std::optional<std::bitset<32>> snk_audio_location,
+ std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont),
+ (override));
+ MOCK_METHOD(void, OnSinkAudioLocationAvailable,
+ (const RawAddress& bd_addr, std::optional<std::bitset<32>> snk_audio_location),
(override));
- MOCK_METHOD((void), OnSinkAudioLocationAvailable,
- (const RawAddress& bd_addr, uint32_t snk_audio_location), (override));
MOCK_METHOD((void), OnAudioLocalCodecCapabilities,
(std::vector<btle_audio_codec_config_t> local_input_capa_codec_conf,
std::vector<btle_audio_codec_config_t> local_output_capa_codec_conf),
@@ -1292,6 +1291,18 @@ protected:
}
group->SetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+ // Set streaming metadata
+ for (LeAudioDevice* device = group->GetFirstActiveDevice(); device != nullptr;
+ device = group->GetNextActiveDevice(device)) {
+ for (auto& ase : device->ases_) {
+ if (!ase.active) {
+ continue;
+ }
+ group->SetStreamingMetadataContexts(metadata_context_types.get(ase.direction),
+ ase.direction);
+ }
+ }
+
do_in_main_thread(base::BindOnce(
[](int group_id, bluetooth::le_audio::LeAudioGroupStateMachine::Callbacks*
state_machine_callbacks) {
@@ -1314,6 +1325,7 @@ protected:
// Inject the state
group->SetTargetState(types::AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED);
+ group->ClearStreamingMetadataContexts();
group->SetState(group->GetTargetState());
state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::SUSPENDED);
});
@@ -1349,65 +1361,8 @@ protected:
ases_pair.source->active = false;
ases_pair.source->cis_state = types::CisState::ASSIGNED;
}
- /* Invalidate stream configuration if needed */
- auto* stream_conf = &group->stream_conf;
- if (!stream_conf->stream_params.sink.stream_config.stream_map.empty() ||
- !stream_conf->stream_params.source.stream_config.stream_map.empty()) {
- stream_conf->stream_params.sink.stream_config.stream_map.erase(
- std::remove_if(
- stream_conf->stream_params.sink.stream_config.stream_map.begin(),
- stream_conf->stream_params.sink.stream_config.stream_map.end(),
- [leAudioDevice, &stream_conf](auto& info) {
- auto ases =
- leAudioDevice->GetAsesByCisConnHdl(info.stream_handle);
-
- log::info(
- ", sink ase to delete. Cis handle: {}, ase pointer: "
- "{}",
- (int)(info.stream_handle), std::format_ptr(+ases.sink));
- if (ases.sink) {
- stream_conf->stream_params.sink.num_of_devices--;
- stream_conf->stream_params.sink.num_of_channels -=
- ases.sink->codec_config.channel_count_per_iso_stream;
-
- log::info(
- "Sink Number Of Devices: {}, Sink Number Of "
- "Channels: {}",
- stream_conf->stream_params.sink.num_of_devices,
- stream_conf->stream_params.sink.num_of_channels);
- }
- return ases.sink;
- }),
- stream_conf->stream_params.sink.stream_config.stream_map.end());
-
- stream_conf->stream_params.source.stream_config.stream_map.erase(
- std::remove_if(
- stream_conf->stream_params.source.stream_config.stream_map.begin(),
- stream_conf->stream_params.source.stream_config.stream_map.end(),
- [leAudioDevice, &stream_conf](auto& info) {
- auto ases =
- leAudioDevice->GetAsesByCisConnHdl(info.stream_handle);
-
- log::info(", source to delete. Cis handle: {}, ase pointer: {}",
- (int)(info.stream_handle),
- std::format_ptr(ases.source));
- if (ases.source) {
- stream_conf->stream_params.source.num_of_devices--;
- stream_conf->stream_params.source.num_of_channels -=
- ases.source->codec_config.channel_count_per_iso_stream;
-
- log::info(
- ", Source Number Of Devices: {}, Source Number Of "
- "Channels: {}",
- stream_conf->stream_params.source.num_of_devices,
- stream_conf->stream_params.source.num_of_channels);
- }
- return ases.source;
- }),
- stream_conf->stream_params.source.stream_config.stream_map.end());
- }
- group->cig.UnassignCis(leAudioDevice, event->cis_conn_hdl);
+ group->RemoveCisFromStreamIfNeeded(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
@@ -1484,6 +1439,7 @@ protected:
stream_conf->stream_params.source.stream_config.stream_map.end());
}
+ group->ClearStreamingMetadataContexts();
for (auto& ase : device->ases_) {
group->cig.UnassignCis(device, ase.cis_conn_hdl);
@@ -1517,6 +1473,8 @@ protected:
void SetUp() override {
__android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
+ com::android::bluetooth::flags::provider_->reset_flags();
+
init_message_loop_thread();
reset_mock_function_count_map();
ON_CALL(controller_, SupportsBleConnectedIsochronousStreamCentral).WillByDefault(Return(true));
@@ -1536,7 +1494,7 @@ protected:
mock_iso_manager_ = MockIsoManager::GetInstance();
ON_CALL(*mock_iso_manager_, RegisterCigCallbacks(_)).WillByDefault(SaveArg<0>(&cig_callbacks_));
- ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(mock_btm_interface_, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(true)));
// Required since we call OnAudioDataReady()
const auto codec_location = ::bluetooth::le_audio::types::CodecLocation::HOST;
@@ -1600,7 +1558,9 @@ protected:
}
void TearDown() override {
- com::android::bluetooth::flags::provider_->reset_flags();
+ // WARNING: Message loop cleanup should wait for all the 'till now' scheduled calls
+ // so it should be called right at the very begginning of teardown.
+ cleanup_message_loop_thread();
if (is_audio_unicast_source_acquired) {
if (unicast_source_hal_cb_ != nullptr) {
@@ -1616,10 +1576,6 @@ protected:
EXPECT_CALL(*mock_le_audio_sink_hal_client_, OnDestroyed()).Times(1);
}
- // Message loop cleanup should wait for all the 'till now' scheduled calls
- // so it should be called right at the very begginning of teardown.
- cleanup_message_loop_thread();
-
// This is required since Stop() and Cleanup() may trigger some callbacks or
// drop unique pointers to mocks we have raw pointer for and we want to
// verify them all.
@@ -1780,7 +1736,7 @@ protected:
ON_CALL(mock_btm_interface_, BTM_IsEncrypted(address, _))
.WillByDefault(DoAll(Return(isEncrypted)));
- ON_CALL(mock_btm_interface_, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(mock_btm_interface_, IsDeviceBonded(address, _)).WillByDefault(DoAll(Return(true)));
EXPECT_CALL(mock_gatt_interface_, Open(gatt_if, address, BTM_BLE_DIRECT_CONNECTION, _))
.Times(1);
@@ -2274,8 +2230,8 @@ protected:
uint16_t conn_id;
RawAddress addr;
- uint32_t sink_audio_allocation = codec_spec_conf::kLeAudioLocationStereo;
- uint32_t source_audio_allocation = codec_spec_conf::kLeAudioLocationStereo;
+ std::optional<uint32_t> sink_audio_allocation = std::nullopt;
+ std::optional<uint32_t> source_audio_allocation = std::nullopt;
uint8_t sink_channel_cnt = 0x03;
uint8_t source_channel_cnt = 0x03;
uint16_t sample_freq_mask = 0x0004;
@@ -2363,14 +2319,18 @@ protected:
if (add_pacs) {
// attribute handles
pacs->start = 0x0060;
- pacs->sink_pac_char = 0x0061;
- pacs->sink_pac_ccc = 0x0063;
- pacs->sink_audio_loc_char = 0x0064;
- pacs->sink_audio_loc_ccc = 0x0066;
- pacs->source_pac_char = 0x0067;
- pacs->source_pac_ccc = 0x0069;
- pacs->source_audio_loc_char = 0x0070;
- pacs->source_audio_loc_ccc = 0x0072;
+ if (sink_audio_allocation.has_value()) {
+ pacs->sink_pac_char = 0x0061;
+ pacs->sink_pac_ccc = 0x0063;
+ pacs->sink_audio_loc_char = 0x0064;
+ pacs->sink_audio_loc_ccc = 0x0066;
+ }
+ if (source_audio_allocation.has_value()) {
+ pacs->source_pac_char = 0x0067;
+ pacs->source_pac_ccc = 0x0069;
+ pacs->source_audio_loc_char = 0x0070;
+ pacs->source_audio_loc_ccc = 0x0072;
+ }
pacs->avail_contexts_char = 0x0073;
pacs->avail_contexts_ccc = 0x0075;
pacs->supp_contexts_char = 0x0076;
@@ -2385,14 +2345,14 @@ protected:
ascs->start = 0x0090;
uint16_t handle = 0x0091;
for (int i = 0; i < add_ascs_cnt; i++) {
- if (sink_audio_allocation != 0) {
+ if (sink_audio_allocation.has_value()) {
ascs->sink_ase_char[i] = handle;
handle += 2;
ascs->sink_ase_ccc[i] = handle;
handle++;
}
- if (source_audio_allocation != 0) {
+ if (source_audio_allocation.has_value()) {
ascs->source_ase_char[i] = handle;
handle += 2;
ascs->source_ase_ccc[i] = handle;
@@ -2411,19 +2371,6 @@ protected:
std::move(pacs));
if (add_pacs) {
- uint8_t snk_allocation[4];
- uint8_t src_allocation[4];
-
- snk_allocation[0] = (uint8_t)(sink_audio_allocation);
- snk_allocation[1] = (uint8_t)(sink_audio_allocation >> 8);
- snk_allocation[2] = (uint8_t)(sink_audio_allocation >> 16);
- snk_allocation[3] = (uint8_t)(sink_audio_allocation >> 24);
-
- src_allocation[0] = (uint8_t)(source_audio_allocation);
- src_allocation[1] = (uint8_t)(source_audio_allocation >> 8);
- src_allocation[2] = (uint8_t)(source_audio_allocation >> 16);
- src_allocation[3] = (uint8_t)(source_audio_allocation >> 24);
-
uint8_t sample_freq[2];
sample_freq[0] = (uint8_t)(sample_freq_mask);
sample_freq[1] = (uint8_t)(sample_freq_mask >> 8);
@@ -2500,11 +2447,10 @@ protected:
}
} else if (handle == pacs->sink_audio_loc_char + 1) {
value = {
- // Audio Locations
- snk_allocation[0],
- snk_allocation[1],
- snk_allocation[2],
- snk_allocation[3],
+ (uint8_t)(sink_audio_allocation.value_or(0)),
+ (uint8_t)(sink_audio_allocation.value_or(0) >> 8),
+ (uint8_t)(sink_audio_allocation.value_or(0) >> 16),
+ (uint8_t)(sink_audio_allocation.value_or(0) >> 24),
};
} else if (handle == pacs->source_pac_char + 1) {
if (empty_source_pack_) {
@@ -2569,11 +2515,10 @@ protected:
}
} else if (handle == pacs->source_audio_loc_char + 1) {
value = {
- // Audio Locations
- src_allocation[0],
- src_allocation[1],
- src_allocation[2],
- src_allocation[3],
+ (uint8_t)(source_audio_allocation.value_or(0)),
+ (uint8_t)(source_audio_allocation.value_or(0) >> 8),
+ (uint8_t)(source_audio_allocation.value_or(0) >> 16),
+ (uint8_t)(source_audio_allocation.value_or(0) >> 24),
};
} else if (handle == pacs->avail_contexts_char + 1) {
value = {
@@ -5809,7 +5754,7 @@ TEST_F(UnicastTest, ConnectAfterRemove) {
LeAudioClient::Get(), test_address0));
SyncOnMainLoop();
- ON_CALL(mock_btm_interface_, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(false)));
+ ON_CALL(mock_btm_interface_, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(false)));
do_in_main_thread(base::BindOnce(&LeAudioClient::Connect, base::Unretained(LeAudioClient::Get()),
test_address0));
@@ -6718,6 +6663,110 @@ TEST_F(UnicastTest, TestUnidirectionalGameAndLiveRecording) {
Mock::VerifyAndClearExpectations(&mock_state_machine_);
}
+TEST_F(UnicastTest, TestUnidirectionalGameAndLiveRecordingMicOnlyDev) {
+ const RawAddress test_address0 = GetTestAddress(0);
+ int group_id = bluetooth::groups::kGroupUnknown;
+
+ /**
+ * Scenario test steps
+ * 1. Configure group to support GAME | LIVE | CONVERSATIONAL | VOICEASSISTANTS only on Source
+ * 2. Start a GAME
+ * 3. Start recording during the GAME
+ */
+
+ // No sink at all
+ available_snk_context_types_ = 0;
+ supported_snk_context_types_ = 0;
+
+ // Source available for
+ available_src_context_types_ =
+ (types::LeAudioContextType::CONVERSATIONAL | types::LeAudioContextType::GAME |
+ types::LeAudioContextType::LIVE | types::LeAudioContextType::VOICEASSISTANTS |
+ types::LeAudioContextType::UNSPECIFIED)
+ .value();
+ supported_src_context_types_ = available_src_context_types_;
+
+ // Setup a single mic-only device
+ empty_sink_pack_ = true;
+ default_channel_cnt = 1;
+ SampleDatabaseParameters db_params{
+ .conn_id = 1,
+ .addr = test_address0,
+ .sink_audio_allocation = std::nullopt,
+ .source_audio_allocation = codec_spec_conf::kLeAudioLocationMonoAudio,
+ .sink_channel_cnt = 0,
+ .source_channel_cnt = default_channel_cnt,
+ .sample_freq_mask = le_audio::codec_spec_caps::kLeAudioSamplingFreq32000Hz,
+ .add_csis = false,
+ .add_cas = false,
+ .add_pacs = true,
+ .add_ascs_cnt = 1,
+ .set_size = 0,
+ .rank = 0,
+ .gatt_status = GATT_SUCCESS,
+ .max_supported_codec_frames_per_sdu = 1,
+ };
+ SetSampleDatabaseEarbudsValid(db_params);
+
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnConnectionState(ConnectionState::CONNECTED, test_address0))
+ .Times(1);
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnGroupNodeStatus(test_address0, _, GroupNodeStatus::ADDED))
+ .WillOnce(DoAll(SaveArg<1>(&group_id)));
+
+ types::BidirectionalPair<types::AudioContexts> expected_metadata_contexts = {
+ .sink = types::AudioContexts(),
+ .source = types::AudioContexts(types::LeAudioContextType::GAME)};
+ EXPECT_CALL(mock_state_machine_,
+ StartStream(_, types::LeAudioContextType::GAME, expected_metadata_contexts, _))
+ .Times(1);
+
+ log::info("Connecting LeAudio to {}", test_address0);
+ ConnectLeAudio(test_address0);
+ ASSERT_NE(group_id, bluetooth::groups::kGroupUnknown);
+
+ // Both audio sessions are always started to monitor the metadata (even for mic only devices)
+ EXPECT_CALL(*mock_le_audio_source_hal_client_, Start(_, _, _)).Times(1);
+ EXPECT_CALL(*mock_le_audio_sink_hal_client_, Start(_, _, _)).Times(1);
+
+ EXPECT_CALL(*mock_codec_manager_,
+ UpdateActiveUnicastAudioHalClient(mock_le_audio_source_hal_client_,
+ mock_le_audio_sink_hal_client_, true))
+ .Times(1);
+
+ LeAudioClient::Get()->GroupSetActive(group_id);
+ SyncOnMainLoop();
+
+ // Configure a bidirectional GAME scenario (on a mic-only device)
+ UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN);
+ UpdateLocalSinkMetadata(AUDIO_SOURCE_MIC);
+ LocalAudioSinkResume();
+ SyncOnMainLoop();
+
+ Mock::VerifyAndClearExpectations(&mock_audio_hal_client_callbacks_);
+ Mock::VerifyAndClearExpectations(mock_le_audio_source_hal_client_);
+ Mock::VerifyAndClearExpectations(mock_le_audio_sink_hal_client_);
+ Mock::VerifyAndClearExpectations(mock_codec_manager_);
+ Mock::VerifyAndClearExpectations(&mock_state_machine_);
+ SyncOnMainLoop();
+
+ // We do expect only unidirectional CIS
+ uint8_t cis_count_out = 0;
+ uint8_t cis_count_in = 1;
+
+ // Verify Data transfer on one local audio sink
+ TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 0, 40);
+ SyncOnMainLoop();
+
+ // Expect no reconfiguration triggered by the GAME updates
+ EXPECT_CALL(mock_state_machine_, StopStream(_)).Times(0);
+ UpdateLocalSourceMetadata(AUDIO_USAGE_GAME, AUDIO_CONTENT_TYPE_UNKNOWN);
+ LocalAudioSinkSuspend();
+ SyncOnMainLoop();
+ Mock::VerifyAndClearExpectations(&mock_state_machine_);
+}
+
TEST_F(UnicastTest, TestUnidirectionalVoiceAssistant_Sink) {
com::android::bluetooth::flags::provider_->le_audio_support_unidirectional_voice_assistant(true);
const RawAddress test_address0 = GetTestAddress(0);
@@ -9290,6 +9339,67 @@ TEST_F(UnicastTest, TwoEarbuds2ndLateConnect) {
TestAudioDataTransfer(group_id, cis_count_out, cis_count_in, 1920);
}
+TEST_F(UnicastTest, TestStreamingContextTypeBehaviour) {
+ uint8_t group_size = 2;
+ int group_id = 2;
+ int conn_id_1 = 1;
+ int conn_id_2 = 2;
+
+ /* Scenario
+ * 1. Connect Set of devices with all the context types available
+ * 2. Create stream for Media
+ * 3. Remote devices removes all the Available Contexts but UNSPECIFIED
+ * 4. Verify GetAvailableContexts() returns accepted MEDIA and UNSPECIFIED
+ */
+
+ // 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; }));
+
+ const RawAddress test_address0 = GetTestAddress(0);
+ const RawAddress test_address1 = GetTestAddress(1);
+
+ // First earbud connects
+ ConnectCsisDevice(test_address0, conn_id_1, codec_spec_conf::kLeAudioLocationFrontLeft,
+ codec_spec_conf::kLeAudioLocationFrontLeft, group_size, group_id, 1 /* rank*/);
+
+ // Second earbud connects
+ ConnectCsisDevice(test_address1, conn_id_2, codec_spec_conf::kLeAudioLocationFrontRight,
+ codec_spec_conf::kLeAudioLocationFrontRight, group_size, group_id, 2 /* rank*/,
+ true /*connect_through_csis*/);
+
+ // Start streaming
+ 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();
+
+ EXPECT_CALL(mock_state_machine_, StartStream(_, _, _, _)).Times(1);
+ StartStreaming(AUDIO_USAGE_MEDIA, AUDIO_CONTENT_TYPE_MUSIC, group_id);
+ SyncOnMainLoop();
+ Mock::VerifyAndClearExpectations(&mock_state_machine_);
+
+ auto group = streaming_groups.at(group_id);
+
+ /* Simulate available context type being cleared */
+ InjectAvailableContextTypes(test_address0, conn_id_1,
+ types::AudioContexts(LeAudioContextType::UNSPECIFIED),
+ types::AudioContexts(LeAudioContextType::UNSPECIFIED));
+ InjectAvailableContextTypes(test_address1, conn_id_2,
+ types::AudioContexts(LeAudioContextType::UNSPECIFIED),
+ types::AudioContexts(LeAudioContextType::UNSPECIFIED));
+
+ auto remote_sink_contexts =
+ group->GetAvailableContexts(bluetooth::le_audio::types::kLeAudioDirectionSink);
+ auto remote_source_contexts =
+ group->GetAvailableContexts(bluetooth::le_audio::types::kLeAudioDirectionSource);
+ ASSERT_EQ(remote_sink_contexts,
+ types::AudioContexts(LeAudioContextType::MEDIA | LeAudioContextType::UNSPECIFIED));
+ ASSERT_EQ(remote_source_contexts, types::AudioContexts(LeAudioContextType::UNSPECIFIED));
+}
+
TEST_F(UnicastTest, LateStreamConnectBasedOnContextType) {
uint8_t group_size = 2;
int group_id = 2;
@@ -12330,9 +12440,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) {
EXPECT_CALL(mock_audio_hal_client_callbacks_,
OnConnectionState(ConnectionState::CONNECTED, test_address0))
.Times(0);
- EXPECT_CALL(
- mock_audio_hal_client_callbacks_,
- OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft))
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnSinkAudioLocationAvailable(test_address0,
+ std::make_optional<std::bitset<32>>(
+ codec_spec_conf::kLeAudioLocationFrontLeft)))
.Times(0);
// First earbud initial connection
@@ -12368,9 +12479,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) {
InjectGroupDeviceAdded(test_address0, group_id);
// Second earbud initial connection
- EXPECT_CALL(
- mock_audio_hal_client_callbacks_,
- OnSinkAudioLocationAvailable(test_address1, codec_spec_conf::kLeAudioLocationFrontRight))
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnSinkAudioLocationAvailable(test_address1,
+ std::make_optional<std::bitset<32>>(
+ codec_spec_conf::kLeAudioLocationFrontRight)))
.Times(1);
EXPECT_CALL(mock_btif_storage_, AddLeaudioAutoconnect(test_address1, true)).Times(1);
@@ -12406,9 +12518,10 @@ TEST_F(UnicastTest, DisconnectAclBeforeGettingReadResponses) {
EXPECT_CALL(mock_audio_hal_client_callbacks_,
OnConnectionState(ConnectionState::CONNECTED, test_address0))
.Times(1);
- EXPECT_CALL(
- mock_audio_hal_client_callbacks_,
- OnSinkAudioLocationAvailable(test_address0, codec_spec_conf::kLeAudioLocationFrontLeft))
+ EXPECT_CALL(mock_audio_hal_client_callbacks_,
+ OnSinkAudioLocationAvailable(test_address0,
+ std::make_optional<std::bitset<32>>(
+ codec_spec_conf::kLeAudioLocationFrontLeft)))
.Times(1);
/* Prepare valid GATT status responsing attributes */
@@ -13551,9 +13664,18 @@ TEST_F(UnicastTest, CodecFrameBlocks2) {
SampleDatabaseParameters remote_params{
.conn_id = 1,
.addr = test_address0,
+ .sink_audio_allocation = codec_spec_conf::kLeAudioLocationStereo,
+ .source_audio_allocation = codec_spec_conf::kLeAudioLocationStereo,
+ .sink_channel_cnt = default_channel_cnt,
+ .source_channel_cnt = default_channel_cnt,
+ .sample_freq_mask = le_audio::codec_spec_caps::kLeAudioSamplingFreq32000Hz,
.add_csis = false,
+ .add_cas = true,
+ .add_pacs = true,
+ .add_ascs_cnt = 1,
.set_size = 0,
.rank = 0,
+ .gatt_status = GATT_SUCCESS,
.max_supported_codec_frames_per_sdu = 2,
};
SetSampleDatabaseEarbudsValid(remote_params);
diff --git a/system/bta/le_audio/le_audio_types.h b/system/bta/le_audio/le_audio_types.h
index 6b9c2df3ac..d5c2b3da31 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 {
@@ -665,8 +669,8 @@ struct LeAudioCoreCodecCapabilities {
};
struct LeAudioMetadata {
- std::optional<uint16_t> preferred_audio_context;
- std::optional<uint16_t> streaming_audio_context;
+ std::optional<AudioContexts> preferred_audio_context;
+ std::optional<AudioContexts> streaming_audio_context;
std::optional<std::string> program_info;
std::optional<std::string> language; // ISO 639-3 (3 lowercase letter codes)
std::optional<std::vector<uint8_t>> ccid_list;
@@ -833,17 +837,21 @@ private:
LeAudioMetadata metadata;
auto vec_opt = ltvs.Find(types::kLeAudioMetadataTypePreferredAudioContext);
- if (vec_opt &&
- (vec_opt->size() == sizeof(decltype(metadata.preferred_audio_context)::value_type))) {
+ if (vec_opt && (vec_opt->size() == sizeof(uint16_t))) {
auto ptr = vec_opt->data();
- STREAM_TO_UINT16(metadata.preferred_audio_context, ptr);
+ uint16_t raw_ctx;
+ STREAM_TO_UINT16(raw_ctx, ptr);
+ AudioContexts ctx(raw_ctx);
+ metadata.preferred_audio_context = ctx;
}
vec_opt = ltvs.Find(types::kLeAudioMetadataTypeStreamingAudioContext);
- if (vec_opt &&
- (vec_opt->size() == sizeof(decltype(metadata.streaming_audio_context)::value_type))) {
+ if (vec_opt && (vec_opt->size() == sizeof(uint16_t))) {
auto ptr = vec_opt->data();
- STREAM_TO_UINT16(metadata.streaming_audio_context, ptr);
+ uint16_t raw_ctx;
+ STREAM_TO_UINT16(raw_ctx, ptr);
+ AudioContexts ctx(raw_ctx);
+ metadata.streaming_audio_context = ctx;
}
vec_opt = ltvs.Find(types::kLeAudioMetadataTypeProgramInfo);
@@ -1098,6 +1106,12 @@ struct hdl_pair {
uint16_t ccc_hdl = 0;
};
+template <typename T>
+struct hdl_pair_wrapper {
+ hdl_pair handles;
+ T value;
+};
+
struct AseQosConfiguration {
uint32_t presentation_delay = 0;
uint32_t sdu_interval = 0;
@@ -1142,6 +1156,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; }
diff --git a/system/bta/le_audio/le_audio_utils.cc b/system/bta/le_audio/le_audio_utils.cc
index 7e2495ffce..2d2c0da641 100644
--- a/system/bta/le_audio/le_audio_utils.cc
+++ b/system/bta/le_audio/le_audio_utils.cc
@@ -600,6 +600,8 @@ const struct types::acs_ac_record* GetConfigurationSupportedPac(
/* Doesn't match required configuration with any PAC */
if (pacs.size() == 0) {
log::error("No PAC records");
+ } else {
+ log::error("No matching PAC record");
}
return nullptr;
}
diff --git a/system/bta/le_audio/mock_state_machine.h b/system/bta/le_audio/mock_state_machine.h
index bee2ea6599..ea3326f5f6 100644
--- a/system/bta/le_audio/mock_state_machine.h
+++ b/system/bta/le_audio/mock_state_machine.h
@@ -50,9 +50,9 @@ public:
bluetooth::le_audio::LeAudioDevice* leAudioDevice,
bluetooth::le_audio::LeAudioDeviceGroup* group),
(override));
-
MOCK_METHOD((void), ProcessGattCtpNotification,
- (bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t* value, uint16_t len),
+ (bluetooth::le_audio::LeAudioDeviceGroup * group,
+ bluetooth::le_audio::LeAudioDevice* leAudioDevice, uint8_t* value, uint16_t len),
(override));
MOCK_METHOD((void), ProcessHciNotifOnCigCreate,
(bluetooth::le_audio::LeAudioDeviceGroup * group, uint8_t status, uint8_t cig_id,
diff --git a/system/bta/le_audio/state_machine.cc b/system/bta/le_audio/state_machine.cc
index 1c991e624e..cf6d4cf18f 100644
--- a/system/bta/le_audio/state_machine.cc
+++ b/system/bta/le_audio/state_machine.cc
@@ -131,6 +131,7 @@ using bluetooth::le_audio::types::CigState;
using bluetooth::le_audio::types::CisState;
using bluetooth::le_audio::types::DataPathState;
using bluetooth::le_audio::types::LeAudioContextType;
+using bluetooth::le_audio::types::LeAudioLtvMap;
namespace {
@@ -281,11 +282,11 @@ public:
group->PrintDebugState();
StopStream(group);
return false;
- } else {
- // Even stream is already configured for the context, update the metadata.
- group->SetMetadataContexts(metadata_context_types);
}
+ // Even stream is already configured for the context, update the metadata.
+ group->SetMetadataContexts(metadata_context_types);
+
/* All ASEs should aim to achieve target state */
SetTargetState(group, AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
PrepareAndSendEnableToTheGroup(group);
@@ -310,7 +311,7 @@ public:
}
while (leAudioDevice) {
- PrepareAndSendUpdateMetadata(leAudioDevice, metadata_context_types, ccid_lists);
+ PrepareAndSendUpdateMetadata(group, leAudioDevice, metadata_context_types, ccid_lists);
leAudioDevice = group->GetNextActiveDevice(leAudioDevice);
}
break;
@@ -394,7 +395,8 @@ public:
}
}
- void ProcessGattCtpNotification(LeAudioDeviceGroup* group, uint8_t* value, uint16_t len) {
+ void ProcessGattCtpNotification(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice,
+ uint8_t* value, uint16_t len) {
auto ntf = std::make_unique<struct bluetooth::le_audio::client_parser::ascs::ctp_ntf>();
bool valid_notification = ParseAseCtpNotification(*ntf, len, value);
@@ -415,10 +417,13 @@ public:
*/
auto target_state = group->GetTargetState();
+ auto current_state = group->GetState();
auto in_transition = group->IsInTransition();
if (!in_transition || target_state != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- log::debug("Not interested in ctp result for group {} inTransition: {} , targetState: {}",
- group->group_id_, in_transition, ToString(target_state));
+ log::debug(
+ "Not interested in ctp result for group {} inTransition: {} , targetState: {}, "
+ "currentState: {}",
+ group->group_id_, in_transition, ToString(target_state), ToString(current_state));
return;
}
@@ -429,24 +434,59 @@ public:
}
for (auto& entry : ntf->entries) {
+ // release ASEs on device which did not accept control point command
if (entry.response_code !=
bluetooth::le_audio::client_parser::ascs::kCtpResponseCodeSuccess) {
- /* Gracefully stop the stream */
- log::error(
- "Stopping stream due to control point error for ase: {}, error: "
- "0x{:02x}, reason: 0x{:02x}",
- entry.ase_id, entry.response_code, entry.reason);
+ if (ntf->op == bluetooth::le_audio::client_parser::ascs::kCtpOpcodeRelease) {
+ log::warn(
+ "Release failed for {}, ase: {}, last_ase_ctp_command_sent: {:#x}, error: {:#x}, "
+ "reason: {:#x}, let "
+ "watchdog to fire",
+ leAudioDevice->address_, entry.ase_id, leAudioDevice->last_ase_ctp_command_sent,
+ entry.response_code, entry.reason);
+ return;
+ }
- notifyLeAudioHealth(
- group,
- bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED);
- StopStream(group);
+ auto release_sent_to_remote = PrepareAndSendRelease(leAudioDevice);
+ auto active_devices = group->GetNumOfActiveDevices();
+
+ int releasing_devices = 0;
+ for (auto dev = group->GetFirstActiveDevice(); dev; dev = group->GetNextActiveDevice(dev)) {
+ if (dev->last_ase_ctp_command_sent ==
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeRelease) {
+ releasing_devices++;
+ }
+ }
+
+ log::error(
+ "Releasing ASE due to control point error for {}, ase: {}, opcode: {:#x}, "
+ "last_ase_ctp_command_sent: {:#x}, error: "
+ "{:#x}, reason: {:#x}. release_sent_to_remote: {}, active_devices: {}, "
+ "releasing_devices: {}",
+ leAudioDevice->address_, entry.ase_id, ntf->op,
+ leAudioDevice->last_ase_ctp_command_sent, entry.response_code, entry.reason,
+ release_sent_to_remote, active_devices, releasing_devices);
+
+ // If there is no active devices it means, the whole set got released
+ if (releasing_devices == 0 && active_devices == 0) {
+ /* No remote communication expected */
+ ClearGroup(group, true);
+ notifyLeAudioHealth(
+ group,
+ bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED);
+ } else if (active_devices != 0 && releasing_devices == active_devices) {
+ group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
+ state_machine_callbacks_->StatusReportCb(group->group_id_, GroupStreamStatus::RELEASING);
+ notifyLeAudioHealth(
+ group,
+ bluetooth::le_audio::LeAudioHealthGroupStatType::STREAM_CREATE_SIGNALING_FAILED);
+ }
return;
}
}
- log::debug("Ctp result OK for group {} inTransition: {} , targetState: {}", group->group_id_,
- in_transition, ToString(target_state));
+ log::debug("Ctp result OK for group {} inTransition: {} , targetState: {}, currentState: {}",
+ group->group_id_, in_transition, ToString(target_state), ToString(current_state));
}
void ProcessGattNotifEvent(uint8_t* value, uint16_t len, struct ase* ase,
@@ -838,7 +878,6 @@ public:
*/
group->ReloadAudioLocations();
group->ReloadAudioDirections();
- group->UpdateAudioContextAvailability();
group->InvalidateCachedConfigurations();
group->InvalidateGroupStrategy();
@@ -976,6 +1015,15 @@ public:
" STATUS=" + loghex(event->status));
if (event->status != HCI_SUCCESS) {
+ log::warn("{}: failed to create CIS 0x{:04x}, status: {} (0x{:02x})", leAudioDevice->address_,
+ event->cis_conn_hdl, ErrorCodeText((ErrorCode)event->status), event->status);
+
+ if (event->status == HCI_ERR_CANCELLED_BY_LOCAL_HOST) {
+ log::info("{} CIS creation aborted by us, waiting for disconnection complete",
+ leAudioDevice->address_);
+ return;
+ }
+
if (ases_pair.sink) {
ases_pair.sink->cis_state = CisState::ASSIGNED;
}
@@ -983,9 +1031,6 @@ public:
ases_pair.source->cis_state = CisState::ASSIGNED;
}
- log::warn("{}: failed to create CIS 0x{:04x}, status: {} (0x{:02x})", leAudioDevice->address_,
- event->cis_conn_hdl, ErrorCodeText((ErrorCode)event->status), event->status);
-
if (event->status == HCI_ERR_CONN_FAILED_ESTABLISHMENT &&
((leAudioDevice->cis_failed_to_be_established_retry_cnt_++) < kNumberOfCisRetries) &&
(CisCreateForDevice(group, leAudioDevice))) {
@@ -1024,9 +1069,25 @@ public:
leAudioDevice->cis_failed_to_be_established_retry_cnt_ = 0;
}
- if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
- log::error("Unintended CIS establishement event came for group id: {}", group->group_id_);
- StopStream(group);
+ bool is_cis_connecting =
+ (ases_pair.sink && ases_pair.sink->cis_state == CisState::CONNECTING) ||
+ (ases_pair.source && ases_pair.source->cis_state == CisState::CONNECTING);
+
+ if (group->GetTargetState() != AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING ||
+ !is_cis_connecting) {
+ bool is_cis_disconnecting =
+ (ases_pair.sink && ases_pair.sink->cis_state == CisState::DISCONNECTING) ||
+ (ases_pair.source && ases_pair.source->cis_state == CisState::DISCONNECTING);
+ if (is_cis_disconnecting) {
+ /* We are in the process of CIS disconnection while the Established event came.
+ * The Disconnection Complete shall come right after.
+ */
+ log::info("{} got CIS is in disconnecting state", leAudioDevice->address_);
+ } else {
+ log::error("Unintended CIS establishment event came for group id: {}", group->group_id_);
+ StopStream(group);
+ }
+
return;
}
@@ -1100,16 +1161,19 @@ public:
auto ases_pair = leAudioDevice->GetAsesByCisConnHdl(cis_conn_hdl);
uint8_t value = 0;
- if (ases_pair.sink && ases_pair.sink->data_path_state == DataPathState::CONFIGURED) {
+ if (ases_pair.sink && (ases_pair.sink->data_path_state == DataPathState::CONFIGURED ||
+ ases_pair.sink->data_path_state == DataPathState::CONFIGURING)) {
value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionInput;
ases_pair.sink->data_path_state = DataPathState::REMOVING;
}
- if (ases_pair.source && ases_pair.source->data_path_state == DataPathState::CONFIGURED) {
+ if (ases_pair.source && (ases_pair.source->data_path_state == DataPathState::CONFIGURED ||
+ ases_pair.source->data_path_state == DataPathState::CONFIGURING)) {
value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput;
ases_pair.source->data_path_state = DataPathState::REMOVING;
} else {
- if (leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURED) {
+ if (leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURED ||
+ leAudioDevice->GetDsaDataPathState() == DataPathState::CONFIGURING) {
value |= bluetooth::hci::iso_manager::kRemoveIsoDataPathDirectionOutput;
leAudioDevice->SetDsaDataPathState(DataPathState::REMOVING);
}
@@ -1280,6 +1344,9 @@ public:
/* We should send Receiver Stop Ready when acting as a source */
if (ases_pair.source && ases_pair.source->state == AseState::BTA_LE_AUDIO_ASE_STATE_DISABLING) {
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeReceiverStopReady;
+
std::vector<uint8_t> ids = {ases_pair.source->id};
std::vector<uint8_t> value;
@@ -1936,6 +2003,9 @@ private:
extra_stream << +conf.codec_id.coding_format << "," << +conf.target_latency << ";;";
}
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeCodecConfiguration;
+
std::vector<uint8_t> value;
log::info("{} -> ", leAudioDevice->address_);
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpCodecConfig(confs, value);
@@ -2137,7 +2207,8 @@ private:
return;
}
- if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
+ if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING &&
+ group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
/* We are here because of the reconnection of the single device. */
/* Make sure that device is ready to be configured as we could also
* get here triggered by the remote device. If device is not connected
@@ -2400,7 +2471,7 @@ private:
group->SetTargetState(AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
/* Clear group pending status */
- group->ClearPendingAvailableContextsChange();
+ group->ClearStreamingMetadataContexts();
group->ClearPendingConfiguration();
cancel_watchdog_if_needed(group->group_id_);
@@ -2453,6 +2524,9 @@ private:
<< ";;";
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeEnable;
+
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpEnable(confs, value);
WriteToControlPoint(leAudioDevice, value);
@@ -2494,10 +2568,12 @@ private:
msg_stream << "ASE_ID " << +ase->id << ", ";
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeDisable;
+
log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_);
std::vector<uint8_t> value;
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpDisable(ids, value);
-
WriteToControlPoint(leAudioDevice, value);
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
@@ -2514,14 +2590,19 @@ private:
return GroupStreamStatus::IDLE;
}
+ bool releasing = false;
for (; leAudioDevice; leAudioDevice = group->GetNextActiveDevice(leAudioDevice)) {
- PrepareAndSendRelease(leAudioDevice);
+ releasing |= PrepareAndSendRelease(leAudioDevice);
}
- return GroupStreamStatus::RELEASING;
+ if (releasing) {
+ return GroupStreamStatus::RELEASING;
+ }
+
+ return GroupStreamStatus::IDLE;
}
- void PrepareAndSendRelease(LeAudioDevice* leAudioDevice) {
+ bool PrepareAndSendRelease(LeAudioDevice* leAudioDevice) {
ase* ase = leAudioDevice->GetFirstActiveAse();
log::assert_that(ase, "shouldn't be called without an active ASE");
@@ -2532,10 +2613,23 @@ private:
do {
log::debug("device: {}, ase_id: {}, cis_id: {}, ase state: {}", leAudioDevice->address_,
ase->id, ase->cis_id, ToString(ase->state));
- ids.push_back(ase->id);
- stream << "ASE_ID " << +ase->id << ",";
+ if (ase->state != AseState::BTA_LE_AUDIO_ASE_STATE_IDLE) {
+ ids.push_back(ase->id);
+ stream << "ASE_ID " << +ase->id << ",";
+ } else {
+ log::info("{}, ase: {} already in idle. Deactivate it", leAudioDevice->address_, ase->id);
+ ase->active = false;
+ }
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
+ if (ids.empty()) {
+ log::info("Nothing to send to {}", leAudioDevice->address_);
+ return false;
+ }
+
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeRelease;
+
std::vector<uint8_t> value;
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpRelease(ids, value);
WriteToControlPoint(leAudioDevice, value);
@@ -2543,6 +2637,7 @@ private:
log::info("group_id: {}, {}", leAudioDevice->group_id_, leAudioDevice->address_);
log_history_->AddLogHistory(kLogControlPointCmd, leAudioDevice->group_id_,
leAudioDevice->address_, stream.str());
+ return true;
}
void PrepareAndSendConfigQos(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice) {
@@ -2634,6 +2729,9 @@ private:
return;
}
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeQosConfiguration;
+
std::vector<uint8_t> value;
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpConfigQos(confs, value);
WriteToControlPoint(leAudioDevice, value);
@@ -2643,7 +2741,7 @@ private:
msg_stream.str(), extra_stream.str());
}
- void PrepareAndSendUpdateMetadata(LeAudioDevice* leAudioDevice,
+ void PrepareAndSendUpdateMetadata(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice,
const BidirectionalPair<AudioContexts>& context_types,
const BidirectionalPair<std::vector<uint8_t>>& ccid_lists) {
std::vector<struct bluetooth::le_audio::client_parser::ascs::ctp_update_metadata> confs;
@@ -2680,10 +2778,10 @@ private:
}
/* Filter multidirectional audio context for each ase direction */
- auto directional_audio_context = context_types.get(ase->direction) &
- leAudioDevice->GetAvailableContexts(ase->direction);
+ auto directional_audio_context =
+ context_types.get(ase->direction) & group->GetAvailableContexts(ase->direction);
- bluetooth::le_audio::types::LeAudioLtvMap new_metadata;
+ LeAudioLtvMap new_metadata;
if (directional_audio_context.any()) {
new_metadata = leAudioDevice->GetMetadata(directional_audio_context,
ccid_lists.get(ase->direction));
@@ -2710,6 +2808,9 @@ private:
}
if (confs.size() != 0) {
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeUpdateMetadata;
+
std::vector<uint8_t> value;
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpUpdateMetadata(confs, value);
WriteToControlPoint(leAudioDevice, value);
@@ -2736,6 +2837,9 @@ private:
} while ((ase = leAudioDevice->GetNextActiveAse(ase)));
if (ids.size() > 0) {
+ leAudioDevice->last_ase_ctp_command_sent =
+ bluetooth::le_audio::client_parser::ascs::kCtpOpcodeReceiverStartReady;
+
bluetooth::le_audio::client_parser::ascs::PrepareAseCtpAudioReceiverStartReady(ids, value);
WriteToControlPoint(leAudioDevice, value);
@@ -2822,6 +2926,21 @@ private:
return;
}
+ struct bluetooth::le_audio::client_parser::ascs::ase_transient_state_params rsp;
+
+ bool valid_response = ParseAseStatusTransientStateParams(rsp, len, data);
+
+ std::optional<AudioContexts> streaming_audio_context;
+ LeAudioLtvMap meta;
+ if (valid_response && !rsp.metadata.empty() &&
+ meta.Parse(rsp.metadata.data(), rsp.metadata.size())) {
+ streaming_audio_context = meta.GetAsLeAudioMetadata().streaming_audio_context;
+ if (!streaming_audio_context) {
+ log::error("{}, ase_id: {}, Did not found streaming metadata while parsing metadata: {}",
+ leAudioDevice->address_, ase->id, bluetooth::common::ToHexString(rsp.metadata));
+ }
+ }
+
switch (ase->state) {
case AseState::BTA_LE_AUDIO_ASE_STATE_QOS_CONFIGURED:
log::error("{}, ase_id: {}, moving from QoS Configured to Streaming is impossible.",
@@ -2834,6 +2953,9 @@ private:
std::vector<uint8_t> value;
SetAseState(leAudioDevice, ase, AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+ if (streaming_audio_context) {
+ group->SetStreamingMetadataContexts(streaming_audio_context.value(), ase->direction);
+ }
if (!group->HaveAllActiveDevicesAsesTheSameState(
AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING)) {
@@ -2842,6 +2964,14 @@ private:
return;
}
+ /* The group is not ready to stream yet as there is still pending CIS Establish event and/or
+ * Data Path setup complete event */
+ if (!group->IsGroupStreamReady()) {
+ log::info("CISes are not yet ready, wait for it.");
+ group->SetNotifyStreamingWhenCisesAreReadyFlag(true);
+ return;
+ }
+
if (group->GetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
/* We are here because of the reconnection of the single device */
log::info("{}, Ase id: {}, ase state: {}", leAudioDevice->address_, ase->id,
@@ -2851,13 +2981,6 @@ private:
return;
}
- /* Not all CISes establish events will came */
- if (!group->IsGroupStreamReady()) {
- log::info("CISes are not yet ready, wait for it.");
- group->SetNotifyStreamingWhenCisesAreReadyFlag(true);
- return;
- }
-
if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
/* No more transition for group */
cancel_watchdog_if_needed(group->group_id_);
@@ -2876,20 +2999,14 @@ private:
break;
}
case AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING: {
- struct bluetooth::le_audio::client_parser::ascs::ase_transient_state_params rsp;
-
- if (!ParseAseStatusTransientStateParams(rsp, len, data)) {
+ if (!valid_response) {
StopStream(group);
return;
}
- /* Cache current set up metadata values for for further possible
- * reconfiguration
- */
- if (!rsp.metadata.empty() &&
- !ase->metadata.Parse(rsp.metadata.data(), rsp.metadata.size())) {
- log::error("Error while parsing metadata: {}",
- bluetooth::common::ToHexString(rsp.metadata));
+ /* Cache current as streaming metadata */
+ if (streaming_audio_context) {
+ group->SetStreamingMetadataContexts(streaming_audio_context.value(), ase->direction);
}
break;
@@ -3064,6 +3181,7 @@ private:
if (group->HaveAllActiveDevicesAsesTheSameState(
AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING)) {
group->SetState(AseState::BTA_LE_AUDIO_ASE_STATE_RELEASING);
+ group->ClearStreamingMetadataContexts();
if (group->GetTargetState() == AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING) {
log::info("Group {} is doing autonomous release", group->group_id_);
SetTargetState(group, AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
diff --git a/system/bta/le_audio/state_machine.h b/system/bta/le_audio/state_machine.h
index 19b50e68c9..be6f80e8da 100644
--- a/system/bta/le_audio/state_machine.h
+++ b/system/bta/le_audio/state_machine.h
@@ -60,8 +60,8 @@ public:
types::BidirectionalPair<std::vector<uint8_t>> ccid_lists = {.sink = {}, .source = {}},
bool configure_qos = false) = 0;
virtual void StopStream(LeAudioDeviceGroup* group) = 0;
- virtual void ProcessGattCtpNotification(LeAudioDeviceGroup* group, uint8_t* value,
- uint16_t len) = 0;
+ virtual void ProcessGattCtpNotification(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice,
+ uint8_t* value, uint16_t len) = 0;
virtual void ProcessGattNotifEvent(uint8_t* value, uint16_t len, struct types::ase* ase,
LeAudioDevice* leAudioDevice, LeAudioDeviceGroup* group) = 0;
diff --git a/system/bta/le_audio/state_machine_test.cc b/system/bta/le_audio/state_machine_test.cc
index 89a5682b9d..d17bfda188 100644
--- a/system/bta/le_audio/state_machine_test.cc
+++ b/system/bta/le_audio/state_machine_test.cc
@@ -58,8 +58,6 @@ using ::testing::Test;
extern struct fake_osi_alarm_set_on_mloop fake_osi_alarm_set_on_mloop_;
-void osi_property_set_bool(const char* key, bool value);
-
constexpr uint8_t media_ccid = 0xC0;
constexpr auto media_context = LeAudioContextType::MEDIA;
@@ -239,19 +237,26 @@ protected:
int retry_cis_established_cnt_;
bool do_not_send_cis_establish_event_;
bool do_not_send_cis_disconnected_event_;
+ bool do_not_send_setup_iso_data_path_event_;
+ bool do_not_send_remove_iso_data_path_event_;
uint8_t overwrite_cis_status_idx_;
std::vector<uint8_t> cis_status_;
/* Keep ASE in releasing state */
bool stay_in_releasing_state_;
+ /* Do not response immediately on Release CTP for the devices in the list*/
+ std::vector<RawAddress> block_releasing_state_device_list_;
/* Use for single test to simulate late ASE notifications */
bool stop_inject_configured_ase_after_first_ase_configured_;
+ uint16_t attr_handle = ATTR_HANDLE_ASCS_POOL_START;
uint16_t pacs_attr_handle_next = ATTR_HANDLE_PACS_POOL_START;
virtual void SetUp() override {
__android_log_set_minimum_priority(ANDROID_LOG_DEBUG);
+ com::android::bluetooth::flags::provider_->reset_flags();
+
reset_mock_function_count_map();
bluetooth::manager::SetMockBtmInterface(&btm_interface);
gatt::SetMockBtaGattInterface(&gatt_interface);
@@ -264,7 +269,10 @@ protected:
overwrite_cis_status_ = false;
do_not_send_cis_establish_event_ = false;
do_not_send_cis_disconnected_event_ = false;
+ do_not_send_setup_iso_data_path_event_ = false;
+ do_not_send_remove_iso_data_path_event_ = false;
stay_in_releasing_state_ = false;
+ block_releasing_state_device_list_.clear();
stop_inject_configured_ase_after_first_ase_configured_ = false;
cis_status_.clear();
@@ -408,6 +416,11 @@ protected:
ASSERT_NE(conn_handle, kInvalidCisConnHandle);
+ if (do_not_send_setup_iso_data_path_event_) {
+ log::debug("Don't setup ISO data path event");
+ return;
+ }
+
auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(),
[&conn_handle](auto& dev) {
auto ases = dev->GetAsesByCisConnHdl(conn_handle);
@@ -434,6 +447,11 @@ protected:
ASSERT_NE(conn_handle, kInvalidCisConnHandle);
+ if (do_not_send_remove_iso_data_path_event_) {
+ log::debug("Don't send remove ISO data path event");
+ return;
+ }
+
auto dev_it = std::find_if(le_audio_devices_.begin(), le_audio_devices_.end(),
[&conn_handle](auto& dev) {
auto ases = dev->GetAsesByCisConnHdl(conn_handle);
@@ -608,8 +626,6 @@ protected:
}
void TearDown() override {
- com::android::bluetooth::flags::provider_->reset_flags();
-
/* Clear the alarm on tear down in case test case ends when the
* alarm is scheduled
*/
@@ -643,11 +659,6 @@ protected:
leAudioDevice->conn_id_ = id;
leAudioDevice->SetConnectionState(DeviceConnectState::CONNECTED);
- uint16_t attr_handle = ATTR_HANDLE_ASCS_POOL_START;
- leAudioDevice->snk_audio_locations_hdls_.val_hdl = attr_handle++;
- leAudioDevice->snk_audio_locations_hdls_.ccc_hdl = attr_handle++;
- leAudioDevice->src_audio_locations_hdls_.val_hdl = attr_handle++;
- leAudioDevice->src_audio_locations_hdls_.ccc_hdl = attr_handle++;
leAudioDevice->audio_avail_hdls_.val_hdl = attr_handle++;
leAudioDevice->audio_avail_hdls_.ccc_hdl = attr_handle++;
leAudioDevice->audio_supp_cont_hdls_.val_hdl = attr_handle++;
@@ -711,7 +722,6 @@ protected:
/* Update all stuff on the group when device got connected */
group->ReloadAudioLocations();
group->ReloadAudioDirections();
- group->UpdateAudioContextAvailability();
group->InvalidateCachedConfigurations();
group->InvalidateGroupStrategy();
}
@@ -1056,7 +1066,6 @@ protected:
if (group) {
bool group_conf_changed = group->ReloadAudioLocations();
group_conf_changed |= group->ReloadAudioDirections();
- group_conf_changed |= group->UpdateAudioContextAvailability();
if (group_conf_changed) {
/* All the configurations should be recalculated for the new conditions */
group->InvalidateCachedConfigurations();
@@ -1084,7 +1093,10 @@ protected:
leAudioDevice->snk_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs));
- leAudioDevice->snk_audio_locations_ = audio_locations;
+ auto val_hdl = attr_handle++;
+ auto ccc_hdl = attr_handle++;
+ leAudioDevice->audio_locations_.sink.emplace(types::hdl_pair(val_hdl, ccc_hdl),
+ types::AudioLocations(audio_locations));
}
if ((direction & types::kLeAudioDirectionSource) > 0) {
@@ -1105,7 +1117,10 @@ protected:
leAudioDevice->src_pacs_.emplace_back(std::make_tuple(std::move(handle_pair), pac_recs));
- leAudioDevice->src_audio_locations_ = audio_locations;
+ auto val_hdl = attr_handle++;
+ auto ccc_hdl = attr_handle++;
+ leAudioDevice->audio_locations_.source.emplace(types::hdl_pair(val_hdl, ccc_hdl),
+ types::AudioLocations(audio_locations));
}
DeviceContextsUpdate(leAudioDevice, direction, contexts_available, contexts_supported);
@@ -1260,6 +1275,8 @@ protected:
cached_codec_configuration_map_[ase_id] = codec_configured_state_params;
}
+ InjectCtpNotification(group, device, value);
+
if (inject_configured) {
InjectAseStateNotification(ase, device, group, ascs::kAseStateCodecConfigured,
&codec_configured_state_params);
@@ -1278,6 +1295,7 @@ protected:
.WillByDefault(Invoke([group, verify_ase_count, caching, inject_qos_configured, this](
LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value);
auto num_ase = value[1];
// Verify ase count if needed
@@ -1345,43 +1363,70 @@ protected:
}));
}
- void PrepareCtpNotificationError(LeAudioDeviceGroup* group, uint8_t opcode, uint8_t response_code,
- uint8_t reason) {
- auto foo = [group, opcode, response_code, reason](LeAudioDevice* device,
- std::vector<uint8_t> value,
- GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
- auto num_ase = value[1];
- std::vector<uint8_t> notif_value(2 +
- num_ase * sizeof(struct client_parser::ascs::ctp_ase_entry));
- auto* p = notif_value.data();
-
- UINT8_TO_STREAM(p, opcode);
- UINT8_TO_STREAM(p, num_ase);
-
- auto* ase_p = &value[2];
- for (auto i = 0u; i < num_ase; ++i) {
- /* Check if this is a valid ASE ID */
- auto ase_id = *ase_p++;
- auto it = std::find_if(device->ases_.begin(), device->ases_.end(),
+ void InjectCtpNotification(LeAudioDeviceGroup* group, LeAudioDevice* leAudioDevice,
+ std::vector<uint8_t>& ctp_command, uint8_t response_code = 0x00,
+ uint8_t reason = 0x00) {
+ auto opcode = ctp_command[0];
+ auto num_ase = ctp_command[1];
+ std::vector<uint8_t> notif_value(2 +
+ num_ase * sizeof(struct client_parser::ascs::ctp_ase_entry));
+ auto* p = notif_value.data();
+
+ UINT8_TO_STREAM(p, opcode);
+ UINT8_TO_STREAM(p, num_ase);
+
+ auto* ase_p = &ctp_command[2];
+ for (auto i = 0u; i < num_ase; ++i) {
+ /* Check if this is a valid ASE ID */
+ auto ase_id = *ase_p++;
+
+ /* Do additional verification with the device ASE only when opcode is different than codec
+ * config. This is because, device will get ASE id when Codec Configured Notification arrives.
+ */
+ if (opcode != client_parser::ascs::kCtpOpcodeCodecConfiguration) {
+ auto it = std::find_if(leAudioDevice->ases_.begin(), leAudioDevice->ases_.end(),
[ase_id](auto& ase) { return ase.id == ase_id; });
- ASSERT_NE(it, device->ases_.end());
+ ASSERT_NE(it, leAudioDevice->ases_.end());
+ }
- auto meta_len = *ase_p++;
- auto num_handled_bytes = ase_p - value.data();
- ase_p += meta_len;
+ switch (opcode) {
+ case client_parser::ascs::kCtpOpcodeCodecConfiguration: {
+ ase_p += 7;
+ auto codec_spec_len = *ase_p++;
+ ase_p += codec_spec_len;
+ } break;
+ case client_parser::ascs::kCtpOpcodeQosConfiguration:
+ ase_p += 15;
+ break;
+ case client_parser::ascs::kCtpOpcodeUpdateMetadata:
+ case client_parser::ascs::kCtpOpcodeEnable: {
+ auto meta_len = *ase_p++;
+ ase_p += meta_len;
+ } break;
+ case client_parser::ascs::kCtpOpcodeReceiverStartReady:
+ case client_parser::ascs::kCtpOpcodeDisable:
+ case client_parser::ascs::kCtpOpcodeReceiverStopReady:
+ case client_parser::ascs::kCtpOpcodeRelease:
+ default:
+ break;
+ }
- client_parser::ascs::ase_transient_state_params enable_params = {
- .metadata = std::vector<uint8_t>(value.begin() + num_handled_bytes,
- value.begin() + num_handled_bytes + meta_len)};
+ // Inject error response
+ UINT8_TO_STREAM(p, ase_id);
+ UINT8_TO_STREAM(p, response_code);
+ UINT8_TO_STREAM(p, reason);
+ }
- // Inject error response
- UINT8_TO_STREAM(p, ase_id);
- UINT8_TO_STREAM(p, response_code);
- UINT8_TO_STREAM(p, reason);
- }
+ LeAudioGroupStateMachine::Get()->ProcessGattCtpNotification(
+ group, leAudioDevice, notif_value.data(), notif_value.size());
+ }
- LeAudioGroupStateMachine::Get()->ProcessGattCtpNotification(group, notif_value.data(),
- notif_value.size());
+ void PrepareCtpNotificationError(LeAudioDeviceGroup* group, uint8_t opcode, uint8_t response_code,
+ uint8_t reason) {
+ auto foo = [group, response_code, reason, this](LeAudioDevice* device,
+ std::vector<uint8_t> value,
+ GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value, response_code, reason);
};
switch (opcode) {
@@ -1420,6 +1465,8 @@ protected:
.WillByDefault(Invoke([group, verify_ase_count, inject_enabling, incject_streaming,
this](LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value);
+
auto num_ase = value[1];
// Verify ase count if needed
@@ -1472,6 +1519,7 @@ protected:
.WillByDefault(Invoke([group, verify_ase_count, this](
LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value);
auto num_ase = value[1];
// Verify ase count if needed
@@ -1515,6 +1563,7 @@ protected:
.WillByDefault(Invoke([group, verify_ase_count, this](
LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value);
auto num_ase = value[1];
// Verify ase count if needed
@@ -1547,6 +1596,7 @@ protected:
.WillByDefault(Invoke([group, verify_ase_count, this](
LeAudioDevice* device, std::vector<uint8_t> value,
GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ InjectCtpNotification(group, device, value);
auto num_ase = value[1];
// Verify ase count if needed
@@ -1575,16 +1625,18 @@ protected:
}
void PrepareReleaseHandler(LeAudioDeviceGroup* group, int verify_ase_count = 0,
- bool inject_disconnect_device = false, LeAudioDevice* dev = nullptr) {
+ bool inject_disconnect_device = false, LeAudioDevice* dev = nullptr,
+ bool inject_releasing = true) {
ON_CALL(ase_ctp_handler, AseCtpReleaseHandler)
- .WillByDefault(Invoke([group, verify_ase_count, inject_disconnect_device, dev, this](
- LeAudioDevice* device, std::vector<uint8_t> value,
- GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
+ .WillByDefault(Invoke([group, verify_ase_count, inject_disconnect_device, dev,
+ inject_releasing,
+ this](LeAudioDevice* device, std::vector<uint8_t> value,
+ GATT_WRITE_OP_CB /*cb*/, void* /*cb_data*/) {
if (dev != nullptr && device != dev) {
log::info("Do nothing for {}", dev->address_);
return;
}
-
+ InjectCtpNotification(group, device, value);
auto num_ase = value[1];
// Verify ase count if needed
@@ -1608,6 +1660,18 @@ protected:
ASSERT_NE(it, device->ases_.end());
const auto ase = &(*it);
+ // Prevent RELEASING notification for the whole group
+ if (!inject_releasing) {
+ continue;
+ }
+
+ // Prevent RELEASING notification for single devices in the group
+ auto iter = std::find(block_releasing_state_device_list_.begin(),
+ block_releasing_state_device_list_.end(), device->address_);
+ if (iter != block_releasing_state_device_list_.end()) {
+ continue;
+ }
+
InjectAseStateNotification(ase, device, group, ascs::kAseStateReleasing, nullptr);
if (stay_in_releasing_state_) {
@@ -2059,11 +2123,15 @@ TEST_F(StateMachineTest, testConfigureQosFailed) {
group, client_parser::ascs::kCtpOpcodeQosConfiguration,
client_parser::ascs::kCtpResponseCodeInvalidConfigurationParameterValue,
client_parser::ascs::kCtpResponsePhy);
+
PrepareReleaseHandler(group);
auto* leAudioDevice = group->GetFirstDevice();
auto expected_devices_written = 0;
while (leAudioDevice) {
+ // We will inject state after manually for test porpuse
+ block_releasing_state_device_list_.push_back(leAudioDevice->address_);
+
EXPECT_CALL(gatt_queue,
WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _,
GATT_WRITE_NO_RSP, _, _))
@@ -2088,9 +2156,13 @@ TEST_F(StateMachineTest, testConfigureQosFailed) {
{.sink = types::AudioContexts(context_type),
.source = types::AudioContexts(context_type)}));
+ InjectReleaseAndIdleStateForAGroup(group);
+
// Check if group has transitioned to a proper state
ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
- ASSERT_EQ(2, get_func_call_count("alarm_cancel"));
+
+ // During error only one cancel will happen when all devices will go down to IDLE
+ ASSERT_EQ(1, get_func_call_count("alarm_cancel"));
testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
}
@@ -2168,7 +2240,10 @@ TEST_F(StateMachineTest, testStreamCreationError) {
client_parser::ascs::kCtpResponseNoReason);
PrepareReleaseHandler(group);
- auto* leAudioDevice = group->GetFirstDevice();
+ auto leAudioDevice = group->GetFirstDevice();
+
+ /* To avoid the loop. Will Inject release later. */
+ block_releasing_state_device_list_.push_back(leAudioDevice->address_);
/*
* 1 - Configure ASE
@@ -2202,9 +2277,11 @@ TEST_F(StateMachineTest, testStreamCreationError) {
{.sink = types::AudioContexts(context_type),
.source = types::AudioContexts(context_type)}));
+ InjectReleaseAndIdleStateForAGroup(group);
+
// Check if group has transitioned to a proper state
ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
- ASSERT_EQ(2, get_func_call_count("alarm_cancel"));
+ ASSERT_EQ(1, get_func_call_count("alarm_cancel"));
}
TEST_F(StateMachineTest, testStreamSingle) {
@@ -2955,7 +3032,8 @@ TEST_F(StateMachineTest, remoteRejectsEnable) {
InjectInitialIdleNotification(group);
- auto* leAudioDevice = group->GetFirstDevice();
+ auto leAudioDevice = group->GetFirstDevice();
+ block_releasing_state_device_list_.push_back(leAudioDevice->address_);
/* First device Control Point actions
* Codec Config
@@ -2967,17 +3045,20 @@ TEST_F(StateMachineTest, remoteRejectsEnable) {
WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _,
GATT_WRITE_NO_RSP, _, _))
.Times(4);
+
leAudioDevice = group->GetNextDevice(leAudioDevice);
+ block_releasing_state_device_list_.push_back(leAudioDevice->address_);
/* Second device Control Point actions
* Codec Config
* QoS Config
+ * Enable
* Release
*/
EXPECT_CALL(gatt_queue,
WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _,
GATT_WRITE_NO_RSP, _, _))
- .Times(3);
+ .Times(4);
// Start the configuration and stream Media content
ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
@@ -2985,9 +3066,11 @@ TEST_F(StateMachineTest, remoteRejectsEnable) {
{.sink = types::AudioContexts(context_type),
.source = types::AudioContexts(context_type)}));
+ InjectReleaseAndIdleStateForAGroup(group);
+
// Check if group has transitioned to a proper state
ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
- ASSERT_EQ(2, get_func_call_count("alarm_cancel"));
+ ASSERT_EQ(1, get_func_call_count("alarm_cancel"));
}
TEST_F(StateMachineTest, testStreamMultiple) {
@@ -5548,6 +5631,72 @@ TEST_F(StateMachineTest, testAttachDeviceToTheStreamV2) {
ASSERT_NE(ase->qos_config.retrans_nb, 0);
}
+TEST_F(StateMachineTest, testStreamingContextMechanism) {
+ const auto context_type = kContextTypeMedia;
+ const auto leaudio_group_id = 6;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ // Prepare multiple fake connected devices in a group
+ auto* group = PrepareSingleTestDeviceGroup(leaudio_group_id, context_type, num_devices);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ PrepareConfigureCodecHandler(group);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ auto* leAudioDevice = group->GetFirstDevice();
+ LeAudioDevice* firstDevice = leAudioDevice;
+ LeAudioDevice* lastDevice;
+
+ auto expected_devices_written = 0;
+ while (leAudioDevice) {
+ /* Three Writes:
+ * 1: Codec Config
+ * 2: Codec QoS
+ * 3: Enabling
+ */
+ lastDevice = leAudioDevice;
+ EXPECT_CALL(gatt_queue,
+ WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _,
+ GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+ expected_devices_written++;
+ leAudioDevice = group->GetNextDevice(leAudioDevice);
+ }
+ ASSERT_EQ(expected_devices_written, num_devices);
+
+ EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(1);
+ EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1);
+ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(_, _)).Times(2);
+
+ InjectInitialIdleNotification(group);
+
+ // Start the configuration and stream Media content
+ LeAudioGroupStateMachine::Get()->StartStream(group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)});
+
+ // Check if group has transitioned to a proper state
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+ testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
+
+ auto test_context_type = kContextTypeUnspecified | kContextTypeConversational;
+ firstDevice->SetAvailableContexts({.sink = test_context_type, .source = test_context_type});
+ lastDevice->SetAvailableContexts({.sink = test_context_type, .source = test_context_type});
+
+ auto expected_sink_context_type =
+ kContextTypeUnspecified | kContextTypeConversational | kContextTypeMedia;
+ auto expected_source_context_type = kContextTypeUnspecified | kContextTypeConversational;
+
+ ASSERT_EQ(group->GetAvailableContexts(types::kLeAudioDirectionSink), expected_sink_context_type);
+ ASSERT_EQ(group->GetAvailableContexts(types::kLeAudioDirectionSource),
+ expected_source_context_type);
+}
+
TEST_F(StateMachineTest, testAttachDeviceToTheStreamDeviceNoAvailableContext) {
const auto context_type = kContextTypeMedia;
const auto leaudio_group_id = 6;
@@ -5718,7 +5867,7 @@ TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_CodecConfigStat
* 3. Reconnect
* 4. Trigger attach the stream
* 6. StopStream while getting to Codec Configured State on attaching device
- * 7. Check that Attaching device will also go to IDLE
+ * 7. Check that Attaching device will not get Release CMD
*/
ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
@@ -5796,11 +5945,12 @@ TEST_F(StateMachineTest, testReleaseStreamWithLateAttachToStream_CodecConfigStat
/*
* 1. Codec Configure for attaching device
- * 2. Release for both devices
+ * 2. Release for streaming device only as the attaching one is still not in Codec Configured
+ * state.
*/
EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl,
_, GATT_WRITE_NO_RSP, _, _))
- .Times(2);
+ .Times(1);
EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl,
_, GATT_WRITE_NO_RSP, _, _))
@@ -6798,7 +6948,6 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttached) {
lastDevice->conn_id_ = 3;
lastDevice->SetConnectionState(DeviceConnectState::CONNECTED);
- group->UpdateAudioContextAvailability();
group->UpdateAudioSetConfigurationCache(context_type);
/* Start stream, make sure 2 devices are started. */
@@ -6904,7 +7053,6 @@ TEST_F(StateMachineTest, testReconfigureAfterLateDeviceAttachedConversationalSwb
lastDevice->conn_id_ = 3;
lastDevice->SetConnectionState(DeviceConnectState::CONNECTED);
- group->UpdateAudioContextAvailability();
group->UpdateAudioSetConfigurationCache(context_type);
/* Start stream, make sure 2 devices are started. */
@@ -7016,7 +7164,6 @@ TEST_F(StateMachineTestNoSwb, testReconfigureAfterLateDeviceAttachedConversation
lastDevice->conn_id_ = 3;
lastDevice->SetConnectionState(DeviceConnectState::CONNECTED);
- group->UpdateAudioContextAvailability();
group->UpdateAudioSetConfigurationCache(context_type);
/* Start stream, make sure 2 devices are started. */
@@ -7072,7 +7219,6 @@ TEST_F(StateMachineTest, testStreamToGettingReadyDevice) {
auto* secondDevice = group->GetNextDevice(firstDevice);
secondDevice->SetConnectionState(DeviceConnectState::CONNECTED_BY_USER_GETTING_READY);
- group->UpdateAudioContextAvailability();
group->UpdateAudioSetConfigurationCache(context_type);
ASSERT_EQ(group->Size(), num_devices);
@@ -9232,7 +9378,7 @@ TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisDisc
/* Now lets try to attach the device back to the stream (Enabling and Receiver
* Start ready to be called)*/
- EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl,
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl,
_, GATT_WRITE_NO_RSP, _, _))
.Times(2);
@@ -9341,7 +9487,7 @@ TEST_F(StateMachineTest, testAutonomousDisableOneDeviceAndGoBackToStream_CisConn
/* Now lets try to attach the device back to the stream (Enabling and Receiver
* Start ready to be called)*/
- EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl,
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(lastDevice->conn_id_, lastDevice->ctp_hdls_.val_hdl,
_, GATT_WRITE_NO_RSP, _, _))
.Times(2);
@@ -9483,12 +9629,12 @@ TEST_F(StateMachineTest, testStopStreamBeforeCodecConfigureIsArrived) {
/*
* 1 - Configure ASE
- * 2 - Release ASE
+ * 2 - Release ASE (we are not Release in such a case)
*/
EXPECT_CALL(gatt_queue,
WriteCharacteristic(leAudioDevice->conn_id_, leAudioDevice->ctp_hdls_.val_hdl, _,
GATT_WRITE_NO_RSP, _, _))
- .Times(2);
+ .Times(1);
EXPECT_CALL(*mock_iso_manager_, CreateCig(_, _)).Times(0);
EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(0);
@@ -9499,9 +9645,11 @@ TEST_F(StateMachineTest, testStopStreamBeforeCodecConfigureIsArrived) {
InjectInitialIdleNotification(group);
- // Validate GroupStreamStatus
+ // Validate GroupStreamStatus and we should just received IDLE state as There is no Release CMD
+ // sent to the remote
EXPECT_CALL(mock_callbacks_,
- StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING));
+ StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::RELEASING))
+ .Times(0);
EXPECT_CALL(mock_callbacks_,
StatusReportCb(leaudio_group_id, bluetooth::le_audio::GroupStreamStatus::IDLE));
@@ -9521,7 +9669,7 @@ TEST_F(StateMachineTest, testStopStreamBeforeCodecConfigureIsArrived) {
// Check if group has transitioned to a proper state
ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_IDLE);
- ASSERT_EQ(2, get_func_call_count("alarm_cancel"));
+ ASSERT_EQ(1, get_func_call_count("alarm_cancel"));
}
TEST_F(StateMachineTest, testAutonomousReleaseFromEnablingState) {
@@ -9639,6 +9787,495 @@ TEST_F(StateMachineTest, testAutonomousReleaseFromEnablingState) {
ASSERT_TRUE(earbudRightAse->state == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
}
+TEST_F(StateMachineTest, testLateSetupIsoDatPathCompleteEvent) {
+ const auto context_type = kContextTypeRingtone;
+ const auto audio_contexts = types::AudioContexts(context_type);
+ const auto group_id = 4;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ /**
+ * Scenario:
+ * 1. Having set of 2 devices start streaming to 1 device.
+ * 2. Verify the group is streaming.
+ * 3. Attach the other device.
+ * 4. Device sends ASE Streaming state notification.
+ * 5. The Data Path is not been set up yet, so the StatusReportCb is not called yet.
+ * 6. Once the Data Path is set up, the StatusReportCb is called so that the new configuration is
+ * applied.
+ */
+
+ log::debug("[TESTING] Prepare 2 fake connected devices in a group");
+ auto* group = PrepareSingleTestDeviceGroup(group_id, context_type, num_devices);
+ ASSERT_NE(nullptr, group);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ auto* firstDevice = group->GetFirstDevice();
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+ ASSERT_NE(nullptr, firstDevice);
+
+ auto* secondDevice = group->GetNextDevice(firstDevice);
+ EXPECT_CALL(gatt_queue,
+ WriteCharacteristic(secondDevice->conn_id_, secondDevice->ctp_hdls_.val_hdl, _,
+ GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ log::debug("[TESTING] firstDevice notifies there are no available context at the time");
+ DeviceContextsUpdate(firstDevice, types::kLeAudioDirectionSink, types::AudioContexts(),
+ audio_contexts);
+
+ PrepareConfigureCodecHandler(group, 0, true);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group, 0, true, /* inject_streaming */ true);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ // StartStream action initiated by upper layer
+ log::debug("[TESTING] StartStream. Expect STREAMING state to be not reported");
+ ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
+ group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)}));
+
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+
+ // let us decide when the ISO Data Path Setup Complete event
+ do_not_send_setup_iso_data_path_event_ = true;
+
+ uint16_t cis_conn_handle;
+ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(::testing::_, ::testing::_))
+ .WillOnce(::testing::SaveArg<0>(&cis_conn_handle));
+
+ EXPECT_CALL(mock_callbacks_,
+ StatusReportCb(group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING))
+ .Times(0);
+
+ log::debug("[TESTING] firstDevice notifies the available context are back");
+ DeviceContextsUpdate(firstDevice, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ log::debug("[TESTING] ProcessHciNotifSetupIsoDataPath. Expect StatusReportCb to be not called");
+ LeAudioGroupStateMachine::Get()->AttachToStream(group, firstDevice,
+ {.sink = {media_ccid}, .source = {}});
+
+ testing::Mock::VerifyAndClearExpectations(&mock_callbacks_);
+
+ EXPECT_CALL(mock_callbacks_,
+ StatusReportCb(group_id, bluetooth::le_audio::GroupStreamStatus::STREAMING));
+
+ log::debug("[TESTING] ProcessHciNotifSetupIsoDataPath. Expect StatusReportCb to be called");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifSetupIsoDataPath(group, firstDevice, 0,
+ cis_conn_handle);
+}
+
+TEST_F(StateMachineTest, testRemoveIsoDataPathOnCisDisconnection) {
+ const auto context_type = kContextTypeRingtone;
+ const auto audio_contexts = types::AudioContexts(context_type);
+ const auto group_id = 4;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ /**
+ * Scenario:
+ * 1. Having set of 2 devices start streaming to 1 device.
+ * 2. Verify the group is streaming.
+ * 3. Attach the other device.
+ * 4. Central successfully creates CIS and issues HCI LE Setup ISO Data Path command.
+ * 5. The Data Path is not been set up yet. while Peripheral notifies ASE Releasing state.
+ * 6. The Central disconnects CIS and issues HCI LE Remove ISO Data Path command.
+ */
+
+ log::debug("[TESTING] Prepare 2 fake connected devices in a group");
+ auto* group = PrepareSingleTestDeviceGroup(group_id, context_type, num_devices);
+ ASSERT_NE(nullptr, group);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ auto* firstDevice = group->GetFirstDevice();
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(firstDevice->conn_id_, firstDevice->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+ ASSERT_NE(nullptr, firstDevice);
+
+ auto* secondDevice = group->GetNextDevice(firstDevice);
+ EXPECT_CALL(gatt_queue,
+ WriteCharacteristic(secondDevice->conn_id_, secondDevice->ctp_hdls_.val_hdl, _,
+ GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ log::debug("[TESTING] firstDevice notifies there are no available context at the time");
+ DeviceContextsUpdate(firstDevice, types::kLeAudioDirectionSink, types::AudioContexts(),
+ audio_contexts);
+
+ PrepareConfigureCodecHandler(group, 0, true);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group, 0, /* inject_enabling */ true, /* inject_streaming */ true);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ // StartStream action initiated by upper layer
+ log::debug("[TESTING] StartStream. Expect STREAMING state to be not reported");
+ ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
+ group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)}));
+
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+
+ PrepareEnableHandler(group, 0, /* inject_enabling */ true, /* inject_streaming */ false);
+
+ uint16_t cis_conn_handle;
+ EXPECT_CALL(*mock_iso_manager_, SetupIsoDataPath(::testing::_, ::testing::_))
+ .WillOnce(::testing::SaveArg<0>(&cis_conn_handle));
+ EXPECT_CALL(*mock_iso_manager_, EstablishCis(_)).Times(1);
+
+ log::debug("[TESTING] firstDevice notifies the available context are back");
+ DeviceContextsUpdate(firstDevice, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ log::debug("[TESTING] ProcessHciNotifSetupIsoDataPath. Expect StatusReportCb to be not called");
+ LeAudioGroupStateMachine::Get()->AttachToStream(group, firstDevice,
+ {.sink = {media_ccid}, .source = {}});
+
+ testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
+
+ auto* firstDeviceAse = firstDevice->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_NE(nullptr, firstDeviceAse);
+
+ /* Expect the Data Path in CONFIGURING state */
+ ASSERT_EQ(types::DataPathState::CONFIGURING, firstDeviceAse->data_path_state);
+
+ // let us decide when the ISO Data Path Setup Complete and CIS Disconnection Complete event
+ do_not_send_setup_iso_data_path_event_ = true;
+ do_not_send_remove_iso_data_path_event_ = true;
+ do_not_send_cis_disconnected_event_ = true;
+
+ EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(cis_conn_handle, _)).Times(1);
+ EXPECT_CALL(*mock_iso_manager_, DisconnectCis(cis_conn_handle, _)).Times(1);
+
+ log::debug("[TESTING] first device performs autonomous ASE state transition to Releasing state");
+ InjectAseStateNotification(firstDeviceAse, firstDevice, group, ascs::kAseStateReleasing, nullptr);
+
+ log::debug("[TESTING] ProcessHciNotifSetupIsoDataPath");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifSetupIsoDataPath(group, firstDevice, 0,
+ cis_conn_handle);
+
+ bluetooth::hci::iso_manager::cis_disconnected_evt cis_disconnected_evt = {
+ .reason = HCI_ERR_PEER_USER,
+ .cig_id = group_id,
+ .cis_conn_hdl = firstDeviceAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports first device CIS has been disconnected eventually");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisDisconnected(group, firstDevice,
+ &cis_disconnected_evt);
+
+ testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
+
+ log::debug("[TESTING] ProcessHciNotifRemoveIsoDataPath");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifRemoveIsoDataPath(group, firstDevice, 0,
+ cis_conn_handle);
+ ASSERT_EQ(types::DataPathState::IDLE, firstDeviceAse->data_path_state);
+}
+
+TEST_F(StateMachineTest, testDoNotQoSConfiguredIfNotStreaming) {
+ const auto context_type = kContextTypeMedia;
+ const auto audio_contexts = types::AudioContexts(context_type);
+ const auto group_id = 4;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ // Prepare multiple fake connected devices in a group
+ auto* group = PrepareSingleTestDeviceGroup(group_id, context_type, num_devices);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ auto* earbudLeft = group->GetFirstDevice();
+ auto* earbudRight = group->GetNextDevice(earbudLeft);
+
+ log::debug("[TESTING] Inject initial ASE state notification");
+ InjectInitialConfiguredNotification(group);
+
+ log::debug("[TESTING] right earbud indicates there are available context");
+ DeviceContextsUpdate(earbudRight, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ log::debug("[TESTING] left earbud indicates there are no available context at the time");
+ DeviceContextsUpdate(earbudLeft, types::kLeAudioDirectionSink, types::AudioContexts(),
+ audio_contexts);
+
+ PrepareConfigureCodecHandler(group, 0, true);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group, 0, /* inject_enabling */ true, /* inject_streaming */ true);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ log::debug("[TESTING] StartStream action initiated by upper layer");
+ ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
+ group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)}));
+
+ // check if group is streaming
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+
+ // make sure the ASEs is in correct state, required in this scenario
+ auto* earbudLeftAse = earbudLeft->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_EQ(nullptr, earbudLeftAse);
+ auto* earbudRightAse = earbudRight->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_NE(nullptr, earbudRightAse);
+
+ testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
+ testing::Mock::VerifyAndClearExpectations(&gatt_queue);
+
+ log::debug("[TESTING] left earbud available contexts are back");
+ DeviceContextsUpdate(earbudLeft, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ PrepareConfigureCodecHandler(group, 0, false, /* inject_configured */ false);
+ PrepareReleaseHandler(group, 0, false, nullptr, /* inject_releasing */ false);
+
+ log::debug("[TESTING] AttachToStream, start Codec Configure procedure.");
+ LeAudioGroupStateMachine::Get()->AttachToStream(group, earbudLeft,
+ {.sink = {media_ccid}, .source = {}});
+
+ earbudLeftAse = earbudLeft->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_FALSE(earbudLeftAse == nullptr);
+
+ log::debug("[TESTING] Upper Layer stop the stream in the meantime");
+ LeAudioGroupStateMachine::Get()->StopStream(group);
+
+ testing::Mock::VerifyAndClearExpectations(&gatt_queue);
+
+ log::debug("[TESTING] Expect the stack will not QoS configure as the stream is about to stop");
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(earbudLeft->conn_id_, earbudLeft->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(0);
+
+ log::debug("[TESTING] left earbud notifies ASE Codec Configured state, as expected");
+ auto* codec_configured_params = &cached_codec_configuration_map_[earbudRightAse->id];
+ InjectAseStateNotification(earbudLeftAse, earbudLeft, group, ascs::kAseStateCodecConfigured,
+ codec_configured_params);
+}
+
+TEST_F(StateMachineTest, testUnexpectedCisEstablishedEvent) {
+ const auto context_type = kContextTypeMedia;
+ const auto audio_contexts = types::AudioContexts(context_type);
+ const auto group_id = 4;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ /**
+ * Scenario:
+ * 1. Start stream to set of 2 devices
+ * 2. The CIS Create is issued to 2 devices
+ * 3. One of the devices reports Releasing state before CIS Established event.
+ * 4. Phone Cancel the CIS Create by sending HCI Disconnect
+ * 5. The scheduled CIS Established event is reported by the controller.
+ * 5. The CIS Disconnection Complete event is reported later on.
+ * 6. Verify we keep streaming.
+ */
+
+ // Prepare multiple fake connected devices in a group
+ log::debug("[TESTING] PrepareSingleTestDeviceGroup");
+ auto* group = PrepareSingleTestDeviceGroup(group_id, context_type, num_devices);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ log::debug("[TESTING] group->GetFirstDevice()");
+ auto* earbudLeft = group->GetFirstDevice();
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(earbudLeft->conn_id_, earbudLeft->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ log::debug("[TESTING] group->GetNextDevice(earbudLeft)");
+ auto* earbudRight = group->GetNextDevice(earbudLeft);
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(earbudRight->conn_id_, earbudRight->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ // let us decide when the HCI Disconnection Complete event and HCI Connection
+ // Established events will be reported
+ do_not_send_cis_disconnected_event_ = true;
+ do_not_send_cis_establish_event_ = true;
+
+ PrepareConfigureCodecHandler(group, 0, true);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group, 0, true, /* inject_streaming */ false);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ // StartStream action initiated by upper layer
+ log::debug("[TESTING] StartStream");
+ ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
+ group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)}));
+
+ log::debug("[TESTING] left earbud indicates there are no available context at the time");
+ DeviceContextsUpdate(earbudLeft, types::kLeAudioDirectionSink, types::AudioContexts(),
+ audio_contexts);
+
+ log::debug("[TESTING] GetFirstActiveAseByDirection earbudLeftAse");
+ auto* earbudLeftAse = earbudLeft->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_FALSE(earbudLeftAse == nullptr);
+
+ // make sure the ASE is in correct state, required in this scenario
+ ASSERT_TRUE(earbudLeftAse->state == types::AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING);
+
+ log::debug("[TESTING] left earbud performs autonomous ASE state transition to Releasing state");
+ InjectAseStateNotification(earbudLeftAse, earbudLeft, group, ascs::kAseStateReleasing, nullptr);
+
+ //
+ log::debug(
+ "[TESTING] left earbud performs autonomous ASE state transition to Codec Configured "
+ "state (caching)");
+ auto* codec_configured_params = &cached_codec_configuration_map_[earbudLeftAse->id];
+ InjectAseStateNotification(earbudLeftAse, earbudLeft, group, ascs::kAseStateCodecConfigured,
+ codec_configured_params);
+
+ log::debug("[TESTING] GetFirstActiveAseByDirection earbudRightAse");
+ auto* earbudRightAse = earbudRight->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_FALSE(earbudRightAse == nullptr);
+
+ // make sure the ASE is in correct state, required in this scenario
+ ASSERT_TRUE(earbudRightAse->state == types::AseState::BTA_LE_AUDIO_ASE_STATE_ENABLING);
+
+ bluetooth::hci::iso_manager::cis_establish_cmpl_evt cis_establish_evt = {
+ .status = 0,
+ .cig_id = group_id,
+ .cis_conn_hdl = earbudRightAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports right earbud CIS has been successfully established");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished(group, earbudRight,
+ &cis_establish_evt);
+
+ std::vector<uint8_t> streaming_params{};
+ log::debug("[TESTING] InjectAseStateNotification earbudRight kAseStateStreaming");
+ InjectAseStateNotification(earbudRightAse, earbudRight, group, ascs::kAseStateStreaming,
+ &streaming_params);
+
+ cis_establish_evt = {
+ .status = 0,
+ .cig_id = group_id,
+ .cis_conn_hdl = earbudLeftAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports left earbud CIS has been successfully established");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished(group, earbudLeft,
+ &cis_establish_evt);
+
+ bluetooth::hci::iso_manager::cis_disconnected_evt cis_disconnected_evt = {
+ .reason = HCI_ERR_PEER_USER,
+ .cig_id = group_id,
+ .cis_conn_hdl = earbudLeftAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports left earbud CIS has been disconnected eventually");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisDisconnected(group, earbudLeft,
+ &cis_disconnected_evt);
+
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+}
+
+TEST_F(StateMachineTest, testKeepStreamingWhenCisCreateOperationCancelled) {
+ const auto context_type = kContextTypeMedia;
+ const auto audio_contexts = types::AudioContexts(context_type);
+ const auto group_id = 4;
+ const auto num_devices = 2;
+
+ ContentControlIdKeeper::GetInstance()->SetCcid(media_context, media_ccid);
+
+ // Prepare multiple fake connected devices in a group
+ auto* group = PrepareSingleTestDeviceGroup(group_id, context_type, num_devices);
+ ASSERT_EQ(group->Size(), num_devices);
+
+ auto* earbudLeft = group->GetFirstDevice();
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(earbudLeft->conn_id_, earbudLeft->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ auto* earbudRight = group->GetNextDevice(earbudLeft);
+ EXPECT_CALL(gatt_queue, WriteCharacteristic(earbudRight->conn_id_, earbudRight->ctp_hdls_.val_hdl,
+ _, GATT_WRITE_NO_RSP, _, _))
+ .Times(AtLeast(3));
+
+ log::debug("[TESTING] right earbud indicates there are available context");
+ DeviceContextsUpdate(earbudRight, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ log::debug("[TESTING] left earbud indicates there are no available context at the time");
+ DeviceContextsUpdate(earbudLeft, types::kLeAudioDirectionSink, types::AudioContexts(),
+ audio_contexts);
+
+ PrepareConfigureCodecHandler(group, 0, true);
+ PrepareConfigureQosHandler(group);
+ PrepareEnableHandler(group, 0, /* inject_enabling */ true, /* inject_streaming */ true);
+ PrepareDisableHandler(group);
+ PrepareReleaseHandler(group);
+
+ log::debug("[TESTING] StartStream action initiated by upper layer");
+ ASSERT_TRUE(LeAudioGroupStateMachine::Get()->StartStream(
+ group, context_type,
+ {.sink = types::AudioContexts(context_type),
+ .source = types::AudioContexts(context_type)}));
+
+ // check if group is streaming
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+
+ // make sure the ASEs is in correct state, required in this scenario
+ auto* earbudLeftAse = earbudLeft->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_TRUE(earbudLeftAse == nullptr);
+ auto* earbudRightAse = earbudRight->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_FALSE(earbudRightAse == nullptr);
+ ASSERT_TRUE(earbudRightAse->state == types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+
+ log::debug("[TESTING] the available contexts are back");
+ DeviceContextsUpdate(earbudLeft, types::kLeAudioDirectionSink, audio_contexts, audio_contexts);
+
+ // let us decide when the HCI Disconnection Complete event and HCI Connection
+ // Established events will be reported
+ do_not_send_cis_disconnected_event_ = true;
+ do_not_send_cis_establish_event_ = true;
+
+ PrepareEnableHandler(group, 0, /* inject_enabling */ true, /* inject_streaming */ false);
+
+ log::debug("[TESTING] once the contexts are back, the upper layer calls AttachToStream");
+ LeAudioGroupStateMachine::Get()->AttachToStream(group, earbudLeft,
+ {.sink = {media_ccid}, .source = {}});
+
+ EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(1);
+
+ earbudLeftAse = earbudLeft->GetFirstActiveAseByDirection(types::kLeAudioDirectionSink);
+ ASSERT_FALSE(earbudLeftAse == nullptr);
+
+ log::debug("[TESTING] left earbud performs autonomous ASE state transition to Releasing state ");
+ InjectAseStateNotification(earbudLeftAse, earbudLeft, group, ascs::kAseStateReleasing, nullptr);
+
+ testing::Mock::VerifyAndClearExpectations(mock_iso_manager_);
+
+ log::debug("[TESTING] Expect the CIS cancelled operation won't trigger stack to stop streaming");
+
+ EXPECT_CALL(*mock_iso_manager_, DisconnectCis(_, _)).Times(0);
+ EXPECT_CALL(*mock_iso_manager_, RemoveIsoDataPath(_, _)).Times(0);
+ EXPECT_CALL(*mock_iso_manager_, RemoveCig(_, _)).Times(0);
+
+ bluetooth::hci::iso_manager::cis_establish_cmpl_evt cis_establish_evt = {
+ .status = 0x44,
+ .cig_id = group_id,
+ .cis_conn_hdl = earbudLeftAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports left earbud CIS establishment has been cancelled");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisEstablished(group, earbudLeft,
+ &cis_establish_evt);
+
+ bluetooth::hci::iso_manager::cis_disconnected_evt cis_disconnected_evt = {
+ .reason = HCI_ERR_PEER_USER,
+ .cig_id = group_id,
+ .cis_conn_hdl = earbudLeftAse->cis_conn_hdl,
+ };
+ log::debug("[TESTING] controller reports first device CIS has been disconnected");
+ LeAudioGroupStateMachine::Get()->ProcessHciNotifCisDisconnected(group, earbudLeft,
+ &cis_disconnected_evt);
+
+ ASSERT_EQ(group->GetState(), types::AseState::BTA_LE_AUDIO_ASE_STATE_STREAMING);
+}
+
TEST_F(StateMachineTest, testDoNotCodecConfigureDeviceWithoutContextsAvailable) {
const auto context_type = kContextTypeMedia;
const auto audio_contexts = types::AudioContexts(context_type);
diff --git a/system/bta/le_audio/storage_helper.cc b/system/bta/le_audio/storage_helper.cc
index 308befe6b5..95c308ff15 100644
--- a/system/bta/le_audio/storage_helper.cc
+++ b/system/bta/le_audio/storage_helper.cc
@@ -360,11 +360,19 @@ bool SerializeHandles(const LeAudioDevice* leAudioDevice, std::vector<uint8_t>&
UINT16_TO_STREAM(ptr, leAudioDevice->ctp_hdls_.val_hdl);
UINT16_TO_STREAM(ptr, leAudioDevice->ctp_hdls_.ccc_hdl);
- UINT16_TO_STREAM(ptr, leAudioDevice->snk_audio_locations_hdls_.val_hdl);
- UINT16_TO_STREAM(ptr, leAudioDevice->snk_audio_locations_hdls_.ccc_hdl);
-
- UINT16_TO_STREAM(ptr, leAudioDevice->src_audio_locations_hdls_.val_hdl);
- UINT16_TO_STREAM(ptr, leAudioDevice->src_audio_locations_hdls_.ccc_hdl);
+ UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.sink
+ ? leAudioDevice->audio_locations_.sink->handles.val_hdl
+ : 0);
+ UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.sink
+ ? leAudioDevice->audio_locations_.sink->handles.ccc_hdl
+ : 0);
+
+ UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.source
+ ? leAudioDevice->audio_locations_.source->handles.val_hdl
+ : 0);
+ UINT16_TO_STREAM(ptr, leAudioDevice->audio_locations_.source
+ ? leAudioDevice->audio_locations_.source->handles.ccc_hdl
+ : 0);
UINT16_TO_STREAM(ptr, leAudioDevice->audio_supp_cont_hdls_.val_hdl);
UINT16_TO_STREAM(ptr, leAudioDevice->audio_supp_cont_hdls_.ccc_hdl);
@@ -404,21 +412,26 @@ bool DeserializeHandles(LeAudioDevice* leAudioDevice, const std::vector<uint8_t>
log::verbose("ctp.val_hdl: 0x{:04x}, ctp.ccc_hdl: 0x{:04x}", leAudioDevice->ctp_hdls_.val_hdl,
leAudioDevice->ctp_hdls_.ccc_hdl);
- STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.val_hdl, ptr);
- STREAM_TO_UINT16(leAudioDevice->snk_audio_locations_hdls_.ccc_hdl, ptr);
+ uint16_t val_hdl, ccc_hdl;
+ STREAM_TO_UINT16(val_hdl, ptr);
+ STREAM_TO_UINT16(ccc_hdl, ptr);
log::verbose(
- "snk_audio_locations_hdls_.val_hdl: "
- "0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
- leAudioDevice->snk_audio_locations_hdls_.val_hdl,
- leAudioDevice->snk_audio_locations_hdls_.ccc_hdl);
+ "snk_audio_locations_hdls_.val_hdl: 0x{:04x},snk_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
+ val_hdl, ccc_hdl);
+ if (val_hdl) {
+ leAudioDevice->audio_locations_.sink.emplace(hdl_pair(val_hdl, ccc_hdl),
+ types::AudioLocations(0));
+ }
- STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.val_hdl, ptr);
- STREAM_TO_UINT16(leAudioDevice->src_audio_locations_hdls_.ccc_hdl, ptr);
+ STREAM_TO_UINT16(val_hdl, ptr);
+ STREAM_TO_UINT16(ccc_hdl, ptr);
log::verbose(
- "src_audio_locations_hdls_.val_hdl: "
- "0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
- leAudioDevice->src_audio_locations_hdls_.val_hdl,
- leAudioDevice->src_audio_locations_hdls_.ccc_hdl);
+ "src_audio_locations_hdls_.val_hdl: 0x{:04x},src_audio_locations_hdls_.ccc_hdl: 0x{:04x}",
+ val_hdl, ccc_hdl);
+ if (val_hdl) {
+ leAudioDevice->audio_locations_.source.emplace(hdl_pair(val_hdl, ccc_hdl),
+ types::AudioLocations(0));
+ }
STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.val_hdl, ptr);
STREAM_TO_UINT16(leAudioDevice->audio_supp_cont_hdls_.ccc_hdl, ptr);
diff --git a/system/bta/test/bta_ag_sco_test.cc b/system/bta/test/bta_ag_sco_test.cc
index cadf4a9919..16caac7665 100644
--- a/system/bta/test/bta_ag_sco_test.cc
+++ b/system/bta/test/bta_ag_sco_test.cc
@@ -39,7 +39,7 @@ class BtaAgScoParameterSelectionTest
protected:
void SetUp() override {
test::mock::device_esco_parameters::esco_parameters_for_codec.body =
- [this](esco_codec_t codec) {
+ [this](esco_codec_t codec, bool /* offload */) {
this->codec = codec;
return enh_esco_params_t{};
};
diff --git a/system/bta/test/bta_ag_test.cc b/system/bta/test/bta_ag_test.cc
index 84d2addeb2..5fa3884669 100644
--- a/system/bta/test/bta_ag_test.cc
+++ b/system/bta/test/bta_ag_test.cc
@@ -74,11 +74,11 @@ protected:
bta_ag_cb.p_cback = [](tBTA_AG_EVT /*event*/, tBTA_AG* /*p_data*/) {};
RawAddress::FromString("00:11:22:33:44:55", addr);
- test::mock::device_esco_parameters::esco_parameters_for_codec.body =
- [this](esco_codec_t codec) {
- this->codec = codec;
- return enh_esco_params_t{};
- };
+ test::mock::device_esco_parameters::esco_parameters_for_codec.body = [this](esco_codec_t codec,
+ bool /*offload*/) {
+ this->codec = codec;
+ return enh_esco_params_t{};
+ };
}
void TearDown() override {
test::mock::device_esco_parameters::esco_parameters_for_codec = {};
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/common/btif_storage_mock.cc b/system/bta/test/common/btif_storage_mock.cc
index 9df26fe0a6..7e4a4e5118 100644
--- a/system/bta/test/common/btif_storage_mock.cc
+++ b/system/bta/test/common/btif_storage_mock.cc
@@ -57,10 +57,15 @@ void btif_storage_leaudio_update_handles_bin(const RawAddress& addr) {
btif_storage_interface->LeAudioUpdateHandles(addr);
}
-void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location,
- uint32_t source_location) {
+void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) {
log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!");
- btif_storage_interface->SetLeAudioLocations(addr, sink_location, source_location);
+ btif_storage_interface->SetLeAudioSinkLocations(addr, sink_location);
+}
+
+void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr,
+ uint32_t source_location) {
+ log::assert_that(btif_storage_interface != nullptr, "Mock storage module not set!");
+ btif_storage_interface->SetLeAudioSourceLocations(addr, source_location);
}
void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr,
diff --git a/system/bta/test/common/btif_storage_mock.h b/system/bta/test/common/btif_storage_mock.h
index c756336dab..8809643f70 100644
--- a/system/bta/test/common/btif_storage_mock.h
+++ b/system/bta/test/common/btif_storage_mock.h
@@ -31,8 +31,8 @@ public:
virtual void LeAudioUpdateGmap(RawAddress const& addr) = 0;
virtual void LeAudioUpdateAses(RawAddress const& addr) = 0;
virtual void LeAudioUpdateHandles(RawAddress const& addr) = 0;
- virtual void SetLeAudioLocations(RawAddress const& addr, uint32_t sink_location,
- uint32_t source_location) = 0;
+ virtual void SetLeAudioSinkLocations(RawAddress const& addr, uint32_t sink_location) = 0;
+ virtual void SetLeAudioSourceLocations(RawAddress const& addr, uint32_t source_location) = 0;
virtual void SetLeAudioContexts(RawAddress const& addr, uint16_t sink_context,
uint16_t source_context) = 0;
virtual void ClearLeAudioServiceData(RawAddress const& addr) = 0;
@@ -61,8 +61,9 @@ public:
MOCK_METHOD((void), LeAudioUpdateGmap, (RawAddress const& addr), (override));
MOCK_METHOD((void), LeAudioUpdateAses, (RawAddress const& addr), (override));
MOCK_METHOD((void), LeAudioUpdateHandles, (RawAddress const& addr), (override));
- MOCK_METHOD((void), SetLeAudioLocations,
- (RawAddress const& addr, uint32_t sink_location, uint32_t source_location),
+ MOCK_METHOD((void), SetLeAudioSinkLocations, (RawAddress const& addr, uint32_t sink_location),
+ (override));
+ MOCK_METHOD((void), SetLeAudioSourceLocations, (RawAddress const& addr, uint32_t source_location),
(override));
MOCK_METHOD((void), SetLeAudioContexts,
(RawAddress const& addr, uint16_t sink_context, uint16_t source_context), (override));
diff --git a/system/bta/test/common/btm_api_mock.cc b/system/bta/test/common/btm_api_mock.cc
index 87907f80f8..cc27d344b8 100644
--- a/system/bta/test/common/btm_api_mock.cc
+++ b/system/bta/test/common/btm_api_mock.cc
@@ -61,9 +61,9 @@ void bluetooth::manager::SetMockBtmInterface(MockBtmInterface* mock_btm_interfac
};
}
-bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
+bool BTM_IsBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
log::assert_that(btm_interface != nullptr, "Mock btm interface not set!");
- return btm_interface->IsLinkKeyKnown(bd_addr, transport);
+ return btm_interface->IsDeviceBonded(bd_addr, transport);
}
bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
@@ -110,11 +110,6 @@ std::optional<Octet16> BTM_BleGetPeerIRK(const RawAddress address) {
return btm_interface->BTM_BleGetPeerIRK(address);
}
-bool BTM_BleIsLinkKeyKnown(const RawAddress address) {
- log::assert_that(btm_interface != nullptr, "Mock btm interface not set!");
- return btm_interface->BTM_BleIsLinkKeyKnown(address);
-}
-
std::optional<tBLE_BD_ADDR> BTM_BleGetIdentityAddress(const RawAddress address) {
log::assert_that(btm_interface != nullptr, "Mock btm interface not set!");
return btm_interface->BTM_BleGetIdentityAddress(address);
diff --git a/system/bta/test/common/btm_api_mock.h b/system/bta/test/common/btm_api_mock.h
index 6f746a66ac..29eab3fb57 100644
--- a/system/bta/test/common/btm_api_mock.h
+++ b/system/bta/test/common/btm_api_mock.h
@@ -35,7 +35,7 @@ class BtmInterface {
public:
virtual bool GetSecurityFlagsByTransport(const RawAddress& bd_addr, uint8_t* p_sec_flags,
tBT_TRANSPORT transport) = 0;
- virtual bool IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0;
+ virtual bool IsDeviceBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0;
virtual bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0;
virtual tBTM_STATUS SetEncryption(const RawAddress& bd_addr, tBT_TRANSPORT transport,
tBTM_SEC_CALLBACK* p_callback, void* p_ref_data,
@@ -54,7 +54,7 @@ public:
virtual std::optional<Octet16> BTM_BleGetPeerLTK(const RawAddress address) = 0;
virtual std::optional<Octet16> BTM_BleGetPeerIRK(const RawAddress address) = 0;
- virtual bool BTM_BleIsLinkKeyKnown(const RawAddress address) = 0;
+ virtual bool BTM_IsBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport) = 0;
virtual std::optional<tBLE_BD_ADDR> BTM_BleGetIdentityAddress(const RawAddress address) = 0;
virtual bool BTM_IsAclConnectionUp(const RawAddress& remote_bda, tBT_TRANSPORT transport) = 0;
@@ -66,7 +66,7 @@ public:
MOCK_METHOD((bool), GetSecurityFlagsByTransport,
(const RawAddress& bd_addr, uint8_t* p_sec_flags, tBT_TRANSPORT transport),
(override));
- MOCK_METHOD((bool), IsLinkKeyKnown, (const RawAddress& bd_addr, tBT_TRANSPORT transport),
+ MOCK_METHOD((bool), IsDeviceBonded, (const RawAddress& bd_addr, tBT_TRANSPORT transport),
(override));
MOCK_METHOD((bool), BTM_IsEncrypted, (const RawAddress& bd_addr, tBT_TRANSPORT transport),
(override));
@@ -93,7 +93,8 @@ public:
MOCK_METHOD((std::optional<Octet16>), BTM_BleGetPeerLTK, (const RawAddress address), (override));
MOCK_METHOD((std::optional<Octet16>), BTM_BleGetPeerIRK, (const RawAddress address), (override));
- MOCK_METHOD((bool), BTM_BleIsLinkKeyKnown, (const RawAddress address), (override));
+ MOCK_METHOD((bool), BTM_IsBonded, (const RawAddress& bd_addr, tBT_TRANSPORT transport),
+ (override));
MOCK_METHOD((std::optional<tBLE_BD_ADDR>), BTM_BleGetIdentityAddress, (const RawAddress address),
(override));
MOCK_METHOD((bool), BTM_IsAclConnectionUp,
diff --git a/system/bta/vc/devices_test.cc b/system/bta/vc/devices_test.cc
index 80c860e04e..6ad0cacf1a 100644
--- a/system/bta/vc/devices_test.cc
+++ b/system/bta/vc/devices_test.cc
@@ -56,16 +56,16 @@ static RawAddress GetTestAddress(int index) {
class VolumeControlDevicesTest : public ::testing::Test {
protected:
void SetUp() override {
- com::android::bluetooth::flags::provider_->leaudio_add_aics_support(true);
__android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
+ com::android::bluetooth::flags::provider_->reset_flags();
+
+ com::android::bluetooth::flags::provider_->leaudio_add_aics_support(true);
devices_ = new VolumeControlDevices();
gatt::SetMockBtaGattInterface(&gatt_interface);
gatt::SetMockBtaGattQueue(&gatt_queue);
}
void TearDown() override {
- com::android::bluetooth::flags::provider_->reset_flags();
-
gatt::SetMockBtaGattQueue(nullptr);
gatt::SetMockBtaGattInterface(nullptr);
delete devices_;
@@ -219,8 +219,10 @@ TEST_F(VolumeControlDevicesTest, test_control_point_skip_not_connected) {
class VolumeControlDeviceTest : public ::testing::Test {
protected:
void SetUp() override {
- com::android::bluetooth::flags::provider_->leaudio_add_aics_support(true);
__android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
+ com::android::bluetooth::flags::provider_->reset_flags();
+
+ com::android::bluetooth::flags::provider_->leaudio_add_aics_support(true);
device = new VolumeControlDevice(GetTestAddress(1), true);
gatt::SetMockBtaGattInterface(&gatt_interface);
gatt::SetMockBtaGattQueue(&gatt_queue);
@@ -259,7 +261,6 @@ protected:
}
void TearDown() override {
- com::android::bluetooth::flags::provider_->reset_flags();
bluetooth::manager::SetMockBtmInterface(nullptr);
gatt::SetMockBtaGattQueue(nullptr);
gatt::SetMockBtaGattInterface(nullptr);
diff --git a/system/bta/vc/vc.cc b/system/bta/vc/vc.cc
index 0313b3962c..df8e6a00e7 100644
--- a/system/bta/vc/vc.cc
+++ b/system/bta/vc/vc.cc
@@ -144,7 +144,7 @@ public:
auto device = volume_control_devices_.FindByAddress(address);
if (!device) {
- if (!BTM_IsLinkKeyKnown(address, BT_TRANSPORT_LE)) {
+ if (!BTM_IsBonded(address, BT_TRANSPORT_LE)) {
bluetooth::log::error("Connecting {} when not bonded", address);
callbacks_->OnConnectionState(ConnectionState::DISCONNECTED, address);
return;
diff --git a/system/bta/vc/vc_test.cc b/system/bta/vc/vc_test.cc
index 4961a32399..b52a9c4405 100644
--- a/system/bta/vc/vc_test.cc
+++ b/system/bta/vc/vc_test.cc
@@ -435,6 +435,7 @@ protected:
void SetUp(void) override {
__android_log_set_minimum_priority(ANDROID_LOG_VERBOSE);
+ com::android::bluetooth::flags::provider_->reset_flags();
com::android::bluetooth::flags::provider_->leaudio_add_aics_support(true);
@@ -444,7 +445,7 @@ protected:
gatt::SetMockBtaGattQueue(&gatt_queue);
reset_mock_function_count_map();
- ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(true)));
// default action for GetCharacteristic function call
ON_CALL(gatt_interface, GetCharacteristic(_, _))
@@ -540,7 +541,6 @@ protected:
}
void TearDown(void) override {
- com::android::bluetooth::flags::provider_->reset_flags();
services_map.clear();
gatt::SetMockBtaGattQueue(nullptr);
gatt::SetMockBtaGattInterface(nullptr);
@@ -695,7 +695,7 @@ protected:
void SetEncryptionResult(const RawAddress& address, bool success) {
ON_CALL(btm_interface, BTM_IsEncrypted(address, _)).WillByDefault(DoAll(Return(false)));
- ON_CALL(btm_interface, IsLinkKeyKnown(address, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(address, _)).WillByDefault(DoAll(Return(true)));
ON_CALL(btm_interface, SetEncryption(address, _, _, _, BTM_BLE_SEC_ENCRYPT))
.WillByDefault(
Invoke([&success, this](const RawAddress& bd_addr, tBT_TRANSPORT transport,
@@ -820,7 +820,7 @@ TEST_F(VolumeControlTest, test_connect_after_remove) {
Mock::VerifyAndClearExpectations(&callbacks);
EXPECT_CALL(callbacks, OnConnectionState(ConnectionState::DISCONNECTED, test_address)).Times(1);
- ON_CALL(btm_interface, IsLinkKeyKnown(_, _)).WillByDefault(DoAll(Return(false)));
+ ON_CALL(btm_interface, IsDeviceBonded(_, _)).WillByDefault(DoAll(Return(false)));
VolumeControl::Get()->Connect(test_address);
Mock::VerifyAndClearExpectations(&callbacks);
@@ -1033,7 +1033,7 @@ TEST_F(VolumeControlTest, test_service_discovery_completed_before_encryption) {
TestConnect(test_address);
ON_CALL(btm_interface, BTM_IsEncrypted(test_address, _)).WillByDefault(DoAll(Return(false)));
- ON_CALL(btm_interface, IsLinkKeyKnown(test_address, _)).WillByDefault(DoAll(Return(true)));
+ ON_CALL(btm_interface, IsDeviceBonded(test_address, _)).WillByDefault(DoAll(Return(true)));
ON_CALL(btm_interface, SetEncryption(test_address, _, _, _, _))
.WillByDefault(Return(tBTM_STATUS::BTM_SUCCESS));
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/src/osi_module.cc b/system/btcore/src/osi_module.cc
index 638748fe03..7656801296 100644
--- a/system/btcore/src/osi_module.cc
+++ b/system/btcore/src/osi_module.cc
@@ -26,12 +26,9 @@
#include "osi/include/osi.h"
#include "osi/include/wakelock.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+static future_t* osi_init(void) { return future_new_immediate(FUTURE_SUCCESS); }
-future_t* osi_init(void) { return future_new_immediate(FUTURE_SUCCESS); }
-
-future_t* osi_clean_up(void) {
+static future_t* osi_clean_up(void) {
alarm_cleanup();
wakelock_cleanup();
return future_new_immediate(FUTURE_SUCCESS);
diff --git a/system/btcore/test/device_class_test.cc b/system/btcore/test/device_class_test.cc
index af114ffed5..ed5f9581f0 100644
--- a/system/btcore/test/device_class_test.cc
+++ b/system/btcore/test/device_class_test.cc
@@ -21,10 +21,8 @@
#include <arpa/inet.h>
#include <gtest/gtest.h>
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-::testing::AssertionResult check_bitfield(const char* m_expr, const char* n_expr, int m, int n) {
+static ::testing::AssertionResult check_bitfield(const char* m_expr, const char* n_expr, int m,
+ int n) {
if (m == n) {
return ::testing::AssertionSuccess();
}
diff --git a/system/btif/Android.bp b/system/btif/Android.bp
index cbb42f1587..d6aee63815 100644
--- a/system/btif/Android.bp
+++ b/system/btif/Android.bp
@@ -82,113 +82,52 @@ genrule {
out: ["statslog_bt.cpp"],
}
-// libbtif static library for target
-
cc_library_static {
name: "libbtif",
defaults: ["fluoride_defaults"],
include_dirs: btifCommonIncludes,
srcs: [
- // AVRCP Target Service
"avrcp/avrcp_service.cc",
- // Callouts
"co/bta_av_co.cc",
"co/bta_av_co_peer.cc",
+ "co/bta_dm_co.cc",
+ "co/bta_gatts_co.cc",
"co/bta_hh_co.cc",
"co/bta_pan_co.cc",
- // HAL layer
"src/bluetooth.cc",
- // BTIF implementation
"src/btif_a2dp.cc",
"src/btif_a2dp_sink.cc",
"src/btif_a2dp_source.cc",
"src/btif_av.cc",
- "src/btif_csis_client.cc",
- "src/btif_has_client.cc",
- "src/btif_hd.cc",
- "src/btif_hearing_aid.cc",
- "src/btif_hf.cc",
- "src/btif_hf_client.cc",
- "src/btif_hh.cc",
- "src/btif_iot_config.cc",
- "src/btif_le_audio.cc",
- "src/btif_le_audio_broadcaster.cc",
- "src/btif_pan.cc",
- "src/btif_profile_queue.cc",
- "src/btif_profile_storage.cc",
- "src/btif_rc.cc",
- "src/btif_vc.cc",
- ],
- local_include_dirs: [
- "include",
- ],
- target: {
- android: {
- whole_static_libs: [
- "libPlatformProperties",
- ],
- srcs: ["src/btif_avrcp_audio_track.cc"],
- shared_libs: ["libaaudio"],
- },
- host: {
- srcs: [
- "src/btif_avrcp_audio_track_linux.cc",
- "src/btif_leaudio_hal_version_host.cc",
- ],
- },
- },
- static_libs: [
- "aics",
- "avrcp-target-service",
- "bluetooth_flags_c_lib",
- "lib-bt-packets",
- "lib-bt-packets-avrcp",
- "lib-bt-packets-base",
- "libbluetooth-types",
- "libbluetooth_hci_pdl",
- "libbluetooth_log",
- "libbt-audio-hal-interface",
- "libbt-platform-protos-lite",
- "libbt-stack",
- "libbt-stack-core",
- "libbtif-core",
- "libflatbuffers-cpp",
- ],
- aidl: {
- libs: ["bluetooth_constants"],
- },
- shared_libs: [
- "libbinder",
- ],
- apex_available: ["com.android.bt"],
- host_supported: true,
- min_sdk_version: "Tiramisu",
-}
-
-cc_library_static {
- name: "libbtif-core",
- defaults: ["fluoride_defaults"],
- include_dirs: btifCommonIncludes,
- srcs: [
- // Callouts
- "co/bta_dm_co.cc",
- "co/bta_gatts_co.cc",
- // BTIF implementation
"src/btif_ble_scanner.cc",
"src/btif_bqr.cc",
"src/btif_config.cc",
"src/btif_core.cc",
+ "src/btif_csis_client.cc",
"src/btif_debug_conn.cc",
"src/btif_dm.cc",
"src/btif_gatt.cc",
"src/btif_gatt_client.cc",
"src/btif_gatt_server.cc",
"src/btif_gatt_util.cc",
+ "src/btif_has_client.cc",
"src/btif_hci_vs.cc",
+ "src/btif_hd.cc",
+ "src/btif_hearing_aid.cc",
+ "src/btif_hf.cc",
+ "src/btif_hf_client.cc",
+ "src/btif_hh.cc",
+ "src/btif_iot_config.cc",
"src/btif_iot_config.cc",
"src/btif_keystore.cc",
+ "src/btif_le_audio.cc",
+ "src/btif_le_audio_broadcaster.cc",
"src/btif_metrics_logging.cc",
+ "src/btif_pan.cc",
+ "src/btif_profile_queue.cc",
"src/btif_profile_queue.cc",
+ "src/btif_profile_storage.cc",
+ "src/btif_rc.cc",
"src/btif_sdp.cc",
"src/btif_sdp_server.cc",
"src/btif_sock.cc",
@@ -203,8 +142,12 @@ cc_library_static {
"src/btif_storage.cc",
"src/btif_uid.cc",
"src/btif_util.cc",
+ "src/btif_vc.cc",
"src/stack_manager.cc",
],
+ local_include_dirs: [
+ "include",
+ ],
target: {
android: {
whole_static_libs: [
@@ -221,16 +164,20 @@ cc_library_static {
},
},
static_libs: [
+ "aics",
+ "avrcp-target-service",
"bluetooth_flags_c_lib",
"lib-bt-packets",
+ "lib-bt-packets-avrcp",
"lib-bt-packets-base",
+ "libbluetooth-types",
"libbluetooth_crypto_toolbox",
"libbluetooth_hci_pdl",
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-jni-thread",
"libbt-platform-protos-lite",
- "libbt-stack-core",
+ "libbt-stack",
"libcom.android.sysprop.bluetooth.wrapped",
"libflatbuffers-cpp",
"libstatslog_bt",
@@ -243,14 +190,10 @@ cc_library_static {
"libcrypto",
"libcutils",
],
- cflags: [
- /* we export all classes, so change default visibility, instead of having EXPORT_SYMBOL on each class*/
- "-fvisibility=default",
- ],
+ header_libs: ["libbluetooth_headers"],
apex_available: ["com.android.bt"],
host_supported: true,
min_sdk_version: "Tiramisu",
- header_libs: ["libbluetooth_headers"],
}
cc_test {
@@ -303,7 +246,6 @@ cc_test {
"libbt-audio-asrc",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -311,11 +253,9 @@ cc_test {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libevent",
@@ -596,7 +536,6 @@ cc_test {
"libbt-sbc-encoder",
"libbtdevice",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libevent",
@@ -720,7 +659,6 @@ cc_test {
"libbt-sbc-encoder",
"libbtdevice",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libevent",
diff --git a/system/osi/include/thread_scheduler.h b/system/btif/include/bluetooth.h
index e377268897..61bbb12a28 100644
--- a/system/osi/include/thread_scheduler.h
+++ b/system/btif/include/bluetooth.h
@@ -1,5 +1,5 @@
/*
- * Copyright 2021 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.
@@ -16,5 +16,8 @@
#pragma once
-bool thread_scheduler_enable_real_time(pid_t pid);
-bool thread_scheduler_get_priority_range(int& min, int& max);
+int GetAdapterIndex();
+
+namespace bluetooth::testing {
+void set_hal_cbacks(bt_callbacks_t* callbacks);
+} // namespace bluetooth::testing
diff --git a/system/btif/include/btif_api.h b/system/btif/include/btif_api.h
index 63357a2b09..3083ed9be4 100644
--- a/system/btif/include/btif_api.h
+++ b/system/btif/include/btif_api.h
@@ -308,17 +308,6 @@ void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, uint8_t pin_len
/*******************************************************************************
*
- * Function btif_dm_passkey_reply
- *
- * Description BT SSP passkey reply
- *
- * Returns bt_status_t
- *
- ******************************************************************************/
-bt_status_t btif_dm_passkey_reply(const RawAddress* bd_addr, uint8_t accept, uint32_t passkey);
-
-/*******************************************************************************
- *
* Function btif_dm_ssp_reply
*
* Description BT SSP Reply - Just Works, Numeric Comparison & Passkey
diff --git a/system/btif/include/btif_profile_storage.h b/system/btif/include/btif_profile_storage.h
index 681ea2b0af..d411a95e00 100644
--- a/system/btif/include/btif_profile_storage.h
+++ b/system/btif/include/btif_profile_storage.h
@@ -124,8 +124,11 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr);
void btif_storage_leaudio_update_handles_bin(const RawAddress& addr);
/** Store Le Audio device audio locations */
-void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location,
- uint32_t source_location);
+void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location);
+
+/** Store Le Audio device audio locations */
+void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr,
+ uint32_t source_location);
/** Store Le Audio device context types */
void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr,
diff --git a/system/btif/include/btif_storage.h b/system/btif/include/btif_storage.h
index 2e81246bcd..083e27413d 100644
--- a/system/btif/include/btif_storage.h
+++ b/system/btif/include/btif_storage.h
@@ -296,8 +296,11 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr);
void btif_storage_leaudio_update_handles_bin(const RawAddress& addr);
/** Store Le Audio device audio locations */
-void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location,
- uint32_t source_location);
+void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location);
+
+/** Store Le Audio device audio locations */
+void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr,
+ uint32_t source_location);
/** Store Le Audio device context types */
void btif_storage_set_leaudio_supported_context_types(const RawAddress& addr,
diff --git a/system/btif/src/bluetooth.cc b/system/btif/src/bluetooth.cc
index 11b9d3ed69..1e3db0be50 100644
--- a/system/btif/src/bluetooth.cc
+++ b/system/btif/src/bluetooth.cc
@@ -53,6 +53,7 @@
#include "bta/include/bta_le_audio_broadcaster_api.h"
#include "bta/include/bta_vc_api.h"
#include "btif/avrcp/avrcp_service.h"
+#include "btif/include/bluetooth.h"
#include "btif/include/btif_a2dp.h"
#include "btif/include/btif_a2dp_source.h"
#include "btif/include/btif_api.h"
@@ -133,9 +134,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::csis::CsisClientInterface;
using bluetooth::has::HasClientInterface;
using bluetooth::le_audio::LeAudioBroadcasterInterface;
@@ -408,7 +406,7 @@ static void set_adapter_index(int adapter) { global_hci_adapter = adapter; }
int GetAdapterIndex() { return global_hci_adapter; }
#else
int GetAdapterIndex() { return 0; } // Unsupported outside of FLOSS
-#endif
+#endif // TARGET_FLOSS
static int init(bt_callbacks_t* callbacks, bool start_restricted, bool is_common_criteria_mode,
int config_compare_result, bool is_atv) {
@@ -556,7 +554,7 @@ static int set_adapter_property(const bt_property_t* property) {
return BT_STATUS_SUCCESS;
}
-int get_remote_device_properties(RawAddress* remote_addr) {
+static int get_remote_device_properties(RawAddress* remote_addr) {
if (!btif_is_enabled()) {
return BT_STATUS_NOT_READY;
}
@@ -565,7 +563,7 @@ int get_remote_device_properties(RawAddress* remote_addr) {
return BT_STATUS_SUCCESS;
}
-int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) {
+static int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) {
if (!btif_is_enabled()) {
return BT_STATUS_NOT_READY;
}
@@ -574,7 +572,7 @@ int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type)
return BT_STATUS_SUCCESS;
}
-int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) {
+static int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) {
if (!btif_is_enabled()) {
return BT_STATUS_NOT_READY;
}
@@ -588,7 +586,7 @@ int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* pro
return BT_STATUS_SUCCESS;
}
-int get_remote_services(RawAddress* remote_addr, int transport) {
+static int get_remote_services(RawAddress* remote_addr, int transport) {
if (!interface_ready()) {
return BT_STATUS_NOT_READY;
}
@@ -998,7 +996,7 @@ static const void* get_profile_interface(const char* profile_id) {
return NULL;
}
-int dut_mode_configure(uint8_t enable) {
+static int dut_mode_configure(uint8_t enable) {
if (!interface_ready()) {
return BT_STATUS_NOT_READY;
}
@@ -1010,7 +1008,7 @@ int dut_mode_configure(uint8_t enable) {
return BT_STATUS_SUCCESS;
}
-int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
+static int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
if (!interface_ready()) {
return BT_STATUS_NOT_READY;
}
@@ -1030,7 +1028,7 @@ int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
return BT_STATUS_SUCCESS;
}
-int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) {
+static int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) {
if (!interface_ready()) {
return BT_STATUS_NOT_READY;
}
@@ -1285,7 +1283,7 @@ EXPORT_SYMBOL bt_interface_t bluetoothInterface = {
// callback reporting helpers
-bt_property_t* property_deep_copy_array(int num_properties, bt_property_t* properties) {
+static bt_property_t* property_deep_copy_array(int num_properties, bt_property_t* properties) {
bt_property_t* copy = nullptr;
if (num_properties > 0) {
size_t content_len = 0;
@@ -1544,5 +1542,4 @@ void invoke_encryption_change_cb(bt_encryption_change_evt encryption_change) {
namespace bluetooth::testing {
void set_hal_cbacks(bt_callbacks_t* callbacks) { ::set_hal_cbacks(callbacks); }
-
} // namespace bluetooth::testing
diff --git a/system/btif/src/btif_a2dp_sink.cc b/system/btif/src/btif_a2dp_sink.cc
index 0328ba9cbc..e2258d35f2 100644
--- a/system/btif/src/btif_a2dp_sink.cc
+++ b/system/btif/src/btif_a2dp_sink.cc
@@ -207,8 +207,7 @@ bool btif_a2dp_sink_init() {
log::fatal("Failed to increase A2DP decoder thread priority");
#endif
}
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_init_delayed));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_init_delayed));
return true;
}
@@ -219,8 +218,7 @@ static void btif_a2dp_sink_init_delayed() {
bool btif_a2dp_sink_startup() {
log::info("");
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_startup_delayed));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_startup_delayed));
return true;
}
@@ -305,9 +303,8 @@ static bool btif_a2dp_sink_initialize_a2dp_control_block(const RawAddress& peer_
bool btif_a2dp_sink_start_session(const RawAddress& peer_address,
std::promise<void> peer_ready_promise) {
log::info("peer_address={}", peer_address);
- if (btif_a2dp_sink_cb.worker_thread.DoInThread(
- FROM_HERE, base::BindOnce(btif_a2dp_sink_start_session_delayed, peer_address,
- std::move(peer_ready_promise)))) {
+ if (btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(
+ btif_a2dp_sink_start_session_delayed, peer_address, std::move(peer_ready_promise)))) {
return true;
} else {
// cannot set promise but triggers crash
@@ -353,8 +350,7 @@ bool btif_a2dp_sink_restart_session(const RawAddress& old_peer_address,
bool btif_a2dp_sink_end_session(const RawAddress& peer_address) {
log::info("peer_address={}", peer_address);
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_end_session_delayed));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_end_session_delayed));
return true;
}
@@ -366,8 +362,7 @@ static void btif_a2dp_sink_end_session_delayed() {
void btif_a2dp_sink_shutdown() {
log::info("");
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_shutdown_delayed));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_shutdown_delayed));
}
static void btif_a2dp_sink_shutdown_delayed() {
@@ -401,8 +396,7 @@ void btif_a2dp_sink_cleanup() {
alarm_free(decode_alarm);
// Exit the thread
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_cleanup_delayed));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_cleanup_delayed));
btif_a2dp_sink_cb.worker_thread.ShutDown();
}
@@ -460,15 +454,14 @@ void btif_a2dp_sink_update_decoder(const RawAddress& peer_address, const uint8_t
p_buf->hdr.event = BTIF_MEDIA_SINK_DECODER_UPDATE;
btif_a2dp_sink_cb.worker_thread.DoInThread(
- FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
+ base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
}
void btif_a2dp_sink_on_idle() {
log::info("");
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
return;
@@ -481,8 +474,7 @@ void btif_a2dp_sink_on_stopped(tBTA_AV_SUSPEND* /* p_av_suspend */) {
log::info("");
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
return;
@@ -494,8 +486,7 @@ void btif_a2dp_sink_on_suspended(tBTA_AV_SUSPEND* /* p_av_suspend */) {
log::info("");
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_SUSPEND;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
if (btif_a2dp_sink_state == BTIF_A2DP_SINK_STATE_OFF) {
return;
@@ -508,8 +499,7 @@ bool btif_a2dp_sink_on_start() {
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_START;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
return true;
}
@@ -540,8 +530,7 @@ static void btif_a2dp_sink_audio_handle_stop_decoding() {
}
static void btif_decode_alarm_cb(void* /* context */) {
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_avk_handle_timer));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_avk_handle_timer));
}
static void btif_a2dp_sink_clear_track_event() {
@@ -767,8 +756,7 @@ void btif_a2dp_sink_audio_rx_flush_req() {
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_AUDIO_RX_FLUSH;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
}
void btif_a2dp_sink_debug_dump(int /* fd */) {
@@ -782,7 +770,7 @@ void btif_a2dp_sink_set_focus_state_req(btif_a2dp_sink_focus_state_t state) {
p_buf->focus_state = state;
p_buf->hdr.event = BTIF_MEDIA_SINK_SET_FOCUS_STATE;
btif_a2dp_sink_cb.worker_thread.DoInThread(
- FROM_HERE, base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
+ base::BindOnce(btif_a2dp_sink_command_ready, (BT_HDR_RIGID*)p_buf));
}
static void btif_a2dp_sink_set_focus_state_event(btif_a2dp_sink_focus_state_t state) {
@@ -815,8 +803,7 @@ static void btif_a2dp_sink_clear_track_event_req() {
BT_HDR_RIGID* p_buf = reinterpret_cast<BT_HDR_RIGID*>(osi_malloc(sizeof(BT_HDR_RIGID)));
p_buf->event = BTIF_MEDIA_SINK_CLEAR_TRACK;
- btif_a2dp_sink_cb.worker_thread.DoInThread(FROM_HERE,
- base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
+ btif_a2dp_sink_cb.worker_thread.DoInThread(base::BindOnce(btif_a2dp_sink_command_ready, p_buf));
}
static void btif_a2dp_sink_on_start_event() {
diff --git a/system/btif/src/btif_a2dp_source.cc b/system/btif/src/btif_a2dp_source.cc
index 70634b9984..25a5fe7093 100644
--- a/system/btif/src/btif_a2dp_source.cc
+++ b/system/btif/src/btif_a2dp_source.cc
@@ -343,7 +343,7 @@ bool btif_a2dp_source_init(void) {
// Start A2DP Source media task
btif_a2dp_source_thread.StartUp();
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_init_delayed));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_init_delayed));
return true;
}
@@ -441,7 +441,7 @@ static bool btif_a2dp_source_startup(void) {
btif_a2dp_source_cb.tx_audio_queue = fixed_queue_new(SIZE_MAX);
// Schedule the rest of the operations
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_startup_delayed));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_startup_delayed));
return true;
}
@@ -466,9 +466,8 @@ bool btif_a2dp_source_start_session(const RawAddress& peer_address,
btif_a2dp_source_audio_tx_flush_req();
- if (local_thread()->DoInThread(
- FROM_HERE, base::BindOnce(&btif_a2dp_source_start_session_delayed, peer_address,
- std::move(peer_ready_promise)))) {
+ if (local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_start_session_delayed,
+ peer_address, std::move(peer_ready_promise)))) {
return true;
} else {
// cannot set promise but triggers crash
@@ -535,9 +534,7 @@ bool btif_a2dp_source_end_session(const RawAddress& peer_address) {
btif_a2dp_source_cleanup_codec();
btif_a2dp_source_end_session_delayed(peer_address);
} else {
-
- local_thread()->DoInThread(FROM_HERE,
- base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_end_session_delayed, peer_address));
btif_a2dp_source_cleanup_codec();
}
return true;
@@ -565,7 +562,6 @@ void btif_a2dp_source_allow_low_latency_audio(bool allowed) {
log::info("allowed={}", allowed);
local_thread()->DoInThread(
- FROM_HERE,
base::BindOnce(bluetooth::audio::a2dp::set_audio_low_latency_mode_allowed, allowed));
}
@@ -582,8 +578,8 @@ void btif_a2dp_source_shutdown(std::promise<void> shutdown_complete_promise) {
// TODO(b/374166531) Remove the check for get_main_thread.
if (local_thread() != get_main_thread()) {
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_shutdown_delayed,
- std::move(shutdown_complete_promise)));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_shutdown_delayed,
+ std::move(shutdown_complete_promise)));
} else {
btif_a2dp_source_shutdown_delayed(std::move(shutdown_complete_promise));
}
@@ -696,7 +692,7 @@ static void btif_a2dp_source_cleanup_codec() {
log::info("state={}", btif_a2dp_source_cb.StateStr());
// Must stop media task first before cleaning up the encoder
btif_a2dp_source_stop_audio_req();
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_cleanup_codec_delayed));
}
static void btif_a2dp_source_cleanup_codec_delayed() {
@@ -710,13 +706,13 @@ static void btif_a2dp_source_cleanup_codec_delayed() {
void btif_a2dp_source_start_audio_req(void) {
log::info("state={}", btif_a2dp_source_cb.StateStr());
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_start_event));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_start_event));
}
void btif_a2dp_source_stop_audio_req(void) {
log::info("state={}", btif_a2dp_source_cb.StateStr());
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_stop_event));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_stop_event));
}
void btif_a2dp_source_encoder_user_config_update_req(
@@ -727,7 +723,6 @@ void btif_a2dp_source_encoder_user_config_update_req(
btif_a2dp_source_cb.StateStr(), codec_user_preferences.size());
if (!local_thread()->DoInThread(
- FROM_HERE,
base::BindOnce(&btif_a2dp_source_encoder_user_config_update_event, peer_address,
codec_user_preferences, std::move(peer_ready_promise)))) {
// cannot set promise but triggers crash
@@ -772,8 +767,8 @@ static void btif_a2dp_source_encoder_user_config_update_event(
void btif_a2dp_source_feeding_update_req(const btav_a2dp_codec_config_t& codec_audio_config) {
log::info("state={}", btif_a2dp_source_cb.StateStr());
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_feeding_update_event,
- codec_audio_config));
+ local_thread()->DoInThread(
+ base::BindOnce(&btif_a2dp_source_audio_feeding_update_event, codec_audio_config));
}
static void btif_a2dp_source_audio_feeding_update_event(
@@ -889,7 +884,7 @@ static void btif_a2dp_source_audio_tx_start_event(void) {
btif_a2dp_source_cb.tx_flush = false;
btif_a2dp_source_cb.sw_audio_is_encoding = true;
btif_a2dp_source_cb.media_alarm.SchedulePeriodic(
- btif_a2dp_source_thread.GetWeakPtr(), FROM_HERE,
+ btif_a2dp_source_thread.GetWeakPtr(),
base::BindRepeating(&btif_a2dp_source_audio_handle_timer),
std::chrono::milliseconds(
btif_a2dp_source_cb.encoder_interface->get_encoder_interval_ms()));
@@ -1086,7 +1081,7 @@ static void btif_a2dp_source_audio_tx_flush_event(void) {
static bool btif_a2dp_source_audio_tx_flush_req(void) {
log::info("state={}", btif_a2dp_source_cb.StateStr());
- local_thread()->DoInThread(FROM_HERE, base::BindOnce(&btif_a2dp_source_audio_tx_flush_event));
+ local_thread()->DoInThread(base::BindOnce(&btif_a2dp_source_audio_tx_flush_event));
return true;
}
diff --git a/system/btif/src/btif_dm.cc b/system/btif/src/btif_dm.cc
index 9ce8e1bfb5..29301cd712 100644
--- a/system/btif/src/btif_dm.cc
+++ b/system/btif/src/btif_dm.cc
@@ -930,6 +930,9 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
return;
}
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
cod = devclass2uint(p_pin_req->dev_class);
@@ -984,6 +987,18 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
p_pin_req->min_16_digit);
}
+static tBTM_BOND_TYPE btif_dm_get_pairing_type(const RawAddress& bd_addr, const bool just_works,
+ const uint8_t loc_auth_req,
+ const uint8_t rmt_auth_req) {
+ // Just works pairing without bonding bit is treated as temporary
+ if (just_works && !(loc_auth_req & BTM_AUTH_BONDS) && !(rmt_auth_req & BTM_AUTH_BONDS)) {
+ if (!(btif_check_cod_hid_major(bd_addr, COD_HID_POINTING))) {
+ return BOND_TYPE_TEMPORARY;
+ }
+ }
+ return BOND_TYPE_PERSISTENT;
+}
+
/*******************************************************************************
*
* Function btif_dm_ssp_cfm_req_evt
@@ -994,7 +1009,6 @@ static void btif_dm_pin_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
*
******************************************************************************/
static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) {
- bool is_incoming = !(pairing_cb.state == BT_BOND_STATE_BONDING);
int dev_type;
log::info("addr:{}, CoD: {}, just_works:{}, loc_auth_req={}, rmt_auth_req={}",
@@ -1019,36 +1033,25 @@ static void btif_dm_ssp_cfm_req_evt(tBTA_DM_SP_CFM_REQ* p_ssp_cfm_req) {
return;
}
- /* Set the pairing_cb based on the local & remote authentication requirements
- */
+ bool api_initiated_bonding = (pairing_cb.state == BT_BOND_STATE_BONDING);
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
- /* 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) &&
- !(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;
- }
-
- btm_set_bond_type_dev(p_ssp_cfm_req->bd_addr, pairing_cb.bond_type);
-
pairing_cb.is_ssp = true;
+ pairing_cb.sdp_attempts = 0;
+ pairing_cb.bond_type =
+ btif_dm_get_pairing_type(p_ssp_cfm_req->bd_addr, p_ssp_cfm_req->just_works,
+ p_ssp_cfm_req->loc_auth_req, p_ssp_cfm_req->rmt_auth_req);
+ if (!com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ btm_set_bond_type_dev(p_ssp_cfm_req->bd_addr, pairing_cb.bond_type);
+ }
- /* If JustWorks auto-accept */
- if (p_ssp_cfm_req->just_works) {
- /* Pairing consent for JustWorks NOT needed if:
- * Incoming temporary pairing is detected
- */
- if (is_incoming && pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
- log::debug("Auto-accept JustWorks incoming pairing for temporary bonding");
- btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_CONSENT, true);
- return;
- }
+ if (!api_initiated_bonding && pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
+ // Pairing without bonding either initiated by local service or remote device
+ log::info("Auto-accept temporary pairing {}", bd_addr);
+ btif_dm_ssp_reply(bd_addr, BT_SSP_VARIANT_CONSENT, true);
+ return;
}
- pairing_cb.sdp_attempts = 0;
BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
std::format("just_works:{:c} pin:{}", (p_ssp_cfm_req->just_works) ? 'T' : 'F',
p_ssp_cfm_req->num_val));
@@ -1078,12 +1081,16 @@ static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) {
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_ssp = true;
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
std::format("passkey:{}", p_ssp_key_notif->passkey));
GetInterfaceToProfiles()->events->invoke_ssp_request_cb(
bd_addr, BT_SSP_VARIANT_PASSKEY_NOTIFICATION, p_ssp_key_notif->passkey);
}
+
/*******************************************************************************
*
* Function btif_dm_auth_cmpl_evt
@@ -1094,49 +1101,45 @@ static void btif_dm_ssp_key_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif) {
*
******************************************************************************/
static void btif_dm_auth_cmpl_evt(tBTA_DM_AUTH_CMPL* p_auth_cmpl) {
- /* Save link key, if not temporary */
bt_status_t status = BT_STATUS_FAIL;
bt_bond_state_t state = BT_BOND_STATE_NONE;
bool skip_sdp = false;
-
- log::info("bond state={}, success={}, key_present={}", pairing_cb.state, p_auth_cmpl->success,
- p_auth_cmpl->key_present);
+ RawAddress bd_addr = p_auth_cmpl->bd_addr;
+ tBLE_ADDR_TYPE addr_type = p_auth_cmpl->addr_type;
pairing_cb.fail_reason = p_auth_cmpl->fail_reason;
+ log::info("device={}, bond state={}, success={}, key_present={}", bd_addr, pairing_cb.state,
+ p_auth_cmpl->success, p_auth_cmpl->key_present);
- RawAddress bd_addr = p_auth_cmpl->bd_addr;
- tBLE_ADDR_TYPE addr_type = p_auth_cmpl->addr_type;
- if ((p_auth_cmpl->success) && (p_auth_cmpl->key_present)) {
- if ((p_auth_cmpl->key_type < HCI_LKEY_TYPE_DEBUG_COMB) ||
- (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB) ||
- (p_auth_cmpl->key_type == HCI_LKEY_TYPE_CHANGED_COMB) ||
- (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB_P_256) ||
- pairing_cb.bond_type == BOND_TYPE_PERSISTENT) {
- bt_status_t ret;
-
- if (!bd_addr.IsEmpty()) {
+ if (p_auth_cmpl->success) {
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ btm_set_bond_type_dev(bd_addr, pairing_cb.bond_type);
+ }
+
+ if (p_auth_cmpl->key_present) {
+ if ((p_auth_cmpl->key_type < HCI_LKEY_TYPE_DEBUG_COMB) ||
+ (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB) ||
+ (p_auth_cmpl->key_type == HCI_LKEY_TYPE_CHANGED_COMB) ||
+ (p_auth_cmpl->key_type == HCI_LKEY_TYPE_AUTH_COMB_P_256) ||
+ pairing_cb.bond_type == BOND_TYPE_PERSISTENT) {
+ ASSERTC(bd_addr.IsEmpty(), "bd_addr is empty", BT_STATUS_PARM_INVALID);
log::debug("Storing link key. key_type=0x{:x}, bond_type={}", p_auth_cmpl->key_type,
pairing_cb.bond_type);
- ret = btif_storage_add_bonded_device(&bd_addr, p_auth_cmpl->key, p_auth_cmpl->key_type,
- pairing_cb.pin_code_len);
+ bt_status_t ret = btif_storage_add_bonded_device(
+ &bd_addr, p_auth_cmpl->key, p_auth_cmpl->key_type, pairing_cb.pin_code_len);
+ ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret);
} else {
- log::warn("bd_addr is empty");
- ret = BT_STATUS_PARM_INVALID;
- }
- ASSERTC(ret == BT_STATUS_SUCCESS, "storing link key failed", ret);
- } else {
- log::debug("Temporary key. Not storing. key_type=0x{:x}, bond_type={}", p_auth_cmpl->key_type,
- pairing_cb.bond_type);
- if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
- log::debug("sending BT_BOND_STATE_NONE for Temp pairing");
- btif_storage_remove_bonded_device(&bd_addr);
- bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_NONE);
- return;
+ log::debug("Temporary key. Not storing. key_type=0x{:x}, bond_type={}",
+ p_auth_cmpl->key_type, pairing_cb.bond_type);
+ if (pairing_cb.bond_type == BOND_TYPE_TEMPORARY) {
+ log::debug("sending BT_BOND_STATE_NONE for Temp pairing");
+ btif_storage_remove_bonded_device(&bd_addr);
+ bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_NONE);
+ return;
+ }
}
}
- }
- if (p_auth_cmpl->success) {
// save remote info to iot conf file
btif_iot_update_remote_info(p_auth_cmpl, false, pairing_cb.is_ssp);
@@ -2641,7 +2644,7 @@ void btif_dm_remove_bond(const RawAddress bd_addr) {
void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, uint8_t pin_len,
bt_pin_code_t pin_code) {
- log::verbose("accept={}", accept);
+ log::verbose("{}({}) accept:{}", bd_addr, pairing_cb.is_le_only ? "LE" : "BR/EDR", accept);
if (pairing_cb.is_le_only) {
int i;
@@ -2650,9 +2653,6 @@ void btif_dm_pin_reply(const RawAddress bd_addr, uint8_t accept, uint8_t pin_len
for (i = 0; i < 6; i++) {
passkey += (multi[i] * (pin_code.pin[i] - '0'));
}
- // TODO:
- // FIXME: should we hide part of passkey here?
- log::verbose("btif_dm_pin_reply: passkey: {}", passkey);
BTA_DmBlePasskeyReply(bd_addr, accept, passkey);
} else {
@@ -3276,6 +3276,9 @@ static void btif_dm_ble_passkey_notif_evt(tBTA_DM_SP_KEY_NOTIF* p_ssp_key_notif)
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_ssp = false;
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
std::format("passkey:{}", p_ssp_key_notif->passkey));
@@ -3561,7 +3564,9 @@ static void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* p_ble_req, bool is_cons
pairing_cb.is_le_only = true;
pairing_cb.is_le_nc = false;
pairing_cb.is_ssp = true;
- btm_set_bond_type_dev(p_ble_req->bd_addr, pairing_cb.bond_type);
+ if (!com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ btm_set_bond_type_dev(p_ble_req->bd_addr, pairing_cb.bond_type);
+ }
BTM_LogHistory(kBtmLogTagCallback, bd_addr, "SSP ble request", "BT_SSP_VARIANT_CONSENT");
@@ -3594,6 +3599,9 @@ static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
bond_state_changed(BT_STATUS_SUCCESS, bd_addr, BT_BOND_STATE_BONDING);
pairing_cb.is_le_only = true;
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
cod = COD_UNCLASSIFIED;
@@ -3602,6 +3610,7 @@ static void btif_dm_ble_passkey_req_evt(tBTA_DM_PIN_REQ* p_pin_req) {
GetInterfaceToProfiles()->events->invoke_pin_request_cb(bd_addr, bd_name, cod, false);
}
+
static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) {
/* TODO implement key notification for numeric comparison */
@@ -3616,7 +3625,9 @@ static void btif_dm_ble_key_nc_req_evt(tBTA_DM_SP_KEY_NOTIF* p_notif_req) {
pairing_cb.is_ssp = false;
pairing_cb.is_le_only = true;
pairing_cb.is_le_nc = true;
-
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
BTM_LogHistory(kBtmLogTagCallback, bd_addr, "Ssp request",
std::format("passkey:{}", p_notif_req->passkey));
@@ -3650,6 +3661,9 @@ static void btif_dm_ble_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) {
pairing_cb.is_ssp = false;
pairing_cb.is_le_only = true;
pairing_cb.is_le_nc = false;
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
BTM_BleOobDataReply(req_oob_type->bd_addr, tBTM_STATUS::BTM_SUCCESS, 16, oob_cb.p192_data.sm_tk);
}
@@ -3702,6 +3716,9 @@ static void btif_dm_ble_sc_oob_req_evt(tBTA_DM_SP_RMT_OOB* req_oob_type) {
// TODO: we can derive classic pairing from this one
pairing_cb.is_le_only = true;
pairing_cb.is_le_nc = false;
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ pairing_cb.bond_type = BOND_TYPE_PERSISTENT;
+ }
BTM_BleSecureConnectionOobDataReply(req_oob_type->bd_addr, oob_data_to_use.c, oob_data_to_use.r);
}
diff --git a/system/btif/src/btif_hf_client.cc b/system/btif/src/btif_hf_client.cc
index 30495459c1..842b5868aa 100644
--- a/system/btif/src/btif_hf_client.cc
+++ b/system/btif/src/btif_hf_client.cc
@@ -95,7 +95,8 @@ typedef struct {
/******************************************************************************
* Local function declarations
******************************************************************************/
-static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& addr);
+static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& bd_addr);
+static btif_hf_client_cb_t* btif_hf_client_get_connected_device(const RawAddress& bd_addr);
static bool is_connected(const btif_hf_client_cb_t* cb);
/*******************************************************************************
@@ -162,9 +163,9 @@ constexpr uint16_t BTIF_HF_CLIENT_CB_AUDIO_CONNECTING = 0x8501;
static void btif_in_hf_client_generic_evt(uint16_t event, char* p_param) {
log::verbose("");
RawAddress* bd_addr = (RawAddress*)p_param;
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
- log::error("failed to find block for bda");
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
+ log::error("failed to find block for bda:{}", *bd_addr);
return;
}
@@ -188,8 +189,6 @@ static bool is_connected(const btif_hf_client_cb_t* cb) {
(cb->state == BTHF_CLIENT_CONNECTION_STATE_SLC_CONNECTED)) {
return true;
}
-
- log::error("not connected!");
return false;
}
@@ -212,8 +211,26 @@ static btif_hf_client_cb_t* btif_hf_client_get_cb_by_bda(const RawAddress& bd_ad
return &btif_hf_client_cb_arr.cb[i];
}
}
- log::error("could not find block for bdaddr");
- return NULL;
+ return nullptr;
+}
+
+/*******************************************************************************
+ *
+ * Function btif_hf_client_get_connected_device
+ *
+ * Description Get control block of connected device indexed by remote
+ * bluetooth address.
+ *
+ * Returns btif_hf_client_cb_t pointer if device connected, NULL
+ * otherwise
+ *
+ ******************************************************************************/
+static btif_hf_client_cb_t* btif_hf_client_get_connected_device(const RawAddress& bd_addr) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(bd_addr);
+ if (cb == nullptr || !is_connected(cb)) {
+ return nullptr;
+ }
+ return cb;
}
/*******************************************************************************
@@ -281,6 +298,7 @@ static bt_status_t connect_int(RawAddress* bd_addr, uint16_t /*uuid*/) {
cb->peer_bda = *bd_addr;
if (is_connected(cb)) {
+ log::warn("Peer is already connected remote:{}", *bd_addr);
return BT_STATUS_BUSY;
}
@@ -331,8 +349,8 @@ static bt_status_t disconnect(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t connect_audio(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -362,8 +380,8 @@ static bt_status_t connect_audio(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t disconnect_audio(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -383,8 +401,8 @@ static bt_status_t disconnect_audio(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t start_voice_recognition(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -407,8 +425,8 @@ static bt_status_t start_voice_recognition(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -432,8 +450,8 @@ static bt_status_t stop_voice_recognition(const RawAddress* bd_addr) {
******************************************************************************/
static bt_status_t volume_control(const RawAddress* bd_addr, bthf_client_volume_type_t type,
int volume) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -463,8 +481,8 @@ static bt_status_t volume_control(const RawAddress* bd_addr, bthf_client_volume_
*
******************************************************************************/
static bt_status_t dial(const RawAddress* bd_addr, const char* number) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -488,8 +506,8 @@ static bt_status_t dial(const RawAddress* bd_addr, const char* number) {
*
******************************************************************************/
static bt_status_t dial_memory(const RawAddress* bd_addr, int location) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -510,8 +528,8 @@ static bt_status_t dial_memory(const RawAddress* bd_addr, int location) {
******************************************************************************/
static bt_status_t handle_call_action(const RawAddress* bd_addr, bthf_client_call_action_t action,
int idx) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -600,8 +618,8 @@ static bt_status_t handle_call_action(const RawAddress* bd_addr, bthf_client_cal
*
******************************************************************************/
static bt_status_t query_current_calls(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -625,8 +643,8 @@ static bt_status_t query_current_calls(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t query_current_operator_name(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -646,8 +664,8 @@ static bt_status_t query_current_operator_name(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -667,8 +685,8 @@ static bt_status_t retrieve_subscriber_info(const RawAddress* bd_addr) {
*
******************************************************************************/
static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -688,8 +706,8 @@ static bt_status_t send_dtmf(const RawAddress* bd_addr, char code) {
*
******************************************************************************/
static bt_status_t request_last_voice_tag_number(const RawAddress* bd_addr) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -732,8 +750,8 @@ static void cleanup(void) {
******************************************************************************/
static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, int val2,
const char* arg) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -755,8 +773,8 @@ static bt_status_t send_at_cmd(const RawAddress* bd_addr, int cmd, int val1, int
*
******************************************************************************/
static bt_status_t send_android_at(const RawAddress* bd_addr, const char* arg) {
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(*bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(*bd_addr);
+ if (!cb) {
return BT_STATUS_DEVICE_NOT_FOUND;
}
@@ -794,8 +812,8 @@ static const bthf_client_interface_t bthfClientInterface = {
static void process_ind_evt(tBTA_HF_CLIENT_IND* ind) {
log::verbose("");
- btif_hf_client_cb_t* cb = btif_hf_client_get_cb_by_bda(ind->bd_addr);
- if (cb == NULL || !is_connected(cb)) {
+ btif_hf_client_cb_t* cb = btif_hf_client_get_connected_device(ind->bd_addr);
+ if (!cb) {
return;
}
diff --git a/system/btif/src/btif_jni_task.cc b/system/btif/src/btif_jni_task.cc
index 3937dd1591..5eb7dcd50a 100644
--- a/system/btif/src/btif_jni_task.cc
+++ b/system/btif/src/btif_jni_task.cc
@@ -105,7 +105,7 @@ bt_status_t btif_transfer_context(tBTIF_CBACK* p_cback, uint16_t event, char* p_
* the JNI message loop.
**/
bt_status_t do_in_jni_thread(base::OnceClosure task) {
- if (!jni_thread.DoInThread(FROM_HERE, std::move(task))) {
+ if (!jni_thread.DoInThread(std::move(task))) {
log::error("Post task to task runner failed!");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
diff --git a/system/btif/src/btif_le_audio.cc b/system/btif/src/btif_le_audio.cc
index 9b4fdc81fc..10eb8f99fb 100644
--- a/system/btif/src/btif_le_audio.cc
+++ b/system/btif/src/btif_le_audio.cc
@@ -71,14 +71,16 @@ class LeAudioClientInterfaceImpl : public LeAudioClientInterface, public LeAudio
group_id, node_status));
}
- void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location,
- uint32_t src_audio_location, uint16_t avail_cont) override {
+ void OnAudioConf(uint8_t direction, int group_id,
+ std::optional<std::bitset<32>> snk_audio_location,
+ std::optional<std::bitset<32>> src_audio_location,
+ uint16_t avail_cont) override {
do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnAudioConf, Unretained(callbacks), direction,
group_id, snk_audio_location, src_audio_location, avail_cont));
}
void OnSinkAudioLocationAvailable(const RawAddress& address,
- uint32_t snk_audio_location) override {
+ std::optional<std::bitset<32>> snk_audio_location) override {
do_in_jni_thread(Bind(&LeAudioClientCallbacks::OnSinkAudioLocationAvailable,
Unretained(callbacks), address, snk_audio_location));
}
diff --git a/system/btif/src/btif_profile_storage.cc b/system/btif/src/btif_profile_storage.cc
index 4a8d13d59d..6051de1415 100644
--- a/system/btif/src/btif_profile_storage.cc
+++ b/system/btif/src/btif_profile_storage.cc
@@ -683,17 +683,27 @@ void btif_storage_leaudio_update_ase_bin(const RawAddress& addr) {
}
/** Store Le Audio device audio locations */
-void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location,
- uint32_t source_location) {
+void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) {
do_in_jni_thread(Bind(
- [](const RawAddress& addr, int sink_location, int source_location) {
+ [](const RawAddress& addr, int sink_location) {
std::string bdstr = addr.ToString();
- log::debug("saving le audio device: {}", addr);
+ log::debug("saving le audio device: {} sink locations", addr);
btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, sink_location);
+ },
+ addr, sink_location));
+}
+
+/** Store Le Audio device audio locations */
+void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr,
+ uint32_t source_location) {
+ do_in_jni_thread(Bind(
+ [](const RawAddress& addr, int source_location) {
+ std::string bdstr = addr.ToString();
+ log::debug("saving le audio device: {} source locations", addr);
btif_config_set_int(bdstr, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION,
source_location);
},
- addr, sink_location, source_location));
+ addr, source_location));
}
/** Store Le Audio device context types */
@@ -729,12 +739,12 @@ void btif_storage_load_bonded_leaudio() {
autoconnect = !!value;
}
- int sink_audio_location = 0;
+ std::optional<int> sink_audio_location = std::nullopt;
if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SINK_AUDIOLOCATION, &value)) {
sink_audio_location = value;
}
- int source_audio_location = 0;
+ std::optional<int> source_audio_location = std::nullopt;
if (btif_config_get_int(name, BTIF_STORAGE_KEY_LEAUDIO_SOURCE_AUDIOLOCATION, &value)) {
source_audio_location = value;
}
diff --git a/system/btif/src/stack_manager.cc b/system/btif/src/stack_manager.cc
index 430ed84d23..216e1c2f4a 100644
--- a/system/btif/src/stack_manager.cc
+++ b/system/btif/src/stack_manager.cc
@@ -143,8 +143,8 @@ static void init_stack(bluetooth::core::CoreInterface* interface) {
// and do not overlap.
std::promise<void> promise;
auto future = promise.get_future();
- management_thread.DoInThread(FROM_HERE, base::BindOnce(event_init_stack, std::move(promise),
- base::Unretained(interface)));
+ management_thread.DoInThread(
+ base::BindOnce(event_init_stack, std::move(promise), base::Unretained(interface)));
future.wait();
}
@@ -152,11 +152,11 @@ static void start_up_stack_async(bluetooth::core::CoreInterface* interface,
ProfileStartCallback startProfiles,
ProfileStopCallback stopProfiles) {
management_thread.DoInThread(
- FROM_HERE, base::BindOnce(event_start_up_stack, interface, startProfiles, stopProfiles));
+ base::BindOnce(event_start_up_stack, interface, startProfiles, stopProfiles));
}
static void shut_down_stack_async(ProfileStopCallback stopProfiles) {
- management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_stack, stopProfiles));
+ management_thread.DoInThread(base::BindOnce(event_shut_down_stack, stopProfiles));
}
static void clean_up_stack(ProfileStopCallback stopProfiles) {
@@ -165,7 +165,7 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) {
std::promise<void> promise;
auto future = promise.get_future();
management_thread.DoInThread(
- FROM_HERE, base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles));
+ base::BindOnce(event_clean_up_stack, std::move(promise), stopProfiles));
auto status = future.wait_for(std::chrono::milliseconds(
bluetooth::os::GetSystemPropertyUint32("bluetooth.cleanup_timeout",
@@ -178,12 +178,11 @@ static void clean_up_stack(ProfileStopCallback stopProfiles) {
}
static void start_up_rust_module_async(std::promise<void> promise) {
- management_thread.DoInThread(FROM_HERE,
- base::BindOnce(event_start_up_rust_module, std::move(promise)));
+ management_thread.DoInThread(base::BindOnce(event_start_up_rust_module, std::move(promise)));
}
static void shut_down_rust_module_async() {
- management_thread.DoInThread(FROM_HERE, base::BindOnce(event_shut_down_rust_module));
+ management_thread.DoInThread(base::BindOnce(event_shut_down_rust_module));
}
static bool get_stack_is_running() { return stack_is_running; }
@@ -321,7 +320,7 @@ static void event_start_up_stack(bluetooth::core::CoreInterface* interface,
return;
}
- if (!com::android::bluetooth::flags::scan_manager_refactor()) {
+ if (!com::android::bluetooth::flags::only_start_scan_during_ble_on()) {
info("Starting rust module");
module_start_up(get_local_module(RUST_MODULE));
if (com::android::bluetooth::flags::channel_sounding_in_stack()) {
@@ -347,7 +346,7 @@ static void event_shut_down_stack(ProfileStopCallback stopProfiles) {
hack_future = local_hack_future;
stack_is_running = false;
- if (!com::android::bluetooth::flags::scan_manager_refactor()) {
+ if (!com::android::bluetooth::flags::only_start_scan_during_ble_on()) {
info("Stopping rust module");
module_shut_down(get_local_module(RUST_MODULE));
}
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_rc_test.cc b/system/btif/test/btif_rc_test.cc
index b537e06e04..64a899baae 100644
--- a/system/btif/test/btif_rc_test.cc
+++ b/system/btif/test/btif_rc_test.cc
@@ -99,7 +99,7 @@ bool btif_av_both_enable(void) { return true; }
static bluetooth::common::MessageLoopThread jni_thread("bt_jni_thread");
bt_status_t do_in_jni_thread(base::OnceClosure task) {
- if (!jni_thread.DoInThread(FROM_HERE, std::move(task))) {
+ if (!jni_thread.DoInThread(std::move(task))) {
log::error("Post task to task runner failed!");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
diff --git a/system/common/benchmark/thread_performance_benchmark.cc b/system/common/benchmark/thread_performance_benchmark.cc
index 3ae5033c69..b2b5e7fe5d 100644
--- a/system/common/benchmark/thread_performance_benchmark.cc
+++ b/system/common/benchmark/thread_performance_benchmark.cc
@@ -326,8 +326,7 @@ protected:
std::future<void> set_up_future = set_up_promise_->get_future();
message_loop_thread_ = new MessageLoopThread("BM_MessageLooopThread thread");
message_loop_thread_->StartUp();
- message_loop_thread_->DoInThread(FROM_HERE,
- base::BindOnce(&std::promise<void>::set_value,
+ message_loop_thread_->DoInThread(base::BindOnce(&std::promise<void>::set_value,
base::Unretained(set_up_promise_.get())));
set_up_future.wait();
}
@@ -349,8 +348,7 @@ BENCHMARK_F(BM_MessageLooopThread, batch_enque_dequeue)(State& state) {
std::future<void> counter_future = g_counter_promise->get_future();
for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {
fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter);
- message_loop_thread_->DoInThread(FROM_HERE,
- base::BindOnce(&callback_batch, bt_msg_queue_, nullptr));
+ message_loop_thread_->DoInThread(base::BindOnce(&callback_batch, bt_msg_queue_, nullptr));
}
counter_future.wait();
}
@@ -361,7 +359,7 @@ BENCHMARK_F(BM_MessageLooopThread, sequential_execution)(State& state) {
for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {
g_counter_promise = std::make_unique<std::promise<void>>();
std::future<void> counter_future = g_counter_promise->get_future();
- message_loop_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_sequential, nullptr));
+ message_loop_thread_->DoInThread(base::BindOnce(&callback_sequential, nullptr));
counter_future.wait();
}
}
diff --git a/system/common/message_loop_thread.cc b/system/common/message_loop_thread.cc
index 1de1ff036e..a6dd211d77 100644
--- a/system/common/message_loop_thread.cc
+++ b/system/common/message_loop_thread.cc
@@ -70,22 +70,20 @@ void MessageLoopThread::StartUp() {
start_up_future.wait();
}
-bool MessageLoopThread::DoInThread(const base::Location& from_here, base::OnceClosure task) {
- return DoInThreadDelayed(from_here, std::move(task), std::chrono::microseconds(0));
+bool MessageLoopThread::DoInThread(base::OnceClosure task) {
+ return DoInThreadDelayed(std::move(task), std::chrono::microseconds(0));
}
-bool MessageLoopThread::DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task,
- std::chrono::microseconds delay) {
+bool MessageLoopThread::DoInThreadDelayed(base::OnceClosure task, std::chrono::microseconds delay) {
std::lock_guard<std::recursive_mutex> api_lock(api_mutex_);
if (message_loop_ == nullptr) {
- log::error("message loop is null for thread {}, from {}", *this, from_here.ToString());
+ log::error("message loop is null for thread {}", *this);
return false;
}
- if (!message_loop_->task_runner()->PostDelayedTask(from_here, std::move(task),
+ if (!message_loop_->task_runner()->PostDelayedTask(FROM_HERE, std::move(task),
timeDeltaFromMicroseconds(delay))) {
- log::error("failed to post task to message loop for thread {}, from {}", *this,
- from_here.ToString());
+ log::error("failed to post task to message loop for thread {}", *this);
return false;
}
return true;
@@ -199,9 +197,7 @@ void MessageLoopThread::Run(std::promise<void> start_up_promise) {
}
}
-void MessageLoopThread::Post(base::OnceClosure closure) {
- DoInThread(FROM_HERE, std::move(closure));
-}
+void MessageLoopThread::Post(base::OnceClosure closure) { DoInThread(std::move(closure)); }
PostableContext* MessageLoopThread::Postable() { return this; }
diff --git a/system/common/message_loop_thread.h b/system/common/message_loop_thread.h
index 301a4848a7..f51e2c9595 100644
--- a/system/common/message_loop_thread.h
+++ b/system/common/message_loop_thread.h
@@ -67,12 +67,11 @@ public:
/**
* Post a task to run on this thread
*
- * @param from_here location where this task is originated
* @param task task created through base::Bind()
* @return true if task is successfully scheduled, false if task cannot be
* scheduled
*/
- bool DoInThread(const base::Location& from_here, base::OnceClosure task);
+ bool DoInThread(base::OnceClosure task);
/**
* Shutdown the current thread as if it is never started. IsRunning() and
@@ -147,26 +146,22 @@ public:
* <code>
* base::CancelableClosure cancelable_task;
* cancelable_task.Reset(base::Bind(...)); // bind the task
- * same_thread->DoInThreadDelayed(FROM_HERE,
- * cancelable_task.callback(), delay);
+ * same_thread->DoInThreadDelayed(cancelable_task.callback(), delay);
* ...
* // Cancel the task closure
- * same_thread->DoInThread(FROM_HERE,
- * base::Bind(&base::CancelableClosure::Cancel,
- * base::Unretained(&cancelable_task)));
+ * same_thread->DoInThread(base::Bind(&base::CancelableClosure::Cancel,
+ * base::Unretained(&cancelable_task)));
* </code>
*
* Warning: base::CancelableClosure objects must be created on, posted to,
* cancelled on, and destroyed on the same thread.
*
- * @param from_here location where this task is originated
* @param task task created through base::Bind()
* @param delay delay for the task to be executed
* @return true if task is successfully scheduled, false if task cannot be
* scheduled
*/
- bool DoInThreadDelayed(const base::Location& from_here, base::OnceClosure task,
- std::chrono::microseconds delay);
+ bool DoInThreadDelayed(base::OnceClosure task, std::chrono::microseconds delay);
/**
* Wrapper around DoInThread without a location.
*/
diff --git a/system/common/message_loop_thread_unittest.cc b/system/common/message_loop_thread_unittest.cc
index 8b6d598aaf..160f61e2c8 100644
--- a/system/common/message_loop_thread_unittest.cc
+++ b/system/common/message_loop_thread_unittest.cc
@@ -115,7 +115,6 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_before_start) {
std::string name = "test_thread";
MessageLoopThread message_loop_thread(name);
ASSERT_FALSE(message_loop_thread.DoInThread(
- FROM_HERE,
base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this))));
}
@@ -125,7 +124,6 @@ TEST_F(MessageLoopThreadTest, test_do_in_thread_after_shutdown) {
message_loop_thread.StartUp();
message_loop_thread.ShutDown();
ASSERT_FALSE(message_loop_thread.DoInThread(
- FROM_HERE,
base::BindOnce(&MessageLoopThreadTest::ShouldNotHappen, base::Unretained(this))));
}
@@ -136,9 +134,8 @@ TEST_F(MessageLoopThreadTest, test_name) {
ASSERT_GE(message_loop_thread.GetThreadId(), 0);
std::promise<std::string> name_promise;
std::future<std::string> name_future = name_promise.get_future();
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetName, base::Unretained(this),
- std::move(name_promise)));
+ message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetName,
+ base::Unretained(this), std::move(name_promise)));
std::string my_name = name_future.get();
ASSERT_EQ(name, my_name);
ASSERT_EQ(name, message_loop_thread.GetName());
@@ -152,9 +149,9 @@ TEST_F(MessageLoopThreadTest, test_thread_id) {
ASSERT_GE(thread_id, 0);
std::promise<base::PlatformThreadId> thread_id_promise;
std::future<base::PlatformThreadId> thread_id_future = thread_id_promise.get_future();
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetThreadId, base::Unretained(this),
- std::move(thread_id_promise)));
+ message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetThreadId,
+ base::Unretained(this),
+ std::move(thread_id_promise)));
base::PlatformThreadId my_thread_id = thread_id_future.get();
ASSERT_EQ(thread_id, my_thread_id);
}
@@ -189,19 +186,17 @@ TEST_F(MessageLoopThreadTest, test_set_realtime_priority_success) {
std::future<void> execution_future = execution_promise.get_future();
int scheduling_policy = -1;
int scheduling_priority = -1;
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetSchedulingPolicyAndPriority,
- base::Unretained(this), &scheduling_policy,
- &scheduling_priority, std::move(execution_promise)));
+ message_loop_thread.DoInThread(base::BindOnce(
+ &MessageLoopThreadTest::GetSchedulingPolicyAndPriority, base::Unretained(this),
+ &scheduling_policy, &scheduling_priority, std::move(execution_promise)));
execution_future.wait();
ASSERT_EQ(scheduling_policy, SCHED_FIFO);
// Internal implementation verified here
ASSERT_EQ(scheduling_priority, 1);
std::promise<pid_t> tid_promise;
std::future<pid_t> tid_future = tid_promise.get_future();
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(&MessageLoopThreadTest::GetLinuxTid, base::Unretained(this),
- std::move(tid_promise)));
+ message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::GetLinuxTid,
+ base::Unretained(this), std::move(tid_promise)));
pid_t linux_tid = tid_future.get();
ASSERT_GT(linux_tid, 0);
ASSERT_EQ(sched_getscheduler(linux_tid), SCHED_FIFO);
@@ -260,9 +255,9 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback) {
std::promise<std::string> name_promise;
std::future<std::string> name_future = name_promise.get_future();
uint32_t delay_ms = 5;
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce(&MessageLoopThreadTest::SleepAndGetName, base::Unretained(this),
- std::move(name_promise), delay_ms));
+ message_loop_thread.DoInThread(base::BindOnce(&MessageLoopThreadTest::SleepAndGetName,
+ base::Unretained(this), std::move(name_promise),
+ delay_ms));
message_loop_thread.ShutDown();
std::string my_name = name_future.get();
ASSERT_EQ(name, my_name);
@@ -273,9 +268,8 @@ TEST_F(MessageLoopThreadTest, shut_down_while_in_callback_check_lock) {
std::string name = "test_thread";
MessageLoopThread message_loop_thread(name);
message_loop_thread.StartUp();
- message_loop_thread.DoInThread(
- FROM_HERE, base::BindOnce([](MessageLoopThread* thread) { thread->IsRunning(); },
- &message_loop_thread));
+ message_loop_thread.DoInThread(base::BindOnce(
+ [](MessageLoopThread* thread) { thread->IsRunning(); }, &message_loop_thread));
message_loop_thread.ShutDown();
}
diff --git a/system/common/repeating_timer.cc b/system/common/repeating_timer.cc
index f1e645182a..98ff8c442a 100644
--- a/system/common/repeating_timer.cc
+++ b/system/common/repeating_timer.cc
@@ -37,7 +37,7 @@ RepeatingTimer::~RepeatingTimer() {
// This runs on user thread
bool RepeatingTimer::SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread,
- const base::Location& from_here, base::RepeatingClosure task,
+ base::RepeatingClosure task,
std::chrono::microseconds period) {
if (period < kMinimumPeriod) {
log::error("period must be at least {}", kMinimumPeriod.count());
@@ -58,10 +58,9 @@ bool RepeatingTimer::SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& th
message_loop_thread_ = thread;
period_ = period;
uint64_t time_until_next_us = time_next_task_us - clock_tick_us_();
- if (!thread->DoInThreadDelayed(from_here, task_wrapper_.callback(),
+ if (!thread->DoInThreadDelayed(task_wrapper_.callback(),
std::chrono::microseconds(time_until_next_us))) {
- log::error("failed to post task to message loop for thread {}, from {}", *thread,
- from_here.ToString());
+ log::error("failed to post task to message loop for thread {}", *thread);
expected_time_next_task_us_ = 0;
task_wrapper_.Cancel();
message_loop_thread_ = nullptr;
@@ -97,9 +96,8 @@ void RepeatingTimer::CancelHelper(std::promise<void> promise) {
CancelClosure(std::move(promise));
return;
}
- scheduled_thread->DoInThread(
- FROM_HERE, base::BindOnce(&RepeatingTimer::CancelClosure, base::Unretained(this),
- std::move(promise)));
+ scheduled_thread->DoInThread(base::BindOnce(&RepeatingTimer::CancelClosure,
+ base::Unretained(this), std::move(promise)));
}
// This runs on message loop thread
@@ -140,7 +138,7 @@ void RepeatingTimer::RunTask() {
// multiple of period
remaining_time_us = (remaining_time_us % period_us + period_us) % period_us;
}
- message_loop_thread_->DoInThreadDelayed(FROM_HERE, task_wrapper_.callback(),
+ message_loop_thread_->DoInThreadDelayed(task_wrapper_.callback(),
std::chrono::microseconds(remaining_time_us));
uint64_t time_before_task_us = clock_tick_us_();
diff --git a/system/common/repeating_timer.h b/system/common/repeating_timer.h
index 6c22f0d467..c7d0505e86 100644
--- a/system/common/repeating_timer.h
+++ b/system/common/repeating_timer.h
@@ -54,13 +54,11 @@ public:
* blocks until the previous task is cancelled.
*
* @param thread thread to run the task
- * @param from_here location where this task is originated
* @param task task created through base::Bind()
* @param period period for the task to be executed
* @return true iff task is scheduled successfully
*/
- bool SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread,
- const base::Location& from_here, base::RepeatingClosure task,
+ bool SchedulePeriodic(const base::WeakPtr<MessageLoopThread>& thread, base::RepeatingClosure task,
std::chrono::microseconds period);
/**
diff --git a/system/common/repeating_timer_unittest.cc b/system/common/repeating_timer_unittest.cc
index 817f3e9bb0..a8a7a4cd80 100644
--- a/system/common/repeating_timer_unittest.cc
+++ b/system/common/repeating_timer_unittest.cc
@@ -81,7 +81,7 @@ public:
auto future = promise_->get_future();
auto start_time = std::chrono::steady_clock::now();
timer_->SchedulePeriodic(
- message_loop_thread.GetWeakPtr(), FROM_HERE,
+ message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::VerifyDelayTimeAndSleep,
base::Unretained(this), start_time, interval_between_tasks_ms,
scheduled_tasks, task_length_ms, promise_),
@@ -136,7 +136,7 @@ TEST_F(RepeatingTimerTest, periodic_run) {
uint32_t delay_ms = 5;
int num_tasks = 200;
- timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE,
+ timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter,
base::Unretained(this), num_tasks, promise_),
std::chrono::milliseconds(delay_ms));
@@ -152,7 +152,7 @@ TEST_F(RepeatingTimerTest, schedule_periodic_task_zero_interval) {
uint32_t interval_ms = 0;
ASSERT_FALSE(timer_->SchedulePeriodic(
- message_loop_thread.GetWeakPtr(), FROM_HERE,
+ message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)),
std::chrono::milliseconds(interval_ms)));
std::this_thread::sleep_for(std::chrono::milliseconds(delay_error_ms));
@@ -165,7 +165,7 @@ TEST_F(RepeatingTimerTest, periodic_delete_without_cancel) {
message_loop_thread.StartUp();
uint32_t delay_ms = 5;
timer_->SchedulePeriodic(
- message_loop_thread.GetWeakPtr(), FROM_HERE,
+ message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::ShouldNotHappen, base::Unretained(this)),
std::chrono::milliseconds(delay_ms));
delete timer_;
@@ -178,7 +178,7 @@ TEST_F(RepeatingTimerTest, cancel_single_task_near_fire_no_race_condition) {
MessageLoopThread message_loop_thread(name);
message_loop_thread.StartUp();
uint32_t delay_ms = 5;
- timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE, base::DoNothing(),
+ timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), base::DoNothing(),
std::chrono::milliseconds(delay_ms));
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
timer_->CancelAndWait();
@@ -192,7 +192,7 @@ TEST_F(RepeatingTimerTest, cancel_periodic_task) {
int num_tasks = 5;
auto future = promise_->get_future();
- timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE,
+ timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter,
base::Unretained(this), num_tasks, promise_),
std::chrono::milliseconds(delay_ms));
@@ -225,7 +225,7 @@ TEST_F(RepeatingTimerTest, message_loop_thread_down_cancel_scheduled_periodic_ta
uint32_t delay_ms = 5;
int num_tasks = 5;
- timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(), FROM_HERE,
+ timer_->SchedulePeriodic(message_loop_thread.GetWeakPtr(),
base::BindRepeating(&RepeatingTimerTest::IncreaseTaskCounter,
base::Unretained(this), num_tasks, promise_),
std::chrono::milliseconds(delay_ms));
diff --git a/system/common/test/thread_performance_test.cc b/system/common/test/thread_performance_test.cc
index f875cd6aa6..17ca715c4f 100644
--- a/system/common/test/thread_performance_test.cc
+++ b/system/common/test/thread_performance_test.cc
@@ -261,8 +261,8 @@ protected:
std::future<void> set_up_future = set_up_promise_->get_future();
worker_thread_ = new MessageLoopThread("WorkerThreadPerformanceTest thread");
worker_thread_->StartUp();
- worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&std::promise<void>::set_value,
- base::Unretained(set_up_promise_.get())));
+ worker_thread_->DoInThread(base::BindOnce(&std::promise<void>::set_value,
+ base::Unretained(set_up_promise_.get())));
set_up_future.wait();
}
@@ -285,7 +285,7 @@ TEST_F(WorkerThreadPerformanceTest, worker_thread_speed_test) {
for (int i = 0; i < NUM_MESSAGES_TO_SEND; i++) {
fixed_queue_enqueue(bt_msg_queue_, (void*)&g_counter);
- worker_thread_->DoInThread(FROM_HERE, base::BindOnce(&callback_batch, bt_msg_queue_, nullptr));
+ worker_thread_->DoInThread(base::BindOnce(&callback_batch, bt_msg_queue_, nullptr));
}
counter_future.wait();
diff --git a/system/device/fuzzer/Android.bp b/system/device/fuzzer/Android.bp
index c7a6917898..3b7822ac61 100644
--- a/system/device/fuzzer/Android.bp
+++ b/system/device/fuzzer/Android.bp
@@ -26,6 +26,9 @@ package {
cc_fuzz {
name: "btdevice_esco_fuzzer",
defaults: ["fluoride_defaults"],
+ cflags: [
+ "-Wno-missing-prototypes",
+ ],
srcs: [
":TestMockMainShimEntry",
"btdevice_esco_fuzzer.cpp",
diff --git a/system/device/fuzzer/btdevice_esco_fuzzer.cpp b/system/device/fuzzer/btdevice_esco_fuzzer.cpp
index 99b3f78cd8..b79d3527cd 100644
--- a/system/device/fuzzer/btdevice_esco_fuzzer.cpp
+++ b/system/device/fuzzer/btdevice_esco_fuzzer.cpp
@@ -23,9 +23,6 @@
#include "device/include/interop.h"
#include "device/include/interop_config.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace std;
constexpr size_t kNumAddressOctets = 6;
constexpr size_t kMaxStringLength = 10;
diff --git a/system/device/src/interop.cc b/system/device/src/interop.cc
index c6f4d30a33..60d90cf6d6 100644
--- a/system/device/src/interop.cc
+++ b/system/device/src/interop.cc
@@ -47,9 +47,6 @@
#include "osi/include/osi.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
#ifdef __ANDROID__
@@ -792,7 +789,7 @@ static char* trim(char* str) {
return str;
}
-bool token_to_ul(char* token, uint16_t* ul) {
+static bool token_to_ul(char* token, uint16_t* ul) {
char* e;
bool ret_value = false;
diff --git a/system/gd/hal/hci_hal_android.cc b/system/gd/hal/hci_hal_android.cc
index 20d9e29e3d..8f1246d064 100644
--- a/system/gd/hal/hci_hal_android.cc
+++ b/system/gd/hal/hci_hal_android.cc
@@ -27,6 +27,7 @@
#include "hal/hci_hal.h"
#include "hal/link_clocker.h"
#include "hal/snoop_logger.h"
+#include "main/shim/entry.h"
namespace bluetooth::hal {
@@ -167,10 +168,7 @@ public:
}
protected:
- void ListDependencies(ModuleList* list) const override {
- list->add<LinkClocker>();
- list->add<SnoopLogger>();
- }
+ void ListDependencies(ModuleList* list) const override { list->add<LinkClocker>(); }
void Start() override {
common::StopWatch stop_watch(__func__);
@@ -178,7 +176,7 @@ protected:
"Start can't be called more than once before Stop is called.");
link_clocker_ = GetDependency<LinkClocker>();
- btsnoop_logger_ = GetDependency<SnoopLogger>();
+ btsnoop_logger_ = shim::GetSnoopLogger();
backend_ = HciBackend::CreateAidl();
if (!backend_) {
diff --git a/system/gd/hal/hci_hal_host.cc b/system/gd/hal/hci_hal_host.cc
index 65c1671c8d..970a2ae48c 100644
--- a/system/gd/hal/hci_hal_host.cc
+++ b/system/gd/hal/hci_hal_host.cc
@@ -35,6 +35,7 @@
#include "hal/hci_hal.h"
#include "hal/link_clocker.h"
#include "hal/snoop_logger.h"
+#include "main/shim/entry.h"
#include "metrics/counter_metrics.h"
#include "os/mgmt.h"
#include "os/reactor.h"
@@ -326,10 +327,7 @@ public:
}
protected:
- void ListDependencies(ModuleList* list) const {
- list->add<LinkClocker>();
- list->add<SnoopLogger>();
- }
+ void ListDependencies(ModuleList* list) const { list->add<LinkClocker>(); }
void Start() override {
std::lock_guard<std::mutex> lock(api_mutex_);
@@ -350,7 +348,7 @@ protected:
hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_,
os::Reactor::REACT_ON_READ_ONLY);
link_clocker_ = GetDependency<LinkClocker>();
- btsnoop_logger_ = GetDependency<SnoopLogger>();
+ btsnoop_logger_ = shim::GetSnoopLogger();
log::info("HAL opened successfully");
}
diff --git a/system/gd/hal/hci_hal_host_rootcanal.cc b/system/gd/hal/hci_hal_host_rootcanal.cc
index f4866a5115..612372a962 100644
--- a/system/gd/hal/hci_hal_host_rootcanal.cc
+++ b/system/gd/hal/hci_hal_host_rootcanal.cc
@@ -30,6 +30,7 @@
#include "hal/hci_hal.h"
#include "hal/hci_hal_host.h"
#include "hal/snoop_logger.h"
+#include "main/shim/entry.h"
#include "metrics/counter_metrics.h"
#include "os/reactor.h"
#include "os/thread.h"
@@ -163,7 +164,7 @@ public:
}
protected:
- void ListDependencies(ModuleList* list) const { list->add<SnoopLogger>(); }
+ void ListDependencies(ModuleList* /*list*/) const {}
void Start() override {
std::lock_guard<std::mutex> lock(api_mutex_);
@@ -175,7 +176,7 @@ protected:
common::Bind(&HciHalHost::send_packet_ready, common::Unretained(this)));
hci_incoming_thread_.GetReactor()->ModifyRegistration(reactable_,
os::Reactor::REACT_ON_READ_ONLY);
- btsnoop_logger_ = GetDependency<SnoopLogger>();
+ btsnoop_logger_ = shim::GetSnoopLogger();
log::info("HAL opened successfully");
}
diff --git a/system/gd/hal/snoop_logger.cc b/system/gd/hal/snoop_logger.cc
index 53f5509a0b..f5e0242dfd 100644
--- a/system/gd/hal/snoop_logger.cc
+++ b/system/gd/hal/snoop_logger.cc
@@ -51,6 +51,29 @@ using bluetooth::os::fake_timer::fake_timerfd_get_clock;
namespace bluetooth {
namespace hal {
+static std::string GetBtSnoopMode() {
+ // Default mode is FILTERED on userdebug/eng build, DISABLED on user build.
+ // In userdebug/eng build, it can also be overwritten by modifying the global setting
+ std::string btsnoop_mode = SnoopLogger::kBtSnoopLogModeDisabled;
+ if (os::GetSystemPropertyBool(SnoopLogger::kIsDebuggableProperty, false)) {
+ btsnoop_mode = os::GetSystemProperty(SnoopLogger::kBtSnoopDefaultLogModeProperty)
+ .value_or(SnoopLogger::kBtSnoopLogModeFiltered);
+ }
+
+ btsnoop_mode = os::GetSystemProperty(SnoopLogger::kBtSnoopLogModeProperty).value_or(btsnoop_mode);
+
+ // Only allow a subset of values:
+ if (!(btsnoop_mode == SnoopLogger::kBtSnoopLogModeDisabled ||
+ btsnoop_mode == SnoopLogger::kBtSnoopLogModeFull ||
+ btsnoop_mode == SnoopLogger::kBtSnoopLogModeFiltered ||
+ btsnoop_mode == SnoopLogger::kBtSnoopLogModeKernel)) {
+ log::warn("{}: Invalid btsnoop value, default back to disabled", btsnoop_mode);
+ return SnoopLogger::kBtSnoopLogModeDisabled;
+ }
+
+ return btsnoop_mode;
+}
+
// Adds L2CAP channel to acceptlist.
void FilterTracker::AddL2capCid(uint16_t local_cid, uint16_t remote_cid) {
l2c_local_cid.insert(local_cid);
@@ -492,13 +515,22 @@ const size_t SnoopLogger::PACKET_TYPE_LENGTH = 1;
const size_t SnoopLogger::MAX_HCI_ACL_LEN = 14;
const uint32_t SnoopLogger::L2CAP_HEADER_SIZE = 8;
-SnoopLogger::SnoopLogger(std::string snoop_log_path, std::string snooz_log_path,
- size_t max_packets_per_file, size_t max_packets_per_buffer,
- const std::string& btsnoop_mode, bool qualcomm_debug_log_enabled,
+SnoopLogger::SnoopLogger(os::Handler* handler)
+ : SnoopLogger(handler, os::ParameterProvider::SnoopLogFilePath(),
+ os::ParameterProvider::SnoozLogFilePath(), GetMaxPacketsPerFile(),
+ GetMaxPacketsPerBuffer(), GetBtSnoopMode(), IsQualcommDebugLogEnabled(),
+ kBtSnoozLogLifeTime, kBtSnoozLogDeleteRepeatingAlarmInterval,
+ IsBtSnoopLogPersisted()) {}
+
+SnoopLogger::SnoopLogger(os::Handler* handler, std::string snoop_log_path,
+ std::string snooz_log_path, size_t max_packets_per_file,
+ size_t max_packets_per_buffer, const std::string& btsnoop_mode,
+ bool qualcomm_debug_log_enabled,
const std::chrono::milliseconds snooz_log_life_time,
const std::chrono::milliseconds snooz_log_delete_alarm_interval,
bool snoop_log_persists)
- : btsnoop_mode_(btsnoop_mode),
+ : Module(handler),
+ btsnoop_mode_(btsnoop_mode),
snoop_log_path_(std::move(snoop_log_path)),
snooz_log_path_(std::move(snooz_log_path)),
max_packets_per_file_(max_packets_per_file),
@@ -1292,10 +1324,6 @@ void SnoopLogger::DumpSnoozLogToFile() {
}
}
-void SnoopLogger::ListDependencies(ModuleList* /* list */) const {
- // We have no dependencies
-}
-
void SnoopLogger::Start() {
std::lock_guard<std::recursive_mutex> lock(file_mutex_);
if (btsnoop_mode_ != kBtSnoopLogModeDisabled && btsnoop_mode_ != kBtSnoopLogModeKernel) {
@@ -1385,29 +1413,6 @@ size_t SnoopLogger::GetMaxPacketsPerBuffer() {
std::string SnoopLogger::GetCurrentSnoopMode() { return btsnoop_mode_; }
-static std::string GetBtSnoopMode() {
- // Default mode is FILTERED on userdebug/eng build, DISABLED on user build.
- // In userdebug/eng build, it can also be overwritten by modifying the global setting
- std::string btsnoop_mode = SnoopLogger::kBtSnoopLogModeDisabled;
- if (os::GetSystemPropertyBool(SnoopLogger::kIsDebuggableProperty, false)) {
- btsnoop_mode = os::GetSystemProperty(SnoopLogger::kBtSnoopDefaultLogModeProperty)
- .value_or(SnoopLogger::kBtSnoopLogModeFiltered);
- }
-
- btsnoop_mode = os::GetSystemProperty(SnoopLogger::kBtSnoopLogModeProperty).value_or(btsnoop_mode);
-
- // Only allow a subset of values:
- if (!(btsnoop_mode == SnoopLogger::kBtSnoopLogModeDisabled ||
- btsnoop_mode == SnoopLogger::kBtSnoopLogModeFull ||
- btsnoop_mode == SnoopLogger::kBtSnoopLogModeFiltered ||
- btsnoop_mode == SnoopLogger::kBtSnoopLogModeKernel)) {
- log::warn("{}: Invalid btsnoop value, default back to disabled", btsnoop_mode);
- return SnoopLogger::kBtSnoopLogModeDisabled;
- }
-
- return btsnoop_mode;
-}
-
void SnoopLogger::RegisterSocket(SnoopLoggerSocketInterface* socket) {
std::lock_guard<std::recursive_mutex> lock(file_mutex_);
socket_ = socket;
@@ -1430,14 +1435,6 @@ bool SnoopLogger::IsQualcommDebugLogEnabled() {
return qualcomm_debug_log_enabled;
}
-const ModuleFactory SnoopLogger::Factory = ModuleFactory([]() {
- return new SnoopLogger(os::ParameterProvider::SnoopLogFilePath(),
- os::ParameterProvider::SnoozLogFilePath(), GetMaxPacketsPerFile(),
- GetMaxPacketsPerBuffer(), GetBtSnoopMode(), IsQualcommDebugLogEnabled(),
- kBtSnoozLogLifeTime, kBtSnoozLogDeleteRepeatingAlarmInterval,
- IsBtSnoopLogPersisted());
-});
-
#ifdef __ANDROID__
void SnoopLogger::LogTracePoint(uint64_t timestamp_us, const HciPacket& packet, Direction direction,
PacketType type) {
diff --git a/system/gd/hal/snoop_logger.h b/system/gd/hal/snoop_logger.h
index c1546d6ed4..d13113c9af 100644
--- a/system/gd/hal/snoop_logger.h
+++ b/system/gd/hal/snoop_logger.h
@@ -194,6 +194,8 @@ public:
uint16_t remote_cid;
};
+ SnoopLogger(os::Handler* handler);
+
// Returns the maximum number of packets per file
// Changes to this value is only effective after restarting Bluetooth
static size_t GetMaxPacketsPerFile();
@@ -224,6 +226,8 @@ public:
OUTGOING,
};
+ void Start() override;
+ void Stop() override;
void Capture(const HciPacket& packet, Direction direction, PacketType type);
// Set a L2CAP channel as acceptlisted, allowing packets with that L2CAP CID
@@ -268,6 +272,8 @@ public:
// Dump the contents of the snooz buffer to a file.
void DumpSnoozLogToFile();
+ SnoopLoggerSocketThread const* GetSocketThread() { return snoop_logger_socket_thread_.get(); }
+
protected:
// Packet type length
static const size_t PACKET_TYPE_LENGTH;
@@ -277,16 +283,16 @@ protected:
// Max packet data size when headersfiltered option enabled
static const size_t MAX_HCI_ACL_LEN;
- void ListDependencies(ModuleList* list) const override;
- void Start() override;
- void Stop() override;
+ void ListDependencies(ModuleList* /*list*/) const override {}
std::string ToString() const override { return std::string("SnoopLogger"); }
- SnoopLogger(std::string snoop_log_path, std::string snooz_log_path, size_t max_packets_per_file,
- size_t max_packets_per_buffer, const std::string& btsnoop_mode,
- bool qualcomm_debug_log_enabled, const std::chrono::milliseconds snooz_log_life_time,
+ SnoopLogger(os::Handler* handler, std::string snoop_log_path, std::string snooz_log_path,
+ size_t max_packets_per_file, size_t max_packets_per_buffer,
+ const std::string& btsnoop_mode, bool qualcomm_debug_log_enabled,
+ const std::chrono::milliseconds snooz_log_life_time,
const std::chrono::milliseconds snooz_log_delete_alarm_interval,
bool snoop_log_persists);
+
void CloseCurrentSnoopLogFile();
void OpenNextSnoopLogFile();
// Enable filters according to their sysprops
@@ -341,6 +347,8 @@ private:
SnoopLoggerSocketInterface* socket_;
SyscallWrapperImpl syscall_if;
bool snoop_log_persists = false;
+
+ friend class SnoopLoggerTest;
};
} // namespace hal
diff --git a/system/gd/hal/snoop_logger_socket_thread.cc b/system/gd/hal/snoop_logger_socket_thread.cc
index b2829626cf..efe3c5f546 100644
--- a/system/gd/hal/snoop_logger_socket_thread.cc
+++ b/system/gd/hal/snoop_logger_socket_thread.cc
@@ -72,7 +72,7 @@ void SnoopLoggerSocketThread::Write(const void* data, size_t length) {
bool SnoopLoggerSocketThread::ThreadIsRunning() const { return listen_thread_running_; }
-SnoopLoggerSocket* SnoopLoggerSocketThread::GetSocket() { return socket_.get(); }
+SnoopLoggerSocket* SnoopLoggerSocketThread::GetSocket() const { return socket_.get(); }
void SnoopLoggerSocketThread::Run(std::promise<bool> thread_started) {
log::debug("");
diff --git a/system/gd/hal/snoop_logger_socket_thread.h b/system/gd/hal/snoop_logger_socket_thread.h
index bdf62b720d..f508ff9e9b 100644
--- a/system/gd/hal/snoop_logger_socket_thread.h
+++ b/system/gd/hal/snoop_logger_socket_thread.h
@@ -42,7 +42,7 @@ public:
void Write(const void* data, size_t length) override;
bool ThreadIsRunning() const;
- SnoopLoggerSocket* GetSocket();
+ SnoopLoggerSocket* GetSocket() const;
private:
void Run(std::promise<bool> thread_started);
diff --git a/system/gd/hal/snoop_logger_test.cc b/system/gd/hal/snoop_logger_test.cc
index 4681f82f30..de42db5c06 100644
--- a/system/gd/hal/snoop_logger_test.cc
+++ b/system/gd/hal/snoop_logger_test.cc
@@ -34,37 +34,33 @@
#include "os/system_properties.h"
#include "os/utils.h"
-namespace testing {
+namespace bluetooth::hal {
-using bluetooth::hal::SnoopLoggerCommon;
-using bluetooth::hal::SnoopLoggerSocket;
-using bluetooth::hal::SnoopLoggerSocketInterface;
-using bluetooth::hal::SnoopLoggerSocketThread;
-using bluetooth::hal::SyscallWrapperImpl;
-using bluetooth::os::fake_timer::fake_timerfd_advance;
-using bluetooth::os::fake_timer::fake_timerfd_reset;
-using namespace bluetooth;
+using os::fake_timer::fake_timerfd_advance;
+using os::fake_timer::fake_timerfd_reset;
+using namespace std::chrono_literals;
namespace {
-std::vector<uint8_t> kInformationRequest = {
+static const std::vector<uint8_t> kInformationRequest = {
0xfe, 0x2e, 0x0a, 0x00, 0x06, 0x00, 0x01, 0x00, 0x0a, 0x02, 0x02, 0x00, 0x02, 0x00,
};
-std::vector<uint8_t> kSdpConnectionRequest = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00, 0x01, 0x00,
- 0x02, 0x0c, 0x04, 0x00, 0x01, 0x00, 0x44, 0x00};
+static const std::vector<uint8_t> kSdpConnectionRequest = {0x08, 0x20, 0x0c, 0x00, 0x08, 0x00,
+ 0x01, 0x00, 0x02, 0x0c, 0x04, 0x00,
+ 0x01, 0x00, 0x44, 0x00};
-std::vector<uint8_t> kAvdtpSuspend = {0x02, 0x02, 0x00, 0x07, 0x00, 0x03,
- 0x00, 0x8d, 0x00, 0x90, 0x09, 0x04};
+static const std::vector<uint8_t> kAvdtpSuspend = {0x02, 0x02, 0x00, 0x07, 0x00, 0x03,
+ 0x00, 0x8d, 0x00, 0x90, 0x09, 0x04};
-std::vector<uint8_t> kHfpAtNrec0 = {0x02, 0x02, 0x20, 0x13, 0x00, 0x0f, 0x00, 0x41,
- 0x00, 0x09, 0xff, 0x15, 0x01, 0x41, 0x54, 0x2b,
- 0x4e, 0x52, 0x45, 0x43, 0x3d, 0x30, 0x0d, 0x5c};
+static const std::vector<uint8_t> kHfpAtNrec0 = {0x02, 0x02, 0x20, 0x13, 0x00, 0x0f, 0x00, 0x41,
+ 0x00, 0x09, 0xff, 0x15, 0x01, 0x41, 0x54, 0x2b,
+ 0x4e, 0x52, 0x45, 0x43, 0x3d, 0x30, 0x0d, 0x5c};
-std::vector<uint8_t> kQualcommConnectionRequest = {0xdc, 0x2e, 0x54, 0x00, 0x50, 0x00, 0xff,
- 0x00, 0x00, 0x0a, 0x0f, 0x09, 0x01, 0x00,
- 0x5c, 0x93, 0x01, 0x00, 0x42, 0x00};
+static const std::vector<uint8_t> kQualcommConnectionRequest = {
+ 0xdc, 0x2e, 0x54, 0x00, 0x50, 0x00, 0xff, 0x00, 0x00, 0x0a,
+ 0x0f, 0x09, 0x01, 0x00, 0x5c, 0x93, 0x01, 0x00, 0x42, 0x00};
-std::vector<uint8_t> kA2dpMediaPacket = {
+static const std::vector<uint8_t> kA2dpMediaPacket = {
0x0b, 0x20, 0x3a, 0x00, 0x36, 0x00, 0x40, 0xa0, 0x80, 0xe0, 0x07, 0x7f, 0x00,
0x1e, 0x08, 0x00, 0x00, 0x00, 0x00, 0x02, 0x47, 0xfc, 0x00, 0x00, 0xb0, 0x90,
0x80, 0x03, 0x00, 0x20, 0x21, 0x11, 0x45, 0x00, 0x14, 0x50, 0x01, 0x46, 0xf0,
@@ -72,7 +68,7 @@ std::vector<uint8_t> kA2dpMediaPacket = {
0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e,
};
-std::vector<bluetooth::hal::HciPacket> kTestData = {
+static const std::vector<bluetooth::hal::HciPacket> kTestData = {
{0x02, 0x20, 0x11, 0x00, 0x0d, 0x00, 0x41, 0x00, 0x9d, 0xef, 0x35,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0x02, 0x00, 0x12, 0x00, 0x0e, 0x00, 0x40, 0x00, 0x9f, 0xff, 0x3f,
@@ -104,35 +100,16 @@ std::vector<bluetooth::hal::HciPacket> kTestData = {
} // namespace
-using bluetooth::TestModuleRegistry;
-using bluetooth::hal::SnoopLogger;
-using namespace std::chrono_literals;
-
-// Expose protected constructor for test
-class TestSnoopLoggerModule : public SnoopLogger {
+class SnoopLoggerTest : public testing::Test {
public:
- TestSnoopLoggerModule(std::string snoop_log_path, std::string snooz_log_path,
- size_t max_packets_per_file, const std::string& btsnoop_mode,
- bool qualcomm_debug_log_enabled, bool snoop_log_persists)
- : SnoopLogger(std::move(snoop_log_path), std::move(snooz_log_path), max_packets_per_file,
- SnoopLogger::GetMaxPacketsPerBuffer(), btsnoop_mode, qualcomm_debug_log_enabled,
- 20ms, 5ms, snoop_log_persists) {}
-
- std::string ToString() const override { return std::string("TestSnoopLoggerModule"); }
-
- SnoopLoggerSocketThread* GetSocketThread() { return snoop_logger_socket_thread_.get(); }
-
- static uint32_t GetL2capHeaderSize() { return L2CAP_HEADER_SIZE; }
-
- static size_t GetMaxFilteredSize() { return MAX_HCI_ACL_LEN - PACKET_TYPE_LENGTH; }
-};
-
-class SnoopLoggerModuleTest : public Test {
-public:
- TestModuleRegistry* test_registry;
+ os::Thread* thread_;
+ os::Handler* handler_;
protected:
void SetUp() override {
+ thread_ = new os::Thread("test_thread", bluetooth::os::Thread::Priority::NORMAL);
+ handler_ = new os::Handler(thread_);
+
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
@@ -144,28 +121,30 @@ protected:
temp_snoop_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.last");
temp_snooz_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log");
temp_snooz_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log.last");
- temp_snoop_log_filtered =
+ temp_snoop_log_filtered_ =
temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered");
- temp_snoop_log_filtered_last =
+ temp_snoop_log_filtered_last_ =
temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered.last");
DeleteSnoopLogFiles();
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_last_));
- ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_filtered));
- ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_filtered_last));
+ ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_filtered_));
+ ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_filtered_last_));
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_last_));
-
- test_registry = new TestModuleRegistry();
}
void TearDown() override {
+ handler_->Clear();
+ handler_->WaitUntilStopped(200ms);
+ thread_->Stop();
+ delete handler_;
+ delete thread_;
+
com::android::bluetooth::flags::provider_->reset_flags();
DeleteSnoopLogFiles();
fake_timerfd_reset();
- test_registry->StopAll();
- delete test_registry;
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
@@ -173,14 +152,25 @@ protected:
test_info->test_suite_name());
}
+ static uint32_t GetL2capHeaderSize() { return SnoopLogger::L2CAP_HEADER_SIZE; }
+ static size_t GetMaxFilteredSize() {
+ return SnoopLogger::MAX_HCI_ACL_LEN - SnoopLogger::PACKET_TYPE_LENGTH;
+ }
+
+ SnoopLogger* NewSnoopLogger(size_t max_packets_per_file, const std::string& btsnoop_mode,
+ bool qualcomm_debug_log_enabled, bool snoop_log_persists) {
+ return new SnoopLogger(handler_, temp_snoop_log_.string(), temp_snooz_log_.string(),
+ max_packets_per_file, SnoopLogger::GetMaxPacketsPerBuffer(),
+ btsnoop_mode, qualcomm_debug_log_enabled, 20ms, 5ms, snoop_log_persists);
+ }
+
std::filesystem::path temp_snoop_log_;
std::filesystem::path temp_snoop_log_last_;
std::filesystem::path temp_snooz_log_;
std::filesystem::path temp_snooz_log_last_;
- std::filesystem::path temp_snoop_log_filtered;
- std::filesystem::path temp_snoop_log_filtered_last;
+ std::filesystem::path temp_snoop_log_filtered_;
+ std::filesystem::path temp_snoop_log_filtered_last_;
-private:
void DeleteSnoopLogFiles() {
if (std::filesystem::exists(temp_snoop_log_)) {
ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_));
@@ -188,11 +178,11 @@ private:
if (std::filesystem::exists(temp_snoop_log_last_)) {
ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_last_));
}
- if (std::filesystem::exists(temp_snoop_log_filtered)) {
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ if (std::filesystem::exists(temp_snoop_log_filtered_)) {
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
- if (std::filesystem::exists(temp_snoop_log_filtered_last)) {
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_last));
+ if (std::filesystem::exists(temp_snoop_log_filtered_last_)) {
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_last_));
}
if (std::filesystem::exists(temp_snooz_log_)) {
ASSERT_TRUE(std::filesystem::remove(temp_snooz_log_));
@@ -203,13 +193,11 @@ private:
}
};
-TEST_F(SnoopLoggerModuleTest, empty_snoop_log_test) {
+TEST_F(SnoopLoggerTest, empty_snoop_log_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
- test_registry->StopAll();
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_));
@@ -217,13 +205,11 @@ TEST_F(SnoopLoggerModuleTest, empty_snoop_log_test) {
ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_), sizeof(SnoopLoggerCommon::FileHeaderType));
}
-TEST_F(SnoopLoggerModuleTest, disable_snoop_log_test) {
+TEST_F(SnoopLoggerTest, disable_snoop_log_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
- test_registry->StopAll();
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -231,17 +217,13 @@ TEST_F(SnoopLoggerModuleTest, disable_snoop_log_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, capture_one_packet_test) {
+TEST_F(SnoopLoggerTest, capture_one_packet_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
-
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_));
@@ -251,13 +233,10 @@ TEST_F(SnoopLoggerModuleTest, capture_one_packet_test) {
kInformationRequest.size());
}
-TEST_F(SnoopLoggerModuleTest, capture_hci_cmd_btsnooz_test) {
+TEST_F(SnoopLoggerTest, capture_hci_cmd_btsnooz_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
snoop_logger->DumpSnoozLogToFile();
@@ -266,8 +245,7 @@ TEST_F(SnoopLoggerModuleTest, capture_hci_cmd_btsnooz_test) {
ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kInformationRequest.size());
-
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -275,13 +253,10 @@ TEST_F(SnoopLoggerModuleTest, capture_hci_cmd_btsnooz_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, capture_l2cap_signal_packet_btsnooz_test) {
+TEST_F(SnoopLoggerTest, capture_l2cap_signal_packet_btsnooz_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kSdpConnectionRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -291,7 +266,7 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_signal_packet_btsnooz_test) {
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kSdpConnectionRequest.size());
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -299,13 +274,10 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_signal_packet_btsnooz_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, capture_l2cap_short_data_packet_btsnooz_test) {
+TEST_F(SnoopLoggerTest, capture_l2cap_short_data_packet_btsnooz_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kAvdtpSuspend, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -315,7 +287,7 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_short_data_packet_btsnooz_test) {
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kAvdtpSuspend.size());
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -323,13 +295,10 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_short_data_packet_btsnooz_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, capture_l2cap_long_data_packet_btsnooz_test) {
+TEST_F(SnoopLoggerTest, capture_l2cap_long_data_packet_btsnooz_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -338,7 +307,7 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_long_data_packet_btsnooz_test) {
ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14);
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -346,13 +315,10 @@ TEST_F(SnoopLoggerModuleTest, capture_l2cap_long_data_packet_btsnooz_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, snoop_log_persists) {
+TEST_F(SnoopLoggerTest, snoop_log_persists) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, true);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
-
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, true);
+ snoop_logger->Start();
snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -361,7 +327,7 @@ TEST_F(SnoopLoggerModuleTest, snoop_log_persists) {
ASSERT_EQ(std::filesystem::file_size(temp_snooz_log_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14);
- test_registry->StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_));
}
@@ -374,44 +340,39 @@ static void sync_handler(bluetooth::os::Handler* handler) {
ASSERT_EQ(future_status, std::future_status::ready);
}
-TEST_F(SnoopLoggerModuleTest, delete_old_snooz_log_files) {
+TEST_F(SnoopLoggerTest, delete_old_snooz_log_files) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
std::filesystem::create_directories(temp_snooz_log_.parent_path());
os::WriteToFile(temp_snooz_log_.string(), "");
- auto* handler = test_registry->GetTestModuleHandler(&SnoopLogger::Factory);
ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_));
- handler->Post(bluetooth::common::BindOnce(fake_timerfd_advance, 10));
+ handler_->Post(bluetooth::common::BindOnce(fake_timerfd_advance, 10));
ASSERT_TRUE(std::filesystem::exists(temp_snooz_log_));
- handler->Post(bluetooth::common::BindOnce(fake_timerfd_advance, 15));
- sync_handler(handler);
- handler->Post(bluetooth::common::BindOnce(
+ handler_->Post(bluetooth::common::BindOnce(fake_timerfd_advance, 15));
+ sync_handler(handler_);
+ handler_->Post(bluetooth::common::BindOnce(
[](std::filesystem::path path) {
log::info("path: {}", path.string());
ASSERT_FALSE(std::filesystem::exists(path));
},
temp_snooz_log_));
- sync_handler(handler);
+ sync_handler(handler_);
- test_registry->StopAll();
+ snoop_logger->Stop();
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, rotate_file_at_new_session_test) {
+TEST_F(SnoopLoggerTest, rotate_file_at_new_session_test) {
// Start once
{
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
// Verify states after test
@@ -423,15 +384,13 @@ TEST_F(SnoopLoggerModuleTest, rotate_file_at_new_session_test) {
// Start again
{
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
// Verify states after test
@@ -445,19 +404,17 @@ TEST_F(SnoopLoggerModuleTest, rotate_file_at_new_session_test) {
kInformationRequest.size());
}
-TEST_F(SnoopLoggerModuleTest, rotate_file_after_full_test) {
+TEST_F(SnoopLoggerTest, rotate_file_after_full_test) {
// Actual test
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
for (int i = 0; i < 11; i++) {
snoop_logger->Capture(kInformationRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::CMD);
}
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_));
@@ -470,11 +427,9 @@ TEST_F(SnoopLoggerModuleTest, rotate_file_after_full_test) {
(sizeof(SnoopLogger::PacketHeaderType) + kInformationRequest.size()) * 10);
}
-TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_test) {
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+TEST_F(SnoopLoggerTest, qualcomm_debug_log_test) {
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, true, false);
+ snoop_logger->Start();
snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -484,7 +439,7 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_test) {
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kQualcommConnectionRequest.size());
- test_registry->StopAll();
+ snoop_logger->Stop();
// Verify states after test
ASSERT_FALSE(std::filesystem::exists(temp_snoop_log_));
@@ -492,12 +447,10 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) {
+TEST_F(SnoopLoggerTest, qualcomm_debug_log_regression_test) {
{
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, true, false);
+ snoop_logger->Start();
snoop_logger->Capture(kHfpAtNrec0, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -506,7 +459,7 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) {
ASSERT_EQ(
std::filesystem::file_size(temp_snooz_log_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
// Verify states after test
@@ -515,10 +468,8 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
{
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, false, false);
+ snoop_logger->Start();
snoop_logger->Capture(kQualcommConnectionRequest, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
snoop_logger->DumpSnoozLogToFile();
@@ -527,7 +478,7 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) {
ASSERT_EQ(
std::filesystem::file_size(temp_snooz_log_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) + 14);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
// Verify states after test
@@ -536,7 +487,7 @@ TEST_F(SnoopLoggerModuleTest, qualcomm_debug_log_regression_test) {
ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, filter_tracker_test) {
+TEST_F(SnoopLoggerTest, filter_tracker_test) {
std::unordered_map<uint16_t, bluetooth::hal::FilterTracker> filter_list;
uint16_t handle = 1;
uint16_t local_cid = 0x40;
@@ -564,7 +515,7 @@ TEST_F(SnoopLoggerModuleTest, filter_tracker_test) {
ASSERT_FALSE(filter_list[handle].IsAcceptlistedDlci(dlci));
}
-TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_test) {
+TEST_F(SnoopLoggerTest, a2dp_packets_filtered_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0001;
@@ -576,12 +527,8 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_test) {
bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty);
ASSERT_TRUE(filter_a2dp_property && filter_a2dp_property.value() == "true");
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
// Simulate A2dp Media channel setup
snoop_logger->AddA2dpMediaChannel(conn_handle, local_cid, remote_cid);
@@ -589,22 +536,22 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_test) {
snoop_logger->Capture(kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Should filter packet
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType));
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_negative_test) {
+TEST_F(SnoopLoggerTest, a2dp_packets_filtered_negative_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0001;
@@ -616,12 +563,9 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_negative_test) {
bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty);
ASSERT_TRUE(filter_a2dp_property && filter_a2dp_property.value() == "true");
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
// Simulate A2dp Media channel setup
snoop_logger->AddA2dpMediaChannel(conn_handle, local_cid, remote_cid);
@@ -630,35 +574,32 @@ TEST_F(SnoopLoggerModuleTest, a2dp_packets_filtered_negative_test) {
snoop_logger->Capture(kA2dpMediaPacket, SnoopLogger::Direction::OUTGOING,
SnoopLogger::PacketType::ACL);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileA2dpProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Should not filter
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kA2dpMediaPacket.size());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, headers_filtered_test) {
+TEST_F(SnoopLoggerTest, headers_filtered_test) {
ASSERT_TRUE(
bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "true"));
auto filter_headers_property =
bluetooth::os::GetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty);
ASSERT_TRUE(filter_headers_property && filter_headers_property.value() == "true");
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
std::vector<uint8_t> kAclPacket = {
0x0b, 0x20, 0x18, 0x00, 0x14, 0x00, 0x44, 0x00, 0x1b, 0x2f, 0x21, 0x41, 0x54, 0x2b,
@@ -667,28 +608,27 @@ TEST_F(SnoopLoggerModuleTest, headers_filtered_test) {
snoop_logger->Capture(kAclPacket, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(
bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterHeadersProperty, "false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
log::info("const size: {}", (int)(sizeof(SnoopLoggerCommon::FileHeaderType) +
sizeof(SnoopLogger::PacketHeaderType)));
// Packet should be filtered
- const size_t file_size = (size_t)std::filesystem::file_size(temp_snoop_log_filtered);
+ const size_t file_size = (size_t)std::filesystem::file_size(temp_snoop_log_filtered_);
const size_t expected_file_size = sizeof(SnoopLoggerCommon::FileHeaderType) +
- sizeof(SnoopLogger::PacketHeaderType) +
- TestSnoopLoggerModule::GetMaxFilteredSize();
+ sizeof(SnoopLogger::PacketHeaderType) + GetMaxFilteredSize();
ASSERT_EQ(file_size, expected_file_size);
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) {
+TEST_F(SnoopLoggerTest, rfcomm_channel_filtered_sabme_ua_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0044;
@@ -701,12 +641,9 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) {
ASSERT_TRUE(filter_rfcomm_property);
ASSERT_EQ("true", filter_rfcomm_property.value());
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
// Simulate Rfcomm channel
snoop_logger->AddRfcommL2capChannel(conn_handle, local_cid, remote_cid);
@@ -723,24 +660,24 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_sabme_ua_test) {
SnoopLogger::PacketType::ACL);
snoop_logger->Capture(kRfcommUa, SnoopLogger::Direction::INCOMING, SnoopLogger::PacketType::ACL);
snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packets should not be filtered because because they are SAMBE and UA events.
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + 2 * sizeof(SnoopLogger::PacketHeaderType) +
kRfcommSabme.size() + kRfcommUa.size());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) {
+TEST_F(SnoopLoggerTest, rfcomm_channel_filtered_acceptlisted_dlci_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0041;
@@ -755,12 +692,9 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) {
ASSERT_TRUE(filter_rfcomm_property);
ASSERT_EQ("true", filter_rfcomm_property.value());
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
// Simulate Rfcomm channel
snoop_logger->AddRfcommL2capChannel(conn_handle, local_cid, remote_cid);
@@ -774,24 +708,24 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_dlci_test) {
snoop_logger->Capture(kRfcommDlci, SnoopLogger::Direction::INCOMING,
SnoopLogger::PacketType::ACL);
snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packet should not be filtered because DLCI acceptlisted
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kRfcommDlci.size());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test) {
+TEST_F(SnoopLoggerTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0041;
@@ -806,12 +740,9 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test
ASSERT_TRUE(filter_rfcomm_property);
ASSERT_EQ("true", filter_rfcomm_property.value());
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
// Simulate Rfcomm channel
snoop_logger->AddRfcommL2capChannel(conn_handle, local_cid, remote_cid);
@@ -825,24 +756,24 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_dlci_test
SnoopLogger::PacketType::ACL);
snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packet should be filtered because DLCI not acceptlisted
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
- TestSnoopLoggerModule::GetL2capHeaderSize());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ GetL2capHeaderSize());
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_channel_test) {
+TEST_F(SnoopLoggerTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_channel_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0041;
@@ -855,12 +786,9 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_cha
ASSERT_TRUE(filter_rfcomm_property);
ASSERT_EQ("true", filter_rfcomm_property.value());
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
std::vector<uint8_t> kRfcommL2capChannel = {
0x0b, 0x20, 0x12, 0x00, 0x0e, 0x00, 0x41, 0x00, 0x00, 0xef, 0x15,
@@ -871,24 +799,24 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_not_acceptlisted_l2cap_cha
SnoopLogger::PacketType::ACL);
snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packet should be filtered because L2CAP channel not acceptlisted
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
- TestSnoopLoggerModule::GetL2capHeaderSize());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ GetL2capHeaderSize());
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel_test) {
+TEST_F(SnoopLoggerTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0041;
@@ -901,13 +829,9 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel
ASSERT_TRUE(filter_rfcomm_property);
ASSERT_EQ("true", filter_rfcomm_property.value());
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
snoop_logger->AcceptlistL2capChannel(conn_handle, local_cid, remote_cid);
std::vector<uint8_t> kRfcommL2capChannel = {
@@ -919,24 +843,24 @@ TEST_F(SnoopLoggerModuleTest, rfcomm_channel_filtered_acceptlisted_l2cap_channel
SnoopLogger::PacketType::ACL);
snoop_logger->ClearL2capAcceptlist(conn_handle, local_cid, remote_cid);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileRfcommProperty,
"false"));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packet should not be filtered because L2CAP channel acceptlisted
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
kRfcommL2capChannel.size());
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) {
+TEST_F(SnoopLoggerTest, profiles_filtered_hfp_hf_test) {
// Actual test
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0043;
@@ -966,13 +890,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) {
(filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) !=
std::string::npos));
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
snoop_logger->SetL2capChannelOpen(conn_handle, local_cid, remote_cid, psm, false);
snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_hfp_hf, flow);
@@ -988,9 +908,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) {
snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid);
snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_hfp_hf);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty,
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
@@ -999,16 +919,16 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_hfp_hf_test) {
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packet should be filtered
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) + sizeof(SnoopLogger::PacketHeaderType) +
HEADER_SIZE + strlen(clcc_pattern.c_str()));
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) {
+TEST_F(SnoopLoggerTest, profiles_filtered_pbap_magic_test) {
// Actual test
constexpr uint16_t PROFILE_PSM_PBAP = 0x1025;
constexpr uint16_t PROFILE_UUID_PBAP = 0x112f;
@@ -1039,13 +959,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) {
(filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) !=
std::string::npos));
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(15, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
snoop_logger->SetL2capChannelOpen(conn_handle, local_cid, remote_cid, psm, false);
snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow);
@@ -1057,9 +973,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) {
snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid);
snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_pbap);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty,
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
@@ -1068,18 +984,18 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_magic_test) {
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packets should be filtered
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) +
(int)kTestData.size() * (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE +
strlen(magic_string.c_str())));
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) {
+TEST_F(SnoopLoggerTest, profiles_filtered_pbap_header_test) {
// Actual test
constexpr uint16_t PROFILE_PSM_PBAP = 0x1025;
constexpr uint16_t PROFILE_UUID_PBAP = 0x112f;
@@ -1109,13 +1025,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) {
(filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeHeader) !=
std::string::npos));
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(15, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
snoop_logger->SetL2capChannelOpen(conn_handle, local_cid, remote_cid, psm, false);
snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow);
@@ -1127,9 +1039,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) {
snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid);
snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_pbap);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty,
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
@@ -1138,17 +1050,17 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_header_test) {
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packets should be filtered
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType) +
(int)kTestData.size() * (sizeof(SnoopLogger::PacketHeaderType) + HEADER_SIZE));
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
-TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) {
+TEST_F(SnoopLoggerTest, profiles_filtered_pbap_fullfilter_test) {
// Actual test
constexpr uint16_t PROFILE_PSM_PBAP = 0x1025;
constexpr uint16_t PROFILE_UUID_PBAP = 0x112f;
@@ -1178,13 +1090,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) {
(filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeFullfillter) !=
std::string::npos));
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 15,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
-
- TestModuleRegistry test_registry;
- test_registry.InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(15, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
snoop_logger->SetL2capChannelOpen(conn_handle, local_cid, remote_cid, psm, false);
snoop_logger->SetRfcommPortOpen(conn_handle, local_cid, dlci, profile_uuid_pbap, flow);
@@ -1196,9 +1104,9 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) {
snoop_logger->SetL2capChannelClose(conn_handle, local_cid, remote_cid);
snoop_logger->SetRfcommPortClose(conn_handle, local_cid, dlci, profile_uuid_pbap);
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
- test_registry.StopAll();
+ snoop_logger->Stop();
ASSERT_TRUE(bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfileMapModeProperty,
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
@@ -1207,22 +1115,20 @@ TEST_F(SnoopLoggerModuleTest, profiles_filtered_pbap_fullfilter_test) {
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
// Verify states after test
- ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
// Packets should be filtered
- ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered),
+ ASSERT_EQ(std::filesystem::file_size(temp_snoop_log_filtered_),
sizeof(SnoopLoggerCommon::FileHeaderType));
- ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered));
+ ASSERT_TRUE(std::filesystem::remove(temp_snoop_log_filtered_));
}
static constexpr int INVALID_FD = -1;
-TEST_F(SnoopLoggerModuleTest, socket_disabled_connect_fail_test) {
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+TEST_F(SnoopLoggerTest, socket_disabled_connect_fail_test) {
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, true, false);
+ snoop_logger->Start();
// // Create a TCP socket file descriptor
int socket_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
@@ -1239,15 +1145,14 @@ TEST_F(SnoopLoggerModuleTest, socket_disabled_connect_fail_test) {
RUN_NO_INTR(ret = connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr)));
ASSERT_NE(0, ret);
- test_registry->StopAll();
+ snoop_logger->Stop();
close(socket_fd);
}
-TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) {
+TEST_F(SnoopLoggerTest, default_socket_enabled_capture_recv_test) {
int ret;
- auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(),
- 10, SnoopLogger::kBtSnoopLogModeFull, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, true, false);
+ snoop_logger->Start();
// // Create a TCP socket file descriptor
int socket_fd = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
@@ -1285,14 +1190,13 @@ TEST_F(SnoopLoggerModuleTest, default_socket_enabled_capture_recv_test) {
ASSERT_EQ(bytes_read, static_cast<int>(kHfpAtNrec0.size()));
ASSERT_EQ(0, std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()));
- test_registry->StopAll();
+ snoop_logger->Stop();
close(socket_fd);
}
-TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test) {
- auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(),
- 10, SnoopLogger::kBtSnoopLogModeFull, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+TEST_F(SnoopLoggerTest, custom_socket_register_enabled_capture_recv_test) {
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, true, false);
+ snoop_logger->Start();
int new_port = 8873;
SyscallWrapperImpl syscall_if;
@@ -1342,15 +1246,13 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_register_enabled_capture_recv_test)
ASSERT_EQ(bytes_read, static_cast<int>(kHfpAtNrec0.size()));
ASSERT_EQ(0, std::memcmp(recv_buf3, kHfpAtNrec0.data(), kHfpAtNrec0.size()));
- test_registry->StopAll();
+ snoop_logger->Stop();
close(socket_fd);
}
-TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_disabled_test) {
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeDisabled, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+TEST_F(SnoopLoggerTest, custom_socket_interface_register_logging_disabled_test) {
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeDisabled, true, false);
+ snoop_logger->Start();
class SnoopLoggerSocketMock : public SnoopLoggerSocketInterface {
public:
@@ -1367,13 +1269,12 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_disabled_
ASSERT_FALSE(mock.write_called);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
-TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_enabled_test) {
- auto* snoop_logger = new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(),
- 10, SnoopLogger::kBtSnoopLogModeFull, true, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+TEST_F(SnoopLoggerTest, custom_socket_interface_register_logging_enabled_test) {
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, true, false);
+ snoop_logger->Start();
class SnoopLoggerSocketMock : public SnoopLoggerSocketInterface {
public:
@@ -1390,10 +1291,10 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_interface_register_logging_enabled_t
ASSERT_TRUE(mock.write_called);
- test_registry->StopAll();
+ snoop_logger->Stop();
}
-TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) {
+TEST_F(SnoopLoggerTest, custom_socket_profiles_filtered_hfp_hf_test) {
uint16_t conn_handle = 0x000b;
uint16_t local_cid = 0x0043;
uint16_t remote_cid = 0x3040;
@@ -1439,11 +1340,9 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) {
(filterMapModeProperty->find(SnoopLogger::kBtSnoopLogFilterProfileModeMagic) !=
std::string::npos));
- auto* snoop_logger =
- new TestSnoopLoggerModule(temp_snoop_log_.string(), temp_snooz_log_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ snoop_logger->Start();
int new_port = 8873;
SyscallWrapperImpl syscall_if;
@@ -1504,95 +1403,75 @@ TEST_F(SnoopLoggerModuleTest, custom_socket_profiles_filtered_hfp_hf_test) {
bluetooth::os::SetSystemProperty(SnoopLogger::kBtSnoopLogFilterProfilePbapModeProperty,
SnoopLogger::kBtSnoopLogFilterProfileModeDisabled));
- test_registry->StopAll();
+ snoop_logger->Stop();
close(socket_fd);
}
#ifdef __ANDROID__
-TEST_F(SnoopLoggerModuleTest, recreate_log_directory_when_enabled_test) {
+TEST_F(SnoopLoggerTest, recreate_log_directory_when_enabled_test) {
com::android::bluetooth::flags::provider_->snoop_logger_recreate_logs_directory(true);
- // Actual test
const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info();
- const std::filesystem::path os_btsnoop_file_path_ = os::ParameterProvider::SnoopLogFilePath();
- std::filesystem::path temp_dir_path_ = os_btsnoop_file_path_.parent_path();
-
- const std::filesystem::path temp_log_btsnoop_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnoop_hci.log");
- const std::filesystem::path temp_log_btsnooz_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnooz_hci.log");
+ const std::filesystem::path file_path = os::ParameterProvider::SnoopLogFilePath();
+ const std::filesystem::path temp_dir_ = file_path.parent_path();
- if (std::filesystem::exists(temp_dir_path_)) {
- std::filesystem::remove_all(temp_dir_path_);
- }
+ // Override the paths used for the test. The feature tested here relies on the actual
+ // snoop path on Android to work.
+ temp_snoop_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log");
+ temp_snoop_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.last");
+ temp_snooz_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log");
+ temp_snooz_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log.last");
+ temp_snoop_log_filtered_ =
+ temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered");
+ temp_snoop_log_filtered_last_ =
+ temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered.last");
+ DeleteSnoopLogFiles();
+ std::filesystem::remove_all(temp_dir_);
- ASSERT_FALSE(std::filesystem::exists(temp_dir_path_));
+ ASSERT_FALSE(std::filesystem::exists(temp_dir_));
- auto* snoop_logger = new TestSnoopLoggerModule(temp_log_btsnoop_file_.string(),
- temp_log_btsnooz_file_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFull, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFull, false, false);
+ snoop_logger->Start();
- ASSERT_TRUE(std::filesystem::exists(temp_dir_path_));
+ ASSERT_TRUE(std::filesystem::exists(temp_dir_));
- test_registry->StopAll();
+ snoop_logger->Stop();
- // btsnoop file should exist
- ASSERT_TRUE(std::filesystem::exists(temp_log_btsnoop_file_));
- // btsnooz file should be removed as snoop_log_persists is false
- ASSERT_FALSE(std::filesystem::exists(temp_log_btsnooz_file_));
- // remove temp_dir_path_ contents after test
- if (std::filesystem::exists(temp_dir_path_)) {
- for (const auto& entry : std::filesystem::directory_iterator(temp_dir_path_)) {
- std::filesystem::remove_all(entry.path());
- }
- }
- ASSERT_TRUE(std::filesystem::exists(temp_dir_path_));
+ // btsnoop file should exist, but btsnooz should be removed as snoop_log_persist is false.
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_));
+ ASSERT_FALSE(std::filesystem::exists(temp_snooz_log_));
}
-TEST_F(SnoopLoggerModuleTest, recreate_log_directory_when_filtered_test) {
+TEST_F(SnoopLoggerTest, recreate_log_directory_when_filtered_test) {
com::android::bluetooth::flags::provider_->snoop_logger_recreate_logs_directory(true);
- // Actual test
const testing::TestInfo* const test_info = testing::UnitTest::GetInstance()->current_test_info();
- const std::filesystem::path os_btsnoop_file_path_ = os::ParameterProvider::SnoopLogFilePath();
- std::filesystem::path temp_dir_path_ = os_btsnoop_file_path_.parent_path();
+ const std::filesystem::path file_path = os::ParameterProvider::SnoopLogFilePath();
+ const std::filesystem::path temp_dir_ = file_path.parent_path();
- const std::filesystem::path temp_log_btsnoop_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnoop_hci.log");
- const std::filesystem::path temp_log_btsnooz_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnooz_hci.log");
+ // Override the paths used for the test. The feature tested here relies on the actual
+ // snoop path on Android to work.
+ temp_snoop_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log");
+ temp_snoop_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.last");
+ temp_snooz_log_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log");
+ temp_snooz_log_last_ = temp_dir_ / (std::string(test_info->name()) + "_btsnooz_hci.log.last");
+ temp_snoop_log_filtered_ =
+ temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered");
+ temp_snoop_log_filtered_last_ =
+ temp_dir_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered.last");
+ DeleteSnoopLogFiles();
+ std::filesystem::remove_all(temp_dir_);
- if (std::filesystem::exists(temp_dir_path_)) {
- std::filesystem::remove_all(temp_dir_path_);
- }
-
- ASSERT_FALSE(std::filesystem::exists(temp_dir_path_));
-
- auto* snoop_logger = new TestSnoopLoggerModule(
- temp_log_btsnoop_file_.string(), temp_log_btsnooz_file_.string(), 10,
- SnoopLogger::kBtSnoopLogModeFiltered, false, false);
- test_registry->InjectTestModule(&SnoopLogger::Factory, snoop_logger);
+ ASSERT_FALSE(std::filesystem::exists(temp_dir_));
- ASSERT_TRUE(std::filesystem::exists(temp_dir_path_));
+ auto* snoop_logger = NewSnoopLogger(10, SnoopLogger::kBtSnoopLogModeFiltered, false, false);
+ snoop_logger->Start();
- test_registry->StopAll();
+ ASSERT_TRUE(std::filesystem::exists(temp_dir_));
- const std::filesystem::path temp_log_btsnoop_filtered_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnoop_hci.log.filtered");
- const std::filesystem::path temp_log_btsnooz_filtered_file_ =
- temp_dir_path_ / (std::string(test_info->name()) + "_btsnooz_hci.log.filtered");
+ snoop_logger->Stop();
- // btsnoop file should exist
- ASSERT_TRUE(std::filesystem::exists(temp_log_btsnoop_filtered_file_));
- // btsnooz file should be removed as snoop_log_persists is false
- ASSERT_FALSE(std::filesystem::exists(temp_log_btsnooz_filtered_file_));
- // remove temp_dir_path_ contents after test
- if (std::filesystem::exists(temp_dir_path_)) {
- for (const auto& entry : std::filesystem::directory_iterator(temp_dir_path_)) {
- std::filesystem::remove_all(entry.path());
- }
- }
- ASSERT_TRUE(std::filesystem::exists(temp_dir_path_));
+ // btsnoop file should exist.
+ ASSERT_TRUE(std::filesystem::exists(temp_snoop_log_filtered_));
}
#endif // __ANDROID__
-} // namespace testing
+} // namespace bluetooth::hal
diff --git a/system/gd/hal/socket_hal_android.cc b/system/gd/hal/socket_hal_android.cc
index 4974efb0cf..bdbf0a8663 100644
--- a/system/gd/hal/socket_hal_android.cc
+++ b/system/gd/hal/socket_hal_android.cc
@@ -61,7 +61,8 @@ public:
::ndk::ScopedAStatus openedComplete(int64_t socket_id,
::aidl::android::hardware::bluetooth::socket::Status status,
const std::string& reason) override {
- log::info("socket_id: {} status: {} reason: {}", socket_id, static_cast<int>(status), reason);
+ log::info("socket_id: {} status: {} reason: {}", static_cast<uint64_t>(socket_id),
+ static_cast<int>(status), reason);
socket_hal_cb_->SocketOpenedComplete(
socket_id, status == ::aidl::android::hardware::bluetooth::socket::Status::SUCCESS
? hal::SocketStatus::SUCCESS
@@ -70,7 +71,7 @@ public:
}
::ndk::ScopedAStatus close(int64_t socket_id, const std::string& reason) override {
- log::info("socket_id: {} reason: {}", socket_id, reason);
+ log::info("socket_id: {} reason: {}", static_cast<uint64_t>(socket_id), reason);
socket_hal_cb_->SocketClose(socket_id);
return ::ndk::ScopedAStatus::ok();
}
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.cc b/system/gd/hci/acl_manager.cc
index 40e38c9c68..6da8b37a6d 100644
--- a/system/gd/hci/acl_manager.cc
+++ b/system/gd/hci/acl_manager.cc
@@ -373,6 +373,10 @@ void AclManager::SetSystemSuspendState(bool suspended) {
CallOn(pimpl_->le_impl_, &le_impl::set_system_suspend_state, suspended);
}
+void AclManager::AddDeviceToRelaxedConnectionIntervalList(const Address address) {
+ CallOn(pimpl_->le_impl_, &le_impl::add_device_to_relaxed_connection_interval_list, address);
+}
+
LeAddressManager* AclManager::GetLeAddressManager() {
return pimpl_->le_impl_->le_address_manager_;
}
diff --git a/system/gd/hci/acl_manager.h b/system/gd/hci/acl_manager.h
index 5c2960a322..8326d479ab 100644
--- a/system/gd/hci/acl_manager.h
+++ b/system/gd/hci/acl_manager.h
@@ -136,6 +136,7 @@ public:
virtual void OnClassicSuspendInitiatedDisconnect(uint16_t handle, ErrorCode reason);
virtual void OnLeSuspendInitiatedDisconnect(uint16_t handle, ErrorCode reason);
virtual void SetSystemSuspendState(bool suspended);
+ virtual void AddDeviceToRelaxedConnectionIntervalList(const Address address);
static const ModuleFactory Factory;
diff --git a/system/gd/hci/acl_manager/le_impl.h b/system/gd/hci/acl_manager/le_impl.h
index 505aca6cb1..ac3e7171f9 100644
--- a/system/gd/hci/acl_manager/le_impl.h
+++ b/system/gd/hci/acl_manager/le_impl.h
@@ -871,16 +871,37 @@ public:
uint16_t conn_interval_min;
uint16_t conn_interval_max;
+ bool prefer_relaxed_connection_interval = false;
+ if (com::android::bluetooth::flags::channel_sounding_in_stack()) {
+ for (const auto& address_with_type : direct_connections_) {
+ bluetooth::hci::Address address = address_with_type.GetAddress();
+ if (relaxed_connection_interval_devices_set_.count(address) > 0) {
+ log::info(
+ "Found device {} in direct connection list that prefers using the relaxed "
+ "connection interval",
+ address);
+ prefer_relaxed_connection_interval = true;
+ break;
+ }
+ }
+ }
if (com::android::bluetooth::flags::initial_conn_params_p1()) {
- size_t num_classic_acl_connections = classic_impl_->get_connection_count();
- size_t num_acl_connections = connections.size();
+ if (prefer_relaxed_connection_interval) {
+ conn_interval_min = LeConnectionParameters::GetMinConnIntervalRelaxed();
+ conn_interval_max = LeConnectionParameters::GetMaxConnIntervalRelaxed();
+ log::debug("conn_interval_min={}, conn_interval_max={}", conn_interval_min,
+ conn_interval_max);
+ } else {
+ size_t num_classic_acl_connections = classic_impl_->get_connection_count();
+ size_t num_acl_connections = connections.size();
- log::debug("ACL connection count: Classic={}, LE={}", num_classic_acl_connections,
- num_acl_connections);
+ log::debug("ACL connection count: Classic={}, LE={}", num_classic_acl_connections,
+ num_acl_connections);
- choose_connection_mode(num_classic_acl_connections + num_acl_connections, &conn_interval_min,
- &conn_interval_max);
+ choose_connection_mode(num_classic_acl_connections + num_acl_connections,
+ &conn_interval_min, &conn_interval_max);
+ }
} else {
conn_interval_min = os::GetSystemPropertyUint32(kPropertyMinConnInterval, kConnIntervalMin);
conn_interval_max = os::GetSystemPropertyUint32(kPropertyMaxConnInterval, kConnIntervalMax);
@@ -1301,6 +1322,10 @@ public:
void set_system_suspend_state(bool suspended) { system_suspend_ = suspended; }
+ void add_device_to_relaxed_connection_interval_list(const Address address) {
+ relaxed_connection_interval_devices_set_.insert(address);
+ }
+
HciLayer* hci_layer_ = nullptr;
Controller* controller_ = nullptr;
os::Handler* handler_ = nullptr;
@@ -1327,6 +1352,8 @@ public:
bool system_suspend_ = false;
ConnectabilityState connectability_state_{ConnectabilityState::DISARMED};
std::map<AddressWithType, os::Alarm> create_connection_timeout_alarms_{};
+ // Set of devices that should use the relaxed connection intervals.
+ std::unordered_set<Address> relaxed_connection_interval_devices_set_;
};
} // namespace acl_manager
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/distance_measurement_manager.cc b/system/gd/hci/distance_measurement_manager.cc
index 885f0b3bf1..d9b9200552 100644
--- a/system/gd/hci/distance_measurement_manager.cc
+++ b/system/gd/hci/distance_measurement_manager.cc
@@ -86,6 +86,7 @@ static constexpr uint16_t kDefaultRasMtu = 247; // Section 3.1.2 of RAP 1.0
static constexpr uint8_t kAttHeaderSize = 5; // Section 3.2.2.1 of RAS 1.0
static constexpr uint8_t kRasSegmentHeaderSize = 1;
static constexpr uint16_t kEnableSecurityTimeoutMs = 10000; // 10s
+static constexpr uint16_t kProcedureScheduleGuardMs = 1000; // 1s
struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
struct CsProcedureData {
@@ -187,6 +188,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
Address address;
hci::Role local_hci_role = hci::Role::CENTRAL;
uint16_t procedure_counter = 0;
+ uint16_t procedure_counting_after_enable = 0;
CsRole role = CsRole::INITIATOR;
bool local_start = false; // If the CS was started by the local device.
// TODO: clean up, replace the measurement_ongoing with STOPPED
@@ -212,7 +214,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
uint16_t interval_ms = kDefaultIntervalMs;
uint16_t max_procedure_count = 1;
bool waiting_for_start_callback = false;
- std::unique_ptr<os::RepeatingAlarm> repeating_alarm = nullptr;
+ std::unique_ptr<os::Alarm> procedure_schedule_guard_alarm = nullptr;
// RAS data
RangingHeader ranging_header_;
PacketViewForRecombination segment_data_;
@@ -389,7 +391,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
}
bool init_cs_requester_tracker(const Address& cs_remote_address, uint16_t connection_handle,
- hci::Role local_hci_role, uint16_t interval,
+ hci::Role local_hci_role, uint16_t interval_ms,
bool* has_updated_procedure_params) {
*has_updated_procedure_params = false;
auto it = cs_requester_trackers_.find(connection_handle);
@@ -415,24 +417,22 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
}
}
// make sure the repeating_alarm is initialized.
- if (it->second.repeating_alarm == nullptr) {
- it->second.repeating_alarm = std::make_unique<os::RepeatingAlarm>(handler_);
+ if (it->second.procedure_schedule_guard_alarm == nullptr) {
+ it->second.procedure_schedule_guard_alarm = std::make_unique<os::Alarm>(handler_);
}
it->second.state = CsTrackerState::INIT;
- // If the interval is less than 1 second, update it to 1 second and increase the
- // max_procedure_count
- uint16_t max_procedure_count = 1;
- if (interval < 1000) {
- max_procedure_count = 1000 / interval;
- interval = 1000;
- }
- if (max_procedure_count != it->second.max_procedure_count) {
- log::info("Update interval to 1s and max_procedure_count to {}", max_procedure_count);
+
+ if (interval_ms != it->second.interval_ms) {
+ log::info("Update interval to {}", interval_ms);
+ uint16_t max_procedure_count = 1;
+ if (interval_ms < 1000) {
+ max_procedure_count = 5;
+ }
it->second.max_procedure_count = max_procedure_count;
*has_updated_procedure_params = true;
}
- it->second.interval_ms = interval;
+ it->second.interval_ms = interval_ms;
it->second.local_start = true;
it->second.measurement_ongoing = true;
it->second.waiting_for_start_callback = true;
@@ -457,6 +457,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
}
if (!cs_requester_trackers_[connection_handle].setup_complete) {
+ acl_manager_->AddDeviceToRelaxedConnectionIntervalList(cs_remote_address);
send_le_cs_read_remote_supported_capabilities(connection_handle);
return;
}
@@ -465,19 +466,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
cs_requester_trackers_[connection_handle].requesting_config_id);
return;
}
- log::info("enable cs procedure regularly with interval: {} ms",
- cs_requester_trackers_[connection_handle].interval_ms);
- cs_requester_trackers_[connection_handle].repeating_alarm->Cancel();
+
+ cs_requester_trackers_[connection_handle].procedure_schedule_guard_alarm->Cancel();
if (has_updated_procedure_params) {
send_le_cs_set_procedure_parameters(
connection_handle, cs_requester_trackers_[connection_handle].used_config_id,
cs_requester_trackers_[connection_handle].remote_num_antennas_supported_);
} else {
send_le_cs_procedure_enable(connection_handle, Enable::ENABLED);
- cs_requester_trackers_[connection_handle].repeating_alarm->Schedule(
- common::Bind(&impl::send_le_cs_procedure_enable, common::Unretained(this),
- connection_handle, Enable::ENABLED),
- std::chrono::milliseconds(cs_requester_trackers_[connection_handle].interval_ms));
}
}
@@ -505,7 +501,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
if (it == cs_requester_trackers_.end()) {
log::warn("Can't find CS tracker for {}", address);
} else if (it->second.measurement_ongoing) {
- it->second.repeating_alarm->Cancel();
+ it->second.procedure_schedule_guard_alarm->Cancel();
send_le_cs_procedure_enable(connection_handle, Enable::DISABLED);
// does not depend on the 'disable' command result.
reset_tracker_on_stopped(it->second);
@@ -568,9 +564,9 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
log::info("address:{}", address);
for (auto it = cs_requester_trackers_.begin(); it != cs_requester_trackers_.end();) {
if (it->second.address == address) {
- if (it->second.repeating_alarm != nullptr) {
- it->second.repeating_alarm->Cancel();
- it->second.repeating_alarm.reset();
+ if (it->second.procedure_schedule_guard_alarm != nullptr) {
+ it->second.procedure_schedule_guard_alarm->Cancel();
+ it->second.procedure_schedule_guard_alarm.reset();
}
DistanceMeasurementErrorCode reason = REASON_NO_LE_CONNECTION;
if (ras_disconnect_reason == ras::RasDisconnectReason::SERVER_NOT_AVAILABLE) {
@@ -820,9 +816,21 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
(preferred_peer_antenna_value >> 2) & 0x01;
preferred_peer_antenna.use_fourth_ordered_antenna_element_ =
(preferred_peer_antenna_value >> 3) & 0x01;
+
+ // only change the min_procedure_interval, leave the flexibility to the controller
+ uint16_t min_procedure_interval = kMinProcedureInterval;
+ if (cs_requester_trackers_[connection_handle].max_procedure_count != 1 &&
+ cs_requester_trackers_[connection_handle].interval_ms > 100) {
+ // TODO(b/398253048): keep the burst mode for 'HIGH' for now. allow app to disable it.
+ uint16_t measurement_interval_ms = cs_requester_trackers_[connection_handle].interval_ms;
+ min_procedure_interval = static_cast<uint16_t>(
+ std::round((double)measurement_interval_ms /
+ cs_requester_trackers_[connection_handle].conn_interval_));
+ }
+ log::debug("procedure params: min_int = {}", min_procedure_interval);
hci_layer_->EnqueueCommand(
LeCsSetProcedureParametersBuilder::Create(
- connection_handle, config_id, kMaxProcedureLen, kMinProcedureInterval,
+ connection_handle, config_id, kMaxProcedureLen, min_procedure_interval,
kMaxProcedureInterval,
cs_requester_trackers_[connection_handle].max_procedure_count, kMinSubeventLen,
kMaxSubeventLen, tone_antenna_config_selection, CsPhy::LE_1M_PHY, kTxPwrDelta,
@@ -845,8 +853,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
if (it->second.measurement_ongoing) {
distance_measurement_callbacks_->OnDistanceMeasurementStopped(it->second.address, errorCode,
METHOD_CS);
- it->second.repeating_alarm->Cancel();
- it->second.repeating_alarm.reset();
+ it->second.procedure_schedule_guard_alarm->Cancel();
+ it->second.procedure_schedule_guard_alarm.reset();
}
reset_tracker_on_stopped(it->second);
// the cs_tracker should be kept until the connection is disconnected
@@ -863,11 +871,12 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
if (enable == Enable::ENABLED) {
if (it->second.state == CsTrackerState::STOPPED) {
log::error("safe guard, error state, no local measurement request.");
- if (it->second.repeating_alarm) {
- it->second.repeating_alarm->Cancel();
+ if (it->second.procedure_schedule_guard_alarm) {
+ it->second.procedure_schedule_guard_alarm->Cancel();
}
return;
}
+
it->second.state = CsTrackerState::WAIT_FOR_PROCEDURE_ENABLED;
} else { // Enable::DISABLE
if (it->second.state != CsTrackerState::WAIT_FOR_PROCEDURE_ENABLED &&
@@ -1166,13 +1175,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
}
if (it->second.measurement_ongoing) {
- log::info("enable cs procedure regularly with interval: {} ms", it->second.interval_ms);
- it->second.repeating_alarm->Cancel();
send_le_cs_procedure_enable(connection_handle, Enable::ENABLED);
- it->second.repeating_alarm->Schedule(
- common::Bind(&impl::send_le_cs_procedure_enable, common::Unretained(this),
- connection_handle, Enable::ENABLED),
- std::chrono::milliseconds(it->second.interval_ms));
}
}
@@ -1280,6 +1283,24 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
live_tracker->selected_tx_power = event_view.GetSelectedTxPower();
live_tracker->n_procedure_count = event_view.GetProcedureCount();
live_tracker->retry_counter_for_cs_enable = 0;
+ live_tracker->procedure_counting_after_enable = 0;
+ if (live_tracker->local_start) {
+ uint32_t schedule_interval = live_tracker->interval_ms;
+ if (live_tracker->n_procedure_count > 1) {
+ schedule_interval = live_tracker->n_procedure_count * event_view.GetProcedureInterval() *
+ live_tracker->conn_interval_ +
+ kProcedureScheduleGuardMs;
+ log::debug("guard interval is {} ms", schedule_interval);
+ }
+ if (live_tracker->n_procedure_count >= 1) {
+ live_tracker->procedure_schedule_guard_alarm->Cancel();
+ log::info("schedule next procedure enable after {} ms", schedule_interval);
+ cs_requester_trackers_[connection_handle].procedure_schedule_guard_alarm->Schedule(
+ common::Bind(&impl::send_le_cs_procedure_enable, common::Unretained(this),
+ connection_handle, Enable::ENABLED),
+ std::chrono::milliseconds(schedule_interval));
+ }
+ }
if (live_tracker->local_start && live_tracker->waiting_for_start_callback) {
live_tracker->waiting_for_start_callback = false;
@@ -1352,7 +1373,8 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
subevent_abort_reason = cs_event_result.GetSubeventAbortReason();
result_data_structures = cs_event_result.GetResultDataStructures();
- procedure_data = init_cs_procedure_data(live_tracker, cs_event_result.GetProcedureCounter(),
+ procedure_data = init_cs_procedure_data(connection_handle, live_tracker,
+ cs_event_result.GetProcedureCounter(),
cs_event_result.GetNumAntennaPaths());
if (live_tracker->role == CsRole::INITIATOR) {
procedure_data->frequency_compensation.push_back(
@@ -1530,7 +1552,9 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
log::warn("can't find tracker for 0x{:04x}", connection_handle);
return;
}
- if (cs_requester_trackers_[connection_handle].state != CsTrackerState::STARTED) {
+ if (cs_requester_trackers_[connection_handle].state != CsTrackerState::STARTED &&
+ cs_requester_trackers_[connection_handle].state !=
+ CsTrackerState::WAIT_FOR_PROCEDURE_ENABLED) {
log::warn("The measurement for {} is stopped, ignore the remote data.", connection_handle);
return;
}
@@ -1583,7 +1607,7 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
}
auto& tracker = cs_requester_trackers_[connection_handle];
if (tracker.measurement_ongoing && tracker.local_start) {
- cs_requester_trackers_[connection_handle].repeating_alarm->Cancel();
+ cs_requester_trackers_[connection_handle].procedure_schedule_guard_alarm->Cancel();
send_le_cs_procedure_enable(connection_handle, Enable::DISABLED);
distance_measurement_callbacks_->OnDistanceMeasurementStopped(
tracker.address, REASON_INTERNAL_ERROR, METHOD_CS);
@@ -1984,11 +2008,10 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
connection_handle);
}
- CsProcedureData* init_cs_procedure_data(CsTracker* live_tracker, uint16_t procedure_counter,
- uint8_t num_antenna_paths) {
+ CsProcedureData* init_cs_procedure_data(uint16_t connection_handle, CsTracker* live_tracker,
+ uint16_t procedure_counter, uint8_t num_antenna_paths) {
// Update procedure count
live_tracker->procedure_counter = procedure_counter;
-
std::vector<CsProcedureData>& data_list = live_tracker->procedure_data_list;
for (auto& data : data_list) {
if (data.counter == procedure_counter) {
@@ -1997,6 +2020,14 @@ struct DistanceMeasurementManager::impl : bluetooth::hal::RangingHalCallback {
return &data;
}
}
+ live_tracker->procedure_counting_after_enable += 1;
+ if (live_tracker->local_start && live_tracker->procedure_counting_after_enable > 0 &&
+ live_tracker->n_procedure_count > 1 &&
+ live_tracker->procedure_counting_after_enable == live_tracker->n_procedure_count) {
+ log::debug("enable procedure after finishing the last procedure");
+ send_le_cs_procedure_enable(connection_handle, Enable::ENABLED);
+ }
+
log::info("Create data for procedure_counter: {}", procedure_counter);
data_list.emplace_back(procedure_counter, num_antenna_paths, live_tracker->used_config_id,
live_tracker->selected_tx_power);
diff --git a/system/gd/hci/msft.cc b/system/gd/hci/msft.cc
index b27bcf23d5..1c5a700030 100644
--- a/system/gd/hci/msft.cc
+++ b/system/gd/hci/msft.cc
@@ -56,10 +56,13 @@ struct MsftExtensionManager::impl {
* Query the kernel/drivers to derive the MSFT opcode so that
* we can issue MSFT vendor specific commands.
*/
- if (!supports_msft_extensions()) {
+ uint16_t opcode = hal_->getMsftOpcode();
+ if (opcode == 0) {
log::info("MSFT extension is not supported.");
return;
}
+ msft_.opcode = opcode;
+ log::info("MSFT opcode 0x{:04x}", msft_.opcode.value());
/*
* The vendor prefix is required to distinguish among the vendor events
@@ -121,20 +124,7 @@ struct MsftExtensionManager::impl {
}
}
- bool supports_msft_extensions() {
- if (msft_.opcode.has_value()) {
- return true;
- }
-
- uint16_t opcode = hal_->getMsftOpcode();
- if (opcode == 0) {
- return false;
- }
-
- msft_.opcode = opcode;
- log::info("MSFT opcode 0x{:04x}", msft_.opcode.value());
- return true;
- }
+ bool supports_msft_extensions() { return msft_.opcode.has_value(); }
void msft_adv_monitor_add(const MsftAdvMonitor& monitor, MsftAdvMonitorAddCallback cb) {
if (!supports_msft_extensions()) {
@@ -225,7 +215,11 @@ struct MsftExtensionManager::impl {
log::assert_that(view.IsValid(), "assert failed: view.IsValid()");
auto status_view = MsftReadSupportedFeaturesCommandCompleteView::Create(
MsftCommandCompleteView::Create(view));
- log::assert_that(status_view.IsValid(), "assert failed: status_view.IsValid()");
+ if (!status_view.IsValid()) {
+ log::error("MSFT Read supported features failed");
+ msft_.opcode = std::nullopt;
+ return;
+ }
if (status_view.GetStatus() != ErrorCode::SUCCESS) {
log::warn("MSFT Command complete status {}", ErrorCodeText(status_view.GetStatus()));
diff --git a/system/gd/rust/linux/client/src/callbacks.rs b/system/gd/rust/linux/client/src/callbacks.rs
index 32fdd7f55d..603716376e 100644
--- a/system/gd/rust/linux/client/src/callbacks.rs
+++ b/system/gd/rust/linux/client/src/callbacks.rs
@@ -1473,8 +1473,8 @@ impl IBluetoothMediaCallback for MediaCallback {
&mut self,
_direction: u8,
_group_id: i32,
- _snk_audio_location: u32,
- _src_audio_location: u32,
+ _snk_audio_location: i64,
+ _src_audio_location: i64,
_avail_cont: u16,
) {
}
diff --git a/system/gd/rust/linux/client/src/dbus_iface.rs b/system/gd/rust/linux/client/src/dbus_iface.rs
index ba31286cf0..9e0f2818d1 100644
--- a/system/gd/rust/linux/client/src/dbus_iface.rs
+++ b/system/gd/rust/linux/client/src/dbus_iface.rs
@@ -2989,8 +2989,8 @@ impl IBluetoothMediaCallback for IBluetoothMediaCallbackDBus {
&mut self,
direction: u8,
group_id: i32,
- snk_audio_location: u32,
- src_audio_location: u32,
+ snk_audio_location: i64,
+ src_audio_location: i64,
avail_cont: u16,
) {
}
diff --git a/system/gd/rust/linux/mgmt/src/config_util.rs b/system/gd/rust/linux/mgmt/src/config_util.rs
index 5defe179dc..da2f100db8 100644
--- a/system/gd/rust/linux/mgmt/src/config_util.rs
+++ b/system/gd/rust/linux/mgmt/src/config_util.rs
@@ -33,10 +33,10 @@ pub fn is_floss_enabled() -> bool {
let content = std::str::from_utf8(&v);
match content {
Ok(version) => version.contains("floss"),
- Err(_) => false,
+ Err(_) => true,
}
}
- Err(_) => false,
+ Err(_) => true,
}
}
diff --git a/system/gd/rust/linux/service/src/iface_bluetooth_media.rs b/system/gd/rust/linux/service/src/iface_bluetooth_media.rs
index 88d6b200a5..8da5e60683 100644
--- a/system/gd/rust/linux/service/src/iface_bluetooth_media.rs
+++ b/system/gd/rust/linux/service/src/iface_bluetooth_media.rs
@@ -155,8 +155,8 @@ impl IBluetoothMediaCallback for BluetoothMediaCallbackDBus {
&mut self,
direction: u8,
group_id: i32,
- snk_audio_location: u32,
- src_audio_location: u32,
+ snk_audio_location: i64,
+ src_audio_location: i64,
avail_cont: u16,
) {
dbus_generated!()
diff --git a/system/gd/rust/linux/stack/src/bluetooth_media.rs b/system/gd/rust/linux/stack/src/bluetooth_media.rs
index e87d3d9086..c8ea9bcb7e 100644
--- a/system/gd/rust/linux/stack/src/bluetooth_media.rs
+++ b/system/gd/rust/linux/stack/src/bluetooth_media.rs
@@ -296,8 +296,8 @@ pub trait IBluetoothMediaCallback: RPCProxy {
&mut self,
direction: u8,
group_id: i32,
- snk_audio_location: u32,
- src_audio_location: u32,
+ snk_audio_location: i64,
+ src_audio_location: i64,
avail_cont: u16,
);
@@ -420,8 +420,8 @@ struct UHid {
struct LEAAudioConf {
pub direction: u8,
pub group_id: i32,
- pub snk_audio_location: u32,
- pub src_audio_location: u32,
+ pub snk_audio_location: i64,
+ pub src_audio_location: i64,
pub avail_cont: u16,
}
diff --git a/system/gd/rust/topshim/Android.bp b/system/gd/rust/topshim/Android.bp
deleted file mode 100644
index 9e1a5e976a..0000000000
--- a/system/gd/rust/topshim/Android.bp
+++ /dev/null
@@ -1,166 +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"],
-}
-
-rust_library_host_rlib {
- name: "libbt_topshim",
- crate_name: "bt_topshim",
- srcs: [
- "src/lib.rs",
-
- ":libbt_topshim_wrapper_bindgen",
- ],
- rustlibs: [
- "libbitflags",
- "libcxx",
- "libfutures",
- "libgrpcio",
- "liblog_rust",
- "libnix",
- "libnum_traits",
- "libtokio",
- "libtokio_stream",
- ],
- proc_macros: [
- "libnum_derive",
- "libpaste",
- "libtopshim_macros",
- ],
- lints: "none",
- clippy_lints: "none",
-}
-
-cc_library_static {
- name: "libbt_topshim_cxx",
- srcs: [
- "btav/btav_shim.cc",
- "btav_sink/btav_sink_shim.cc",
- "controller/controller_shim.cc",
- "csis/csis_shim.cc",
- "gatt/gatt_ble_advertiser_shim.cc",
- "gatt/gatt_ble_scanner_shim.cc",
- "gatt/gatt_shim.cc",
- "hfp/hfp_shim.cc",
- "le_audio/le_audio_shim.cc",
- "vc/vc_shim.cc",
- ],
- generated_headers: [
- "cxx-bridge-header",
- "libbt_topshim_bridge_header",
- ],
- generated_sources: ["libbt_topshim_bridge_code"],
- include_dirs: [
- "packages/modules/Bluetooth/system",
- "packages/modules/Bluetooth/system/gd",
- "packages/modules/Bluetooth/system/gd/rust/topshim",
- "packages/modules/Bluetooth/system/include",
- ],
- host_supported: true,
- static_libs: [
- "aics",
- "libbluetooth_hci_pdl",
- "libbluetooth_log",
- "libchrome",
- "libflatbuffers-cpp",
- ],
- aidl: {
- libs: ["bluetooth_constants"],
- },
- shared_libs: [
- "libbinder",
- ],
- target: {
- darwin: {
- enabled: false,
- },
- },
-}
-
-gensrcs {
- name: "libbt_topshim_bridge_header",
- tools: ["cxxbridge"],
- cmd: "$(location cxxbridge) $(in) --header > $(out)",
- srcs: [
- "src/controller.rs",
- "src/profiles/a2dp.rs",
- "src/profiles/avrcp.rs",
- "src/profiles/csis.rs",
- "src/profiles/gatt.rs",
- "src/profiles/hfp.rs",
- "src/profiles/le_audio.rs",
- "src/profiles/vc.rs",
- ],
- output_extension: "rs.h",
- export_include_dirs: ["."],
-}
-
-gensrcs {
- name: "libbt_topshim_bridge_code",
- tools: ["cxxbridge"],
- cmd: "$(location cxxbridge) $(in) > $(out)",
- srcs: [
- "src/controller.rs",
- "src/profiles/a2dp.rs",
- "src/profiles/avrcp.rs",
- "src/profiles/csis.rs",
- "src/profiles/gatt.rs",
- "src/profiles/hfp.rs",
- "src/profiles/le_audio.rs",
- "src/profiles/vc.rs",
- ],
- output_extension: "cc",
- export_include_dirs: ["."],
-}
-
-rust_bindgen {
- name: "libbt_topshim_wrapper_bindgen",
- wrapper_src: "bindings/wrapper.hpp",
- crate_name: "bt_topshim_wrapper_bindgen",
- source_stem: "bindings",
- defaults: ["bluetooth_cflags"],
- c_std: "",
- host_supported: true,
- bindgen_flags: [
- "--allowlist-function=bt_.*",
- "--allowlist-function=btgatt_.*",
- "--allowlist-function=bthh_.*",
- "--allowlist-function=btsdp.*",
- "--allowlist-function=hal_util_.*",
- "--allowlist-function=osi_property_get.*",
- "--allowlist-type=bluetooth_sdp.*",
- "--allowlist-type=bt_.*",
- "--allowlist-type=btgatt_.*",
- "--allowlist-type=bthf_.*",
- "--allowlist-type=bthh_.*",
- "--allowlist-type=btrc_.*",
- "--allowlist-type=btsdp.*",
- "--allowlist-type=btsock_.*",
- "--allowlist-type=sock_connect_signal_t",
- "--enable-cxx-namespaces",
- "--opaque-type=std::.*",
- "--with-derive-default",
- "--with-derive-eq",
- "--with-derive-partialeq",
- ],
- shared_libs: [
- "libc++",
- ],
- cflags: [
- "-DTARGET_FLOSS",
- ],
- static_libs: [
- "libbluetooth_log",
- ],
- // The bindgen rule can only include headers via header_libs and does not
- // support include_dirs. Make sure newly added headers have the correct
- // header export target listed here.
- header_libs: [
- "libbluetooth_headers",
- "libbluetooth_system_headers",
- ],
-}
diff --git a/system/gd/rust/topshim/le_audio/le_audio_shim.cc b/system/gd/rust/topshim/le_audio/le_audio_shim.cc
index 53a0f7d98f..96ecfba464 100644
--- a/system/gd/rust/topshim/le_audio/le_audio_shim.cc
+++ b/system/gd/rust/topshim/le_audio/le_audio_shim.cc
@@ -207,15 +207,19 @@ static void group_stream_status_cb(int group_id, le_audio::GroupStreamStatus sta
le_audio_group_stream_status_callback(group_id, to_rust_btle_audio_group_stream_status(status));
}
-static void audio_conf_cb(uint8_t direction, int group_id, uint32_t snk_audio_location,
- uint32_t src_audio_location, uint16_t avail_cont) {
- le_audio_audio_conf_callback(direction, group_id, snk_audio_location, src_audio_location,
+static void audio_conf_cb(uint8_t direction, int group_id,
+ std::optional<std::bitset<32>> snk_audio_location,
+ std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont) {
+ int64_t rs_snk_audio_location = snk_audio_location ? snk_audio_location->to_ulong() : -1l;
+ int64_t rs_src_audio_location = src_audio_location ? src_audio_location->to_ulong() : -1l;
+ le_audio_audio_conf_callback(direction, group_id, rs_snk_audio_location, rs_src_audio_location,
avail_cont);
}
static void sink_audio_location_available_cb(const RawAddress& address,
- uint32_t snk_audio_locations) {
- le_audio_sink_audio_location_available_callback(address, snk_audio_locations);
+ std::optional<std::bitset<32>> snk_audio_location) {
+ int64_t rs_snk_audio_location = snk_audio_location ? snk_audio_location->to_ulong() : -1l;
+ le_audio_sink_audio_location_available_callback(address, rs_snk_audio_location);
}
static void audio_local_codec_capabilities_cb(
@@ -270,19 +274,24 @@ public:
topshim::rust::internal::group_node_status_cb(bd_addr, group_id, node_status);
}
- void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location,
- uint32_t src_audio_location, uint16_t avail_cont) {
+ void OnAudioConf(uint8_t direction, int group_id,
+ std::optional<std::bitset<32>> snk_audio_location,
+ std::optional<std::bitset<32>> src_audio_location, uint16_t avail_cont) {
log::info(
"direction={}, group_id={}, snk_audio_location={}, src_audio_location={}, "
"avail_cont={}",
- direction, group_id, snk_audio_location, src_audio_location, avail_cont);
+ direction, group_id,
+ std::to_string(snk_audio_location ? snk_audio_location->to_ulong() : -1),
+ std::to_string(src_audio_location ? src_audio_location->to_ulong() : -1), avail_cont);
topshim::rust::internal::audio_conf_cb(direction, group_id, snk_audio_location,
src_audio_location, avail_cont);
}
- void OnSinkAudioLocationAvailable(const RawAddress& address, uint32_t snk_audio_locations) {
- log::info("address={}, snk_audio_locations={}", address, snk_audio_locations);
- topshim::rust::internal::sink_audio_location_available_cb(address, snk_audio_locations);
+ void OnSinkAudioLocationAvailable(const RawAddress& address,
+ std::optional<std::bitset<32>> snk_audio_location) {
+ log::info("address={}, snk_audio_locations={}", address,
+ std::to_string(snk_audio_location ? snk_audio_location->to_ulong() : -1));
+ topshim::rust::internal::sink_audio_location_available_cb(address, snk_audio_location);
}
void OnAudioLocalCodecCapabilities(
diff --git a/system/gd/rust/topshim/src/profiles/le_audio.rs b/system/gd/rust/topshim/src/profiles/le_audio.rs
index 64e5ae4185..b7aa3ed7e3 100644
--- a/system/gd/rust/topshim/src/profiles/le_audio.rs
+++ b/system/gd/rust/topshim/src/profiles/le_audio.rs
@@ -194,13 +194,13 @@ pub mod ffi {
fn le_audio_audio_conf_callback(
direction: u8,
group_id: i32,
- snk_audio_location: u32,
- src_audio_location: u32,
+ snk_audio_location: i64,
+ src_audio_location: i64,
avail_cont: u16,
);
fn le_audio_sink_audio_location_available_callback(
addr: RawAddress,
- snk_audio_locations: u32,
+ snk_audio_locations: i64,
);
fn le_audio_audio_local_codec_capabilities_callback(
local_input_capa_codec_conf: &Vec<BtLeAudioCodecConfig>,
@@ -477,8 +477,8 @@ pub enum LeAudioClientCallbacks {
ConnectionState(BtLeAudioConnectionState, RawAddress),
GroupStatus(i32, BtLeAudioGroupStatus),
GroupNodeStatus(RawAddress, i32, BtLeAudioGroupNodeStatus),
- AudioConf(u8, i32, u32, u32, u16),
- SinkAudioLocationAvailable(RawAddress, u32),
+ AudioConf(u8, i32, i64, i64, u16),
+ SinkAudioLocationAvailable(RawAddress, i64),
AudioLocalCodecCapabilities(Vec<BtLeAudioCodecConfig>, Vec<BtLeAudioCodecConfig>),
AudioGroupCodecConf(
i32,
@@ -520,11 +520,11 @@ cb_variant!(LeAudioClientCb,
cb_variant!(LeAudioClientCb,
le_audio_audio_conf_callback -> LeAudioClientCallbacks::AudioConf,
- u8, i32, u32, u32, u16);
+ u8, i32, i64, i64, u16);
cb_variant!(LeAudioClientCb,
le_audio_sink_audio_location_available_callback -> LeAudioClientCallbacks::SinkAudioLocationAvailable,
- RawAddress, u32);
+ RawAddress, i64);
cb_variant!(LeAudioClientCb,
le_audio_unicast_monitor_mode_status_callback -> LeAudioClientCallbacks::UnicastMonitorModeStatus,
diff --git a/system/include/hardware/bt_le_audio.h b/system/include/hardware/bt_le_audio.h
index 63f79f6d6e..a4ac245f2e 100644
--- a/system/include/hardware/bt_le_audio.h
+++ b/system/include/hardware/bt_le_audio.h
@@ -20,6 +20,7 @@
#include <bluetooth/log.h>
#include <array>
+#include <bitset>
#include <map>
#include <optional>
#include <ostream>
@@ -175,6 +176,7 @@ typedef struct btle_audio_codec_config {
btle_audio_bits_per_sample_index_t bits_per_sample = LE_AUDIO_BITS_PER_SAMPLE_INDEX_NONE;
btle_audio_channel_count_index_t channel_count = LE_AUDIO_CHANNEL_COUNT_INDEX_NONE;
btle_audio_frame_duration_index_t frame_duration = LE_AUDIO_FRAME_DURATION_INDEX_NONE;
+ uint8_t codec_frame_blocks_per_sdu = 0;
uint16_t octets_per_frame = 0;
int32_t codec_priority = 0;
@@ -354,11 +356,13 @@ public:
virtual void OnGroupNodeStatus(const RawAddress& bd_addr, int group_id,
GroupNodeStatus node_status) = 0;
/* Callback for newly recognized or reconfigured existing le audio group */
- virtual void OnAudioConf(uint8_t direction, int group_id, uint32_t snk_audio_location,
- uint32_t src_audio_location, uint16_t avail_cont) = 0;
+ virtual void OnAudioConf(uint8_t direction, int group_id,
+ std::optional<std::bitset<32>> snk_audio_location,
+ std::optional<std::bitset<32>> src_audio_location,
+ uint16_t avail_cont) = 0;
/* Callback for sink audio location recognized */
virtual void OnSinkAudioLocationAvailable(const RawAddress& address,
- uint32_t snk_audio_locations) = 0;
+ std::optional<std::bitset<32>> snk_audio_location) = 0;
/* Callback with local codec capabilities */
virtual void OnAudioLocalCodecCapabilities(
std::vector<btle_audio_codec_config_t> local_input_capa_codec_conf,
diff --git a/system/main/Android.bp b/system/main/Android.bp
index 5fd82531fa..4bddd6a5ab 100644
--- a/system/main/Android.bp
+++ b/system/main/Android.bp
@@ -158,7 +158,6 @@ cc_test {
":TestMockBtif",
":TestMockBtu",
":TestMockJni",
- ":TestMockLegacyHciCommands",
":TestMockLegacyHciInterface",
":TestMockMainShimEntry",
":TestMockStack",
diff --git a/system/main/shim/BUILD.gn b/system/main/shim/BUILD.gn
index ff7bdae78a..5021795e93 100644
--- a/system/main/shim/BUILD.gn
+++ b/system/main/shim/BUILD.gn
@@ -36,6 +36,7 @@ source_set("BluetoothStackManagerSources") {
"//bt/system/gd/packet:BluetoothPacketSources",
"//bt/system/gd/rust/topshim:libbluetooth_topshim",
"//bt/system/osi",
+ "//bt/system/pdl:BluetoothHciPacketSources",
"//bt/system/pdl:BluetoothGeneratedPackets_h",
"//bt/system/stack",
"//bt/system/types",
@@ -81,6 +82,7 @@ source_set("LibBluetoothShimSources") {
"//bt/system/gd/packet:BluetoothPacketSources",
"//bt/system/gd/rust/topshim:libbluetooth_topshim",
"//bt/system/osi",
+ "//bt/system/pdl:BluetoothHciPacketSources",
"//bt/system/pdl:BluetoothGeneratedPackets_h",
"//bt/system/stack",
"//bt/system/types",
diff --git a/system/main/shim/acl.cc b/system/main/shim/acl.cc
index 695c815275..72d8de8040 100644
--- a/system/main/shim/acl.cc
+++ b/system/main/shim/acl.cc
@@ -67,9 +67,6 @@
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
extern tBTM_CB btm_cb;
using namespace bluetooth;
diff --git a/system/main/shim/acl.h b/system/main/shim/acl.h
index 83f62af604..bbe15d0acf 100644
--- a/system/main/shim/acl.h
+++ b/system/main/shim/acl.h
@@ -29,6 +29,9 @@
#include "packet/raw_builder.h"
#include "types/raw_address.h"
+void DumpsysAcl(int fd);
+void DumpsysNeighbor(int fd);
+
namespace bluetooth {
namespace shim {
diff --git a/system/main/shim/entry.cc b/system/main/shim/entry.cc
index ace58f79e4..4937187328 100644
--- a/system/main/shim/entry.cc
+++ b/system/main/shim/entry.cc
@@ -60,7 +60,7 @@ hci::DistanceMeasurementManager* GetDistanceMeasurementManager() {
return Stack::GetInstance()->GetInstance<hci::DistanceMeasurementManager>();
}
-hal::SnoopLogger* GetSnoopLogger() { return Stack::GetInstance()->GetInstance<hal::SnoopLogger>(); }
+hal::SnoopLogger* GetSnoopLogger() { return Stack::GetInstance()->GetSnoopLogger(); }
lpp::LppOffloadInterface* GetLppOffloadManager() {
return Stack::GetInstance()->GetInstance<lpp::LppOffloadManager>();
diff --git a/system/main/shim/hci_layer.cc b/system/main/shim/hci_layer.cc
index 62b3e801ed..2b60141f27 100644
--- a/system/main/shim/hci_layer.cc
+++ b/system/main/shim/hci_layer.cc
@@ -37,9 +37,6 @@
#include "stack/include/hcimsgs.h"
#include "stack/include/main_thread.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
/**
@@ -155,16 +152,16 @@ static void subevent_callback(bluetooth::hci::LeMetaEventView le_meta_event_view
send_data_upwards.Run(WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &le_meta_event_view));
}
-void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context,
- bluetooth::hci::CommandCompleteView view) {
+static void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context,
+ bluetooth::hci::CommandCompleteView view) {
log::debug("Received cmd complete for {}", bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
BT_HDR* response = WrapPacketAndCopy(MSG_HC_TO_STACK_HCI_EVT, &view);
complete_callback(response, context);
}
-void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
- std::unique_ptr<OsiObject> command,
- bluetooth::hci::CommandStatusView view) {
+static void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
+ std::unique_ptr<OsiObject> command,
+ bluetooth::hci::CommandStatusView view) {
log::debug("Received cmd status {} for {}", bluetooth::hci::ErrorCodeText(view.GetStatus()),
bluetooth::hci::OpCodeText(view.GetCommandOpCode()));
uint8_t status = static_cast<uint8_t>(view.GetStatus());
diff --git a/system/main/shim/stack.cc b/system/main/shim/stack.cc
index ef9fd0d5d4..c570a5f542 100644
--- a/system/main/shim/stack.cc
+++ b/system/main/shim/stack.cc
@@ -69,6 +69,7 @@ struct Stack::impl {
Acl* acl_ = nullptr;
metrics::CounterMetrics* counter_metrics_ = nullptr;
storage::StorageModule* storage_ = nullptr;
+ hal::SnoopLogger* snoop_logger_ = nullptr;
};
Stack::Stack() { pimpl_ = std::make_shared<Stack::impl>(); }
@@ -90,6 +91,7 @@ void Stack::StartEverything() {
pimpl_->counter_metrics_ = new metrics::CounterMetrics(new Handler(stack_thread_));
pimpl_->storage_ = new storage::StorageModule(new Handler(stack_thread_));
+ pimpl_->snoop_logger_ = new hal::SnoopLogger(new Handler(stack_thread_));
#if TARGET_FLOSS
modules.add<sysprops::SyspropsModule>();
@@ -116,11 +118,12 @@ void Stack::StartEverything() {
WakelockManager::Get().Acquire();
}
+ is_running_ = true;
+
std::promise<void> promise;
auto future = promise.get_future();
management_handler_->Post(common::BindOnce(&Stack::handle_start_up, common::Unretained(this),
&modules, std::move(promise)));
- is_running_ = true;
auto init_status = future.wait_for(
std::chrono::milliseconds(get_gd_stack_timeout_ms(/* is_start = */ true)));
@@ -223,6 +226,12 @@ storage::StorageModule* Stack::GetStorage() const {
return pimpl_->storage_;
}
+hal::SnoopLogger* Stack::GetSnoopLogger() const {
+ std::lock_guard<std::recursive_mutex> lock(mutex_);
+ log::assert_that(is_running_, "assert failed: is_running_");
+ return pimpl_->snoop_logger_;
+}
+
os::Handler* Stack::GetHandler() {
std::lock_guard<std::recursive_mutex> lock(mutex_);
log::assert_that(is_running_, "assert failed: is_running_");
@@ -249,12 +258,14 @@ void Stack::Dump(int fd, std::promise<void> promise) const {
void Stack::handle_start_up(ModuleList* modules, std::promise<void> promise) {
pimpl_->counter_metrics_->Start();
pimpl_->storage_->Start();
+ pimpl_->snoop_logger_->Start();
registry_.Start(modules, stack_thread_);
promise.set_value();
}
void Stack::handle_shut_down(std::promise<void> promise) {
registry_.StopAll();
+ pimpl_->snoop_logger_->Stop();
pimpl_->storage_->Stop();
pimpl_->counter_metrics_->Stop();
promise.set_value();
diff --git a/system/main/shim/stack.h b/system/main/shim/stack.h
index 2fbdfca43c..8307e00a23 100644
--- a/system/main/shim/stack.h
+++ b/system/main/shim/stack.h
@@ -26,6 +26,10 @@
// The shim layer implementation on the Gd stack side.
namespace bluetooth {
+namespace hal {
+class SnoopLogger;
+}
+
namespace storage {
class StorageModule;
}
@@ -68,6 +72,7 @@ public:
virtual Acl* GetAcl() const;
virtual metrics::CounterMetrics* GetCounterMetrics() const;
virtual storage::StorageModule* GetStorage() const;
+ virtual hal::SnoopLogger* GetSnoopLogger() const;
os::Handler* GetHandler();
diff --git a/system/main/test/main_shim_test.cc b/system/main/test/main_shim_test.cc
index 82bc15bf12..2f4056a381 100644
--- a/system/main/test/main_shim_test.cc
+++ b/system/main/test/main_shim_test.cc
@@ -40,6 +40,7 @@
#include "hci/address_with_type.h"
#include "hci/controller_interface_mock.h"
#include "hci/distance_measurement_manager_mock.h"
+#include "hci/include/packet_fragmenter.h"
#include "hci/le_advertising_manager_mock.h"
#include "hci/le_scanning_manager_mock.h"
#include "include/hardware/ble_scanner.h"
@@ -69,9 +70,6 @@
#include "types/hci_role.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using ::testing::_;
using namespace bluetooth;
@@ -120,41 +118,40 @@ private:
bluetooth::common::TimestamperInMilliseconds timestamper_in_milliseconds;
-void mock_on_send_data_upwards(BT_HDR*) {}
+static void mock_on_send_data_upwards(BT_HDR*) {}
-void mock_on_packets_completed(uint16_t /*handle*/, uint16_t /*num_packets*/) {}
+static void mock_on_packets_completed(uint16_t /*handle*/, uint16_t /*num_packets*/) {}
-void mock_connection_classic_on_connected(const RawAddress& /*bda*/, uint16_t /*handle*/,
- uint8_t /*enc_mode*/, bool /*locally_initiated*/) {}
+static void mock_connection_classic_on_connected(const RawAddress& /*bda*/, uint16_t /*handle*/,
+ uint8_t /*enc_mode*/, bool /*locally_initiated*/) {
+}
-void mock_connection_classic_on_failed(const RawAddress& /*bda*/, tHCI_STATUS /*status*/,
- bool /*locally_initiated*/) {}
+static void mock_connection_classic_on_failed(const RawAddress& /*bda*/, tHCI_STATUS /*status*/,
+ bool /*locally_initiated*/) {}
-void mock_connection_classic_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
- tHCI_STATUS /*reason*/) {
+static void mock_connection_classic_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
+ tHCI_STATUS /*reason*/) {
ASSERT_TRUE(mock_function_handle_promise_map.find(__func__) !=
mock_function_handle_promise_map.end());
mock_function_handle_promise_map[__func__].set_value(handle);
}
-void mock_connection_le_on_connected(const tBLE_BD_ADDR& /*address_with_type*/, uint16_t /*handle*/,
- tHCI_ROLE /*role*/, uint16_t /*conn_interval*/,
- uint16_t /*conn_latency*/, uint16_t /*conn_timeout*/,
- const RawAddress& /*local_rpa*/,
- const RawAddress& /*peer_rpa*/,
- tBLE_ADDR_TYPE /*peer_addr_type*/,
- bool /*can_read_discoverable_characteristics*/) {}
-void mock_connection_le_on_failed(const tBLE_BD_ADDR& /*address_with_type*/, uint16_t /*handle*/,
- bool /*enhanced*/, tHCI_STATUS /*status*/) {}
+static void mock_connection_le_on_connected(
+ const tBLE_BD_ADDR& /*address_with_type*/, uint16_t /*handle*/, tHCI_ROLE /*role*/,
+ uint16_t /*conn_interval*/, uint16_t /*conn_latency*/, uint16_t /*conn_timeout*/,
+ const RawAddress& /*local_rpa*/, const RawAddress& /*peer_rpa*/,
+ tBLE_ADDR_TYPE /*peer_addr_type*/, bool /*can_read_discoverable_characteristics*/) {}
+static void mock_connection_le_on_failed(const tBLE_BD_ADDR& /*address_with_type*/,
+ uint16_t /*handle*/, bool /*enhanced*/,
+ tHCI_STATUS /*status*/) {}
static std::promise<uint16_t> mock_connection_le_on_disconnected_promise;
-void mock_connection_le_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
- tHCI_STATUS /*reason*/) {
+static void mock_connection_le_on_disconnected(tHCI_STATUS /*status*/, uint16_t handle,
+ tHCI_STATUS /*reason*/) {
mock_connection_le_on_disconnected_promise.set_value(handle);
}
-void mock_link_classic_on_read_remote_extended_features_complete(uint16_t /*handle*/,
- uint8_t /*current_page_number*/,
- uint8_t /*max_page_number*/,
- uint64_t /*features*/) {}
+static void mock_link_classic_on_read_remote_extended_features_complete(
+ uint16_t /*handle*/, uint8_t /*current_page_number*/, uint8_t /*max_page_number*/,
+ uint64_t /*features*/) {}
shim::acl_interface_t acl_interface{
.on_send_data_upwards = mock_on_send_data_upwards,
@@ -201,12 +198,7 @@ shim::acl_interface_t acl_interface{
.link.le.on_read_remote_version_information_complete = nullptr,
};
-const shim::acl_interface_t& GetMockAclInterface() { return acl_interface; }
-
-struct hci_packet_parser_t;
-const hci_packet_parser_t* hci_packet_parser_get_interface() { return nullptr; }
-struct hci_t;
-struct packet_fragmenter_t;
+static const shim::acl_interface_t& GetMockAclInterface() { return acl_interface; }
const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; }
template <typename T>
@@ -709,7 +701,6 @@ TEST_F(MainShimTest, OnConnectRequest) {
acl->OnConnectRequest(kAddress, kCod);
}
-void DumpsysNeighbor(int fd);
TEST_F(MainShimTest, DumpsysNeighbor) {
btm_cb.neighbor = {};
diff --git a/system/osi/Android.bp b/system/osi/Android.bp
index 23055416f2..9d26c957ec 100644
--- a/system/osi/Android.bp
+++ b/system/osi/Android.bp
@@ -56,13 +56,11 @@ cc_library_static {
"src/mutex.cc",
"src/properties.cc",
"src/reactor.cc",
- "src/ringbuffer.cc",
"src/socket.cc",
"src/socket_utils/socket_local_client.cc",
"src/socket_utils/socket_local_server.cc",
"src/stack_power_telemetry.cc",
"src/thread.cc",
- "src/thread_scheduler.cc",
"src/wakelock.cc",
// internal source that should not be used outside of libosi
@@ -117,7 +115,6 @@ cc_test {
"test/list_test.cc",
"test/properties_test.cc",
"test/reactor_test.cc",
- "test/ringbuffer_test.cc",
"test/stack_power_telemetry_test.cc",
"test/thread_test.cc",
"test/wakelock_test.cc", // test internal sources only used inside the libosi
diff --git a/system/osi/BUILD.gn b/system/osi/BUILD.gn
index ffc3dfcac8..5bdf04c1e9 100644
--- a/system/osi/BUILD.gn
+++ b/system/osi/BUILD.gn
@@ -27,7 +27,6 @@ static_library("osi") {
"src/mutex.cc",
"src/properties.cc",
"src/reactor.cc",
- "src/ringbuffer.cc",
"src/socket.cc",
# TODO(mcchou): Remove these sources after platform specific
@@ -76,7 +75,6 @@ if (use.test) {
"test/list_test.cc",
"test/properties_test.cc",
"test/reactor_test.cc",
- "test/ringbuffer_test.cc",
"test/thread_test.cc",
"test/internal/semaphore_test.cc",
diff --git a/system/osi/include/properties.h b/system/osi/include/properties.h
index 975574e294..6e13a665d6 100644
--- a/system/osi/include/properties.h
+++ b/system/osi/include/properties.h
@@ -52,6 +52,7 @@ int32_t osi_property_get_int32(const char* key, int32_t default_value);
// returns the value of |key| coerced into a bool. If the property is not set,
// then the |default_value| is used.
bool osi_property_get_bool(const char* key, bool default_value);
+void osi_property_set_bool(const char* key, bool value);
// Helper function that returns the value of |key| coerced into a vector of
// uint32_t. If the property is not set, then the |default_value| is used.
diff --git a/system/osi/include/ringbuffer.h b/system/osi/include/ringbuffer.h
deleted file mode 100644
index 03a7447b57..0000000000
--- a/system/osi/include/ringbuffer.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2015 Google Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at:
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************************/
-
-#pragma once
-
-#include <stdint.h>
-#include <sys/types.h>
-
-typedef struct ringbuffer_t ringbuffer_t;
-
-// NOTE:
-// None of the functions below are thread safe when it comes to accessing the
-// *rb pointer. It is *NOT* possible to insert and pop/delete at the same time.
-// Callers must protect the *rb pointer separately.
-
-// Create a ringbuffer with the specified size
-// Returns NULL if memory allocation failed. Resulting pointer must be freed
-// using |ringbuffer_free|.
-ringbuffer_t* ringbuffer_init(const size_t size);
-
-// Frees the ringbuffer structure and buffer
-// Save to call with NULL.
-void ringbuffer_free(ringbuffer_t* rb);
-
-// Returns remaining buffer size
-size_t ringbuffer_available(const ringbuffer_t* rb);
-
-// Returns size of data in buffer
-size_t ringbuffer_size(const ringbuffer_t* rb);
-
-// Attempts to insert up to |length| bytes of data at |p| into the buffer
-// Return actual number of bytes added. Can be less than |length| if buffer
-// is full.
-size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length);
-
-// Peek |length| number of bytes from the ringbuffer, starting at |offset|,
-// into the buffer |p|. Return the actual number of bytes peeked. Can be less
-// than |length| if there is less than |length| data available. |offset| must
-// be non-negative.
-size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length);
-
-// Does the same as |ringbuffer_peek|, but also advances the ring buffer head
-size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length);
-
-// Deletes |length| bytes from the ringbuffer starting from the head
-// Return actual number of bytes deleted.
-size_t ringbuffer_delete(ringbuffer_t* rb, size_t length);
diff --git a/system/osi/src/alarm.cc b/system/osi/src/alarm.cc
index fa5072474d..6aaf4354ae 100644
--- a/system/osi/src/alarm.cc
+++ b/system/osi/src/alarm.cc
@@ -654,7 +654,7 @@ static void callback_dispatch(void* /* context */) {
}
alarm->closure.i.Reset(Bind(alarm_ready_mloop, alarm));
- get_main_thread()->DoInThread(FROM_HERE, alarm->closure.i.callback());
+ get_main_thread()->DoInThread(alarm->closure.i.callback());
} else {
fixed_queue_enqueue(alarm->queue, alarm);
}
diff --git a/system/osi/src/list.cc b/system/osi/src/list.cc
index d361b18ef9..97b5390031 100644
--- a/system/osi/src/list.cc
+++ b/system/osi/src/list.cc
@@ -4,9 +4,6 @@
#include "osi/include/allocator.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
struct list_node_t {
@@ -27,7 +24,7 @@ static list_node_t* list_free_node_(list_t* list, list_node_t* node);
// Hidden constructor, only to be used by the hash map for the allocation
// tracker.
// Behaves the same as |list_new|, except you get to specify the allocator.
-list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) {
+static list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) {
list_t* list = (list_t*)zeroed_allocator->alloc(sizeof(list_t));
if (!list) {
return NULL;
diff --git a/system/osi/src/ringbuffer.cc b/system/osi/src/ringbuffer.cc
deleted file mode 100644
index 0631432458..0000000000
--- a/system/osi/src/ringbuffer.cc
+++ /dev/null
@@ -1,131 +0,0 @@
-/******************************************************************************
- *
- * Copyright 2015 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 "osi/include/ringbuffer.h"
-
-#include <bluetooth/log.h>
-#include <stdlib.h>
-
-#include "osi/include/allocator.h"
-
-using namespace bluetooth;
-
-struct ringbuffer_t {
- size_t total;
- size_t available;
- uint8_t* base;
- uint8_t* head;
- uint8_t* tail;
-};
-
-ringbuffer_t* ringbuffer_init(const size_t size) {
- ringbuffer_t* p = static_cast<ringbuffer_t*>(osi_calloc(sizeof(ringbuffer_t)));
-
- p->base = static_cast<uint8_t*>(osi_calloc(size));
- p->head = p->tail = p->base;
- p->total = p->available = size;
-
- return p;
-}
-
-void ringbuffer_free(ringbuffer_t* rb) {
- if (rb != NULL) {
- osi_free(rb->base);
- }
- osi_free(rb);
-}
-
-size_t ringbuffer_available(const ringbuffer_t* rb) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
- return rb->available;
-}
-
-size_t ringbuffer_size(const ringbuffer_t* rb) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
- return rb->total - rb->available;
-}
-
-size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
- log::assert_that(p != nullptr, "assert failed: p != nullptr");
-
- if (length > ringbuffer_available(rb)) {
- length = ringbuffer_available(rb);
- }
-
- for (size_t i = 0; i != length; ++i) {
- *rb->tail++ = *p++;
- if (rb->tail >= (rb->base + rb->total)) {
- rb->tail = rb->base;
- }
- }
-
- rb->available -= length;
- return length;
-}
-
-size_t ringbuffer_delete(ringbuffer_t* rb, size_t length) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
-
- if (length > ringbuffer_size(rb)) {
- length = ringbuffer_size(rb);
- }
-
- rb->head += length;
- if (rb->head >= (rb->base + rb->total)) {
- rb->head -= rb->total;
- }
-
- rb->available += length;
- return length;
-}
-
-size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
- log::assert_that(p != nullptr, "assert failed: p != nullptr");
- log::assert_that(offset >= 0, "assert failed: offset >= 0");
- log::assert_that((size_t)offset <= ringbuffer_size(rb),
- "assert failed: (size_t)offset <= ringbuffer_size(rb)");
-
- uint8_t* b = ((rb->head - rb->base + offset) % rb->total) + rb->base;
- const size_t bytes_to_copy =
- (offset + length > ringbuffer_size(rb)) ? ringbuffer_size(rb) - offset : length;
-
- for (size_t copied = 0; copied < bytes_to_copy; ++copied) {
- *p++ = *b++;
- if (b >= (rb->base + rb->total)) {
- b = rb->base;
- }
- }
-
- return bytes_to_copy;
-}
-
-size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length) {
- log::assert_that(rb != nullptr, "assert failed: rb != nullptr");
- log::assert_that(p != nullptr, "assert failed: p != nullptr");
-
- const size_t copied = ringbuffer_peek(rb, 0, p, length);
- rb->head += copied;
- if (rb->head >= (rb->base + rb->total)) {
- rb->head -= rb->total;
- }
-
- rb->available += copied;
- return copied;
-}
diff --git a/system/osi/src/stack_power_telemetry.cc b/system/osi/src/stack_power_telemetry.cc
index 52d5bfcd2a..678db755da 100644
--- a/system/osi/src/stack_power_telemetry.cc
+++ b/system/osi/src/stack_power_telemetry.cc
@@ -34,12 +34,9 @@
#include "stack/include/btm_status.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
-time_t get_current_time() { return time(0); }
+static time_t get_current_time() { return time(0); }
namespace {
diff --git a/system/osi/src/thread_scheduler.cc b/system/osi/src/thread_scheduler.cc
deleted file mode 100644
index e67b9c662a..0000000000
--- a/system/osi/src/thread_scheduler.cc
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright 2021 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 <sched.h>
-#include <sys/types.h>
-
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-namespace {
-constexpr int kRealTimeFifoSchedulingPriority = 1;
-} // namespace
-
-bool thread_scheduler_enable_real_time(pid_t linux_tid) {
- struct sched_param rt_params = {.sched_priority = kRealTimeFifoSchedulingPriority};
- return sched_setscheduler(linux_tid, SCHED_FIFO, &rt_params) == 0;
-}
-
-bool thread_scheduler_get_priority_range(int& min, int& max) {
- min = sched_get_priority_min(SCHED_FIFO);
- max = sched_get_priority_max(SCHED_FIFO);
- return (min != -1 && max != -1) ? true : false;
-}
diff --git a/system/osi/test/alarm_test.cc b/system/osi/test/alarm_test.cc
index cf98d2dcdc..14ca9cb056 100644
--- a/system/osi/test/alarm_test.cc
+++ b/system/osi/test/alarm_test.cc
@@ -27,9 +27,7 @@
#include "osi/include/osi.h"
#include "osi/include/wakelock.h"
#include "osi/semaphore.h"
-
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+#include "stack/include/main_thread.h"
using base::Closure;
using bluetooth::common::MessageLoopThread;
diff --git a/system/osi/test/future_test.cc b/system/osi/test/future_test.cc
index a3ed620302..4acf389be4 100644
--- a/system/osi/test/future_test.cc
+++ b/system/osi/test/future_test.cc
@@ -41,7 +41,7 @@ TEST_F(FutureTest, test_future_non_immediate) {
MessageLoopThread worker_thread("worker_thread");
worker_thread.StartUp();
- worker_thread.DoInThread(FROM_HERE, base::BindOnce(post_to_future, future));
+ worker_thread.DoInThread(base::BindOnce(post_to_future, future));
EXPECT_EQ(pass_back_data0, future_await(future));
diff --git a/system/osi/test/fuzzers/ringbuffer/Android.bp b/system/osi/test/fuzzers/ringbuffer/Android.bp
deleted file mode 100644
index 08d308c70c..0000000000
--- a/system/osi/test/fuzzers/ringbuffer/Android.bp
+++ /dev/null
@@ -1,25 +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_fuzz {
- name: "libosi_fuzz_ringbuffer",
- defaults: ["libosi_fuzz_defaults"],
- host_supported: true,
- srcs: [
- "fuzz_ringbuffer.cc",
- ],
- static_libs: [
- "libbase",
- "libbluetooth_log",
- "libchrome",
- "libcom.android.sysprop.bluetooth.wrapped",
- "liblog",
- "libosi",
- ],
-}
diff --git a/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc b/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc
deleted file mode 100644
index f676bb6f83..0000000000
--- a/system/osi/test/fuzzers/ringbuffer/fuzz_ringbuffer.cc
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright 2020 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 <fuzzer/FuzzedDataProvider.h>
-
-#include "osi/include/ringbuffer.h"
-
-#define MAX_NUM_FUNCTIONS 512
-#define MAX_BUF_SIZE 2048
-
-ringbuffer_t* getArbitraryRingBuf(std::vector<ringbuffer_t*>* ringbuf_vector,
- FuzzedDataProvider* dataProvider) {
- if (ringbuf_vector->empty()) {
- return nullptr;
- }
-
- size_t index = dataProvider->ConsumeIntegralInRange<size_t>(0, ringbuf_vector->size() - 1);
- return ringbuf_vector->at(index);
-}
-
-void callArbitraryFunction(std::vector<ringbuffer_t*>* ringbuf_vector,
- FuzzedDataProvider* dataProvider) {
- // Get our function identifier
- char func_id = dataProvider->ConsumeIntegralInRange<char>(0, 8);
-
- ringbuffer_t* buf = nullptr;
- switch (func_id) {
- // Let 0 be a NO-OP, as ConsumeIntegral will return 0 on an empty buffer
- // (This will likely bias whatever action is here to run more often)
- case 0:
- return;
- case 1: {
- size_t size = dataProvider->ConsumeIntegralInRange<size_t>(0, MAX_BUF_SIZE);
- buf = ringbuffer_init(size);
- if (buf) {
- ringbuf_vector->push_back(buf);
- }
- }
- return;
- case 2: {
- if (ringbuf_vector->empty()) {
- return;
- }
- size_t index = dataProvider->ConsumeIntegralInRange<size_t>(0, ringbuf_vector->size() - 1);
- buf = ringbuf_vector->at(index);
- if (buf) {
- ringbuffer_free(buf);
- ringbuf_vector->erase(ringbuf_vector->begin() + index);
- }
- }
- return;
- case 3:
- buf = getArbitraryRingBuf(ringbuf_vector, dataProvider);
- if (buf) {
- ringbuffer_available(buf);
- }
- return;
- case 4:
- buf = getArbitraryRingBuf(ringbuf_vector, dataProvider);
- if (buf) {
- ringbuffer_size(buf);
- }
- return;
- case 5: {
- buf = getArbitraryRingBuf(ringbuf_vector, dataProvider);
- size_t size = dataProvider->ConsumeIntegralInRange<size_t>(1, MAX_BUF_SIZE);
- if (buf == nullptr || size == 0) {
- return;
- }
- void* src_buf = malloc(size);
- if (src_buf == nullptr) {
- return;
- }
- std::vector<uint8_t> bytes = dataProvider->ConsumeBytes<uint8_t>(size);
- memcpy(src_buf, bytes.data(), bytes.size());
-
- ringbuffer_insert(buf, reinterpret_cast<uint8_t*>(src_buf), size);
- free(src_buf);
- }
- return;
- case 6:
- case 7: {
- buf = getArbitraryRingBuf(ringbuf_vector, dataProvider);
- if (buf == nullptr) {
- return;
- }
- size_t max_size = ringbuffer_size(buf);
- if (max_size == 0) {
- return;
- }
- size_t size = dataProvider->ConsumeIntegralInRange<size_t>(1, max_size);
-
- // NOTE: 0-size may be a valid case, that crashes currently.
- if (size == 0) {
- return;
- }
-
- void* dst_buf = malloc(size);
- if (dst_buf == nullptr) {
- return;
- }
- if (func_id == 6) {
- off_t offset = dataProvider->ConsumeIntegral<off_t>();
- if (offset >= 0 && static_cast<size_t>(offset) <= ringbuffer_size(buf)) {
- ringbuffer_peek(buf, offset, reinterpret_cast<uint8_t*>(dst_buf), size);
- }
- } else {
- ringbuffer_pop(buf, reinterpret_cast<uint8_t*>(dst_buf), size);
- }
- free(dst_buf);
- }
- return;
- case 8: {
- buf = getArbitraryRingBuf(ringbuf_vector, dataProvider);
- size_t size = dataProvider->ConsumeIntegralInRange<size_t>(0, MAX_BUF_SIZE);
- if (buf) {
- ringbuffer_delete(buf, size);
- }
- }
- return;
- default:
- return;
- }
-}
-
-extern "C" int LLVMFuzzerTestOneInput(const uint8_t* Data, size_t Size) {
- // Init our wrapper
- FuzzedDataProvider dataProvider(Data, Size);
-
- // Keep a vector of our allocated objects for freeing later
- std::vector<ringbuffer_t*> ringbuf_vector;
-
- // Call some functions, create some buffers
- size_t num_functions = dataProvider.ConsumeIntegralInRange<size_t>(0, MAX_NUM_FUNCTIONS);
- for (size_t i = 0; i < num_functions; i++) {
- callArbitraryFunction(&ringbuf_vector, &dataProvider);
- }
-
- // Free anything we've allocated
- for (const auto& ringbuf : ringbuf_vector) {
- if (ringbuf != nullptr) {
- ringbuffer_free(ringbuf);
- }
- }
- ringbuf_vector.clear();
- return 0;
-}
diff --git a/system/osi/test/internal/semaphore_test.cc b/system/osi/test/internal/semaphore_test.cc
index 612804749f..92c0194976 100644
--- a/system/osi/test/internal/semaphore_test.cc
+++ b/system/osi/test/internal/semaphore_test.cc
@@ -83,7 +83,7 @@ TEST_F(SemaphoreTest, test_ensure_wait) {
EXPECT_FALSE(semaphore_try_wait(semaphore));
SemaphoreTestSequenceHelper sequence_helper = {semaphore, 0};
- thread.DoInThread(FROM_HERE, base::BindOnce(sleep_then_increment_counter, &sequence_helper));
+ thread.DoInThread(base::BindOnce(sleep_then_increment_counter, &sequence_helper));
semaphore_wait(semaphore);
EXPECT_EQ(sequence_helper.counter, 1) << "semaphore_wait() did not wait for counter to increment";
diff --git a/system/osi/test/ringbuffer_test.cc b/system/osi/test/ringbuffer_test.cc
deleted file mode 100644
index 06f38ff2de..0000000000
--- a/system/osi/test/ringbuffer_test.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-#include "osi/include/ringbuffer.h"
-
-#include <gtest/gtest.h>
-
-#include "osi/include/osi.h"
-
-TEST(RingbufferTest, test_new_simple) {
- ringbuffer_t* rb = ringbuffer_init(4096);
- ASSERT_TRUE(rb != NULL);
- EXPECT_EQ((size_t)4096, ringbuffer_available(rb));
- EXPECT_EQ((size_t)0, ringbuffer_size(rb));
- ringbuffer_free(rb);
-}
-
-TEST(RingbufferTest, test_insert_basic) {
- ringbuffer_t* rb = ringbuffer_init(16);
-
- uint8_t buffer[10] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A};
- ringbuffer_insert(rb, buffer, 10);
- EXPECT_EQ((size_t)10, ringbuffer_size(rb));
- EXPECT_EQ((size_t)6, ringbuffer_available(rb));
-
- uint8_t peek[10] = {0};
- size_t peeked = ringbuffer_peek(rb, 0, peek, 10);
- EXPECT_EQ((size_t)10, ringbuffer_size(rb)); // Ensure size doesn't change
- EXPECT_EQ((size_t)6, ringbuffer_available(rb));
- EXPECT_EQ((size_t)10, peeked);
- ASSERT_EQ(0, memcmp(buffer, peek, peeked));
-
- ringbuffer_free(rb);
-}
-
-TEST(RingbufferTest, test_insert_full) {
- ringbuffer_t* rb = ringbuffer_init(5);
-
- uint8_t aa[] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA};
- uint8_t bb[] = {0xBB, 0xBB, 0xBB, 0xBB, 0xBB};
- uint8_t peek[5] = {0};
-
- size_t added = ringbuffer_insert(rb, aa, 7);
- EXPECT_EQ((size_t)5, added);
- EXPECT_EQ((size_t)0, ringbuffer_available(rb));
- EXPECT_EQ((size_t)5, ringbuffer_size(rb));
-
- added = ringbuffer_insert(rb, bb, 5);
- EXPECT_EQ((size_t)0, added);
- EXPECT_EQ((size_t)0, ringbuffer_available(rb));
- EXPECT_EQ((size_t)5, ringbuffer_size(rb));
-
- size_t peeked = ringbuffer_peek(rb, 0, peek, 5);
- EXPECT_EQ((size_t)5, peeked);
- EXPECT_EQ((size_t)0, ringbuffer_available(rb));
- EXPECT_EQ((size_t)5, ringbuffer_size(rb));
-
- ASSERT_EQ(0, memcmp(aa, peek, peeked));
-
- ringbuffer_free(rb);
-}
-
-TEST(RingbufferTest, test_multi_insert_delete) {
- ringbuffer_t* rb = ringbuffer_init(16);
- EXPECT_EQ((size_t)16, ringbuffer_available(rb));
- EXPECT_EQ((size_t)0, ringbuffer_size(rb));
-
- // Insert some bytes
-
- uint8_t aa[] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA};
- size_t added = ringbuffer_insert(rb, aa, sizeof(aa));
- EXPECT_EQ((size_t)8, added);
- EXPECT_EQ((size_t)8, ringbuffer_available(rb));
- EXPECT_EQ((size_t)8, ringbuffer_size(rb));
-
- uint8_t bb[] = {0xBB, 0xBB, 0xBB, 0xBB, 0xBB};
- ringbuffer_insert(rb, bb, sizeof(bb));
- EXPECT_EQ((size_t)3, ringbuffer_available(rb));
- EXPECT_EQ((size_t)13, ringbuffer_size(rb));
-
- uint8_t content[] = {0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA,
- 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, 0xBB};
- uint8_t peek[16] = {0};
- size_t peeked = ringbuffer_peek(rb, 0, peek, 16);
- EXPECT_EQ((size_t)13, peeked);
- ASSERT_EQ(0, memcmp(content, peek, peeked));
-
- // Delete some bytes
-
- ringbuffer_delete(rb, sizeof(aa));
- EXPECT_EQ((size_t)11, ringbuffer_available(rb));
- EXPECT_EQ((size_t)5, ringbuffer_size(rb));
-
- // Add some more to wrap buffer
-
- uint8_t cc[] = {0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC};
- ringbuffer_insert(rb, cc, sizeof(cc));
- EXPECT_EQ((size_t)2, ringbuffer_available(rb));
- EXPECT_EQ((size_t)14, ringbuffer_size(rb));
-
- uint8_t content2[] = {0xBB, 0xBB, 0xBB, 0xBB, 0xBB, 0xCC, 0xCC};
- peeked = ringbuffer_peek(rb, 0, peek, 7);
- EXPECT_EQ((size_t)7, peeked);
- ASSERT_EQ(0, memcmp(content2, peek, peeked));
-
- // Pop buffer
-
- memset(peek, 0, 16);
- size_t popped = ringbuffer_pop(rb, peek, 7);
- EXPECT_EQ((size_t)7, popped);
- EXPECT_EQ((size_t)9, ringbuffer_available(rb));
- ASSERT_EQ(0, memcmp(content2, peek, peeked));
-
- // Add more again to check head motion
-
- uint8_t dd[] = {0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD};
- added = ringbuffer_insert(rb, dd, sizeof(dd));
- EXPECT_EQ((size_t)8, added);
- EXPECT_EQ((size_t)1, ringbuffer_available(rb));
-
- // Delete everything
-
- ringbuffer_delete(rb, 16);
- EXPECT_EQ((size_t)16, ringbuffer_available(rb));
- EXPECT_EQ((size_t)0, ringbuffer_size(rb));
-
- // Add small token
-
- uint8_t ae[] = {0xAE, 0xAE, 0xAE};
- added = ringbuffer_insert(rb, ae, sizeof(ae));
- EXPECT_EQ((size_t)13, ringbuffer_available(rb));
-
- // Get everything
-
- popped = ringbuffer_pop(rb, peek, 16);
- EXPECT_EQ(added, popped);
- EXPECT_EQ((size_t)16, ringbuffer_available(rb));
- EXPECT_EQ((size_t)0, ringbuffer_size(rb));
- ASSERT_EQ(0, memcmp(ae, peek, popped));
-
- ringbuffer_free(rb);
-}
diff --git a/system/packet/tests/fuzzers/reject_packet_fuzzer.cc b/system/packet/tests/fuzzers/reject_packet_fuzzer.cc
index b06b73f55c..5c0ae1d3c7 100644
--- a/system/packet/tests/fuzzers/reject_packet_fuzzer.cc
+++ b/system/packet/tests/fuzzers/reject_packet_fuzzer.cc
@@ -22,9 +22,6 @@
#include "avrcp_test_packets.h"
#include "packet_test_helper.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace bluetooth {
namespace avrcp {
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/pdl/hci/Android.bp b/system/pdl/hci/Android.bp
index 832598aaff..be954a1550 100644
--- a/system/pdl/hci/Android.bp
+++ b/system/pdl/hci/Android.bp
@@ -49,18 +49,3 @@ cc_library_static {
apex_available: ["com.android.bt"],
min_sdk_version: "33",
}
-
-// Generate the python parser+serializer backend
-genrule {
- name: "gd_hci_packets_python3_gen",
- defaults: ["pdl_python_generator_defaults"],
- cmd: "$(location :pdlc) $(in) |" +
- " $(location :pdl_python_generator)" +
- " --output $(out) --custom-type-location blueberry.utils.bluetooth",
- srcs: [
- "hci_packets.pdl",
- ],
- out: [
- "hci_packets.py",
- ],
-}
diff --git a/system/pdl/security/Android.bp b/system/pdl/security/Android.bp
index fbbc2b7339..22e947ee47 100644
--- a/system/pdl/security/Android.bp
+++ b/system/pdl/security/Android.bp
@@ -31,18 +31,3 @@ cc_library_static {
apex_available: ["com.android.bt"],
min_sdk_version: "33",
}
-
-// Generate the python parser+serializer backend
-genrule {
- name: "gd_smp_packets_python3_gen",
- defaults: ["pdl_python_generator_defaults"],
- cmd: "$(location :pdlc) $(in) |" +
- " $(location :pdl_python_generator)" +
- " --output $(out) --custom-type-location blueberry.utils.bluetooth",
- srcs: [
- "smp_packets.pdl",
- ],
- out: [
- "smp_packets.py",
- ],
-}
diff --git a/system/profile/avrcp/Android.bp b/system/profile/avrcp/Android.bp
index 6ea0ea1abb..b75d6da69b 100644
--- a/system/profile/avrcp/Android.bp
+++ b/system/profile/avrcp/Android.bp
@@ -98,6 +98,9 @@ cc_fuzz {
defaults: [
"fluoride_defaults",
],
+ cflags: [
+ "-Wno-missing-prototypes",
+ ],
srcs: [
"tests/avrcp_device_fuzz/avrcp_device_fuzz.cc",
],
diff --git a/system/profile/avrcp/connection_handler.cc b/system/profile/avrcp/connection_handler.cc
index 0851b3320b..5e034e2133 100644
--- a/system/profile/avrcp/connection_handler.cc
+++ b/system/profile/avrcp/connection_handler.cc
@@ -38,9 +38,6 @@
#include "stack/include/sdp_status.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
extern bool btif_av_peer_is_connected_sink(const RawAddress& peer_address);
extern bool btif_av_peer_is_connected_source(const RawAddress& peer_address);
extern bool btif_av_both_enable(void);
@@ -63,7 +60,7 @@ ConnectionHandler* ConnectionHandler::Get() {
return instance_;
}
-bool IsAbsoluteVolumeEnabled(const RawAddress* bdaddr) {
+static bool IsAbsoluteVolumeEnabled(const RawAddress* bdaddr) {
char volume_disabled[PROPERTY_VALUE_MAX] = {0};
osi_property_get("persist.bluetooth.disableabsvol", volume_disabled, "false");
if (strncmp(volume_disabled, "true", 4) == 0) {
diff --git a/system/profile/avrcp/device.cc b/system/profile/avrcp/device.cc
index d094108d8a..dbf67e60ca 100644
--- a/system/profile/avrcp/device.cc
+++ b/system/profile/avrcp/device.cc
@@ -23,6 +23,7 @@
#include "abstract_message_loop.h"
#include "avrcp_common.h"
+#include "btif/include/btif_av.h"
#include "internal_include/stack_config.h"
#include "packet/avrcp/avrcp_reject_packet.h"
#include "packet/avrcp/general_reject_packet.h"
@@ -36,13 +37,6 @@
#include "packet/avrcp/set_player_application_setting_value.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-extern bool btif_av_peer_is_connected_sink(const RawAddress& peer_address);
-extern bool btif_av_both_enable(void);
-extern bool btif_av_src_sink_coexist_enabled(void);
-
template <>
struct std::formatter<bluetooth::avrcp::PlayState> : enum_formatter<bluetooth::avrcp::PlayState> {};
@@ -90,7 +84,7 @@ void Device::SetBipClientStatus(bool connected) {
bool Device::HasBipClient() const { return has_bip_client_; }
-void filter_cover_art(SongInfo& s) {
+static void filter_cover_art(SongInfo& s) {
for (auto it = s.attributes.begin(); it != s.attributes.end(); it++) {
if (it->attribute() == Attribute::DEFAULT_COVER_ART) {
s.attributes.erase(it);
@@ -1395,8 +1389,8 @@ void Device::GetMediaPlayerListResponse(uint8_t label, std::shared_ptr<GetFolder
send_message(label, true, std::move(builder));
}
-std::set<AttributeEntry> filter_attributes_requested(const SongInfo& song,
- const std::vector<Attribute>& attrs) {
+static std::set<AttributeEntry> filter_attributes_requested(const SongInfo& song,
+ const std::vector<Attribute>& attrs) {
std::set<AttributeEntry> result;
for (const auto& attr : attrs) {
if (song.attributes.find(attr) != song.attributes.end()) {
diff --git a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
index 54f78edcd4..45a10722ae 100644
--- a/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
+++ b/system/profile/avrcp/tests/avrcp_connection_handler_test.cc
@@ -23,14 +23,12 @@
#include "avrcp_internal.h"
#include "avrcp_test_helper.h"
+#include "btif/include/btif_av.h"
#include "connection_handler.h"
#include "sdpdefs.h"
#include "stack/include/sdp_status.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using ::testing::_;
using ::testing::DoAll;
using ::testing::MockFunction;
diff --git a/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc b/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc
index 3bfce3f1fa..39a6d776ea 100644
--- a/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc
+++ b/system/profile/avrcp/tests/avrcp_device_fuzz/avrcp_device_fuzz.cc
@@ -21,9 +21,6 @@
#include "packet_test_helper.h"
#include "pass_through_packet.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool btif_av_src_sink_coexist_enabled(void) { return true; }
namespace bluetooth {
diff --git a/system/profile/avrcp/tests/avrcp_device_test.cc b/system/profile/avrcp/tests/avrcp_device_test.cc
index 204a1e7548..209920817b 100644
--- a/system/profile/avrcp/tests/avrcp_device_test.cc
+++ b/system/profile/avrcp/tests/avrcp_device_test.cc
@@ -24,15 +24,13 @@
#include "avrcp_packet.h"
#include "avrcp_test_helper.h"
+#include "btif/include/btif_av.h"
#include "device.h"
#include "internal_include/stack_config.h"
#include "tests/avrcp/avrcp_test_packets.h"
#include "tests/packet_test_helper.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool btif_av_src_sink_coexist_enabled(void) { return true; }
namespace bluetooth {
@@ -52,7 +50,7 @@ using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SaveArg;
-bool get_pts_avrcp_test(void) { return false; }
+static bool get_pts_avrcp_test(void) { return false; }
const stack_config_t interface = {get_pts_avrcp_test,
nullptr,
diff --git a/system/stack/Android.bp b/system/stack/Android.bp
index 13d7984359..9015c4daa8 100644
--- a/system/stack/Android.bp
+++ b/system/stack/Android.bp
@@ -29,10 +29,12 @@ cc_library_static {
min_sdk_version: "Tiramisu",
}
-// Bluetooth stack static library for target
cc_library_static {
name: "libbt-stack",
- defaults: ["fluoride_defaults"],
+ defaults: [
+ "fluoride_defaults",
+ "hfp_hal_defaults",
+ ],
local_include_dirs: [
"ais",
"avct",
@@ -63,6 +65,7 @@ cc_library_static {
"external/libldac/inc",
"external/libopus/include",
"packages/modules/Bluetooth/system",
+ "packages/modules/Bluetooth/system/bta/ag",
"packages/modules/Bluetooth/system/bta/include",
"packages/modules/Bluetooth/system/bta/sys",
"packages/modules/Bluetooth/system/btif/include",
@@ -71,6 +74,7 @@ cc_library_static {
"packages/modules/Bluetooth/system/udrv/include",
],
srcs: [
+ ":LegacyStackSdp",
"a2dp/a2dp_aac.cc",
"a2dp/a2dp_aac_decoder.cc",
"a2dp/a2dp_aac_encoder.cc",
@@ -91,6 +95,12 @@ cc_library_static {
"a2dp/a2dp_vendor_opus.cc",
"a2dp/a2dp_vendor_opus_decoder.cc",
"a2dp/a2dp_vendor_opus_encoder.cc",
+ "acl/acl.cc",
+ "acl/ble_acl.cc",
+ "acl/btm_acl.cc",
+ "acl/btm_pm.cc",
+ "ais/ais_ble.cc",
+ "arbiter/acl_arbiter.cc",
"avct/avct_api.cc",
"avct/avct_bcb_act.cc",
"avct/avct_ccb.cc",
@@ -117,130 +127,6 @@ cc_library_static {
"bnep/bnep_api.cc",
"bnep/bnep_main.cc",
"bnep/bnep_utils.cc",
- "btm/hfp_lc3_decoder.cc",
- "btm/hfp_lc3_encoder.cc",
- "btm/hfp_msbc_decoder.cc",
- "btm/hfp_msbc_encoder.cc",
- "hid/hidd_api.cc",
- "hid/hidd_conn.cc",
- "hid/hidh_api.cc",
- "hid/hidh_conn.cc",
- "pan/pan_api.cc",
- "pan/pan_main.cc",
- "pan/pan_utils.cc",
- ],
- static_libs: [
- "bluetooth_flags_c_lib",
- "libbluetooth_crypto_toolbox",
- "libbluetooth_hci_pdl",
- "libbluetooth_log",
- "libbt-btu-main-thread",
- "libbt-hci",
- "libbt-platform-protos-lite",
- "libbt-stack-core",
- "liblc3",
- ],
- whole_static_libs: [
- "libaptx_enc",
- "libaptxhd_enc",
- "libcom.android.sysprop.bluetooth.wrapped",
- "libldacBT_abr",
- "libldacBT_enc",
- ],
- apex_available: ["com.android.bt"],
- host_supported: true,
- min_sdk_version: "Tiramisu",
-}
-
-filegroup {
- name: "LegacyStackSdp",
- srcs: [
- "sdp/sdp_api.cc",
- "sdp/sdp_db.cc",
- "sdp/sdp_discovery.cc",
- "sdp/sdp_main.cc",
- "sdp/sdp_server.cc",
- "sdp/sdp_utils.cc",
- ],
-}
-
-soong_config_module_type {
- name: "hfp_hal_cc_defaults",
- module_type: "cc_defaults",
- config_namespace: "hfp_hal",
- variables: ["vertical"],
- properties: ["srcs"],
-}
-
-soong_config_string_variable {
- name: "vertical",
- values: [
- "android_default",
- "android_desktop",
- ],
-}
-
-hfp_hal_cc_defaults {
- name: "hfp_hal_defaults",
- soong_config_variables: {
- vertical: {
- android_desktop: {
- srcs: ["btm/btm_sco_hfp_hal_linux.cc"],
- },
- android_default: {
- srcs: ["btm/btm_sco_hfp_hal.cc"],
- },
- conditions_default: {
- srcs: ["btm/btm_sco_hfp_hal.cc"],
- },
- },
- },
-}
-
-cc_library_static {
- name: "libbt-stack-core",
- defaults: [
- "fluoride_defaults",
- "hfp_hal_defaults",
- ],
- local_include_dirs: [
- "ais",
- "avct",
- "avdt",
- "avrc",
- "bnep",
- "btm",
- "eatt",
- "gap",
- "gatt",
- "hid",
- "include",
- "l2cap",
- "metrics",
- "pan",
- "sdp",
- "smp",
- "srvc",
- ],
- header_libs: [
- "libbluetooth_headers",
- ],
- include_dirs: [
- "packages/modules/Bluetooth/system",
- "packages/modules/Bluetooth/system/bta/ag",
- "packages/modules/Bluetooth/system/bta/include",
- "packages/modules/Bluetooth/system/bta/sys",
- "packages/modules/Bluetooth/system/gd",
- "packages/modules/Bluetooth/system/udrv/include",
- ],
- srcs: [
- ":LegacyStackSdp",
- "acl/acl.cc",
- "acl/ble_acl.cc",
- "acl/btm_acl.cc",
- "acl/btm_pm.cc",
- "ais/ais_ble.cc",
- "arbiter/acl_arbiter.cc",
"btm/ble_scanner_hci_interface.cc",
"btm/btm_ble.cc",
"btm/btm_ble_addr.cc",
@@ -262,6 +148,10 @@ cc_library_static {
"btm/btm_sec.cc",
"btm/btm_sec_cb.cc",
"btm/btm_security_client_interface.cc",
+ "btm/hfp_lc3_decoder.cc",
+ "btm/hfp_lc3_encoder.cc",
+ "btm/hfp_msbc_decoder.cc",
+ "btm/hfp_msbc_encoder.cc",
"btm/security_event_parser.cc",
"btu/btu_hcif.cc",
"connection_manager/connection_manager.cc",
@@ -280,6 +170,10 @@ cc_library_static {
"gatt/gatt_utils.cc",
"hcic/hciblecmds.cc",
"hcic/hcicmds.cc",
+ "hid/hidd_api.cc",
+ "hid/hidd_conn.cc",
+ "hid/hidh_api.cc",
+ "hid/hidh_conn.cc",
"l2cap/l2c_api.cc",
"l2cap/l2c_ble.cc",
"l2cap/l2c_ble_conn_params.cc",
@@ -290,6 +184,9 @@ cc_library_static {
"l2cap/l2c_utils.cc",
"l2cap/l2cap_api.cc",
"metrics/stack_metrics_logging.cc",
+ "pan/pan_api.cc",
+ "pan/pan_main.cc",
+ "pan/pan_utils.cc",
"rfcomm/port_api.cc",
"rfcomm/port_rfc.cc",
"rfcomm/port_utils.cc",
@@ -317,10 +214,6 @@ cc_library_static {
generated_headers: [
"cxx-bridge-header",
],
- cflags: [
- /* we export all classes, so change default visibility, instead of having EXPORT_SYMBOL on each class*/
- "-fvisibility=default",
- ],
static_libs: [
"bluetooth_flags_c_lib",
"libaconfig_storage_read_api_cc",
@@ -329,11 +222,20 @@ cc_library_static {
"libbluetooth_gd",
"libbluetooth_hci_pdl",
"libbluetooth_log",
+ "libbt-btu-main-thread",
"libbt-hci",
"libbt-platform-protos-lite",
"libcom.android.sysprop.bluetooth.wrapped",
+ "liblc3",
"server_configurable_flags",
],
+ whole_static_libs: [
+ "libaptx_enc",
+ "libaptxhd_enc",
+ "libcom.android.sysprop.bluetooth.wrapped",
+ "libldacBT_abr",
+ "libldacBT_enc",
+ ],
shared_libs: [
"libPlatformProperties",
"libcrypto",
@@ -343,6 +245,51 @@ cc_library_static {
min_sdk_version: "Tiramisu",
}
+filegroup {
+ name: "LegacyStackSdp",
+ srcs: [
+ "sdp/sdp_api.cc",
+ "sdp/sdp_db.cc",
+ "sdp/sdp_discovery.cc",
+ "sdp/sdp_main.cc",
+ "sdp/sdp_server.cc",
+ "sdp/sdp_utils.cc",
+ ],
+}
+
+soong_config_module_type {
+ name: "hfp_hal_cc_defaults",
+ module_type: "cc_defaults",
+ config_namespace: "hfp_hal",
+ variables: ["vertical"],
+ properties: ["srcs"],
+}
+
+soong_config_string_variable {
+ name: "vertical",
+ values: [
+ "android_default",
+ "android_desktop",
+ ],
+}
+
+hfp_hal_cc_defaults {
+ name: "hfp_hal_defaults",
+ soong_config_variables: {
+ vertical: {
+ android_desktop: {
+ srcs: ["btm/btm_sco_hfp_hal_linux.cc"],
+ },
+ android_default: {
+ srcs: ["btm/btm_sco_hfp_hal.cc"],
+ },
+ conditions_default: {
+ srcs: ["btm/btm_sco_hfp_hal.cc"],
+ },
+ },
+ },
+}
+
cc_defaults {
name: "btstack_fuzzer_default",
host_supported: true,
@@ -468,7 +415,6 @@ cc_fuzz {
":TestMockDevice",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockSrvcDis",
":TestMockStackAcl",
":TestMockStackArbiter",
@@ -520,7 +466,6 @@ cc_fuzz {
":TestMockDevice",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockSrvcDis",
":TestMockStackAcl",
":TestMockStackArbiter",
@@ -793,7 +738,6 @@ cc_test {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -801,11 +745,9 @@ cc_test {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libflags_rust_cpp_bridge",
@@ -1141,7 +1083,6 @@ cc_test {
srcs: [
":TestCommonMockFunctions",
":TestMockMainShim",
- ":TestMockRustFfi",
":TestMockStackArbiter",
":TestMockStackBtm",
":TestMockStackConnMgr",
@@ -1422,6 +1363,7 @@ cc_test {
"libprotobuf-cpp-lite",
],
static_libs: [
+ "bluetooth_flags_c_lib",
"libFraunhoferAAC",
"libbase",
"libbluetooth-types",
@@ -1476,7 +1418,6 @@ cc_test {
":TestMockBtif",
":TestMockDevice",
":TestMockMainShim",
- ":TestMockRustFfi",
":TestMockStackBtm",
":TestMockStackConnMgr",
":TestMockStackL2cap",
@@ -1691,10 +1632,8 @@ cc_test {
":TestMockBtif",
":TestMockDevice",
":TestMockLegacyHciInterface",
- ":TestMockMainBte",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockStackBtu",
":TestMockStackConnMgr",
":TestMockStackGap",
@@ -1946,7 +1885,6 @@ cc_test {
":TestMockBta",
":TestMockBtif",
":TestMockHci",
- ":TestMockLegacyHciCommands",
":TestMockMainShim",
":TestMockMainShimEntry",
":TestMockStackAcl",
@@ -2024,10 +1962,8 @@ cc_test {
":TestMockBta",
":TestMockBtif",
":TestMockHci",
- ":TestMockLegacyHciCommands",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockSrvcDis",
":TestMockStackAcl",
":TestMockStackBtm",
@@ -2128,7 +2064,6 @@ cc_test {
":TestMockBtif",
":TestMockHci",
":TestMockJni",
- ":TestMockLegacyHciCommands",
":TestMockMainShim",
":TestMockMainShimEntry",
":TestMockStackAcl",
@@ -2227,11 +2162,9 @@ cc_test {
":TestMockBtif",
":TestMockDevice",
":TestMockHci",
- ":TestMockLegacyHciCommands",
":TestMockLegacyHciInterface",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockStackBtm",
":TestMockStackBtu",
":TestMockStackConnMgr",
@@ -2325,10 +2258,8 @@ cc_test {
":TestMockBtif",
":TestMockDevice",
":TestMockLegacyHciInterface",
- ":TestMockMainBte",
":TestMockMainShim",
":TestMockMainShimEntry",
- ":TestMockRustFfi",
":TestMockStackBtm",
":TestMockStackBtu",
":TestMockStackGap",
diff --git a/system/stack/avdt/avdt_int.h b/system/stack/avdt/avdt_int.h
index 73ff0c9103..8311480ed0 100644
--- a/system/stack/avdt/avdt_int.h
+++ b/system/stack/avdt/avdt_int.h
@@ -439,6 +439,7 @@ class AvdtpScb {
public:
AvdtpScb()
: transport_channel_timer(nullptr),
+ init_delay_report_timer(nullptr),
p_pkt(nullptr),
p_ccb(nullptr),
media_seq(0),
diff --git a/system/stack/btm/btm_ble.cc b/system/stack/btm/btm_ble.cc
index b612b684b3..2251835c7d 100644
--- a/system/stack/btm/btm_ble.cc
+++ b/system/stack/btm/btm_ble.cc
@@ -182,8 +182,7 @@ void BTM_BleReadPhy(const RawAddress& bd_addr,
uint8_t data[len];
uint8_t* pp = data;
UINT16_TO_STREAM(pp, handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_READ_PHY, data, len,
- base::Bind(&read_phy_cb, std::move(cb)));
+ btu_hcif_send_cmd_with_cb(HCI_BLE_READ_PHY, data, len, base::Bind(&read_phy_cb, std::move(cb)));
}
void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys,
@@ -229,6 +228,5 @@ void BTM_BleSetPhy(const RawAddress& bd_addr, uint8_t tx_phys, uint8_t rx_phys,
UINT8_TO_STREAM(pp, tx_phys);
UINT8_TO_STREAM(pp, rx_phys);
UINT16_TO_STREAM(pp, phy_options);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_SET_PHY, data, len,
- base::Bind([](uint8_t*, uint16_t) {}));
+ btu_hcif_send_cmd_with_cb(HCI_BLE_SET_PHY, data, len, base::Bind([](uint8_t*, uint16_t) {}));
}
diff --git a/system/stack/btm/btm_ble_adv_filter.cc b/system/stack/btm/btm_ble_adv_filter.cc
index 73050b5047..7f064132b8 100644
--- a/system/stack/btm/btm_ble_adv_filter.cc
+++ b/system/stack/btm/btm_ble_adv_filter.cc
@@ -382,7 +382,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I
BTM_BLE_ADV_FILT_TRACK_NUM;
}
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param, len,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param, len,
base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb));
} else if (BTM_BLE_SCAN_COND_DELETE == action) {
/* select feature based on control block settings */
@@ -391,7 +391,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I
/* Filter index */
UINT8_TO_STREAM(p, filt_index);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param,
(uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH),
base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb));
@@ -403,7 +403,7 @@ void BTM_BleAdvFilterParamSetup(tBTM_BLE_SCAN_COND_OP action, tBTM_BLE_PF_FILT_I
UINT8_TO_STREAM(p, BTM_BLE_META_PF_FEAT_SEL);
UINT8_TO_STREAM(p, BTM_BLE_SCAN_COND_CLEAR);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADV_FILTER, param,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_ADV_FILTER, param,
(uint8_t)(BTM_BLE_ADV_FILT_META_HDR_LENGTH - 1),
base::Bind(&btm_flt_update_cb, BTM_BLE_META_PF_FEAT_SEL, cb));
}
diff --git a/system/stack/btm/btm_ble_sec.cc b/system/stack/btm/btm_ble_sec.cc
index 29d48e6033..db2efdd54b 100644
--- a/system/stack/btm/btm_ble_sec.cc
+++ b/system/stack/btm/btm_ble_sec.cc
@@ -631,6 +631,9 @@ tBTM_STATUS BTM_SetBleDataLength(const RawAddress& bd_addr, uint16_t tx_pdu_leng
tx_time,
bluetooth::shim::GetController()->GetLeMaximumDataLength().supported_max_tx_time_);
+ log::info("Requesting actual tx_pdu_length:{} and tx_time:{} for bd_addr:{}",
+ tx_pdu_length, tx_time, bd_addr);
+
btsnd_hcic_ble_set_data_length(hci_handle, tx_pdu_length, tx_time);
p_dev_rec->set_suggested_tx_octect(tx_pdu_length);
@@ -2109,11 +2112,6 @@ std::optional<Octet16> BTM_BleGetPeerIRK(const RawAddress address) {
return p_dev_rec->sec_rec.ble_keys.irk;
}
-bool BTM_BleIsLinkKeyKnown(const RawAddress address) {
- tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
- return p_dev_rec != nullptr && p_dev_rec->sec_rec.is_le_link_key_known();
-}
-
std::optional<tBLE_BD_ADDR> BTM_BleGetIdentityAddress(const RawAddress address) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(address);
if (p_dev_rec == nullptr) {
diff --git a/system/stack/btm/btm_dev.cc b/system/stack/btm/btm_dev.cc
index 2745041d82..e2fb4387d7 100644
--- a/system/stack/btm/btm_dev.cc
+++ b/system/stack/btm/btm_dev.cc
@@ -84,7 +84,7 @@ void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, LinkKey li
uint8_t key_type, uint8_t pin_length) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- if (!p_dev_rec) {
+ if (p_dev_rec == nullptr) {
p_dev_rec = btm_sec_allocate_dev_rec();
if (p_dev_rec == nullptr) {
@@ -118,14 +118,6 @@ void BTM_SecAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, LinkKey li
/* "Bump" timestamp for existing record */
p_dev_rec->timestamp = btm_sec_cb.dev_rec_count++;
-
- /* TODO(eisenbach):
- * Small refactor, but leaving original logic for now.
- * On the surface, this does not make any sense at all. Why change the
- * bond state for an existing device here? This logic should be verified
- * as part of a larger refactor.
- */
- p_dev_rec->sec_rec.bond_type = BOND_TYPE_UNKNOWN;
}
if (dev_class != kDevClassEmpty) {
diff --git a/system/stack/btm/btm_sec.cc b/system/stack/btm/btm_sec.cc
index 2ee496e5e5..723ba972dc 100644
--- a/system/stack/btm/btm_sec.cc
+++ b/system/stack/btm/btm_sec.cc
@@ -407,8 +407,8 @@ bool BTM_IsLinkKeyAuthed(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
return btm_sec_cb.IsLinkKeyAuthenticated(bd_addr, transport);
}
-bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
- return btm_sec_cb.IsLinkKeyKnown(bd_addr, transport);
+bool BTM_IsBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
+ return btm_sec_cb.IsDeviceBonded(bd_addr, transport);
}
bool BTM_IsAuthenticated(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
@@ -797,8 +797,15 @@ tBTM_STATUS BTM_SecBond(const RawAddress& bd_addr, tBLE_ADDR_TYPE addr_type,
tBT_TRANSPORT transport, tBT_DEVICE_TYPE /* device_type */) {
if (transport == BT_TRANSPORT_AUTO) {
if (addr_type == BLE_ADDR_PUBLIC) {
- transport = get_btm_client_interface().ble.BTM_UseLeLink(bd_addr) ? BT_TRANSPORT_LE
- : BT_TRANSPORT_BR_EDR;
+ bool is_discovered_over_le_only = false;
+ tBTM_INQ_INFO* p_inq_info = BTM_InqDbRead(bd_addr);
+ if (p_inq_info != nullptr && com::android::bluetooth::flags::auto_transport_pairing()) {
+ uint8_t inq_result_type = 0;
+ inq_result_type = p_inq_info->results.inq_result_type;
+ is_discovered_over_le_only = (inq_result_type == BT_DEVICE_TYPE_BLE);
+ }
+ transport = (get_btm_client_interface().ble.BTM_UseLeLink(bd_addr) ||
+ is_discovered_over_le_only) ? BT_TRANSPORT_LE: BT_TRANSPORT_BR_EDR;
} else {
log::info("Forcing transport LE (was auto) because of the address type");
transport = BT_TRANSPORT_LE;
@@ -1979,7 +1986,7 @@ void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) {
* Returns void
*
******************************************************************************/
-void btm_sec_check_pending_reqs(void) {
+static void btm_sec_check_pending_reqs(void) {
if (btm_sec_cb.pairing_state == BTM_PAIR_STATE_IDLE) {
/* First, resubmit L2CAP requests */
if (btm_sec_cb.sec_req_pending) {
diff --git a/system/stack/btm/btm_sec.h b/system/stack/btm/btm_sec.h
index ade49b883e..05bafc40d5 100644
--- a/system/stack/btm/btm_sec.h
+++ b/system/stack/btm/btm_sec.h
@@ -57,7 +57,7 @@ bool BTM_SecRegister(const tBTM_APPL_INFO* p_cb_info);
bool BTM_IsEncrypted(const RawAddress& bd_addr, tBT_TRANSPORT transport);
bool BTM_IsLinkKeyAuthed(const RawAddress& bd_addr, tBT_TRANSPORT transport);
-bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport);
+bool BTM_IsBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport = BT_TRANSPORT_AUTO);
bool BTM_IsAuthenticated(const RawAddress& bd_addr, tBT_TRANSPORT transport);
bool BTM_CanReadDiscoverableCharacteristics(const RawAddress& bd_addr);
void BTM_update_version_info(const RawAddress& bd_addr,
diff --git a/system/stack/btm/btm_sec_cb.cc b/system/stack/btm/btm_sec_cb.cc
index c40d8fe416..a4cb8ea26e 100644
--- a/system/stack/btm/btm_sec_cb.cc
+++ b/system/stack/btm/btm_sec_cb.cc
@@ -20,6 +20,7 @@
#include "stack/btm/btm_sec_cb.h"
#include <bluetooth/log.h>
+#include <com_android_bluetooth_flags.h>
#include <cstdint>
@@ -117,7 +118,7 @@ tBTM_SEC_SERV_REC* tBTM_SEC_CB::find_first_serv_rec(bool is_originator, uint16_t
tBTM_SEC_REC* tBTM_SEC_CB::getSecRec(const RawAddress bd_addr) {
tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- if (p_dev_rec) {
+ if (p_dev_rec != nullptr) {
return &p_dev_rec->sec_rec;
}
return nullptr;
@@ -171,33 +172,29 @@ bool tBTM_SEC_CB::IsDeviceAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT
return false;
}
-bool tBTM_SEC_CB::IsLinkKeyKnown(const RawAddress bd_addr, tBT_TRANSPORT transport) {
+bool tBTM_SEC_CB::IsDeviceBonded(const RawAddress bd_addr, tBT_TRANSPORT transport) {
tBTM_SEC_REC* sec_rec = getSecRec(bd_addr);
- if (sec_rec) {
- if (transport == BT_TRANSPORT_BR_EDR) {
- return sec_rec->is_link_key_known();
- } else if (transport == BT_TRANSPORT_LE) {
- return sec_rec->is_le_link_key_known();
- }
- log::error("unknown transport:{}", bt_transport_text(transport));
+ if (sec_rec == nullptr) {
return false;
}
- log::error("unknown device:{}", bd_addr);
- return false;
-}
+ bool bonded = false;
-bool tBTM_SEC_CB::IsDeviceBonded(const RawAddress bd_addr) {
- tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(bd_addr);
- bool is_bonded = false;
+ // Check BR/EDR bond status if requested transport is BT_TRANSPORT_BR_EDR or BT_TRANSPORT_AUTO
+ if (transport != BT_TRANSPORT_LE) {
+ if (com::android::bluetooth::flags::temporary_pairing_tracking()) {
+ bonded = sec_rec->is_bond_type_persistent() && sec_rec->is_link_key_known();
+ } else {
+ bonded = sec_rec->is_link_key_known();
+ }
+ }
- if (p_dev_rec &&
- ((p_dev_rec->sec_rec.ble_keys.key_type && p_dev_rec->sec_rec.is_le_link_key_known()) ||
- p_dev_rec->sec_rec.is_link_key_known())) {
- is_bonded = true;
+ // Check LE bond status if requested transport is BT_TRANSPORT_LE or BT_TRANSPORT_AUTO
+ if (transport != BT_TRANSPORT_BR_EDR) {
+ bonded |= (sec_rec->ble_keys.key_type != BTM_LE_KEY_NONE && sec_rec->is_le_link_key_known());
}
- log::debug("Device record bonded check peer:{} is_bonded:{}", bd_addr, is_bonded);
- return is_bonded;
+
+ return bonded;
}
#define BTM_NO_AVAIL_SEC_SERVICES ((uint16_t)0xffff)
diff --git a/system/stack/btm/btm_sec_cb.h b/system/stack/btm/btm_sec_cb.h
index b851aa32cb..1e3ae3b258 100644
--- a/system/stack/btm/btm_sec_cb.h
+++ b/system/stack/btm/btm_sec_cb.h
@@ -84,13 +84,11 @@ public:
tBTM_SEC_SERV_REC* find_first_serv_rec(bool is_originator, uint16_t psm);
- bool IsDeviceBonded(const RawAddress bd_addr);
+ bool IsDeviceBonded(const RawAddress bd_addr, tBT_TRANSPORT transport = BT_TRANSPORT_AUTO);
bool IsDeviceEncrypted(const RawAddress bd_addr, tBT_TRANSPORT transport);
bool IsDeviceAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport);
bool IsLinkKeyAuthenticated(const RawAddress bd_addr, tBT_TRANSPORT transport);
- bool IsLinkKeyKnown(const RawAddress bd_addr, tBT_TRANSPORT transport);
-
tBTM_SEC_REC* getSecRec(const RawAddress bd_addr);
bool AddService(bool is_originator, const char* p_name, uint8_t service_id, uint16_t sec_level,
diff --git a/system/stack/btm/btm_security_client_interface.cc b/system/stack/btm/btm_security_client_interface.cc
index 3adda4d0f8..ae3161b6e0 100644
--- a/system/stack/btm/btm_security_client_interface.cc
+++ b/system/stack/btm/btm_security_client_interface.cc
@@ -55,7 +55,7 @@ static SecurityClientInterface security = {
.BTM_SetEncryption = BTM_SetEncryption,
.BTM_IsEncrypted = BTM_IsEncrypted,
.BTM_SecIsLeSecurityPending = BTM_SecIsLeSecurityPending,
- .BTM_IsLinkKeyKnown = BTM_IsLinkKeyKnown,
+ .BTM_IsBonded = BTM_IsBonded,
.BTM_SetSecurityLevel = BTM_SetSecurityLevel,
.BTM_SecClrService = BTM_SecClrService,
diff --git a/system/stack/btm/security_device_record.h b/system/stack/btm/security_device_record.h
index 61a6d182a6..c7074ec253 100644
--- a/system/stack/btm/security_device_record.h
+++ b/system/stack/btm/security_device_record.h
@@ -221,12 +221,11 @@ struct tBTM_SEC_REC {
LinkKey link_key; /* Device link key */
uint8_t link_key_type; /* Type of key used in pairing */
uint8_t enc_key_size; /* current link encryption key size */
+ tBTM_BOND_TYPE bond_type; /* Whether the BR/EDR pairing was persistent or temporary */
// LE Link Key Info
tBTM_SEC_BLE_KEYS ble_keys;
- tBTM_BOND_TYPE bond_type; /* bond type */
-
public:
bool is_device_authenticated() const { return sec_flags & BTM_SEC_AUTHENTICATED; }
void set_device_authenticated() { sec_flags |= BTM_SEC_AUTHENTICATED; }
diff --git a/system/stack/btu/btu_hcif.cc b/system/stack/btu/btu_hcif.cc
index 7d8a0cd618..7a4b6d1256 100644
--- a/system/stack/btu/btu_hcif.cc
+++ b/system/stack/btu/btu_hcif.cc
@@ -64,7 +64,6 @@
#include "types/raw_address.h"
using namespace bluetooth;
-using base::Location;
using bluetooth::hci::IsoManager;
/******************************************************************************/
@@ -574,18 +573,13 @@ using hci_cmd_cb = base::OnceCallback<void(uint8_t* /* return_parameters */,
struct cmd_with_cb_data {
hci_cmd_cb cb;
- base::Location posted_from;
};
static void cmd_with_cb_data_init(cmd_with_cb_data* cb_wrapper) {
new (&cb_wrapper->cb) hci_cmd_cb;
- new (&cb_wrapper->posted_from) Location;
}
-static void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) {
- cb_wrapper->cb.~hci_cmd_cb();
- cb_wrapper->posted_from.~Location();
-}
+static void cmd_with_cb_data_cleanup(cmd_with_cb_data* cb_wrapper) { cb_wrapper->cb.~hci_cmd_cb(); }
/**
* Log command complete events that is not handled individually in this file
@@ -646,7 +640,6 @@ static void btu_hcif_command_complete_evt_with_cb_on_task(BT_HDR* event, void* c
btu_hcif_log_command_complete_metrics(opcode, stream);
cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context;
- log::verbose("command complete for: {}", cb_wrapper->posted_from.ToString());
// 2 for event header: event code (1) + parameter length (1)
// 3 for command complete header: num_hci_pkt (1) + opcode (2)
uint16_t param_len = static_cast<uint16_t>(event->len - 5);
@@ -676,7 +669,6 @@ static void btu_hcif_command_status_evt_with_cb_on_task(uint8_t status, BT_HDR*
// report command status error
cmd_with_cb_data* cb_wrapper = (cmd_with_cb_data*)context;
- log::verbose("command status for: {}", cb_wrapper->posted_from.ToString());
std::move(cb_wrapper->cb).Run(&status, sizeof(uint16_t));
cmd_with_cb_data_cleanup(cb_wrapper);
osi_free(cb_wrapper);
@@ -698,8 +690,8 @@ static void btu_hcif_command_status_evt_with_cb(uint8_t status, BT_HDR* command,
/* This function is called to send commands to the Host Controller. |cb| is
* called when command status event is called with error code, or when the
* command complete event is received. */
-void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params,
- uint8_t params_len, hci_cmd_cb cb) {
+void btu_hcif_send_cmd_with_cb(uint16_t opcode, uint8_t* params, uint8_t params_len,
+ hci_cmd_cb cb) {
BT_HDR* p = (BT_HDR*)osi_malloc(HCI_CMD_BUF_SIZE);
uint8_t* pp = (uint8_t*)(p + 1);
@@ -718,7 +710,6 @@ void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcod
cmd_with_cb_data_init(cb_wrapper);
cb_wrapper->cb = std::move(cb);
- cb_wrapper->posted_from = posted_from;
bluetooth::shim::hci_layer_get_interface()->transmit_command(
p, btu_hcif_command_complete_evt_with_cb, btu_hcif_command_status_evt_with_cb,
diff --git a/system/stack/btu/main_thread.cc b/system/stack/btu/main_thread.cc
index 6223e66716..6364f81e8b 100644
--- a/system/stack/btu/main_thread.cc
+++ b/system/stack/btu/main_thread.cc
@@ -37,7 +37,7 @@ bluetooth::common::MessageLoopThread* get_main_thread() { return &main_thread; }
bluetooth::common::PostableContext* get_main() { return main_thread.Postable(); }
bt_status_t do_in_main_thread(base::OnceClosure task) {
- if (!main_thread.DoInThread(FROM_HERE, std::move(task))) {
+ if (!main_thread.DoInThread(std::move(task))) {
log::error("failed to post task to task runner!");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
@@ -45,7 +45,7 @@ bt_status_t do_in_main_thread(base::OnceClosure task) {
}
bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::microseconds delay) {
- if (!main_thread.DoInThreadDelayed(FROM_HERE, std::move(task), delay)) {
+ if (!main_thread.DoInThreadDelayed(std::move(task), delay)) {
log::error("failed to post task to task runner!");
return BT_STATUS_JNI_THREAD_ATTACH_ERROR;
}
diff --git a/system/stack/connection_manager/connection_manager.cc b/system/stack/connection_manager/connection_manager.cc
index 3b13c63adc..ff878d84ac 100644
--- a/system/stack/connection_manager/connection_manager.cc
+++ b/system/stack/connection_manager/connection_manager.cc
@@ -53,25 +53,20 @@ constexpr char kBtmLogTagTA[] = "TA";
struct closure_data {
base::OnceClosure user_task;
- base::Location posted_from;
};
extern std::string get_client_name(uint8_t gatt_if);
static void alarm_closure_cb(void* p) {
closure_data* data = (closure_data*)p;
- log::verbose("executing timer scheduled at {}", data->posted_from.ToString());
std::move(data->user_task).Run();
delete data;
}
// Periodic alarms are not supported, because we clean up data in callback
-static void alarm_set_closure(const base::Location& posted_from, alarm_t* alarm,
- uint64_t interval_ms, base::OnceClosure user_task) {
+static void alarm_set_closure(alarm_t* alarm, uint64_t interval_ms, base::OnceClosure user_task) {
closure_data* data = new closure_data;
- data->posted_from = posted_from;
data->user_task = std::move(user_task);
- log::verbose("scheduling timer {}", data->posted_from.ToString());
alarm_set_on_mloop(alarm, interval_ms, alarm_closure_cb, data);
}
@@ -561,7 +556,7 @@ bool direct_connect_add(uint8_t app_id, const RawAddress& address, tBLE_ADDR_TYP
// Setup a timer
alarm_t* timeout = alarm_new("wl_conn_params_30s");
- alarm_set_closure(FROM_HERE, timeout, DIRECT_CONNECT_TIMEOUT,
+ alarm_set_closure(timeout, DIRECT_CONNECT_TIMEOUT,
base::BindOnce(&wl_direct_connect_timeout_cb, app_id, address));
bgconn_dev[address].doing_direct_conn.emplace(app_id, unique_alarm_ptr(timeout, &alarm_free));
diff --git a/system/stack/eatt/eatt_impl.h b/system/stack/eatt/eatt_impl.h
index c746695cb7..0d27726af4 100644
--- a/system/stack/eatt/eatt_impl.h
+++ b/system/stack/eatt/eatt_impl.h
@@ -308,7 +308,7 @@ struct eatt_impl {
std::vector<uint16_t> empty;
tL2CAP_LE_RESULT_CODE result =
tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_AUTHENTICATION;
- if (BTM_IsLinkKeyKnown(bda, BT_TRANSPORT_LE)) {
+ if (BTM_IsBonded(bda, BT_TRANSPORT_LE)) {
result = tL2CAP_LE_RESULT_CODE::L2CAP_LE_RESULT_INSUFFICIENT_ENCRYP;
}
log::error("ACL to device {} is unencrypted.", bda);
diff --git a/system/stack/gatt/gatt_auth.cc b/system/stack/gatt/gatt_auth.cc
index 4323c8ed13..7c4b935389 100644
--- a/system/stack/gatt/gatt_auth.cc
+++ b/system/stack/gatt/gatt_auth.cc
@@ -299,7 +299,7 @@ static tGATT_SEC_ACTION gatt_determine_sec_act(tGATT_CLCB* p_clcb) {
return GATT_SEC_ENC_PENDING;
}
- is_link_key_known = BTM_IsLinkKeyKnown(p_tcb->peer_bda, p_clcb->p_tcb->transport);
+ is_link_key_known = BTM_IsBonded(p_tcb->peer_bda, p_clcb->p_tcb->transport);
is_link_encrypted = BTM_IsEncrypted(p_tcb->peer_bda, p_clcb->p_tcb->transport);
is_key_mitm = BTM_IsLinkKeyAuthed(p_tcb->peer_bda, p_clcb->p_tcb->transport);
@@ -363,7 +363,7 @@ tGATT_STATUS gatt_get_link_encrypt_status(tGATT_TCB& tcb) {
tGATT_STATUS encrypt_status = GATT_NOT_ENCRYPTED;
bool encrypted = BTM_IsEncrypted(tcb.peer_bda, tcb.transport);
- bool link_key_known = BTM_IsLinkKeyKnown(tcb.peer_bda, tcb.transport);
+ bool link_key_known = BTM_IsBonded(tcb.peer_bda, tcb.transport);
bool link_key_authed = BTM_IsLinkKeyAuthed(tcb.peer_bda, tcb.transport);
if (encrypted && link_key_known) {
diff --git a/system/stack/gatt/gatt_utils.cc b/system/stack/gatt/gatt_utils.cc
index b0d18f892e..f401be9285 100644
--- a/system/stack/gatt/gatt_utils.cc
+++ b/system/stack/gatt/gatt_utils.cc
@@ -867,7 +867,7 @@ std::list<tGATT_SRV_LIST_ELEM>::iterator gatt_sr_find_i_rcb_by_handle(uint16_t h
void gatt_sr_get_sec_info(const RawAddress& rem_bda, tBT_TRANSPORT transport,
tGATT_SEC_FLAG* p_sec_flag, uint8_t* p_key_size) {
tGATT_SEC_FLAG flags = {};
- flags.is_link_key_known = BTM_IsLinkKeyKnown(rem_bda, transport);
+ flags.is_link_key_known = BTM_IsBonded(rem_bda, transport);
flags.is_link_key_authed = BTM_IsLinkKeyAuthed(rem_bda, transport);
flags.is_encrypted = BTM_IsEncrypted(rem_bda, transport);
flags.can_read_discoverable_characteristics = BTM_CanReadDiscoverableCharacteristics(rem_bda);
diff --git a/system/stack/hcic/hciblecmds.cc b/system/stack/hcic/hciblecmds.cc
index 10d283af90..27be452ce5 100644
--- a/system/stack/hcic/hciblecmds.cc
+++ b/system/stack/hcic/hciblecmds.cc
@@ -238,7 +238,7 @@ void btsnd_hcic_ble_read_remote_feat(uint16_t handle) {
void btsnd_hcic_ble_rand(base::Callback<void(BT_OCTET8)> cb) {
btu_hcif_send_cmd_with_cb(
- FROM_HERE, HCI_BLE_RAND, nullptr, 0,
+ HCI_BLE_RAND, nullptr, 0,
base::Bind(
[](base::Callback<void(BT_OCTET8)> cb, uint8_t* param, uint16_t /* param_len */) {
bluetooth::log::assert_that(param[0] == 0,
@@ -466,7 +466,7 @@ void btsnd_hcic_set_cig_params(uint8_t cig_id, uint32_t sdu_itv_mtos, uint32_t s
UINT8_TO_STREAM(pp, cis_cfg[i].rtn_stom);
}
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_CIG_PARAMS, param, params_len, std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_SET_CIG_PARAMS, param, params_len, std::move(cb));
}
void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg,
@@ -482,7 +482,7 @@ void btsnd_hcic_create_cis(uint8_t num_cis, const EXT_CIS_CREATE_CFG* cis_cfg,
UINT16_TO_STREAM(pp, cis_cfg[i].acl_conn_handle);
}
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_CREATE_CIS, param, params_len, std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_CREATE_CIS, param, params_len, std::move(cb));
}
void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
@@ -492,7 +492,7 @@ void btsnd_hcic_remove_cig(uint8_t cig_id, base::OnceCallback<void(uint8_t*, uin
UINT8_TO_STREAM(pp, cig_id);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_CIG, param, params_len, std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_REMOVE_CIG, param, params_len, std::move(cb));
}
void btsnd_hcic_req_peer_sca(uint16_t conn_handle) {
@@ -578,8 +578,7 @@ void btsnd_hcic_setup_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir,
UINT8_TO_STREAM(pp, codec_conf.size());
ARRAY_TO_STREAM(pp, codec_conf.data(), static_cast<int>(codec_conf.size()));
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SETUP_ISO_DATA_PATH, param, params_len,
- std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_SETUP_ISO_DATA_PATH, param, params_len, std::move(cb));
}
void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir,
@@ -591,8 +590,7 @@ void btsnd_hcic_remove_iso_data_path(uint16_t iso_handle, uint8_t data_path_dir,
UINT16_TO_STREAM(pp, iso_handle);
UINT8_TO_STREAM(pp, data_path_dir);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_REMOVE_ISO_DATA_PATH, param, params_len,
- std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_REMOVE_ISO_DATA_PATH, param, params_len, std::move(cb));
}
void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle,
@@ -603,8 +601,7 @@ void btsnd_hcic_read_iso_link_quality(uint16_t iso_handle,
UINT16_TO_STREAM(pp, iso_handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_READ_ISO_LINK_QUALITY, param, params_len,
- std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_READ_ISO_LINK_QUALITY, param, params_len, std::move(cb));
}
void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t adv_sid,
@@ -632,7 +629,7 @@ void btsnd_hcic_ble_periodic_advertising_create_sync(uint8_t options, uint8_t ad
void btsnd_hcic_ble_periodic_advertising_create_sync_cancel(
base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, nullptr,
HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_CREATE_SYNC_CANCEL, std::move(cb));
}
@@ -643,7 +640,7 @@ void btsnd_hcic_ble_periodic_advertising_terminate_sync(
UINT16_TO_STREAM(pp, sync_handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_PERIODIC_ADVERTISING_TERMINATE_SYNC, param,
HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_TERMINATE_SYNC, std::move(cb));
}
@@ -657,7 +654,7 @@ void btsnd_hci_ble_add_device_to_periodic_advertiser_list(
BDADDR_TO_STREAM(pp, adv_addr);
UINT8_TO_STREAM(pp, adv_sid);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, param,
HCIC_PARAM_SIZE_ADD_DEVICE_TO_PERIODIC_ADVERTISER_LIST, std::move(cb));
}
@@ -671,13 +668,13 @@ void btsnd_hci_ble_remove_device_from_periodic_advertiser_list(
BDADDR_TO_STREAM(pp, adv_addr);
UINT8_TO_STREAM(pp, adv_sid);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST, param,
HCIC_PARAM_SIZE_REMOVE_DEVICE_FROM_PERIODIC_ADVERTISER_LIST,
std::move(cb));
}
void btsnd_hci_ble_clear_periodic_advertiser_list(base::OnceCallback<void(uint8_t*, uint16_t)> cb) {
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr,
+ btu_hcif_send_cmd_with_cb(HCI_BLE_CLEAR_PERIODIC_ADVERTISER_LIST, nullptr,
HCIC_PARAM_SIZE_CLEAR_PERIODIC_ADVERTISER_LIST, std::move(cb));
}
@@ -689,7 +686,7 @@ void btsnd_hcic_ble_set_periodic_advertising_receive_enable(
UINT16_TO_STREAM(pp, sync_handle);
UINT8_TO_STREAM(pp, (enable ? 0x01 : 0x00));
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param,
+ btu_hcif_send_cmd_with_cb(HCI_LE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, param,
HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_RECEIVE_ENABLE, std::move(cb));
}
@@ -703,7 +700,7 @@ void btsnd_hcic_ble_periodic_advertising_sync_transfer(
UINT16_TO_STREAM(pp, service_data);
UINT16_TO_STREAM(pp, sync_handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param,
+ btu_hcif_send_cmd_with_cb(HCI_LE_PERIODIC_ADVERTISING_SYNC_TRANSFER, param,
HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SYNC_TRANSFER, std::move(cb));
}
@@ -717,7 +714,7 @@ void btsnd_hcic_ble_periodic_advertising_set_info_transfer(
UINT16_TO_STREAM(pp, service_data);
UINT8_TO_STREAM(pp, adv_handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param,
+ btu_hcif_send_cmd_with_cb(HCI_LE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, param,
HCIC_PARAM_SIZE_PERIODIC_ADVERTISING_SET_INFO_TRANSFER, std::move(cb));
}
@@ -733,7 +730,7 @@ void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params(
UINT16_TO_STREAM(pp, sync_timeout);
UINT8_TO_STREAM(pp, cte_type);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param,
+ btu_hcif_send_cmd_with_cb(HCI_LE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param,
HCIC_PARAM_SIZE_SET_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS,
std::move(cb));
}
@@ -750,7 +747,7 @@ void btsnd_hcic_ble_set_default_periodic_advertising_sync_transfer_params(
UINT16_TO_STREAM(pp, sync_timeout);
UINT8_TO_STREAM(pp, cte_type);
- btu_hcif_send_cmd_with_cb(
- FROM_HERE, HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param,
- HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS, std::move(cb));
+ btu_hcif_send_cmd_with_cb(HCI_LE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAM, param,
+ HCIC_PARAM_SIZE_SET_DEFAULT_PERIODIC_ADVERTISING_SYNC_TRANSFER_PARAMS,
+ std::move(cb));
}
diff --git a/system/stack/hcic/hcicmds.cc b/system/stack/hcic/hcicmds.cc
index 4183df86c2..257be53656 100644
--- a/system/stack/hcic/hcicmds.cc
+++ b/system/stack/hcic/hcicmds.cc
@@ -1472,7 +1472,7 @@ void btsnd_hcic_read_encryption_key_size(uint16_t handle, ReadEncKeySizeCb cb) {
uint8_t* p = param;
UINT16_TO_STREAM(p, handle);
- btu_hcif_send_cmd_with_cb(FROM_HERE, HCI_READ_ENCR_KEY_SIZE, param, len,
+ btu_hcif_send_cmd_with_cb(HCI_READ_ENCR_KEY_SIZE, param, len,
base::Bind(&read_encryption_key_size_complete, base::Passed(&cb)));
}
@@ -1566,7 +1566,7 @@ void btsnd_hcic_vendor_spec_cmd(uint16_t opcode, uint8_t len, uint8_t* p_data,
tBTM_VSC_CMPL_CB* p_cmd_cplt_cback) {
uint16_t v_opcode = HCI_GRP_VENDOR_SPECIFIC | opcode;
- btu_hcif_send_cmd_with_cb(FROM_HERE, v_opcode, p_data, len,
+ btu_hcif_send_cmd_with_cb(v_opcode, p_data, len,
base::BindOnce(&btsnd_hcic_vendor_spec_complete,
base::Unretained(p_cmd_cplt_cback), v_opcode));
}
diff --git a/system/stack/hid/hidh_conn.cc b/system/stack/hid/hidh_conn.cc
index d658c1ab29..cdc7906d16 100644
--- a/system/stack/hid/hidh_conn.cc
+++ b/system/stack/hid/hidh_conn.cc
@@ -74,7 +74,7 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed);
static void hidh_l2cif_disconnect_cfm(uint16_t l2cap_cid, uint16_t result);
static void hidh_l2cif_disconnect_cfm_actual(uint16_t l2cap_cid, uint16_t result);
static void hidh_l2cif_data_ind(uint16_t l2cap_cid, BT_HDR* p_msg);
-static void hidh_l2cif_disconnect(uint16_t l2cap_cid);
+static bool hidh_l2cif_disconnect(uint16_t l2cap_cid);
static void hidh_l2cif_cong_ind(uint16_t l2cap_cid, bool congested);
static void hidh_on_l2cap_error(uint16_t l2cap_cid, uint16_t result);
@@ -165,10 +165,12 @@ tHID_STATUS hidh_conn_disconnect(uint8_t dhandle) {
log::warn("Unable to set L2CAP idle timeout peer:{}", hh_cb.devices[dhandle].addr);
}
/* Disconnect channels one by one */
- if (p_hcon->intr_cid) {
- hidh_l2cif_disconnect(p_hcon->intr_cid);
- } else if (p_hcon->ctrl_cid) {
- hidh_l2cif_disconnect(p_hcon->ctrl_cid);
+ uint16_t cid = (p_hcon->intr_cid != 0 ? p_hcon->intr_cid : p_hcon->ctrl_cid);
+ if (!hidh_l2cif_disconnect(cid)) {
+ if (com::android::bluetooth::flags::disconnect_hid_channels_serially()) {
+ // call the disconnection callback directly because l2cap won't call it.
+ hidh_l2cif_disconnect_cfm_actual(cid, 0);
+ }
}
BTM_LogHistory(kBtmLogTag, hh_cb.devices[dhandle].addr, "Disconnecting", "local initiated");
@@ -559,14 +561,16 @@ static void hidh_l2cif_disconnect_ind(uint16_t l2cap_cid, bool ack_needed) {
// TODO: after disconnect_hid_channels_serially aflags is the default,
// remove this function and call L2CA_DisconnectReq directly.
-static void hidh_l2cif_disconnect(uint16_t l2cap_cid) {
+static bool hidh_l2cif_disconnect(uint16_t l2cap_cid) {
if (!stack::l2cap::get_interface().L2CA_DisconnectReq(l2cap_cid)) {
log::warn("Unable to send L2CAP disconnect request cid:{}", l2cap_cid);
+ return false;
}
if (!com::android::bluetooth::flags::disconnect_hid_channels_serially()) {
hidh_l2cif_disconnect_cfm_actual(l2cap_cid, 0);
}
+ return true;
}
/*******************************************************************************
diff --git a/system/stack/include/btm_ble_sec_api.h b/system/stack/include/btm_ble_sec_api.h
index a25a0f3ba6..cc7a06e083 100644
--- a/system/stack/include/btm_ble_sec_api.h
+++ b/system/stack/include/btm_ble_sec_api.h
@@ -233,21 +233,6 @@ std::optional<Octet16> BTM_BleGetPeerIRK(const RawAddress address);
/*******************************************************************************
*
- * Function BTM_BleIsLinkKeyKnown
- *
- * Description This function is used to check whether the link key
- * of a peer (LE) device is known or not
- *
- * Parameters: address: address of the peer device
- *
- * Returns true if the link key is known
- * false otherwise
- *
- ******************************************************************************/
-bool BTM_BleIsLinkKeyKnown(const RawAddress address);
-
-/*******************************************************************************
- *
* Function BTM_BleGetIdentityAddress
*
* Description This function is called to get the identity address
diff --git a/system/stack/include/btu_hcif.h b/system/stack/include/btu_hcif.h
index 13ee0f1493..0d1bceba63 100644
--- a/system/stack/include/btu_hcif.h
+++ b/system/stack/include/btu_hcif.h
@@ -27,8 +27,8 @@
***********************************
*/
void btu_hcif_send_cmd(uint8_t controller_id, const BT_HDR* p_msg);
-void btu_hcif_send_cmd_with_cb(const base::Location& posted_from, uint16_t opcode, uint8_t* params,
- uint8_t params_len, base::OnceCallback<void(uint8_t*, uint16_t)> cb);
+void btu_hcif_send_cmd_with_cb(uint16_t opcode, uint8_t* params, uint8_t params_len,
+ base::OnceCallback<void(uint8_t*, uint16_t)> cb);
void btu_hci_msg_process(BT_HDR* p_msg);
namespace bluetooth::legacy::testing {
diff --git a/system/stack/include/security_client_callbacks.h b/system/stack/include/security_client_callbacks.h
index d9d19f33f6..f8a29e7bc3 100644
--- a/system/stack/include/security_client_callbacks.h
+++ b/system/stack/include/security_client_callbacks.h
@@ -111,7 +111,7 @@ typedef struct {
tBTM_BLE_SEC_ACT sec_act);
bool (*BTM_IsEncrypted)(const RawAddress& bd_addr, tBT_TRANSPORT transport);
bool (*BTM_SecIsLeSecurityPending)(const RawAddress& bd_addr);
- bool (*BTM_IsLinkKeyKnown)(const RawAddress& bd_addr, tBT_TRANSPORT transport);
+ bool (*BTM_IsBonded)(const RawAddress& bd_addr, tBT_TRANSPORT transport);
// Secure service management
bool (*BTM_SetSecurityLevel)(bool is_originator, const char* p_name, uint8_t service_id,
diff --git a/system/stack/l2cap/l2c_int.h b/system/stack/l2cap/l2c_int.h
index 639cee872e..c1bffc1533 100644
--- a/system/stack/l2cap/l2c_int.h
+++ b/system/stack/l2cap/l2c_int.h
@@ -758,6 +758,7 @@ bool l2cu_initialize_fixed_ccb(tL2C_LCB* p_lcb, uint16_t fixed_cid);
void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb);
void l2cu_process_fixed_chnl_resp(tL2C_LCB* p_lcb);
bool l2cu_is_ccb_active(tL2C_CCB* p_ccb);
+void l2cu_set_lcb_handle(tL2C_LCB& p_lcb, uint16_t handle);
tL2CAP_CONN le_result_to_l2c_conn(tL2CAP_LE_RESULT_CODE result);
/* Functions provided for Broadcom Aware
diff --git a/system/stack/mmc/daemon/service.cc b/system/stack/mmc/daemon/service.cc
index d2dee226d2..0ac49a5746 100644
--- a/system/stack/mmc/daemon/service.cc
+++ b/system/stack/mmc/daemon/service.cc
@@ -286,9 +286,9 @@ bool Service::StartWorkerThread(int fd, struct sockaddr_un addr,
log::warn("Failed to enable real time scheduling");
}
- if (!thread_pool_.back().first->DoInThread(
- FROM_HERE, base::BindOnce(&StartSocketListener, fd, std::move(addr),
- std::move(task_ended), std::move(codec_server)))) {
+ if (!thread_pool_.back().first->DoInThread(base::BindOnce(&StartSocketListener, fd,
+ std::move(addr), std::move(task_ended),
+ std::move(codec_server)))) {
log::error("Failed to run task");
return false;
}
diff --git a/system/stack/sdp/sdp_api.cc b/system/stack/sdp/sdp_api.cc
index 2380b76043..c7bdf76a31 100644
--- a/system/stack/sdp/sdp_api.cc
+++ b/system/stack/sdp/sdp_api.cc
@@ -1113,8 +1113,6 @@ bluetooth::legacy::stack::sdp::get_legacy_stack_sdp_api() {
return &api_;
}
-extern void BTA_SdpDumpsys(int fd);
-
#define DUMPSYS_TAG "shim::legacy::sdp"
namespace {
diff --git a/system/stack/test/common/mock_btm_api_layer.cc b/system/stack/test/common/mock_btm_api_layer.cc
index 83d969dc72..763309abea 100644
--- a/system/stack/test/common/mock_btm_api_layer.cc
+++ b/system/stack/test/common/mock_btm_api_layer.cc
@@ -37,8 +37,8 @@ bool BTM_IsEncrypted(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport)
return btm_api_interface->IsEncrypted(remote_bd_addr, transport);
}
-bool BTM_IsLinkKeyKnown(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) {
- return btm_api_interface->IsLinkKeyKnown(remote_bd_addr, transport);
+bool BTM_IsBonded(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) {
+ return btm_api_interface->IsDeviceBonded(remote_bd_addr, transport);
}
uint8_t btm_ble_read_sec_key_size(const RawAddress& bd_addr) {
diff --git a/system/stack/test/common/mock_btm_api_layer.h b/system/stack/test/common/mock_btm_api_layer.h
index b9a748d36c..e852053661 100644
--- a/system/stack/test/common/mock_btm_api_layer.h
+++ b/system/stack/test/common/mock_btm_api_layer.h
@@ -31,7 +31,7 @@ public:
uint32_t mx_chan_id) = 0;
virtual uint8_t acl_link_role(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0;
virtual bool IsEncrypted(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0;
- virtual bool IsLinkKeyKnown(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0;
+ virtual bool IsDeviceBonded(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport) = 0;
virtual uint8_t ReadSecKeySize(const RawAddress& remote_bd_addr) = 0;
virtual ~BtmApiInterface() = default;
};
@@ -43,7 +43,7 @@ public:
uint16_t psm, uint32_t mx_proto_id, uint32_t mx_chan_id));
MOCK_METHOD2(acl_link_role, uint8_t(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport));
MOCK_METHOD2(IsEncrypted, bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport));
- MOCK_METHOD2(IsLinkKeyKnown, bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport));
+ MOCK_METHOD2(IsDeviceBonded, bool(const RawAddress& remote_bd_addr, tBT_TRANSPORT transport));
MOCK_METHOD1(ReadSecKeySize, uint8_t(const RawAddress& remote_bd_addr));
};
diff --git a/system/stack/test/eatt/eatt_test.cc b/system/stack/test/eatt/eatt_test.cc
index 31ceba5060..130893a0a5 100644
--- a/system/stack/test/eatt/eatt_test.cc
+++ b/system/stack/test/eatt/eatt_test.cc
@@ -336,7 +336,7 @@ TEST_F(EattTest, IncomingEattConnectionByKnownDeviceEncryptionOff) {
ON_CALL(btm_api_interface_, IsEncrypted)
.WillByDefault(
[](const RawAddress& /*addr*/, tBT_TRANSPORT /*transport*/) { return false; });
- ON_CALL(btm_api_interface_, IsLinkKeyKnown)
+ ON_CALL(btm_api_interface_, IsDeviceBonded)
.WillByDefault(
[](const RawAddress& /*addr*/, tBT_TRANSPORT /*transport*/) { return true; });
ON_CALL(gatt_interface_, ClientReadSupportedFeatures)
@@ -370,7 +370,7 @@ TEST_F(EattTest, IncomingEattConnectionByUnknownDeviceEncryptionOff) {
ON_CALL(btm_api_interface_, IsEncrypted)
.WillByDefault(
[](const RawAddress& /*addr*/, tBT_TRANSPORT /*transport*/) { return false; });
- ON_CALL(btm_api_interface_, IsLinkKeyKnown)
+ ON_CALL(btm_api_interface_, IsDeviceBonded)
.WillByDefault(
[](const RawAddress& /*addr*/, tBT_TRANSPORT /*transport*/) { return false; });
EXPECT_CALL(mock_stack_l2cap_interface_,
diff --git a/system/stack/test/fuzzers/Android.bp b/system/stack/test/fuzzers/Android.bp
index 91bc857f8f..35e25aad6a 100644
--- a/system/stack/test/fuzzers/Android.bp
+++ b/system/stack/test/fuzzers/Android.bp
@@ -8,7 +8,7 @@ package {
}
cc_defaults {
- name: "libbt-stack_fuzz_defaults",
+ name: "bluetooth_fuzz_stack_defaults",
defaults: [
"fluoride_defaults",
"latest_android_hardware_audio_common_ndk_static",
@@ -20,9 +20,11 @@ cc_defaults {
"-Wno-missing-prototypes",
],
include_dirs: [
- "packages/modules/Bluetooth/system/",
- "packages/modules/Bluetooth/system/gd/",
- "packages/modules/Bluetooth/system/include/",
+ "packages/modules/Bluetooth/system",
+ "packages/modules/Bluetooth/system/bta/include",
+ "packages/modules/Bluetooth/system/bta/sys",
+ "packages/modules/Bluetooth/system/gd",
+ "packages/modules/Bluetooth/system/include",
"packages/modules/Bluetooth/system/stack/include",
"packages/modules/Bluetooth/system/stack/test",
],
@@ -45,7 +47,6 @@ cc_defaults {
"libbluetooth_log",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -53,12 +54,11 @@ cc_defaults {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
+ "libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libexpresslog",
"libflags_rust_cpp_bridge",
@@ -97,3 +97,39 @@ cc_defaults {
},
},
}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_a2dp",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["a2dp/fuzz_a2dp.cc"],
+}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_a2dp_codec",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["a2dp/codec/fuzz_a2dp_codec.cc"],
+}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_a2dp_codec_info",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["a2dp/codec/fuzz_a2dp_codec_info.cc"],
+}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_a2dp_codec_config",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["a2dp/codec/fuzz_a2dp_codec_config.cc"],
+}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_avrc",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["avrc/fuzz_avrc.cc"],
+}
+
+cc_fuzz {
+ name: "bluetooth_fuzz_stack_sdp",
+ defaults: ["bluetooth_fuzz_stack_defaults"],
+ srcs: ["sdp/fuzz_sdp.cc"],
+}
diff --git a/system/stack/test/fuzzers/a2dp/Android.bp b/system/stack/test/fuzzers/a2dp/Android.bp
deleted file mode 100644
index 65b56b4895..0000000000
--- a/system/stack/test/fuzzers/a2dp/Android.bp
+++ /dev/null
@@ -1,17 +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_fuzz {
- name: "a2dp_fuzz",
- static_libs: ["libchrome"],
- defaults: ["libbt-stack_fuzz_defaults"],
- srcs: [
- "fuzz_a2dp.cc",
- ],
-}
diff --git a/system/stack/test/fuzzers/a2dp/codec/Android.bp b/system/stack/test/fuzzers/a2dp/codec/Android.bp
deleted file mode 100644
index 7c7825db3d..0000000000
--- a/system/stack/test/fuzzers/a2dp/codec/Android.bp
+++ /dev/null
@@ -1,45 +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: "libbt-stack_fuzz_codec_defaults",
- defaults: ["libbt-stack_fuzz_defaults"],
- include_dirs: [
- "packages/modules/Bluetooth/system/bta/include/", // For tBT_A2DP_OFFLOAD
- "packages/modules/Bluetooth/system/bta/sys/", // For tBT_A2DP_OFFLOAD
- "packages/modules/Bluetooth/system/gd",
- ],
-}
-
-cc_fuzz {
- name: "a2dp_codec_fuzz",
- static_libs: ["libchrome"],
- defaults: ["libbt-stack_fuzz_codec_defaults"],
- srcs: [
- "fuzz_a2dp_codec.cc",
- ],
-}
-
-cc_fuzz {
- name: "a2dp_codec_info_fuzz",
- static_libs: ["libchrome"],
- defaults: ["libbt-stack_fuzz_codec_defaults"],
- srcs: [
- "fuzz_a2dp_codec_info.cc",
- ],
-}
-
-cc_fuzz {
- name: "a2dp_codec_cfg_fuzz",
- static_libs: ["libchrome"],
- defaults: ["libbt-stack_fuzz_codec_defaults"],
- srcs: [
- "fuzz_a2dp_codec_config.cc",
- ],
-}
diff --git a/system/stack/test/fuzzers/avrc/Android.bp b/system/stack/test/fuzzers/avrc/Android.bp
deleted file mode 100644
index d9e2696657..0000000000
--- a/system/stack/test/fuzzers/avrc/Android.bp
+++ /dev/null
@@ -1,17 +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_fuzz {
- name: "avrc_fuzz",
- defaults: ["libbt-stack_fuzz_defaults"],
- srcs: [
- "fuzz_avrc.cc",
- ],
- static_libs: ["libchrome"],
-}
diff --git a/system/stack/test/fuzzers/sdp/Android.bp b/system/stack/test/fuzzers/sdp/Android.bp
deleted file mode 100644
index bc5aaa702b..0000000000
--- a/system/stack/test/fuzzers/sdp/Android.bp
+++ /dev/null
@@ -1,17 +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_fuzz {
- name: "sdp_fuzz",
- static_libs: ["libchrome"],
- defaults: ["libbt-stack_fuzz_defaults"],
- srcs: [
- "fuzz_sdp.cc",
- ],
-}
diff --git a/system/test/Android.bp b/system/test/Android.bp
index fabb5e9847..c35931ea17 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",
@@ -270,13 +265,6 @@ filegroup {
}
filegroup {
- name: "TestMockStackBnep",
- srcs: [
- "mock/mock_stack_bnep_*.cc",
- ],
-}
-
-filegroup {
name: "TestMockStackL2cap",
srcs: [
"mock/mock_stack_l2cap_*.cc",
@@ -354,13 +342,6 @@ filegroup {
}
filegroup {
- name: "TestMockLegacyHciCommands",
- srcs: [
- "mock/mock_hcic_*.cc",
- ],
-}
-
-filegroup {
name: "TestMockMainShimEntry",
srcs: [
"mock/mock_main_shim_entry.cc",
@@ -368,13 +349,6 @@ filegroup {
}
filegroup {
- name: "TestMockMainShimStack",
- srcs: [
- "mock/mock_main_shim_stack.cc",
- ],
-}
-
-filegroup {
name: "TestMockMainShimLeScanning",
srcs: [
"mock/mock_main_shim_le_scanning_manager.cc",
@@ -497,13 +471,6 @@ filegroup {
}
filegroup {
- name: "TestMockStackEatt",
- srcs: [
- "mock/mock_stack_eatt*.cc",
- ],
-}
-
-filegroup {
name: "TestMockStackGatt",
srcs: [
"mock/mock_stack_gatt*.cc",
@@ -511,13 +478,6 @@ filegroup {
}
filegroup {
- name: "TestMockRustFfi",
- srcs: [
- "mock/mock_rust_ffi_connection*.cc",
- ],
-}
-
-filegroup {
name: "TestMockStackBtu",
srcs: [
"mock/mock_stack_btu*.cc",
@@ -525,13 +485,6 @@ filegroup {
}
filegroup {
- name: "TestMockMainBte",
- srcs: [
- "mock/mock_main_bte*.cc",
- ],
-}
-
-filegroup {
name: "TestMockBtu",
srcs: [
"mock/mock_btu_*cc",
diff --git a/system/test/common/jni_thread.cc b/system/test/common/jni_thread.cc
index db1520d36b..ca26fa39da 100644
--- a/system/test/common/jni_thread.cc
+++ b/system/test/common/jni_thread.cc
@@ -21,9 +21,6 @@
#include <map>
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
std::queue<base::OnceClosure> do_in_jni_thread_task_queue;
void run_one_jni_thread_task() {
@@ -39,9 +36,3 @@ void run_all_jni_thread_task() {
run_one_jni_thread_task();
}
}
-
-void reset_mock_jni_thread_queue() {
- while (do_in_jni_thread_task_queue.size()) {
- do_in_jni_thread_task_queue.pop();
- }
-}
diff --git a/system/test/common/main_handler.cc b/system/test/common/main_handler.cc
index c6e792c4dc..c33b663224 100644
--- a/system/test/common/main_handler.cc
+++ b/system/test/common/main_handler.cc
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#include "main_handler.h"
+
#include <base/functional/bind.h>
#include <base/functional/callback_forward.h>
#include <base/location.h>
@@ -28,9 +30,6 @@
#include "common/postable_context.h"
#include "include/hardware/bluetooth.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using bluetooth::common::MessageLoopThread;
using BtMainClosure = std::function<void()>;
@@ -42,13 +41,13 @@ void do_post_on_bt_main(BtMainClosure closure) { closure(); }
} // namespace
bt_status_t do_in_main_thread(base::OnceClosure task) {
- bluetooth::log::assert_that(main_thread.DoInThread(FROM_HERE, std::move(task)),
+ bluetooth::log::assert_that(main_thread.DoInThread(std::move(task)),
"Unable to run on main thread");
return BT_STATUS_SUCCESS;
}
bt_status_t do_in_main_thread_delayed(base::OnceClosure task, std::chrono::microseconds delay) {
- bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(FROM_HERE, std::move(task), delay),
+ bluetooth::log::assert_that(!main_thread.DoInThreadDelayed(std::move(task), delay),
"Unable to run on main thread delayed");
return BT_STATUS_SUCCESS;
}
diff --git a/system/test/common/stack_config.cc b/system/test/common/stack_config.cc
index c1bc7e7ae7..0bf74fa2e3 100644
--- a/system/test/common/stack_config.cc
+++ b/system/test/common/stack_config.cc
@@ -22,36 +22,36 @@
#include <cstdarg>
#include <cstring>
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
+#include "hci/include/packet_fragmenter.h"
+#include "internal_include/stack_config.h"
-const std::string kSmpOptions("mock smp options");
-const std::string kBroadcastAudioConfigOptions("mock broadcast audio config 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_use_eatt_for_all_services(void) { return false; }
-bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; }
-bool get_pts_l2cap_ecoc_upper_tester(void) { return false; }
-int get_pts_l2cap_ecoc_min_key_size(void) { return -1; }
-int get_pts_l2cap_ecoc_initial_chan_cnt(void) { return -1; }
-bool get_pts_l2cap_ecoc_connect_remaining(void) { return false; }
-int get_pts_l2cap_ecoc_send_num_of_sdu(void) { return -1; }
-bool get_pts_l2cap_ecoc_reconfigure(void) { return false; }
-const std::string* get_pts_broadcast_audio_config_options(void) {
+static const std::string kSmpOptions("mock smp options");
+static const std::string kBroadcastAudioConfigOptions("mock broadcast audio config options");
+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_use_eatt_for_all_services(void) { return false; }
+static bool get_pts_force_le_audio_multiple_contexts_metadata(void) { return false; }
+static bool get_pts_l2cap_ecoc_upper_tester(void) { return false; }
+static int get_pts_l2cap_ecoc_min_key_size(void) { return -1; }
+static int get_pts_l2cap_ecoc_initial_chan_cnt(void) { return -1; }
+static bool get_pts_l2cap_ecoc_connect_remaining(void) { return false; }
+static int get_pts_l2cap_ecoc_send_num_of_sdu(void) { return -1; }
+static bool get_pts_l2cap_ecoc_reconfigure(void) { return false; }
+static const std::string* get_pts_broadcast_audio_config_options(void) {
return &kBroadcastAudioConfigOptions;
}
-bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; }
+static bool get_pts_le_audio_disable_ases_before_stopping(void) { return false; }
struct config_t;
-config_t* get_all(void) { return nullptr; }
+static config_t* get_all(void) { return nullptr; }
struct packet_fragmenter_t;
const packet_fragmenter_t* packet_fragmenter_get_interface() { return nullptr; }
diff --git a/system/test/common/sync_main_handler.cc b/system/test/common/sync_main_handler.cc
index 1b6219e761..8bbefb4ff9 100644
--- a/system/test/common/sync_main_handler.cc
+++ b/system/test/common/sync_main_handler.cc
@@ -14,14 +14,13 @@
* limitations under the License.
*/
+#include "test/common/sync_main_handler.h"
+
#include <chrono>
#include <future>
#include "stack/include/main_thread.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
constexpr int sync_timeout_in_ms = 3000;
void sync_main_handler() {
diff --git a/system/test/fake/fake_looper.cc b/system/test/fake/fake_looper.cc
index b7d94dd849..123ba7768b 100644
--- a/system/test/fake/fake_looper.cc
+++ b/system/test/fake/fake_looper.cc
@@ -27,10 +27,7 @@
#include "osi/include/allocator.h"
#include "test/fake/fake_thread.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-pid_t get_thread_id() {
+static pid_t get_thread_id() {
#if defined(OS_MACOSX)
return pthread_mach_thread_np(pthread_self());
#elif defined(OS_LINUX)
diff --git a/system/test/headless/Android.bp b/system/test/headless/Android.bp
index 7b1b487154..0cafcfba63 100644
--- a/system/test/headless/Android.bp
+++ b/system/test/headless/Android.bp
@@ -90,7 +90,6 @@ cc_binary {
"libbt-audio-asrc",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-btu-main-thread",
"libbt-common",
"libbt-hci",
@@ -98,12 +97,10 @@ cc_binary {
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
"libchrome",
"libcom.android.sysprop.bluetooth.wrapped",
"libevent",
diff --git a/system/test/headless/android_namespace.cc b/system/test/headless/android_namespace.cc
deleted file mode 100644
index 2c4eee7f74..0000000000
--- a/system/test/headless/android_namespace.cc
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-extern "C" {
-struct android_namespace_t* android_get_exported_namespace(const char*) { return nullptr; }
-} // "C"
diff --git a/system/test/headless/config.cc b/system/test/headless/config.cc
deleted file mode 100644
index 7a3aab62a0..0000000000
--- a/system/test/headless/config.cc
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2023 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "bt_config"
-
-#include "gd/hal/snoop_logger.h"
-#include "test/headless/log.h"
-
-using namespace bluetooth::hal;
-
-class Config {
- Config() {}
-
- void Help() const {
- // setprop persist.bluetooth.btsnoopdefaultmode full
- LOG_CONSOLE("Flag: %s", SnoopLogger::kBtSnoopLogPersists.c_str());
- // setprop persist.bluetooth.btsnooplogpersists 1
- }
-};
diff --git a/system/test/headless/headless.cc b/system/test/headless/headless.cc
index d257b28e6d..753edd15fd 100644
--- a/system/test/headless/headless.cc
+++ b/system/test/headless/headless.cc
@@ -32,9 +32,6 @@
#include "test/headless/messenger.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
//
// Aggregate disparate variables from callback API into unified single structure
//
@@ -69,12 +66,13 @@ std::mutex adapter_state_mutex_;
std::condition_variable adapter_state_cv_;
bt_state_t bt_state_{BT_STATE_OFF};
-void adapter_state_changed(bt_state_t state) {
+static void adapter_state_changed(bt_state_t state) {
std::unique_lock<std::mutex> lck(adapter_state_mutex_);
bt_state_ = state;
adapter_state_cv_.notify_all();
}
-void adapter_properties(bt_status_t status, int num_properties, ::bt_property_t* properties) {
+static void adapter_properties(bt_status_t status, int num_properties,
+ ::bt_property_t* properties) {
const size_t num_callbacks = interface_api_callback_map_.size();
auto callback_list = interface_api_callback_map_.find(__func__);
if (callback_list != interface_api_callback_map_.end()) {
@@ -87,8 +85,8 @@ void adapter_properties(bt_status_t status, int num_properties, ::bt_property_t*
bt_status_text(status), num_properties, std::format_ptr(properties));
}
-void remote_device_properties(bt_status_t status, RawAddress* bd_addr, int num_properties,
- ::bt_property_t* properties) {
+static void remote_device_properties(bt_status_t status, RawAddress* bd_addr, int num_properties,
+ ::bt_property_t* properties) {
log::assert_that(bd_addr != nullptr, "assert failed: bd_addr != nullptr");
const size_t num_callbacks = interface_api_callback_map_.size();
auto callback_list = interface_api_callback_map_.find(__func__);
@@ -104,7 +102,7 @@ void remote_device_properties(bt_status_t status, RawAddress* bd_addr, int num_p
}
// Aggregate disparate variables from callback API into unified single structure
-void device_found(int num_properties, ::bt_property_t* properties) {
+static void device_found(int num_properties, ::bt_property_t* properties) {
[[maybe_unused]] const size_t num_callbacks = interface_api_callback_map_.size();
auto callback_list = interface_api_callback_map_.find(__func__);
if (callback_list != interface_api_callback_map_.end()) {
@@ -117,7 +115,7 @@ void device_found(int num_properties, ::bt_property_t* properties) {
std::format_ptr(properties));
}
-void discovery_state_changed(bt_discovery_state_t state) {
+static void discovery_state_changed(bt_discovery_state_t state) {
auto callback_list = interface_api_callback_map_.find(__func__);
if (callback_list != interface_api_callback_map_.end()) {
for (auto callback : callback_list->second) {
@@ -128,40 +126,42 @@ void discovery_state_changed(bt_discovery_state_t state) {
}
/** Bluetooth Legacy PinKey Request callback */
-void pin_request([[maybe_unused]] RawAddress* remote_bd_addr, [[maybe_unused]] bt_bdname_t* bd_name,
- [[maybe_unused]] uint32_t cod, [[maybe_unused]] bool min_16_digit) {
+static void pin_request([[maybe_unused]] RawAddress* remote_bd_addr,
+ [[maybe_unused]] bt_bdname_t* bd_name, [[maybe_unused]] uint32_t cod,
+ [[maybe_unused]] bool min_16_digit) {
log::info("");
}
-void ssp_request([[maybe_unused]] RawAddress* remote_bd_addr,
- [[maybe_unused]] bt_ssp_variant_t pairing_variant,
- [[maybe_unused]] uint32_t pass_key) {
+static void ssp_request([[maybe_unused]] RawAddress* remote_bd_addr,
+ [[maybe_unused]] bt_ssp_variant_t pairing_variant,
+ [[maybe_unused]] uint32_t pass_key) {
log::info("");
}
/** Bluetooth Bond state changed callback */
/* Invoked in response to create_bond, cancel_bond or remove_bond */
-void bond_state_changed([[maybe_unused]] bt_status_t status,
- [[maybe_unused]] RawAddress* remote_bd_addr,
- [[maybe_unused]] bt_bond_state_t state, [[maybe_unused]] int fail_reason) {
+static void bond_state_changed([[maybe_unused]] bt_status_t status,
+ [[maybe_unused]] RawAddress* remote_bd_addr,
+ [[maybe_unused]] bt_bond_state_t state,
+ [[maybe_unused]] int fail_reason) {
log::info("");
}
-void address_consolidate([[maybe_unused]] RawAddress* main_bd_addr,
- [[maybe_unused]] RawAddress* secondary_bd_addr) {
+static void address_consolidate([[maybe_unused]] RawAddress* main_bd_addr,
+ [[maybe_unused]] RawAddress* secondary_bd_addr) {
log::info("");
}
-void le_address_associate([[maybe_unused]] RawAddress* main_bd_addr,
- [[maybe_unused]] RawAddress* secondary_bd_addr,
- [[maybe_unused]] uint8_t identity_address_type) {
+static void le_address_associate([[maybe_unused]] RawAddress* main_bd_addr,
+ [[maybe_unused]] RawAddress* secondary_bd_addr,
+ [[maybe_unused]] uint8_t identity_address_type) {
log::info("");
}
/** Bluetooth ACL connection state changed callback */
-void acl_state_changed(bt_status_t status, RawAddress* remote_bd_addr, bt_acl_state_t state,
- int transport_link_type, bt_hci_error_code_t hci_reason,
- bt_conn_direction_t direction, uint16_t acl_handle) {
+static void acl_state_changed(bt_status_t status, RawAddress* remote_bd_addr, bt_acl_state_t state,
+ int transport_link_type, bt_hci_error_code_t hci_reason,
+ bt_conn_direction_t direction, uint16_t acl_handle) {
log::assert_that(remote_bd_addr != nullptr, "assert failed: remote_bd_addr != nullptr");
const size_t num_callbacks = interface_api_callback_map_.size();
auto callback_list = interface_api_callback_map_.find(__func__);
@@ -178,33 +178,34 @@ void acl_state_changed(bt_status_t status, RawAddress* remote_bd_addr, bt_acl_st
}
/** Bluetooth Link Quality Report callback */
-void link_quality_report([[maybe_unused]] uint64_t timestamp, [[maybe_unused]] int report_id,
- [[maybe_unused]] int rssi, [[maybe_unused]] int snr,
- [[maybe_unused]] int retransmission_count,
- [[maybe_unused]] int packets_not_receive_count,
- [[maybe_unused]] int negative_acknowledgement_count) {
+static void link_quality_report([[maybe_unused]] uint64_t timestamp, [[maybe_unused]] int report_id,
+ [[maybe_unused]] int rssi, [[maybe_unused]] int snr,
+ [[maybe_unused]] int retransmission_count,
+ [[maybe_unused]] int packets_not_receive_count,
+ [[maybe_unused]] int negative_acknowledgement_count) {
log::info("");
}
/** Switch buffer size callback */
-void switch_buffer_size([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); }
+static void switch_buffer_size([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); }
/** Switch codec callback */
-void switch_codec([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); }
+static void switch_codec([[maybe_unused]] bool is_low_latency_buffer_size) { log::info(""); }
-void thread_event([[maybe_unused]] bt_cb_thread_evt evt) { log::info(""); }
+static void thread_event([[maybe_unused]] bt_cb_thread_evt evt) { log::info(""); }
-void dut_mode_recv([[maybe_unused]] uint16_t opcode, [[maybe_unused]] uint8_t* buf,
- [[maybe_unused]] uint8_t len) {
+static void dut_mode_recv([[maybe_unused]] uint16_t opcode, [[maybe_unused]] uint8_t* buf,
+ [[maybe_unused]] uint8_t len) {
log::info("");
}
-void le_test_mode([[maybe_unused]] bt_status_t status, [[maybe_unused]] uint16_t num_packets) {
+static void le_test_mode([[maybe_unused]] bt_status_t status,
+ [[maybe_unused]] uint16_t num_packets) {
log::info("");
}
-void energy_info([[maybe_unused]] bt_activity_energy_info* energy_info,
- [[maybe_unused]] bt_uid_traffic_t* uid_data) {
+static void energy_info([[maybe_unused]] bt_activity_energy_info* energy_info,
+ [[maybe_unused]] bt_uid_traffic_t* uid_data) {
log::info("");
}
@@ -233,12 +234,12 @@ bt_callbacks_t bt_callbacks{
// HAL HARDWARE CALLBACKS
// OS CALLOUTS
-int acquire_wake_lock_co([[maybe_unused]] const char* lock_name) {
+static int acquire_wake_lock_co([[maybe_unused]] const char* lock_name) {
log::info("");
return 1;
}
-int release_wake_lock_co([[maybe_unused]] const char* lock_name) {
+static int release_wake_lock_co([[maybe_unused]] const char* lock_name) {
log::info("");
return 0;
}
diff --git a/system/test/headless/log.cc b/system/test/headless/log.cc
index a14368bb2a..0ed78bd8ba 100644
--- a/system/test/headless/log.cc
+++ b/system/test/headless/log.cc
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#include "log.h"
+
#include <chrono>
#include <ctime>
#include <string>
@@ -22,9 +24,6 @@
#include "internal_include/bt_trace.h"
#include "stack/btm/btm_int_types.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
std::chrono::system_clock::time_point _prev = std::chrono::system_clock::now();
extern tBTM_CB btm_cb;
diff --git a/system/test/headless/messenger.cc b/system/test/headless/messenger.cc
index 4e84ad1c49..5dc2e94c6e 100644
--- a/system/test/headless/messenger.cc
+++ b/system/test/headless/messenger.cc
@@ -26,9 +26,6 @@
#include "test/headless/interface.h"
#include "test/headless/log.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth::test::headless;
using namespace std::chrono_literals;
@@ -96,7 +93,7 @@ bool await_callback(Context& context) {
namespace bluetooth::test::headless {
-void messenger_stats() {
+static void messenger_stats() {
// LOG_CONSOLE("%30s cnt:%zu", "device_found",
// discovered::device_found_.size()); LOG_CONSOLE("%30s cnt:%zu",
// "remote_device_properties",
diff --git a/system/test/headless/read/name.cc b/system/test/headless/read/name.cc
index 0dc5aa38b7..e37e0760c0 100644
--- a/system/test/headless/read/name.cc
+++ b/system/test/headless/read/name.cc
@@ -29,12 +29,9 @@
#include "test/headless/headless.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
std::promise<tBTM_REMOTE_DEV_NAME> promise_;
-void RemoteNameCallback(const tBTM_REMOTE_DEV_NAME* data) { promise_.set_value(*data); }
+static void RemoteNameCallback(const tBTM_REMOTE_DEV_NAME* data) { promise_.set_value(*data); }
int bluetooth::test::headless::Name::Run() {
if (options_.loop_ < 1) {
diff --git a/system/test/headless/util.cc b/system/test/headless/util.cc
index 8c18a3893f..0e6d479df2 100644
--- a/system/test/headless/util.cc
+++ b/system/test/headless/util.cc
@@ -14,14 +14,13 @@
* limitations under the License.
*/
+#include "test/headless/util.h"
+
#include <string>
#include "include/hardware/bluetooth.h"
#include "osi/include/properties.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool is_android_running() {
#ifdef __ANDROID__
char value[PROPERTY_VALUE_MAX];
diff --git a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc
index d5ccf7984c..b97a346e16 100644
--- a/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc
+++ b/system/test/mock/mock_audio_hal_interface_a2dp_encoding.cc
@@ -34,9 +34,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace audio_hal_interface_a2dp_encoding {
diff --git a/system/test/mock/mock_bluetooth_interface.cc b/system/test/mock/mock_bluetooth_interface.cc
index 2dda1267b1..c2fb27cb40 100644
--- a/system/test/mock/mock_bluetooth_interface.cc
+++ b/system/test/mock/mock_bluetooth_interface.cc
@@ -17,14 +17,12 @@
#include <cstdint>
#include <future>
+#include "btif/include/btif_common.h"
#include "btif/include/stack_manager_t.h"
#include "hardware/bluetooth.h"
#include "stack/include/bt_octets.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void invoke_adapter_state_changed_cb(bt_state_t /* state */) {}
void invoke_adapter_properties_cb(bt_status_t /* status */, int /* num_properties */,
bt_property_t* /* properties */) {}
diff --git a/system/test/mock/mock_bta_ag_api.cc b/system/test/mock/mock_bta_ag_api.cc
index f59d2e4ed5..00a32ad0f2 100644
--- a/system/test/mock/mock_bta_ag_api.cc
+++ b/system/test/mock/mock_bta_ag_api.cc
@@ -27,12 +27,10 @@
#include <vector>
#include "bta/include/bta_ag_api.h"
+#include "bta/include/bta_ag_swb_aptx.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
tBTA_STATUS BTA_AgEnable(tBTA_AG_CBACK* /* p_cback */) {
inc_func_call_count(__func__);
return BTA_SUCCESS;
diff --git a/system/test/mock/mock_bta_ag_sco.cc b/system/test/mock/mock_bta_ag_sco.cc
index b290955c6a..7e853a64fc 100644
--- a/system/test/mock/mock_bta_ag_sco.cc
+++ b/system/test/mock/mock_bta_ag_sco.cc
@@ -27,9 +27,6 @@
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Original usings
using HfpInterface = bluetooth::audio::hfp::HfpClientInterface;
using namespace bluetooth;
@@ -64,7 +61,6 @@ struct bta_ag_set_sco_allowed bta_ag_set_sco_allowed;
struct bta_ag_set_sco_offload_enabled bta_ag_set_sco_offload_enabled;
struct bta_ag_stream_suspended bta_ag_stream_suspended;
struct bta_clear_active_device bta_clear_active_device;
-struct updateCodecParametersFromProviderInfo updateCodecParametersFromProviderInfo;
} // namespace bta_ag_sco
} // namespace mock
@@ -181,10 +177,5 @@ void bta_clear_active_device() {
inc_func_call_count(__func__);
test::mock::bta_ag_sco::bta_clear_active_device();
}
-void updateCodecParametersFromProviderInfo(tBTA_AG_UUID_CODEC esco_codec,
- enh_esco_params_t& params) {
- inc_func_call_count(__func__);
- test::mock::bta_ag_sco::updateCodecParametersFromProviderInfo(esco_codec, params);
-}
// Mocked functions complete
// END mockcify generation
diff --git a/system/test/mock/mock_bta_ag_sco.h b/system/test/mock/mock_bta_ag_sco.h
index 11f40a758a..f83d9de537 100644
--- a/system/test/mock/mock_bta_ag_sco.h
+++ b/system/test/mock/mock_bta_ag_sco.h
@@ -293,18 +293,6 @@ struct bta_clear_active_device {
};
extern struct bta_clear_active_device bta_clear_active_device;
-// Name: updateCodecParametersFromProviderInfo
-// Params: tBTA_AG_UUID_CODEC esco_codec, enh_esco_params_t& params
-// Return: void
-struct updateCodecParametersFromProviderInfo {
- std::function<void(tBTA_AG_UUID_CODEC esco_codec, enh_esco_params_t& params)> body{
- [](tBTA_AG_UUID_CODEC /* esco_codec */, enh_esco_params_t& /* params */) {}};
- void operator()(tBTA_AG_UUID_CODEC esco_codec, enh_esco_params_t& params) {
- body(esco_codec, params);
- }
-};
-extern struct updateCodecParametersFromProviderInfo updateCodecParametersFromProviderInfo;
-
} // namespace bta_ag_sco
} // namespace mock
} // namespace test
diff --git a/system/test/mock/mock_bta_ar.cc b/system/test/mock/mock_bta_ar.cc
index b0b181e6d8..3c9961f3cc 100644
--- a/system/test/mock/mock_bta_ar.cc
+++ b/system/test/mock/mock_bta_ar.cc
@@ -21,14 +21,12 @@
#include <cstdint>
+#include "bta/include/bta_ar_api.h"
#include "bta/sys/bta_sys.h"
#include "stack/include/avdt_api.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void bta_ar_dereg_avct() { inc_func_call_count(__func__); }
void bta_ar_dereg_avdt() { inc_func_call_count(__func__); }
void bta_ar_dereg_avrc(uint16_t /* service_uuid */) { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_bta_av_ci.cc b/system/test/mock/mock_bta_av_ci.cc
index 07da047861..9bc0f119b1 100644
--- a/system/test/mock/mock_bta_av_ci.cc
+++ b/system/test/mock/mock_bta_av_ci.cc
@@ -20,11 +20,9 @@
*/
#include "bta/include/bta_av_api.h"
+#include "bta/include/bta_av_ci.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void bta_av_ci_setconfig(tBTA_AV_HNDL /* bta_av_handle */, uint8_t /* err_code */,
uint8_t /* category */, bool /* recfg_needed */,
uint8_t /* avdt_handle */) {
diff --git a/system/test/mock/mock_bta_dm_act.cc b/system/test/mock/mock_bta_dm_act.cc
index 9f2686d4fd..65f70c0621 100644
--- a/system/test/mock/mock_bta_dm_act.cc
+++ b/system/test/mock/mock_bta_dm_act.cc
@@ -26,14 +26,16 @@
#include <cstdint>
+#include "bta/dm/bta_dm_act.h"
+#include "bta/dm/bta_dm_device_search.h"
+#include "bta/dm/bta_dm_sec_int.h"
+#include "bta/include/bta_dm_acl.h"
+#include "bta/include/bta_dm_api.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_dm_act {
@@ -74,7 +76,6 @@ struct bta_dm_process_remove_device bta_dm_process_remove_device;
struct bta_dm_remove_device bta_dm_remove_device;
struct bta_dm_remote_key_missing bta_dm_remote_key_missing;
struct bta_dm_on_encryption_change bta_dm_on_encryption_change;
-struct bta_dm_rm_cback bta_dm_rm_cback;
struct bta_dm_set_dev_name bta_dm_set_dev_name;
struct bta_dm_set_encryption bta_dm_set_encryption;
@@ -206,7 +207,7 @@ void bta_dm_enable(tBTA_DM_SEC_CBACK* p_sec_cback) {
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_enable(p_sec_cback);
}
-void bta_dm_encrypt_cback(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
+void bta_dm_encrypt_cback(RawAddress bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
tBTM_STATUS result) {
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_encrypt_cback(bd_addr, transport, p_ref_data, result);
@@ -235,11 +236,6 @@ void bta_dm_on_encryption_change(bt_encryption_change_evt encryption_change) {
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_on_encryption_change(encryption_change);
}
-void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id,
- const RawAddress& peer_addr) {
- inc_func_call_count(__func__);
- test::mock::bta_dm_act::bta_dm_rm_cback(status, id, app_id, peer_addr);
-}
void bta_dm_set_dev_name(const std::vector<uint8_t>& name) {
inc_func_call_count(__func__);
test::mock::bta_dm_act::bta_dm_set_dev_name(name);
diff --git a/system/test/mock/mock_bta_dm_act.h b/system/test/mock/mock_bta_dm_act.h
index df329a53af..ec81b0e62b 100644
--- a/system/test/mock/mock_bta_dm_act.h
+++ b/system/test/mock/mock_bta_dm_act.h
@@ -28,6 +28,7 @@
#include <cstdint>
#include "bta/dm/bta_dm_disc_int.h"
+#include "bta/dm/bta_dm_int.h"
#include "bta/dm/bta_dm_sec_int.h"
#include "types/raw_address.h"
@@ -372,11 +373,11 @@ extern struct bta_dm_enable bta_dm_enable;
// Params: const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
// tBTM_STATUS result Return: void
struct bta_dm_encrypt_cback {
- std::function<void(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
+ std::function<void(RawAddress bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
tBTM_STATUS result)>
- body{[](const RawAddress* /* bd_addr */, tBT_TRANSPORT /* transport */,
- void* /* p_ref_data */, tBTM_STATUS /* result */) {}};
- void operator()(const RawAddress* bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
+ body{[](RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */, void* /* p_ref_data */,
+ tBTM_STATUS /* result */) {}};
+ void operator()(RawAddress bd_addr, tBT_TRANSPORT transport, void* p_ref_data,
tBTM_STATUS result) {
body(bd_addr, transport, p_ref_data, result);
}
@@ -440,21 +441,6 @@ struct bta_dm_on_encryption_change {
};
extern struct bta_dm_on_encryption_change bta_dm_on_encryption_change;
-// Name: bta_dm_rm_cback
-// Params: tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, const
-// RawAddress& peer_addr Return: void
-struct bta_dm_rm_cback {
- std::function<void(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id,
- const RawAddress& peer_addr)>
- body{[](tBTA_SYS_CONN_STATUS /* status */, uint8_t /* id */, uint8_t /* app_id */,
- const RawAddress& /* peer_addr */) {}};
- void operator()(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id,
- const RawAddress& peer_addr) {
- body(status, id, app_id, peer_addr);
- }
-};
-extern struct bta_dm_rm_cback bta_dm_rm_cback;
-
// Name: bta_dm_search_cancel_cmpl
// Params:
// Return: void
diff --git a/system/test/mock/mock_bta_dm_api.cc b/system/test/mock/mock_bta_dm_api.cc
index 2d8129d0a5..1bf8009749 100644
--- a/system/test/mock/mock_bta_dm_api.cc
+++ b/system/test/mock/mock_bta_dm_api.cc
@@ -25,6 +25,8 @@
#include <cstdint>
+#include "bta/include/bta_api.h"
+#include "bta/include/bta_sec_api.h"
#include "hci/le_rand_callback.h"
#include "test/common/mock_functions.h"
@@ -32,9 +34,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_dm_api {
@@ -113,8 +112,8 @@ void BTA_DmAddBleKey(const RawAddress& bd_addr, tBTA_LE_KEY_VALUE* p_le_key,
inc_func_call_count(__func__);
test::mock::bta_dm_api::BTA_DmAddBleKey(bd_addr, p_le_key, key_type);
}
-void BTA_DmAddDevice(const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& link_key,
- uint8_t key_type, uint8_t pin_length) {
+void BTA_DmAddDevice(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, uint8_t key_type,
+ uint8_t pin_length) {
inc_func_call_count(__func__);
test::mock::bta_dm_api::BTA_DmAddDevice(bd_addr, dev_class, link_key, key_type, pin_length);
}
@@ -205,10 +204,10 @@ void BTA_DmDisconnectAllAcls() {
inc_func_call_count(__func__);
test::mock::bta_dm_api::BTA_DmDisconnectAllAcls();
}
-void BTA_DmDiscover(const RawAddress& bd_addr, tBTA_DM_SEARCH_CBACK* p_cback,
+void BTA_DmDiscover(const RawAddress& bd_addr, service_discovery_callbacks cbacks,
tBT_TRANSPORT transport) {
inc_func_call_count(__func__);
- test::mock::bta_dm_api::BTA_DmDiscover(bd_addr, p_cback, transport);
+ test::mock::bta_dm_api::BTA_DmDiscover(bd_addr, cbacks, transport);
}
bool BTA_DmGetConnectionState(const RawAddress& bd_addr) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_bta_dm_api.h b/system/test/mock/mock_bta_dm_api.h
index cbfad950fc..106bcd13bb 100644
--- a/system/test/mock/mock_bta_dm_api.h
+++ b/system/test/mock/mock_bta_dm_api.h
@@ -79,13 +79,12 @@ extern struct BTA_DmAddBleKey BTA_DmAddBleKey;
// Params: const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey&
// link_key, uint8_t key_type, uint8_t pin_length Return: void
struct BTA_DmAddDevice {
- std::function<void(const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& link_key,
- uint8_t key_type, uint8_t pin_length)>
- body{[](const RawAddress& /* bd_addr */, DEV_CLASS /* dev_class */,
- const LinkKey& /* link_key */, uint8_t /* key_type */,
- uint8_t /* pin_length */) {}};
- void operator()(const RawAddress& bd_addr, DEV_CLASS dev_class, const LinkKey& link_key,
- uint8_t key_type, uint8_t pin_length) {
+ std::function<void(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, uint8_t key_type,
+ uint8_t pin_length)>
+ body{[](RawAddress /* bd_addr */, DEV_CLASS /* dev_class */, LinkKey /* link_key */,
+ uint8_t /* key_type */, uint8_t /* pin_length */) {}};
+ void operator()(RawAddress bd_addr, DEV_CLASS dev_class, LinkKey link_key, uint8_t key_type,
+ uint8_t pin_length) {
body(bd_addr, dev_class, link_key, key_type, pin_length);
}
};
@@ -315,13 +314,13 @@ extern struct BTA_DmDisconnectAllAcls BTA_DmDisconnectAllAcls;
// Params: const RawAddress& bd_addr, tBTA_DM_SEARCH_CBACK* p_cback,
// tBT_TRANSPORT transport Return: void
struct BTA_DmDiscover {
- std::function<void(const RawAddress& bd_addr, tBTA_DM_SEARCH_CBACK* p_cback,
+ std::function<void(const RawAddress& bd_addr, service_discovery_callbacks cbacks,
tBT_TRANSPORT transport)>
- body{[](const RawAddress& /* bd_addr */, tBTA_DM_SEARCH_CBACK* /* p_cback */,
+ body{[](const RawAddress& /* bd_addr */, service_discovery_callbacks /* cbacks */,
tBT_TRANSPORT /* transport */) {}};
- void operator()(const RawAddress& bd_addr, tBTA_DM_SEARCH_CBACK* p_cback,
+ void operator()(const RawAddress& bd_addr, service_discovery_callbacks cbacks,
tBT_TRANSPORT transport) {
- body(bd_addr, p_cback, transport);
+ body(bd_addr, cbacks, transport);
}
};
extern struct BTA_DmDiscover BTA_DmDiscover;
diff --git a/system/test/mock/mock_bta_dm_main.cc b/system/test/mock/mock_bta_dm_main.cc
index 4c559cba3c..a7ab35f7ea 100644
--- a/system/test/mock/mock_bta_dm_main.cc
+++ b/system/test/mock/mock_bta_dm_main.cc
@@ -23,15 +23,13 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_bta_dm_main.h"
+#include "bta/include/bta_api.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_dm_main {
diff --git a/system/test/mock/mock_bta_gattc_api.cc b/system/test/mock/mock_bta_gattc_api.cc
index 6932102e84..126ad69267 100644
--- a/system/test/mock/mock_bta_gattc_api.cc
+++ b/system/test/mock/mock_bta_gattc_api.cc
@@ -22,6 +22,7 @@
#include <base/functional/bind.h>
#include <base/functional/callback.h>
+#include "bta/gatt/bta_gattc_int.h"
#include "bta/gatt/database.h"
#include "bta/include/bta_gatt_api.h"
#include "stack/include/gatt_api.h"
@@ -30,9 +31,6 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void BTA_GATTC_Disable(void) { inc_func_call_count(__func__); }
const gatt::Characteristic* BTA_GATTC_GetCharacteristic(uint16_t /* conn_id */,
uint16_t /* handle */) {
diff --git a/system/test/mock/mock_bta_gatts_api.cc b/system/test/mock/mock_bta_gatts_api.cc
index 3d57cbba78..c34f764acd 100644
--- a/system/test/mock/mock_bta_gatts_api.cc
+++ b/system/test/mock/mock_bta_gatts_api.cc
@@ -32,9 +32,6 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void BTA_GATTS_Disable(void) { inc_func_call_count(__func__); }
void BTA_GATTS_AppDeregister(tGATT_IF /* server_if */) { inc_func_call_count(__func__); }
void BTA_GATTS_AppRegister(const bluetooth::Uuid& /* app_uuid */, tBTA_GATTS_CBACK* /* p_cback */,
diff --git a/system/test/mock/mock_bta_hh_utils.cc b/system/test/mock/mock_bta_hh_utils.cc
index a922421242..f6aee6948c 100644
--- a/system/test/mock/mock_bta_hh_utils.cc
+++ b/system/test/mock/mock_bta_hh_utils.cc
@@ -30,9 +30,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_hh_utils {
@@ -47,7 +44,6 @@ struct bta_hh_read_ssr_param bta_hh_read_ssr_param;
struct bta_hh_tod_spt bta_hh_tod_spt;
struct bta_hh_trace_dev_db bta_hh_trace_dev_db;
struct bta_hh_update_di_info bta_hh_update_di_info;
-struct bta_hh_le_is_hh_gatt_if bta_hh_le_is_hh_gatt_if;
} // namespace bta_hh_utils
} // namespace mock
@@ -96,10 +92,5 @@ void bta_hh_update_di_info(tBTA_HH_DEV_CB* p_cb, uint16_t vendor_id, uint16_t pr
test::mock::bta_hh_utils::bta_hh_update_di_info(p_cb, vendor_id, product_id, version, flag,
ctry_code);
}
-bool bta_hh_le_is_hh_gatt_if(tGATT_IF client_if) {
- inc_func_call_count(__func__);
- test::mock::bta_hh_utils::bta_hh_le_is_hh_gatt_if(client_if);
- return false;
-}
// Mocked functions complete
// END mockcify generation
diff --git a/system/test/mock/mock_bta_hh_utils.h b/system/test/mock/mock_bta_hh_utils.h
index a46d616732..172392e832 100644
--- a/system/test/mock/mock_bta_hh_utils.h
+++ b/system/test/mock/mock_bta_hh_utils.h
@@ -146,17 +146,6 @@ struct bta_hh_update_di_info {
};
extern struct bta_hh_update_di_info bta_hh_update_di_info;
-// Name: bta_hh_le_is_hh_gatt_if
-// Params: tGATT_IF client_if
-// Return: bool
-struct bta_hh_le_is_hh_gatt_if {
- bool return_value{false};
- std::function<bool(tGATT_IF client_if)> body{
- [this](tGATT_IF /* client_if */) { return return_value; }};
- bool operator()(tGATT_IF client_if) { return body(client_if); }
-};
-extern struct bta_hh_le_is_hh_gatt_if bta_hh_le_is_hh_gatt_if;
-
} // namespace bta_hh_utils
} // namespace mock
} // namespace test
diff --git a/system/test/mock/mock_bta_leaudio.cc b/system/test/mock/mock_bta_leaudio.cc
index 24824032a3..c135ae9b3d 100644
--- a/system/test/mock/mock_bta_leaudio.cc
+++ b/system/test/mock/mock_bta_leaudio.cc
@@ -42,8 +42,9 @@ class HalVersionManager {
} // namespace bluetooth
void LeAudioClient::AddFromStorage(
- const RawAddress& /* addr */, bool /* autoconnect */, int /* sink_audio_location */,
- int /* source_audio_location */, int /* sink_supported_context_types */,
+ const RawAddress& /* addr */, bool /* autoconnect */,
+ std::optional<int> /* sink_audio_location */,
+ std::optional<int> /* source_audio_location */, int /* sink_supported_context_types */,
int /* source_supported_context_types */, const std::vector<uint8_t>& /* handles */,
const std::vector<uint8_t>& /* sink_pacs */, const std::vector<uint8_t>& /* source_pacs */,
const std::vector<uint8_t>& /* ases */, const std::vector<uint8_t>& /* gmap */) {
diff --git a/system/test/mock/mock_bta_pan_api.cc b/system/test/mock/mock_bta_pan_api.cc
index 0e662c5d19..4f353f3aa1 100644
--- a/system/test/mock/mock_bta_pan_api.cc
+++ b/system/test/mock/mock_bta_pan_api.cc
@@ -25,9 +25,6 @@
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void BTA_PanClose(uint16_t /* handle */) { inc_func_call_count(__func__); }
void BTA_PanDisable(void) { inc_func_call_count(__func__); }
void BTA_PanEnable(tBTA_PAN_CBACK /* p_cback */) { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_bta_sdp_api.cc b/system/test/mock/mock_bta_sdp_api.cc
index 966920221a..a0facebc53 100644
--- a/system/test/mock/mock_bta_sdp_api.cc
+++ b/system/test/mock/mock_bta_sdp_api.cc
@@ -28,16 +28,12 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_sdp_api {
// Function state capture and return values, if needed
struct BTA_SdpCreateRecordByUser BTA_SdpCreateRecordByUser;
-struct BTA_SdpDumpsys BTA_SdpDumpsys;
struct BTA_SdpEnable BTA_SdpEnable;
struct BTA_SdpRemoveRecordByUser BTA_SdpRemoveRecordByUser;
struct BTA_SdpSearch BTA_SdpSearch;
@@ -65,10 +61,6 @@ tBTA_SDP_STATUS BTA_SdpCreateRecordByUser(void* user_data) {
inc_func_call_count(__func__);
return test::mock::bta_sdp_api::BTA_SdpCreateRecordByUser(user_data);
}
-void BTA_SdpDumpsys(int fd) {
- inc_func_call_count(__func__);
- test::mock::bta_sdp_api::BTA_SdpDumpsys(fd);
-}
tBTA_SDP_STATUS BTA_SdpEnable(tBTA_SDP_DM_CBACK* p_cback) {
inc_func_call_count(__func__);
return test::mock::bta_sdp_api::BTA_SdpEnable(p_cback);
diff --git a/system/test/mock/mock_bta_sdp_api.h b/system/test/mock/mock_bta_sdp_api.h
index 8449e40fe7..b45ac94328 100644
--- a/system/test/mock/mock_bta_sdp_api.h
+++ b/system/test/mock/mock_bta_sdp_api.h
@@ -49,15 +49,6 @@ struct BTA_SdpCreateRecordByUser {
};
extern struct BTA_SdpCreateRecordByUser BTA_SdpCreateRecordByUser;
-// Name: BTA_SdpDumpsys
-// Params: int fd
-// Return: void
-struct BTA_SdpDumpsys {
- std::function<void(int fd)> body{[](int /* fd */) {}};
- void operator()(int fd) { body(fd); }
-};
-extern struct BTA_SdpDumpsys BTA_SdpDumpsys;
-
// Name: BTA_SdpEnable
// Params: tBTA_SDP_DM_CBACK* p_cback
// Return: tBTA_SDP_STATUS
diff --git a/system/test/mock/mock_bta_sys_conn.cc b/system/test/mock/mock_bta_sys_conn.cc
index e8453047a3..4d4348de39 100644
--- a/system/test/mock/mock_bta_sys_conn.cc
+++ b/system/test/mock/mock_bta_sys_conn.cc
@@ -26,9 +26,6 @@
#include "types/hci_role.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void bta_sys_app_close(tBTA_SYS_ID /* id */, uint8_t /* app_id */,
const RawAddress& /* peer_addr */) {
inc_func_call_count(__func__);
@@ -66,7 +63,7 @@ void bta_sys_reset_sniff(uint8_t /* id */, uint8_t /* app_id */,
inc_func_call_count(__func__);
}
void bta_sys_rm_register(tBTA_SYS_CONN_CBACK* /* p_cback */) { inc_func_call_count(__func__); }
-void bta_sys_role_chg_register(tBTA_SYS_CONN_CBACK* /* p_cback */) {
+void bta_sys_role_chg_register(tBTA_SYS_ROLE_SWITCH_CBACK* /* p_cback */) {
inc_func_call_count(__func__);
}
void bta_sys_sco_close(tBTA_SYS_ID /* id */, uint8_t /* app_id */,
diff --git a/system/test/mock/mock_bta_sys_main.cc b/system/test/mock/mock_bta_sys_main.cc
index dd7e10e6ea..63da8a5969 100644
--- a/system/test/mock/mock_bta_sys_main.cc
+++ b/system/test/mock/mock_bta_sys_main.cc
@@ -30,9 +30,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace bta_sys_main {
diff --git a/system/test/mock/mock_btif_av.cc b/system/test/mock/mock_btif_av.cc
index 560c5e1a78..8ee4fd05ea 100644
--- a/system/test/mock/mock_btif_av.cc
+++ b/system/test/mock/mock_btif_av.cc
@@ -32,9 +32,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_av {
diff --git a/system/test/mock/mock_btif_bluetooth.cc b/system/test/mock/mock_btif_bluetooth.cc
index c101c6ee4d..7a9de6b076 100644
--- a/system/test/mock/mock_btif_bluetooth.cc
+++ b/system/test/mock/mock_btif_bluetooth.cc
@@ -25,15 +25,13 @@
#include <cstdint>
+#include "btif/include/btif_api.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_bluetooth {
@@ -42,14 +40,7 @@ namespace btif_bluetooth {
struct is_atv_device is_atv_device;
struct is_common_criteria_mode is_common_criteria_mode;
struct is_restricted_mode is_restricted_mode;
-struct dut_mode_configure dut_mode_configure;
-struct dut_mode_send dut_mode_send;
struct get_common_criteria_config_compare_result get_common_criteria_config_compare_result;
-struct get_remote_device_properties get_remote_device_properties;
-struct get_remote_device_property get_remote_device_property;
-struct get_remote_services get_remote_services;
-struct le_test_mode le_test_mode;
-struct set_remote_device_property set_remote_device_property;
struct invoke_switch_buffer_size_cb invoke_switch_buffer_size_cb;
} // namespace btif_bluetooth
@@ -69,38 +60,10 @@ bool is_restricted_mode() {
inc_func_call_count(__func__);
return test::mock::btif_bluetooth::is_restricted_mode();
}
-int dut_mode_configure(uint8_t enable) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::dut_mode_configure(enable);
-}
-int dut_mode_send(uint16_t opcode, uint8_t* buf, uint8_t len) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::dut_mode_send(opcode, buf, len);
-}
int get_common_criteria_config_compare_result() {
inc_func_call_count(__func__);
return test::mock::btif_bluetooth::get_common_criteria_config_compare_result();
}
-int get_remote_device_properties(RawAddress* remote_addr) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::get_remote_device_properties(remote_addr);
-}
-int get_remote_device_property(RawAddress* remote_addr, bt_property_type_t type) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::get_remote_device_property(remote_addr, type);
-}
-int get_remote_services(RawAddress* remote_addr) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::get_remote_services(remote_addr);
-}
-int le_test_mode(uint16_t opcode, uint8_t* buf, uint8_t len) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::le_test_mode(opcode, buf, len);
-}
-int set_remote_device_property(RawAddress* remote_addr, const bt_property_t* property) {
- inc_func_call_count(__func__);
- return test::mock::btif_bluetooth::set_remote_device_property(remote_addr, property);
-}
void invoke_switch_buffer_size_cb(bool invoke_switch_buffer_size_cb) {
inc_func_call_count(__func__);
test::mock::btif_bluetooth::invoke_switch_buffer_size_cb(invoke_switch_buffer_size_cb);
diff --git a/system/test/mock/mock_btif_bluetooth.h b/system/test/mock/mock_btif_bluetooth.h
index 7ecc1ef832..f3f198dfd5 100644
--- a/system/test/mock/mock_btif_bluetooth.h
+++ b/system/test/mock/mock_btif_bluetooth.h
@@ -58,23 +58,6 @@ struct is_restricted_mode {
bool operator()() { return body(); }
};
extern struct is_restricted_mode is_restricted_mode;
-// Name: dut_mode_configure
-// Params: uint8_t enable
-// Returns: int
-struct dut_mode_configure {
- std::function<int(uint8_t enable)> body{[](uint8_t /* enable */) { return 0; }};
- int operator()(uint8_t enable) { return body(enable); }
-};
-extern struct dut_mode_configure dut_mode_configure;
-// Name: dut_mode_send
-// Params: uint16_t opcode, uint8_t* buf, uint8_t len
-// Returns: int
-struct dut_mode_send {
- std::function<int(uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */)> body{
- [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { return 0; }};
- int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { return body(opcode, buf, len); }
-};
-extern struct dut_mode_send dut_mode_send;
// Name: get_common_criteria_config_compare_result
// Params:
// Returns: int
@@ -83,53 +66,6 @@ struct get_common_criteria_config_compare_result {
int operator()() { return body(); }
};
extern struct get_common_criteria_config_compare_result get_common_criteria_config_compare_result;
-// Name: get_remote_device_properties
-// Params: RawAddress* remote_addr
-// Returns: int
-struct get_remote_device_properties {
- std::function<int(RawAddress* remote_addr)> body{[](RawAddress* /* remote_addr */) { return 0; }};
- int operator()(RawAddress* remote_addr) { return body(remote_addr); }
-};
-extern struct get_remote_device_properties get_remote_device_properties;
-// Name: get_remote_device_property
-// Params: RawAddress* remote_addr, bt_property_type_t type
-// Returns: int
-struct get_remote_device_property {
- std::function<int(RawAddress* remote_addr, bt_property_type_t type)> body{
- [](RawAddress* /* remote_addr */, bt_property_type_t /* type */) { return 0; }};
- int operator()(RawAddress* remote_addr, bt_property_type_t type) {
- return body(remote_addr, type);
- }
-};
-extern struct get_remote_device_property get_remote_device_property;
-// Name: get_remote_services
-// Params: RawAddress* remote_addr
-// Returns: int
-struct get_remote_services {
- std::function<int(RawAddress* remote_addr)> body{[](RawAddress* /* remote_addr */) { return 0; }};
- int operator()(RawAddress* remote_addr) { return body(remote_addr); }
-};
-extern struct get_remote_services get_remote_services;
-// Name: le_test_mode
-// Params: uint16_t opcode, uint8_t* buf, uint8_t len
-// Returns: int
-struct le_test_mode {
- std::function<int(uint16_t opcode, uint8_t* buf, uint8_t len)> body{
- [](uint16_t /* opcode */, uint8_t* /* buf */, uint8_t /* len */) { return 0; }};
- int operator()(uint16_t opcode, uint8_t* buf, uint8_t len) { return body(opcode, buf, len); }
-};
-extern struct le_test_mode le_test_mode;
-// Name: set_remote_device_property
-// Params: RawAddress* remote_addr, const bt_property_t* property
-// Returns: int
-struct set_remote_device_property {
- std::function<int(RawAddress* remote_addr, const bt_property_t* property)> body{
- [](RawAddress* /* remote_addr */, const bt_property_t* /* property */) { return 0; }};
- int operator()(RawAddress* remote_addr, const bt_property_t* property) {
- return body(remote_addr, property);
- }
-};
-extern struct set_remote_device_property set_remote_device_property;
// Name: invoke_switch_buffer_size_cb
// Params: bool invoke_switch_buffer_size_cb
// Returns: void
diff --git a/system/test/mock/mock_btif_bqr.cc b/system/test/mock/mock_btif_bqr.cc
deleted file mode 100644
index 2a17a7778e..0000000000
--- a/system/test/mock/mock_btif_bqr.cc
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright 2021 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.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:51
- */
-
-#include <cstdint>
-
-#include "test/common/mock_functions.h"
-
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-namespace bluetooth {
-namespace bqr {
-
-void DumpLmpLlMessage(uint8_t /* length */, const uint8_t* /* p_event */) {
- inc_func_call_count(__func__);
-}
-
-void DumpBtScheduling(uint8_t /* length */, const uint8_t* /* p_event */) {
- inc_func_call_count(__func__);
-}
-
-} // namespace bqr
-} // namespace bluetooth
diff --git a/system/test/mock/mock_btif_bta_pan_co_rx.cc b/system/test/mock/mock_btif_bta_pan_co_rx.cc
index 741104b228..1eed716edf 100644
--- a/system/test/mock/mock_btif_bta_pan_co_rx.cc
+++ b/system/test/mock/mock_btif_bta_pan_co_rx.cc
@@ -25,14 +25,12 @@
#include <cstdint>
+#include "bta/include/bta_pan_co.h"
#include "test/common/mock_functions.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_bta_pan_co_rx {
diff --git a/system/test/mock/mock_btif_co_bta_av_co.cc b/system/test/mock/mock_btif_co_bta_av_co.cc
index efa055531f..f596c047a0 100644
--- a/system/test/mock/mock_btif_co_bta_av_co.cc
+++ b/system/test/mock/mock_btif_co_bta_av_co.cc
@@ -25,15 +25,14 @@
#include <cstdint>
+#include "bta/include/bta_av_co.h"
+#include "btif/include/btif_av_co.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_co_bta_av_co {
diff --git a/system/test/mock/mock_btif_co_bta_dm_co.cc b/system/test/mock/mock_btif_co_bta_dm_co.cc
index 656b94cda2..f33bcf4c68 100644
--- a/system/test/mock/mock_btif_co_bta_dm_co.cc
+++ b/system/test/mock/mock_btif_co_bta_dm_co.cc
@@ -24,14 +24,6 @@
#include "bta/sys/bta_sys.h"
#include "internal_include/bte_appl.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
tBTE_APPL_CFG bte_appl_cfg = {BTA_LE_AUTH_REQ_SC_MITM_BOND, // Authentication requirements
BTM_IO_CAP_UNKNOWN, BTM_BLE_INITIATOR_KEY_SIZE,
BTM_BLE_RESPONDER_KEY_SIZE, BTM_BLE_MAX_KEY_SIZE};
-
-bool bta_dm_co_get_compress_memory(tBTA_SYS_ID /* id */, uint8_t** /* memory_p */,
- uint32_t* /* memory_size */) {
- return true;
-}
diff --git a/system/test/mock/mock_btif_co_bta_hh_co.cc b/system/test/mock/mock_btif_co_bta_hh_co.cc
index 8f9a4ea739..f1a185d99e 100644
--- a/system/test/mock/mock_btif_co_bta_hh_co.cc
+++ b/system/test/mock/mock_btif_co_bta_hh_co.cc
@@ -27,9 +27,6 @@
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
int bta_hh_co_write(int /* fd */, uint8_t* /* rpt */, uint16_t /* len */) {
inc_func_call_count(__func__);
return 0;
diff --git a/system/test/mock/mock_btif_config.cc b/system/test/mock/mock_btif_config.cc
index 549fe4bf44..72c91c04fc 100644
--- a/system/test/mock/mock_btif_config.cc
+++ b/system/test/mock/mock_btif_config.cc
@@ -27,15 +27,13 @@
#include <cstdint>
#include <string>
+#include "btif/include/btif_config.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_config {
diff --git a/system/test/mock/mock_btif_core.cc b/system/test/mock/mock_btif_core.cc
index 001c5b553f..0d601d2af1 100644
--- a/system/test/mock/mock_btif_core.cc
+++ b/system/test/mock/mock_btif_core.cc
@@ -24,14 +24,12 @@
#include <cstdint>
#include "bta/include/bta_api.h"
+#include "btif/include/btif_api.h"
#include "btif/include/btif_common.h"
#include "include/hardware/bluetooth.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool btif_is_dut_mode() {
inc_func_call_count(__func__);
return false;
diff --git a/system/test/mock/mock_btif_dm.cc b/system/test/mock/mock_btif_dm.cc
index cc3bf79edd..9d135c5530 100644
--- a/system/test/mock/mock_btif_dm.cc
+++ b/system/test/mock/mock_btif_dm.cc
@@ -23,6 +23,7 @@
#include "bta/include/bta_api.h"
#include "bta/include/bta_sec_api.h"
+#include "btif/include/btif_api.h"
#include "include/hardware/bluetooth.h"
#include "internal_include/bte_appl.h"
#include "stack/include/acl_api_types.h"
@@ -31,16 +32,13 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
struct uid_set_t;
bool btif_dm_pairing_is_busy() {
inc_func_call_count(__func__);
return false;
}
-bool check_cod_hid(const RawAddress& /* remote_bdaddr */) {
+bool btif_check_cod_hid(const RawAddress& /* remote_bdaddr */) {
inc_func_call_count(__func__);
return false;
}
@@ -71,19 +69,16 @@ void btif_ble_transmitter_test(uint8_t /* tx_freq */, uint8_t /* test_data_len *
inc_func_call_count(__func__);
}
void btif_debug_bond_event_dump(int /* fd */) { inc_func_call_count(__func__); }
-void btif_dm_ble_sec_req_evt(tBTA_DM_BLE_SEC_REQ* /* p_ble_req */, bool /* is_consent */) {
- inc_func_call_count(__func__);
-}
void btif_dm_cancel_bond(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); }
void btif_dm_cancel_discovery(void) { inc_func_call_count(__func__); }
void btif_dm_cleanup(void) { inc_func_call_count(__func__); }
-void btif_dm_create_bond(const RawAddress /* bd_addr */, int /* transport */) {
+void btif_dm_create_bond(const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */) {
inc_func_call_count(__func__);
}
void btif_dm_create_bond_le(const RawAddress /* bd_addr */, tBLE_ADDR_TYPE /* addr_type */) {
inc_func_call_count(__func__);
}
-void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */, int /* transport */,
+void btif_dm_create_bond_out_of_band(const RawAddress /* bd_addr */, tBT_TRANSPORT /* transport */,
const bt_oob_data_t /* p192_data */,
const bt_oob_data_t /* p256_data */) {
inc_func_call_count(__func__);
@@ -95,7 +90,7 @@ void btif_dm_get_ble_local_keys(tBTA_DM_BLE_LOCAL_KEY_MASK* /* p_key_mask */, Oc
tBTA_BLE_LOCAL_ID_KEYS* /* p_id_keys */) {
inc_func_call_count(__func__);
}
-void btif_dm_get_remote_services(RawAddress /* remote_addr */, const int /* transport */) {
+void btif_dm_get_remote_services(RawAddress /* remote_addr */, tBT_TRANSPORT /* transport */) {
inc_func_call_count(__func__);
}
void btif_dm_hh_open_failed(RawAddress* /* bdaddr */) { inc_func_call_count(__func__); }
@@ -118,7 +113,6 @@ void btif_dm_proc_io_rsp(const RawAddress& /* bd_addr */, tBTM_IO_CAP /* io_cap
inc_func_call_count(__func__);
}
void btif_dm_read_energy_info() { inc_func_call_count(__func__); }
-void btif_dm_remove_ble_bonding_keys(void) { inc_func_call_count(__func__); }
void btif_dm_remove_bond(const RawAddress /* bd_addr */) { inc_func_call_count(__func__); }
void btif_dm_set_oob_for_io_req(tBTM_OOB_DATA* /* p_has_oob_data */) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_btif_hf.cc b/system/test/mock/mock_btif_hf.cc
index b3d9b88d16..b8e9f5057a 100644
--- a/system/test/mock/mock_btif_hf.cc
+++ b/system/test/mock/mock_btif_hf.cc
@@ -23,15 +23,13 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_btif_hf.h"
+#include "btif/include/btif_hf.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_hf {
diff --git a/system/test/mock/mock_btif_profile_storage.cc b/system/test/mock/mock_btif_profile_storage.cc
index a65103fa8e..5095788e28 100644
--- a/system/test/mock/mock_btif_profile_storage.cc
+++ b/system/test/mock/mock_btif_profile_storage.cc
@@ -25,11 +25,10 @@
#include <cstdint>
+#include "btif/include/btif_profile_storage.h"
+#include "btif/include/btif_storage.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Original usings
using bluetooth::Uuid;
@@ -74,7 +73,9 @@ struct btif_storage_remove_leaudio btif_storage_remove_leaudio;
struct btif_storage_remove_leaudio_has btif_storage_remove_leaudio_has;
struct btif_storage_set_hearing_aid_acceptlist btif_storage_set_hearing_aid_acceptlist;
struct btif_storage_set_hidd btif_storage_set_hidd;
-struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location;
+struct btif_storage_set_leaudio_sink_audio_location btif_storage_set_leaudio_sink_audio_location;
+struct btif_storage_set_leaudio_source_audio_location
+ btif_storage_set_leaudio_source_audio_location;
struct btif_storage_set_leaudio_autoconnect btif_storage_set_leaudio_autoconnect;
struct btif_storage_set_leaudio_has_acceptlist btif_storage_set_leaudio_has_acceptlist;
struct btif_storage_set_leaudio_has_active_preset btif_storage_set_leaudio_has_active_preset;
@@ -257,11 +258,16 @@ bt_status_t btif_storage_set_hidd(const RawAddress& remote_bd_addr) {
inc_func_call_count(__func__);
return test::mock::btif_profile_storage::btif_storage_set_hidd(remote_bd_addr);
}
-void btif_storage_set_leaudio_audio_location(const RawAddress& addr, uint32_t sink_location,
- uint32_t source_location) {
+void btif_storage_set_leaudio_sink_audio_location(const RawAddress& addr, uint32_t sink_location) {
+ inc_func_call_count(__func__);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_sink_audio_location(addr,
+ sink_location);
+}
+void btif_storage_set_leaudio_source_audio_location(const RawAddress& addr,
+ uint32_t source_location) {
inc_func_call_count(__func__);
- test::mock::btif_profile_storage::btif_storage_set_leaudio_audio_location(addr, sink_location,
- source_location);
+ test::mock::btif_profile_storage::btif_storage_set_leaudio_source_audio_location(addr,
+ source_location);
}
void btif_storage_set_leaudio_autoconnect(const RawAddress& addr, bool autoconnect) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_btif_profile_storage.h b/system/test/mock/mock_btif_profile_storage.h
index 1d0bbd7c96..816dd1f33b 100644
--- a/system/test/mock/mock_btif_profile_storage.h
+++ b/system/test/mock/mock_btif_profile_storage.h
@@ -401,18 +401,25 @@ struct btif_storage_set_hidd {
};
extern struct btif_storage_set_hidd btif_storage_set_hidd;
-// Name: btif_storage_set_leaudio_audio_location
-// Params: const RawAddress& addr, uint32_t sink_location, uint32_t
-// source_location Return: void
-struct btif_storage_set_leaudio_audio_location {
- std::function<void(const RawAddress& addr, uint32_t sink_location, uint32_t source_location)>
- body{[](const RawAddress& /* addr */, uint32_t /* sink_location */,
- uint32_t /* source_location */) {}};
- void operator()(const RawAddress& addr, uint32_t sink_location, uint32_t source_location) {
- body(addr, sink_location, source_location);
- }
-};
-extern struct btif_storage_set_leaudio_audio_location btif_storage_set_leaudio_audio_location;
+// Name: btif_storage_set_leaudio_sink_audio_location
+// Params: const RawAddress& addr, uint32_t sink_location, Return: void
+struct btif_storage_set_leaudio_sink_audio_location {
+ std::function<void(const RawAddress& addr, uint32_t sink_location)> body{
+ [](const RawAddress& /* addr */, uint32_t /* sink_location */) {}};
+ void operator()(const RawAddress& addr, uint32_t sink_location) { body(addr, sink_location); }
+};
+extern struct btif_storage_set_leaudio_sink_audio_location
+ btif_storage_set_leaudio_sink_audio_location;
+
+// Name: btif_storage_set_leaudio_source_audio_location
+// Params: const RawAddress& addr, uint32_t source_location, Return: void
+struct btif_storage_set_leaudio_source_audio_location {
+ std::function<void(const RawAddress& addr, uint32_t source_location)> body{
+ [](const RawAddress& /* addr */, uint32_t /* source_location */) {}};
+ void operator()(const RawAddress& addr, uint32_t source_location) { body(addr, source_location); }
+};
+extern struct btif_storage_set_leaudio_sink_audio_location
+ btif_storage_set_leaudio_sink_audio_location;
// Name: btif_storage_set_leaudio_autoconnect
// Params: const RawAddress& addr, bool autoconnect
diff --git a/system/test/mock/mock_btif_sock_l2cap.cc b/system/test/mock/mock_btif_sock_l2cap.cc
index 41f19f8cd0..135cd47dac 100644
--- a/system/test/mock/mock_btif_sock_l2cap.cc
+++ b/system/test/mock/mock_btif_sock_l2cap.cc
@@ -25,11 +25,9 @@
#include <cstdint>
+#include "btif/include/btif_sock_l2cap.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Original usings
// Mocked internal structures, if any
diff --git a/system/test/mock/mock_btif_sock_rfc.cc b/system/test/mock/mock_btif_sock_rfc.cc
index 6ca7512418..c22a7bf860 100644
--- a/system/test/mock/mock_btif_sock_rfc.cc
+++ b/system/test/mock/mock_btif_sock_rfc.cc
@@ -24,11 +24,10 @@
#include <cstdint>
+#include "bta/include/bta_jv_co.h"
+#include "btif/include/btif_sock_rfc.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Original usings
using bluetooth::Uuid;
@@ -91,11 +90,14 @@ void btsock_rfc_cleanup(void) {
inc_func_call_count(__func__);
test::mock::btif_sock_rfc::btsock_rfc_cleanup();
}
-bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) {
+bt_status_t btsock_rfc_connect(const RawAddress* bd_addr, const bluetooth::Uuid* uuid, int channel,
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size) {
inc_func_call_count(__func__);
- return test::mock::btif_sock_rfc::btsock_rfc_connect(bd_addr, service_uuid, channel, sock_fd,
- flags, app_uid);
+ return test::mock::btif_sock_rfc::btsock_rfc_connect(bd_addr, uuid, channel, sock_fd, flags,
+ app_uid, data_path, socket_name, hub_id,
+ endpoint_id, max_rx_packet_size);
}
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,
@@ -113,10 +115,13 @@ bt_status_t btsock_rfc_init(int poll_thread_handle, uid_set_t* set) {
return test::mock::btif_sock_rfc::btsock_rfc_init(poll_thread_handle, set);
}
bt_status_t btsock_rfc_listen(const char* service_name, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) {
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size) {
inc_func_call_count(__func__);
return test::mock::btif_sock_rfc::btsock_rfc_listen(service_name, service_uuid, channel, sock_fd,
- flags, app_uid);
+ flags, app_uid, data_path, socket_name,
+ hub_id, endpoint_id, max_rx_packet_size);
}
void btsock_rfc_signaled(int fd, int flags, uint32_t id) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_btif_sock_rfc.h b/system/test/mock/mock_btif_sock_rfc.h
index 59f296f016..a0d14cb9bc 100644
--- a/system/test/mock/mock_btif_sock_rfc.h
+++ b/system/test/mock/mock_btif_sock_rfc.h
@@ -30,6 +30,7 @@
#include <functional>
#include "btif/include/btif_uid.h"
+#include "hardware/bt_sock.h"
#include "stack/include/bt_hdr.h"
#include "types/bluetooth/uuid.h"
#include "types/raw_address.h"
@@ -91,14 +92,21 @@ extern struct btsock_rfc_cleanup btsock_rfc_cleanup;
// int* sock_fd, int flags, int app_uid Return: bt_status_t
struct btsock_rfc_connect {
static bt_status_t return_value;
- std::function<bt_status_t(const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid)>
- body{[](const RawAddress* /* bd_addr */, const Uuid* /* service_uuid */,
- int /* channel */, int* /* sock_fd */, int /* flags */,
- int /* app_uid */) { return return_value; }};
- bt_status_t operator()(const RawAddress* bd_addr, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) {
- return body(bd_addr, service_uuid, channel, sock_fd, flags, app_uid);
+ std::function<bt_status_t(const RawAddress* bd_addr, const bluetooth::Uuid* uuid, int channel,
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size)>
+ body{[](const RawAddress* /*bd_addr*/, const bluetooth::Uuid* /*uuid*/, int /*channel*/,
+ int* /*sock_fd*/, int /*flags*/, int /*app_uid*/,
+ btsock_data_path_t /*data_path*/, const char* /*socket_name*/,
+ uint64_t /*hub_id*/, uint64_t /*endpoint_id*/,
+ int /*max_rx_packet_size*/) { return return_value; }};
+ bt_status_t operator()(const RawAddress* bd_addr, const bluetooth::Uuid* uuid, int channel,
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size) {
+ return body(bd_addr, uuid, channel, sock_fd, flags, app_uid, data_path, socket_name, hub_id,
+ endpoint_id, max_rx_packet_size);
}
};
extern struct btsock_rfc_connect btsock_rfc_connect;
@@ -153,12 +161,20 @@ extern struct btsock_rfc_init btsock_rfc_init;
struct btsock_rfc_listen {
static bt_status_t return_value;
std::function<bt_status_t(const char* service_name, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid)>
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size)>
body{[](const char* /* service_name */, const Uuid* /* service_uuid */, int /* channel */,
- int* /* sock_fd */, int /* flags */, int /* app_uid */) { return return_value; }};
+ int* /* sock_fd */, int /* flags */, int /* app_uid */,
+ btsock_data_path_t /*data_path*/, const char* /*socket_name*/,
+ uint64_t /*hub_id*/, uint64_t /*endpoint_id*/,
+ int /*max_rx_packet_size*/) { return return_value; }};
bt_status_t operator()(const char* service_name, const Uuid* service_uuid, int channel,
- int* sock_fd, int flags, int app_uid) {
- return body(service_name, service_uuid, channel, sock_fd, flags, app_uid);
+ int* sock_fd, int flags, int app_uid, btsock_data_path_t data_path,
+ const char* socket_name, uint64_t hub_id, uint64_t endpoint_id,
+ int max_rx_packet_size) {
+ return body(service_name, service_uuid, channel, sock_fd, flags, app_uid, data_path,
+ socket_name, hub_id, endpoint_id, max_rx_packet_size);
}
};
extern struct btsock_rfc_listen btsock_rfc_listen;
diff --git a/system/test/mock/mock_btif_stack_manager.cc b/system/test/mock/mock_btif_stack_manager.cc
index bdc4150ca9..e334b911dd 100644
--- a/system/test/mock/mock_btif_stack_manager.cc
+++ b/system/test/mock/mock_btif_stack_manager.cc
@@ -19,12 +19,10 @@
*/
#include "btif/include/core_callbacks.h"
+#include "btif/include/stack_manager_t.h"
#include "osi/include/future.h"
#include "test/common/core_interface.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
static future_t* hack_future;
future_t* stack_manager_get_hack_future() { return hack_future; }
diff --git a/system/test/mock/mock_btif_storage.cc b/system/test/mock/mock_btif_storage.cc
index 427dd20a54..f8b9ab5ff3 100644
--- a/system/test/mock/mock_btif_storage.cc
+++ b/system/test/mock/mock_btif_storage.cc
@@ -25,11 +25,10 @@
#include <cstdint>
+#include "btif/include/btif_api.h"
+#include "btif/include/btif_storage.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Original usings
using bluetooth::Uuid;
@@ -41,7 +40,6 @@ namespace btif_storage {
// Function state capture and return values, if needed
struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump;
-struct btif_has_ble_keys btif_has_ble_keys;
struct btif_in_fetch_bonded_ble_device btif_in_fetch_bonded_ble_device;
struct btif_in_fetch_bonded_device btif_in_fetch_bonded_device;
struct btif_split_uuids_string btif_split_uuids_string;
@@ -49,7 +47,6 @@ struct btif_storage_add_ble_bonding_key btif_storage_add_ble_bonding_key;
struct btif_storage_add_ble_local_key btif_storage_add_ble_local_key;
struct btif_storage_add_bonded_device btif_storage_add_bonded_device;
struct btif_storage_add_remote_device btif_storage_add_remote_device;
-struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop;
struct btif_storage_get_adapter_property btif_storage_get_adapter_property;
struct btif_storage_get_ble_bonding_key btif_storage_get_ble_bonding_key;
struct btif_storage_get_ble_local_key btif_storage_get_ble_local_key;
@@ -57,11 +54,9 @@ struct btif_storage_get_gatt_cl_db_hash btif_storage_get_gatt_cl_db_hash;
struct btif_storage_get_gatt_cl_supp_feat btif_storage_get_gatt_cl_supp_feat;
struct btif_storage_get_remote_addr_type btif_storage_get_remote_addr_type;
struct btif_storage_get_remote_device_property btif_storage_get_remote_device_property;
-struct btif_storage_get_remote_prop btif_storage_get_remote_prop;
struct btif_storage_get_sr_supp_feat btif_storage_get_sr_supp_feat;
struct btif_storage_get_stored_remote_name btif_storage_get_stored_remote_name;
struct btif_storage_get_cod btif_storage_get_cod;
-struct btif_storage_invoke_addr_type_update btif_storage_invoke_addr_type_update;
struct btif_storage_is_restricted_device btif_storage_is_restricted_device;
struct btif_storage_load_bonded_devices btif_storage_load_bonded_devices;
struct btif_storage_load_le_devices btif_storage_load_le_devices;
@@ -86,7 +81,6 @@ namespace test {
namespace mock {
namespace btif_storage {
-bool btif_has_ble_keys::return_value = false;
bt_status_t btif_in_fetch_bonded_ble_device::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_in_fetch_bonded_device::return_value = BT_STATUS_SUCCESS;
size_t btif_split_uuids_string::return_value = 0;
@@ -94,7 +88,6 @@ bt_status_t btif_storage_add_ble_bonding_key::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_add_ble_local_key::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_add_bonded_device::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_add_remote_device::return_value = BT_STATUS_SUCCESS;
-bt_status_t btif_storage_get_adapter_prop::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_get_adapter_property::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_get_ble_bonding_key::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_get_ble_local_key::return_value = BT_STATUS_SUCCESS;
@@ -102,7 +95,6 @@ Octet16 btif_storage_get_gatt_cl_db_hash::return_value = {};
uint8_t btif_storage_get_gatt_cl_supp_feat::return_value = 0;
bt_status_t btif_storage_get_remote_addr_type::return_value = BT_STATUS_SUCCESS;
bt_status_t btif_storage_get_remote_device_property::return_value = BT_STATUS_SUCCESS;
-bt_status_t btif_storage_get_remote_prop::return_value = BT_STATUS_SUCCESS;
uint8_t btif_storage_get_sr_supp_feat::return_value = 0;
bool btif_storage_get_stored_remote_name::return_value = false;
bool btif_storage_get_cod::return_value = false;
@@ -124,10 +116,6 @@ void btif_debug_linkkey_type_dump(int fd) {
inc_func_call_count(__func__);
test::mock::btif_storage::btif_debug_linkkey_type_dump(fd);
}
-bool btif_has_ble_keys(const std::string& bdstr) {
- inc_func_call_count(__func__);
- return test::mock::btif_storage::btif_has_ble_keys(bdstr);
-}
bt_status_t btif_in_fetch_bonded_ble_device(const std::string& remote_bd_addr, int add,
btif_bonded_devices_t* p_bonded_devices) {
inc_func_call_count(__func__);
@@ -164,11 +152,6 @@ bt_status_t btif_storage_add_remote_device(const RawAddress* remote_bd_addr,
return test::mock::btif_storage::btif_storage_add_remote_device(remote_bd_addr, num_properties,
properties);
}
-bt_status_t btif_storage_get_adapter_prop(bt_property_type_t type, void* buf, int size,
- bt_property_t* property) {
- inc_func_call_count(__func__);
- return test::mock::btif_storage::btif_storage_get_adapter_prop(type, buf, size, property);
-}
bt_status_t btif_storage_get_adapter_property(bt_property_t* property) {
inc_func_call_count(__func__);
return test::mock::btif_storage::btif_storage_get_adapter_property(property);
@@ -202,12 +185,6 @@ bt_status_t btif_storage_get_remote_device_property(const RawAddress* remote_bd_
return test::mock::btif_storage::btif_storage_get_remote_device_property(remote_bd_addr,
property);
}
-bt_status_t btif_storage_get_remote_prop(RawAddress* remote_addr, bt_property_type_t type,
- void* buf, int size, bt_property_t* property) {
- inc_func_call_count(__func__);
- return test::mock::btif_storage::btif_storage_get_remote_prop(remote_addr, type, buf, size,
- property);
-}
uint8_t btif_storage_get_sr_supp_feat(const RawAddress& bd_addr) {
inc_func_call_count(__func__);
return test::mock::btif_storage::btif_storage_get_sr_supp_feat(bd_addr);
@@ -220,11 +197,6 @@ bool btif_storage_get_cod(const RawAddress& bd_addr, uint32_t* cod) {
inc_func_call_count(__func__);
return test::mock::btif_storage::btif_storage_get_cod(bd_addr, cod);
}
-void btif_storage_invoke_addr_type_update(const RawAddress& remote_bd_addr,
- const tBLE_ADDR_TYPE& addr_type) {
- inc_func_call_count(__func__);
- test::mock::btif_storage::btif_storage_invoke_addr_type_update(remote_bd_addr, addr_type);
-}
bool btif_storage_is_restricted_device(const RawAddress* remote_bd_addr) {
inc_func_call_count(__func__);
return test::mock::btif_storage::btif_storage_is_restricted_device(remote_bd_addr);
diff --git a/system/test/mock/mock_btif_storage.h b/system/test/mock/mock_btif_storage.h
index 2df8d149e5..6be7f1200a 100644
--- a/system/test/mock/mock_btif_storage.h
+++ b/system/test/mock/mock_btif_storage.h
@@ -55,17 +55,6 @@ struct btif_debug_linkkey_type_dump {
};
extern struct btif_debug_linkkey_type_dump btif_debug_linkkey_type_dump;
-// Name: btif_has_ble_keys
-// Params: const std::string& bdstr
-// Return: bool
-struct btif_has_ble_keys {
- static bool return_value;
- std::function<bool(const std::string& bdstr)> body{
- [](const std::string& /* bdstr */) { return return_value; }};
- bool operator()(const std::string& bdstr) { return body(bdstr); }
-};
-extern struct btif_has_ble_keys btif_has_ble_keys;
-
// Name: btif_in_fetch_bonded_ble_device
// Params: const std::string& remote_bd_addr, int add, btif_bonded_devices_t*
// p_bonded_devices Return: bt_status_t
@@ -169,20 +158,6 @@ struct btif_storage_add_remote_device {
};
extern struct btif_storage_add_remote_device btif_storage_add_remote_device;
-// Name: btif_storage_get_adapter_prop
-// Params: bt_property_type_t type, void* buf, int size, bt_property_t* property
-// Return: bt_status_t
-struct btif_storage_get_adapter_prop {
- static bt_status_t return_value;
- std::function<bt_status_t(bt_property_type_t type, void* buf, int size, bt_property_t* property)>
- body{[](bt_property_type_t /* type */, void* /* buf */, int /* size */,
- bt_property_t* /* property */) { return return_value; }};
- bt_status_t operator()(bt_property_type_t type, void* buf, int size, bt_property_t* property) {
- return body(type, buf, size, property);
- }
-};
-extern struct btif_storage_get_adapter_prop btif_storage_get_adapter_prop;
-
// Name: btif_storage_get_adapter_property
// Params: bt_property_t* property
// Return: bt_status_t
@@ -272,22 +247,6 @@ struct btif_storage_get_remote_device_property {
};
extern struct btif_storage_get_remote_device_property btif_storage_get_remote_device_property;
-// Name: btif_storage_get_remote_prop
-// Params: RawAddress* remote_addr, bt_property_type_t type, void* buf, int
-// size, bt_property_t* property Return: bt_status_t
-struct btif_storage_get_remote_prop {
- static bt_status_t return_value;
- std::function<bt_status_t(RawAddress* remote_addr, bt_property_type_t type, void* buf, int size,
- bt_property_t* property)>
- body{[](RawAddress* /* remote_addr */, bt_property_type_t /* type */, void* /* buf */,
- int /* size */, bt_property_t* /* property */) { return return_value; }};
- bt_status_t operator()(RawAddress* remote_addr, bt_property_type_t type, void* buf, int size,
- bt_property_t* property) {
- return body(remote_addr, type, buf, size, property);
- }
-};
-extern struct btif_storage_get_remote_prop btif_storage_get_remote_prop;
-
// Name: btif_storage_get_sr_supp_feat
// Params: const RawAddress& bd_addr
// Return: uint8_t
@@ -321,18 +280,6 @@ struct btif_storage_get_cod {
};
extern struct btif_storage_get_cod btif_storage_get_cod;
-// Name: btif_storage_invoke_addr_type_update
-// Params: const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type
-// Return: void
-struct btif_storage_invoke_addr_type_update {
- std::function<void(const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type)> body{
- [](const RawAddress& /* remote_bd_addr */, const tBLE_ADDR_TYPE& /* addr_type */) {}};
- void operator()(const RawAddress& remote_bd_addr, const tBLE_ADDR_TYPE& addr_type) {
- body(remote_bd_addr, addr_type);
- }
-};
-extern struct btif_storage_invoke_addr_type_update btif_storage_invoke_addr_type_update;
-
// Name: btif_storage_is_restricted_device
// Params: const RawAddress* remote_bd_addr
// Return: bool
diff --git a/system/test/mock/mock_btif_util.cc b/system/test/mock/mock_btif_util.cc
index 662fa3fcbc..bfb192409f 100644
--- a/system/test/mock/mock_btif_util.cc
+++ b/system/test/mock/mock_btif_util.cc
@@ -24,15 +24,13 @@
#include <cstdint>
+#include "btif/include/btif_util.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace btif_util {
@@ -67,20 +65,20 @@ namespace btif_util {
int ascii_2_hex::return_value = 0;
uint32_t devclass2uint::return_value = 0;
-const char* dump_adapter_scan_mode::return_value = nullptr;
-const char* dump_av_audio_state::return_value = nullptr;
-const char* dump_av_conn_state::return_value = nullptr;
-const char* dump_bt_status::return_value = nullptr;
-const char* dump_dm_event::return_value = nullptr;
-const char* dump_dm_search_event::return_value = nullptr;
-const char* dump_hd_event::return_value = nullptr;
-const char* dump_hf_client_event::return_value = nullptr;
-const char* dump_hf_event::return_value = nullptr;
-const char* dump_property_type::return_value = nullptr;
-const char* dump_rc_event::return_value = nullptr;
-const char* dump_rc_notification_event_id::return_value = nullptr;
-const char* dump_rc_pdu::return_value = nullptr;
-const char* dump_thread_evt::return_value = nullptr;
+std::string dump_adapter_scan_mode::return_value = "";
+std::string dump_av_audio_state::return_value = "";
+std::string dump_av_conn_state::return_value = "";
+std::string dump_bt_status::return_value = "";
+std::string dump_dm_event::return_value = "";
+std::string dump_dm_search_event::return_value = "";
+std::string dump_hd_event::return_value = "";
+std::string dump_hf_client_event::return_value = "";
+std::string dump_hf_event::return_value = "";
+std::string dump_property_type::return_value = "";
+std::string dump_rc_event::return_value = "";
+std::string dump_rc_notification_event_id::return_value = "";
+std::string dump_rc_pdu::return_value = "";
+std::string dump_thread_evt::return_value = "";
} // namespace btif_util
} // namespace mock
@@ -95,59 +93,59 @@ uint32_t devclass2uint(const DEV_CLASS dev_class) {
inc_func_call_count(__func__);
return test::mock::btif_util::devclass2uint(dev_class);
}
-const char* dump_adapter_scan_mode(bt_scan_mode_t mode) {
+std::string dump_adapter_scan_mode(bt_scan_mode_t mode) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_adapter_scan_mode(mode);
}
-const char* dump_av_audio_state(uint16_t event) {
+std::string dump_av_audio_state(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_av_audio_state(event);
}
-const char* dump_av_conn_state(uint16_t event) {
+std::string dump_av_conn_state(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_av_conn_state(event);
}
-const char* dump_bt_status(bt_status_t status) {
+std::string dump_bt_status(bt_status_t status) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_bt_status(status);
}
-const char* dump_dm_event(uint16_t event) {
+std::string dump_dm_event(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_dm_event(event);
}
-const char* dump_dm_search_event(uint16_t event) {
+std::string dump_dm_search_event(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_dm_search_event(event);
}
-const char* dump_hd_event(uint16_t event) {
+std::string dump_hd_event(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_hd_event(event);
}
-const char* dump_hf_client_event(uint16_t event) {
+std::string dump_hf_client_event(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_hf_client_event(event);
}
-const char* dump_hf_event(uint16_t event) {
+std::string dump_hf_event(uint16_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_hf_event(event);
}
-const char* dump_property_type(bt_property_type_t type) {
+std::string dump_property_type(bt_property_type_t type) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_property_type(type);
}
-const char* dump_rc_event(uint8_t event) {
+std::string dump_rc_event(uint8_t event) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_rc_event(event);
}
-const char* dump_rc_notification_event_id(uint8_t event_id) {
+std::string dump_rc_notification_event_id(uint8_t event_id) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_rc_notification_event_id(event_id);
}
-const char* dump_rc_pdu(uint8_t pdu) {
+std::string dump_rc_pdu(uint8_t pdu) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_rc_pdu(pdu);
}
-const char* dump_thread_evt(bt_cb_thread_evt evt) {
+std::string dump_thread_evt(bt_cb_thread_evt evt) {
inc_func_call_count(__func__);
return test::mock::btif_util::dump_thread_evt(evt);
}
diff --git a/system/test/mock/mock_btif_util.h b/system/test/mock/mock_btif_util.h
index 7dd4188ce0..bd775a8062 100644
--- a/system/test/mock/mock_btif_util.h
+++ b/system/test/mock/mock_btif_util.h
@@ -66,152 +66,152 @@ extern struct devclass2uint devclass2uint;
// Name: dump_adapter_scan_mode
// Params: bt_scan_mode_t mode
-// Return: const char*
+// Return: std::string
struct dump_adapter_scan_mode {
- static const char* return_value;
- std::function<const char*(bt_scan_mode_t mode)> body{
+ static std::string return_value;
+ std::function<std::string(bt_scan_mode_t mode)> body{
[](bt_scan_mode_t /* mode */) { return return_value; }};
- const char* operator()(bt_scan_mode_t mode) { return body(mode); }
+ std::string operator()(bt_scan_mode_t mode) { return body(mode); }
};
extern struct dump_adapter_scan_mode dump_adapter_scan_mode;
// Name: dump_av_audio_state
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_av_audio_state {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_av_audio_state dump_av_audio_state;
// Name: dump_av_conn_state
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_av_conn_state {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_av_conn_state dump_av_conn_state;
// Name: dump_bt_status
// Params: bt_status_t status
-// Return: const char*
+// Return: std::string
struct dump_bt_status {
- static const char* return_value;
- std::function<const char*(bt_status_t status)> body{
+ static std::string return_value;
+ std::function<std::string(bt_status_t status)> body{
[](bt_status_t /* status */) { return return_value; }};
- const char* operator()(bt_status_t status) { return body(status); }
+ std::string operator()(bt_status_t status) { return body(status); }
};
extern struct dump_bt_status dump_bt_status;
// Name: dump_dm_event
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_dm_event {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_dm_event dump_dm_event;
// Name: dump_dm_search_event
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_dm_search_event {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_dm_search_event dump_dm_search_event;
// Name: dump_hd_event
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_hd_event {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_hd_event dump_hd_event;
// Name: dump_hf_client_event
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_hf_client_event {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
extern struct dump_hf_client_event dump_hf_client_event;
// Name: dump_hf_event
// Params: uint16_t event
-// Return: const char*
+// Return: std::string
struct dump_hf_event {
- static const char* return_value;
- std::function<const char*(uint16_t event)> body{
+ static std::string return_value;
+ std::function<std::string(uint16_t event)> body{
[](uint16_t /* event */) { return return_value; }};
- const char* operator()(uint16_t event) { return body(event); }
+ std::string operator()(uint16_t event) { return body(event); }
};
// Name: dump_property_type
// Params: bt_property_type_t type
-// Return: const char*
+// Return: std::string
struct dump_property_type {
- static const char* return_value;
- std::function<const char*(bt_property_type_t type)> body{
+ static std::string return_value;
+ std::function<std::string(bt_property_type_t type)> body{
[](bt_property_type_t /* type */) { return return_value; }};
- const char* operator()(bt_property_type_t type) { return body(type); }
+ std::string operator()(bt_property_type_t type) { return body(type); }
};
extern struct dump_property_type dump_property_type;
// Name: dump_rc_event
// Params: uint8_t event
-// Return: const char*
+// Return: std::string
struct dump_rc_event {
- static const char* return_value;
- std::function<const char*(uint8_t event)> body{[](uint8_t /* event */) { return return_value; }};
- const char* operator()(uint8_t event) { return body(event); }
+ static std::string return_value;
+ std::function<std::string(uint8_t event)> body{[](uint8_t /* event */) { return return_value; }};
+ std::string operator()(uint8_t event) { return body(event); }
};
extern struct dump_rc_event dump_rc_event;
// Name: dump_rc_notification_event_id
// Params: uint8_t event_id
-// Return: const char*
+// Return: std::string
struct dump_rc_notification_event_id {
- static const char* return_value;
- std::function<const char*(uint8_t event_id)> body{
+ static std::string return_value;
+ std::function<std::string(uint8_t event_id)> body{
[](uint8_t /* event_id */) { return return_value; }};
- const char* operator()(uint8_t event_id) { return body(event_id); }
+ std::string operator()(uint8_t event_id) { return body(event_id); }
};
extern struct dump_rc_notification_event_id dump_rc_notification_event_id;
// Name: dump_rc_pdu
// Params: uint8_t pdu
-// Return: const char*
+// Return: std::string
struct dump_rc_pdu {
- static const char* return_value;
- std::function<const char*(uint8_t pdu)> body{[](uint8_t /* pdu */) { return return_value; }};
- const char* operator()(uint8_t pdu) { return body(pdu); }
+ static std::string return_value;
+ std::function<std::string(uint8_t pdu)> body{[](uint8_t /* pdu */) { return return_value; }};
+ std::string operator()(uint8_t pdu) { return body(pdu); }
};
extern struct dump_rc_pdu dump_rc_pdu;
// Name: dump_thread_evt
// Params: bt_cb_thread_evt evt
-// Return: const char*
+// Return: std::string
struct dump_thread_evt {
- static const char* return_value;
- std::function<const char*(bt_cb_thread_evt evt)> body{
+ static std::string return_value;
+ std::function<std::string(bt_cb_thread_evt evt)> body{
[](bt_cb_thread_evt /* evt */) { return return_value; }};
- const char* operator()(bt_cb_thread_evt evt) { return body(evt); }
+ std::string operator()(bt_cb_thread_evt evt) { return body(evt); }
};
extern struct dump_thread_evt dump_thread_evt;
diff --git a/system/test/mock/mock_device_esco_parameters.cc b/system/test/mock/mock_device_esco_parameters.cc
index 5a9a3ad263..c38d546de8 100644
--- a/system/test/mock/mock_device_esco_parameters.cc
+++ b/system/test/mock/mock_device_esco_parameters.cc
@@ -23,13 +23,11 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_device_esco_parameters.h"
+#include "device/include/esco_parameters.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace device_esco_parameters {
@@ -42,14 +40,9 @@ struct esco_parameters_for_codec esco_parameters_for_codec;
} // namespace test
// Mocked functions, if any
-enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec) {
- inc_func_call_count(__func__);
- return test::mock::device_esco_parameters::esco_parameters_for_codec(codec);
-}
-
-enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool /* b */) {
+enh_esco_params_t esco_parameters_for_codec(esco_codec_t codec, bool offload) {
inc_func_call_count(__func__);
- return test::mock::device_esco_parameters::esco_parameters_for_codec(codec);
+ return test::mock::device_esco_parameters::esco_parameters_for_codec(codec, offload);
}
// Mocked functions complete
// END mockcify generation
diff --git a/system/test/mock/mock_device_esco_parameters.h b/system/test/mock/mock_device_esco_parameters.h
index 92e5ad085d..327f2ddc92 100644
--- a/system/test/mock/mock_device_esco_parameters.h
+++ b/system/test/mock/mock_device_esco_parameters.h
@@ -38,9 +38,9 @@ namespace device_esco_parameters {
// Return: enh_esco_params_t
struct esco_parameters_for_codec {
enh_esco_params_t return_value{};
- std::function<enh_esco_params_t(esco_codec_t codec)> body{
- [this](esco_codec_t /* codec */) { return return_value; }};
- enh_esco_params_t operator()(esco_codec_t codec) { return body(codec); }
+ std::function<enh_esco_params_t(esco_codec_t codec, bool offload)> body{
+ [this](esco_codec_t /* codec */, bool /* offload */) { return return_value; }};
+ enh_esco_params_t operator()(esco_codec_t codec, bool offload) { return body(codec, offload); }
};
extern struct esco_parameters_for_codec esco_parameters_for_codec;
diff --git a/system/test/mock/mock_device_interop.cc b/system/test/mock/mock_device_interop.cc
index 0f7a0a27e5..ae65e50634 100644
--- a/system/test/mock/mock_device_interop.cc
+++ b/system/test/mock/mock_device_interop.cc
@@ -25,15 +25,13 @@
#include <cstdint>
#include "device/include/interop.h"
+#include "device/include/interop_config.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace device_interop {
@@ -70,7 +68,6 @@ struct interop_match_addr_or_name interop_match_addr_or_name;
struct interop_match_manufacturer interop_match_manufacturer;
struct interop_match_name interop_match_name;
struct interop_match_vendor_product_ids interop_match_vendor_product_ids;
-struct token_to_ul token_to_ul;
} // namespace device_interop
} // namespace mock
@@ -103,7 +100,6 @@ bool interop_match_addr_or_name::return_value = false;
bool interop_match_manufacturer::return_value = false;
bool interop_match_name::return_value = false;
bool interop_match_vendor_product_ids::return_value = false;
-bool token_to_ul::return_value = false;
} // namespace device_interop
} // namespace mock
@@ -257,9 +253,5 @@ bool interop_match_vendor_product_ids(const interop_feature_t feature, uint16_t
return test::mock::device_interop::interop_match_vendor_product_ids(feature, vendor_id,
product_id);
}
-bool token_to_ul(char* token, uint16_t* ul) {
- inc_func_call_count(__func__);
- return test::mock::device_interop::token_to_ul(token, ul);
-}
// Mocked functions complete
// END mockcify generation
diff --git a/system/test/mock/mock_device_interop.h b/system/test/mock/mock_device_interop.h
index ecb08d79fb..79193f3525 100644
--- a/system/test/mock/mock_device_interop.h
+++ b/system/test/mock/mock_device_interop.h
@@ -460,17 +460,6 @@ struct interop_match_vendor_product_ids {
};
extern struct interop_match_vendor_product_ids interop_match_vendor_product_ids;
-// Name: token_to_ul
-// Params: char* token, uint16_t* ul
-// Return: bool
-struct token_to_ul {
- static bool return_value;
- std::function<bool(char* token, uint16_t* ul)> body{
- [](char* /* token */, uint16_t* /* ul */) { return return_value; }};
- bool operator()(char* token, uint16_t* ul) { return body(token, ul); }
-};
-extern struct token_to_ul token_to_ul;
-
} // namespace device_interop
} // namespace mock
} // namespace test
diff --git a/system/test/mock/mock_device_iot_config.cc b/system/test/mock/mock_device_iot_config.cc
index 61308a883a..9f01127d48 100644
--- a/system/test/mock/mock_device_iot_config.cc
+++ b/system/test/mock/mock_device_iot_config.cc
@@ -19,11 +19,9 @@
#include <cstdint>
#include <string>
+#include "device/include/device_iot_config.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace device_iot_config {
diff --git a/system/test/mock/mock_jni_thread.cc b/system/test/mock/mock_jni_thread.cc
index eb8b6db093..afc1a28570 100644
--- a/system/test/mock/mock_jni_thread.cc
+++ b/system/test/mock/mock_jni_thread.cc
@@ -28,9 +28,6 @@
#include "test/common/jni_thread.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool is_on_jni_thread() {
inc_func_call_count(__func__);
return false;
@@ -46,8 +43,3 @@ bt_status_t do_in_jni_thread(base::OnceClosure task) {
do_in_jni_thread_task_queue.push(std::move(task));
return BT_STATUS_SUCCESS;
}
-bt_status_t do_in_jni_thread(const base::Location& /* from_here */, base::OnceClosure task) {
- inc_func_call_count(__func__);
- do_in_jni_thread_task_queue.push(std::move(task));
- return BT_STATUS_SUCCESS;
-}
diff --git a/system/test/mock/mock_main_shim_acl.cc b/system/test/mock/mock_main_shim_acl.cc
index 14bc02eb49..a98e809ad0 100644
--- a/system/test/mock/mock_main_shim_acl.cc
+++ b/system/test/mock/mock_main_shim_acl.cc
@@ -33,13 +33,8 @@
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
-void DumpsysL2cap(int /* fd */) { inc_func_call_count(__func__); }
-
void DumpsysAcl(int /* fd */) { inc_func_call_count(__func__); }
void DumpsysNeighbor(int /* fd */) { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_main_shim_acl_interface.cc b/system/test/mock/mock_main_shim_acl_interface.cc
index 2ba6014443..b2f1d47af4 100644
--- a/system/test/mock/mock_main_shim_acl_interface.cc
+++ b/system/test/mock/mock_main_shim_acl_interface.cc
@@ -16,14 +16,10 @@
#include "main/shim/acl_interface.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace bluetooth {
namespace shim {
-namespace legacy {
-acl_interface_t acl_interface_ = {
+static acl_interface_t acl_interface_ = {
.on_send_data_upwards = nullptr,
.on_packets_completed = nullptr,
@@ -72,6 +68,5 @@ acl_interface_t acl_interface_ = {
const acl_interface_t& GetAclInterface() { return acl_interface_; }
-} // namespace legacy
} // namespace shim
} // namespace bluetooth
diff --git a/system/test/mock/mock_main_shim_hci_layer.cc b/system/test/mock/mock_main_shim_hci_layer.cc
index c02f009333..97d6c6e801 100644
--- a/system/test/mock/mock_main_shim_hci_layer.cc
+++ b/system/test/mock/mock_main_shim_hci_layer.cc
@@ -31,9 +31,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace bluetooth::shim {
namespace testing {
const hci_t* test_interface = nullptr;
@@ -48,8 +45,6 @@ namespace mock {
namespace main_shim_hci_layer {
// Function state capture and return values, if needed
-struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete;
-struct OnTransmitPacketStatus OnTransmitPacketStatus;
struct hci_on_reset_complete hci_on_reset_complete;
struct hci_on_shutting_down hci_on_shutting_down;
@@ -64,23 +59,6 @@ namespace main_shim_hci_layer {} // namespace main_shim_hci_layer
} // namespace mock
} // namespace test
-// Mocked functions, if any
-namespace cpp {
-void OnTransmitPacketCommandComplete(command_complete_cb complete_callback, void* context,
- bluetooth::hci::CommandCompleteView view) {
- inc_func_call_count(__func__);
- test::mock::main_shim_hci_layer::OnTransmitPacketCommandComplete(complete_callback, context,
- view);
-}
-void OnTransmitPacketStatus(command_status_cb status_callback, void* context,
- std::unique_ptr<OsiObject> command,
- bluetooth::hci::CommandStatusView view) {
- inc_func_call_count(__func__);
- test::mock::main_shim_hci_layer::OnTransmitPacketStatus(status_callback, context,
- std::move(command), view);
-}
-} // namespace cpp
-
void bluetooth::shim::hci_on_reset_complete() {
inc_func_call_count(__func__);
test::mock::main_shim_hci_layer::hci_on_reset_complete();
diff --git a/system/test/mock/mock_main_shim_hci_layer.h b/system/test/mock/mock_main_shim_hci_layer.h
index 7973bece5d..b46e525a9c 100644
--- a/system/test/mock/mock_main_shim_hci_layer.h
+++ b/system/test/mock/mock_main_shim_hci_layer.h
@@ -54,39 +54,6 @@ namespace test {
namespace mock {
namespace main_shim_hci_layer {
-// Shared state between mocked functions and tests
-// Name: OnTransmitPacketCommandComplete
-// Params: command_complete_cb complete_callback, void* context,
-// bluetooth::hci::CommandCompleteView view Return: void
-struct OnTransmitPacketCommandComplete {
- std::function<void(command_complete_cb complete_callback, void* context,
- bluetooth::hci::CommandCompleteView view)>
- body{[](command_complete_cb /* complete_callback */, void* /* context */,
- bluetooth::hci::CommandCompleteView /* view */) {}};
- void operator()(command_complete_cb complete_callback, void* context,
- bluetooth::hci::CommandCompleteView view) {
- body(complete_callback, context, view);
- }
-};
-extern struct OnTransmitPacketCommandComplete OnTransmitPacketCommandComplete;
-
-// Name: OnTransmitPacketStatus
-// Params: command_status_cb status_callback, void* context,
-// std::unique_ptr<OsiObject> command, bluetooth::hci::CommandStatusView view
-// Return: void
-struct OnTransmitPacketStatus {
- std::function<void(command_status_cb status_callback, void* context,
- std::unique_ptr<OsiObject> command, bluetooth::hci::CommandStatusView view)>
- body{[](command_status_cb /* status_callback */, void* /* context */,
- std::unique_ptr<OsiObject> /* command */,
- bluetooth::hci::CommandStatusView /* view */) {}};
- void operator()(command_status_cb status_callback, void* context,
- std::unique_ptr<OsiObject> command, bluetooth::hci::CommandStatusView view) {
- body(status_callback, context, std::move(command), view);
- }
-};
-extern struct OnTransmitPacketStatus OnTransmitPacketStatus;
-
// Name: hci_layer_get_interface
// Params:
// Return: const hci_t*
diff --git a/system/test/mock/mock_main_shim_stack.cc b/system/test/mock/mock_main_shim_stack.cc
deleted file mode 100644
index 03ec09a1b3..0000000000
--- a/system/test/mock/mock_main_shim_stack.cc
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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.
- */
-
-#include "hci/acl_manager.h"
-#include "main/shim/stack.h"
-
-namespace bluetooth {
-namespace shim {
-
-namespace testing {
-Acl* acl_{nullptr};
-Stack* instance_{nullptr};
-} // namespace testing
-
-Stack* Stack::GetInstance() { return testing::instance_; }
-
-void Stack::StartEverything() {}
-
-void Stack::StartModuleStack(const ModuleList* /* modules */, const os::Thread* /* thread */) {}
-
-void Stack::Start(ModuleList* /* modules */) {}
-
-void Stack::Stop() {}
-
-bool Stack::IsRunning() { return stack_thread_ != nullptr; }
-
-Acl* Stack::GetAcl() { return testing::acl_; }
-
-os::Handler* Stack::GetHandler() { return stack_handler_; }
-
-} // namespace shim
-} // namespace bluetooth
diff --git a/system/test/mock/mock_osi_future.cc b/system/test/mock/mock_osi_future.cc
index c7c98a3ac7..d1b5e1b946 100644
--- a/system/test/mock/mock_osi_future.cc
+++ b/system/test/mock/mock_osi_future.cc
@@ -27,9 +27,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_future {
@@ -37,7 +34,6 @@ namespace osi_future {
// Function state capture and return values, if needed
struct future_await future_await;
struct future_new future_new;
-struct future_new_named future_new_named;
struct future_new_immediate future_new_immediate;
struct future_ready future_ready;
@@ -54,10 +50,6 @@ future_t* future_new(void) {
inc_func_call_count(__func__);
return test::mock::osi_future::future_new();
}
-future_t* future_new_named(const char* name) {
- inc_func_call_count(__func__);
- return test::mock::osi_future::future_new_named(name);
-}
future_t* future_new_immediate(void* value) {
inc_func_call_count(__func__);
return test::mock::osi_future::future_new_immediate(value);
diff --git a/system/test/mock/mock_osi_future.h b/system/test/mock/mock_osi_future.h
index bb4ab1f610..e2fa5aad9b 100644
--- a/system/test/mock/mock_osi_future.h
+++ b/system/test/mock/mock_osi_future.h
@@ -57,17 +57,6 @@ struct future_new {
};
extern struct future_new future_new;
-// Name: future_new_named
-// Params: const char* name
-// Return: future_t*
-struct future_new_named {
- future_t* return_value{0};
- std::function<future_t*(const char* name)> body{
- [this](const char* /* name */) { return return_value; }};
- future_t* operator()(const char* name) { return body(name); }
-};
-extern struct future_new_named future_new_named;
-
// Name: future_new_immediate
// Params: void* value
// Return: future_t*
diff --git a/system/test/mock/mock_osi_list.cc b/system/test/mock/mock_osi_list.cc
index 2aa2bfd462..c081aa5fd3 100644
--- a/system/test/mock/mock_osi_list.cc
+++ b/system/test/mock/mock_osi_list.cc
@@ -27,9 +27,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_list {
@@ -49,7 +46,6 @@ struct list_insert_after list_insert_after;
struct list_is_empty list_is_empty;
struct list_length list_length;
struct list_new list_new;
-struct list_new_internal list_new_internal;
struct list_next list_next;
struct list_node list_node;
struct list_prepend list_prepend;
@@ -116,10 +112,6 @@ list_t* list_new(list_free_cb callback) {
inc_func_call_count(__func__);
return test::mock::osi_list::list_new(callback);
}
-list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) {
- inc_func_call_count(__func__);
- return test::mock::osi_list::list_new_internal(callback, zeroed_allocator);
-}
list_node_t* list_next(const list_node_t* node) {
inc_func_call_count(__func__);
return test::mock::osi_list::list_next(node);
diff --git a/system/test/mock/mock_osi_list.h b/system/test/mock/mock_osi_list.h
index 86813a8adc..6f727953b4 100644
--- a/system/test/mock/mock_osi_list.h
+++ b/system/test/mock/mock_osi_list.h
@@ -193,21 +193,6 @@ struct list_new {
};
extern struct list_new list_new;
-// Name: list_new_internal
-// Params: list_free_cb callback, const allocator_t* zeroed_allocator
-// Return: list_t*
-struct list_new_internal {
- list_t* return_value{0};
- std::function<list_t*(list_free_cb callback, const allocator_t* zeroed_allocator)> body{
- [this](list_free_cb /* callback */, const allocator_t* /* zeroed_allocator */) {
- return return_value;
- }};
- list_t* operator()(list_free_cb callback, const allocator_t* zeroed_allocator) {
- return body(callback, zeroed_allocator);
- }
-};
-extern struct list_new_internal list_new_internal;
-
// Name: list_next
// Params: const list_node_t* node
// Return: list_node_t*
diff --git a/system/test/mock/mock_osi_mutex.cc b/system/test/mock/mock_osi_mutex.cc
index ff8aa0afb2..e7e1db9ef8 100644
--- a/system/test/mock/mock_osi_mutex.cc
+++ b/system/test/mock/mock_osi_mutex.cc
@@ -23,13 +23,11 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_osi_mutex.h"
+#include "osi/include/mutex.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_mutex {
diff --git a/system/test/mock/mock_osi_properties.cc b/system/test/mock/mock_osi_properties.cc
index f22b3e0e1d..28c0891f7c 100644
--- a/system/test/mock/mock_osi_properties.cc
+++ b/system/test/mock/mock_osi_properties.cc
@@ -26,13 +26,11 @@
#include <cstdint>
#include <vector>
+#include "osi/include/properties.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_properties {
diff --git a/system/test/mock/mock_osi_properties.h b/system/test/mock/mock_osi_properties.h
index ad1c29c8d3..bbdeb61474 100644
--- a/system/test/mock/mock_osi_properties.h
+++ b/system/test/mock/mock_osi_properties.h
@@ -24,9 +24,6 @@
#include <cstdint>
#include <functional>
-// Original included files, if any
-#include <cutils/properties.h>
-
// Mocked compile conditionals, if any
namespace test {
diff --git a/system/test/mock/mock_osi_ringbuffer.cc b/system/test/mock/mock_osi_ringbuffer.cc
deleted file mode 100644
index be0500715a..0000000000
--- a/system/test/mock/mock_osi_ringbuffer.cc
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2021 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.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:8
- *
- * mockcify.pl ver 0.3.0
- */
-// Mock include file to share data between tests and mock
-#include "test/mock/mock_osi_ringbuffer.h"
-
-#include <cstdint>
-
-#include "test/common/mock_functions.h"
-
-// Mocked internal structures, if any
-
-namespace test {
-namespace mock {
-namespace osi_ringbuffer {
-
-// Function state capture and return values, if needed
-struct ringbuffer_available ringbuffer_available;
-struct ringbuffer_delete ringbuffer_delete;
-struct ringbuffer_free ringbuffer_free;
-struct ringbuffer_init ringbuffer_init;
-struct ringbuffer_insert ringbuffer_insert;
-struct ringbuffer_peek ringbuffer_peek;
-struct ringbuffer_pop ringbuffer_pop;
-struct ringbuffer_size ringbuffer_size;
-
-} // namespace osi_ringbuffer
-} // namespace mock
-} // namespace test
-
-// Mocked functions, if any
-size_t ringbuffer_available(const ringbuffer_t* rb) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_available(rb);
-}
-size_t ringbuffer_delete(ringbuffer_t* rb, size_t length) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_delete(rb, length);
-}
-void ringbuffer_free(ringbuffer_t* rb) {
- inc_func_call_count(__func__);
- test::mock::osi_ringbuffer::ringbuffer_free(rb);
-}
-ringbuffer_t* ringbuffer_init(const size_t size) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_init(size);
-}
-size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_insert(rb, p, length);
-}
-size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_peek(rb, offset, p, length);
-}
-size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_pop(rb, p, length);
-}
-size_t ringbuffer_size(const ringbuffer_t* rb) {
- inc_func_call_count(__func__);
- return test::mock::osi_ringbuffer::ringbuffer_size(rb);
-}
-// Mocked functions complete
-// END mockcify generation
diff --git a/system/test/mock/mock_osi_ringbuffer.h b/system/test/mock/mock_osi_ringbuffer.h
deleted file mode 100644
index 40f649d099..0000000000
--- a/system/test/mock/mock_osi_ringbuffer.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright 2021 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.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:8
- *
- * mockcify.pl ver 0.3.0
- */
-
-#include <cstdint>
-#include <functional>
-
-// Original included files, if any
-
-#include <stdlib.h>
-
-#include "osi/include/ringbuffer.h"
-
-// Mocked compile conditionals, if any
-
-namespace test {
-namespace mock {
-namespace osi_ringbuffer {
-
-// Shared state between mocked functions and tests
-// Name: ringbuffer_available
-// Params: const ringbuffer_t* rb
-// Return: size_t
-struct ringbuffer_available {
- size_t return_value{0};
- std::function<size_t(const ringbuffer_t* rb)> body{
- [this](const ringbuffer_t* /* rb */) { return return_value; }};
- size_t operator()(const ringbuffer_t* rb) { return body(rb); }
-};
-extern struct ringbuffer_available ringbuffer_available;
-
-// Name: ringbuffer_delete
-// Params: ringbuffer_t* rb, size_t length
-// Return: size_t
-struct ringbuffer_delete {
- size_t return_value{0};
- std::function<size_t(ringbuffer_t* rb, size_t length)> body{
- [this](ringbuffer_t* /* rb */, size_t /* length */) { return return_value; }};
- size_t operator()(ringbuffer_t* rb, size_t length) { return body(rb, length); }
-};
-extern struct ringbuffer_delete ringbuffer_delete;
-
-// Name: ringbuffer_free
-// Params: ringbuffer_t* rb
-// Return: void
-struct ringbuffer_free {
- std::function<void(ringbuffer_t* rb)> body{[](ringbuffer_t* /* rb */) {}};
- void operator()(ringbuffer_t* rb) { body(rb); }
-};
-extern struct ringbuffer_free ringbuffer_free;
-
-// Name: ringbuffer_init
-// Params: const size_t size
-// Return: ringbuffer_t*
-struct ringbuffer_init {
- ringbuffer_t* return_value{0};
- std::function<ringbuffer_t*(const size_t size)> body{
- [this](const size_t /* size */) { return return_value; }};
- ringbuffer_t* operator()(const size_t size) { return body(size); }
-};
-extern struct ringbuffer_init ringbuffer_init;
-
-// Name: ringbuffer_insert
-// Params: ringbuffer_t* rb, const uint8_t* p, size_t length
-// Return: size_t
-struct ringbuffer_insert {
- size_t return_value{0};
- std::function<size_t(ringbuffer_t* rb, const uint8_t* p, size_t length)> body{
- [this](ringbuffer_t* /* rb */, const uint8_t* /* p */, size_t /* length */) {
- return return_value;
- }};
- size_t operator()(ringbuffer_t* rb, const uint8_t* p, size_t length) {
- return body(rb, p, length);
- }
-};
-extern struct ringbuffer_insert ringbuffer_insert;
-
-// Name: ringbuffer_peek
-// Params: const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length
-// Return: size_t
-struct ringbuffer_peek {
- size_t return_value{0};
- std::function<size_t(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length)> body{
- [this](const ringbuffer_t* /* rb */, off_t /* offset */, uint8_t* /* p */,
- size_t /* length */) { return return_value; }};
- size_t operator()(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) {
- return body(rb, offset, p, length);
- }
-};
-extern struct ringbuffer_peek ringbuffer_peek;
-
-// Name: ringbuffer_pop
-// Params: ringbuffer_t* rb, uint8_t* p, size_t length
-// Return: size_t
-struct ringbuffer_pop {
- size_t return_value{0};
- std::function<size_t(ringbuffer_t* rb, uint8_t* p, size_t length)> body{
- [this](ringbuffer_t* /* rb */, uint8_t* /* p */, size_t /* length */) {
- return return_value;
- }};
- size_t operator()(ringbuffer_t* rb, uint8_t* p, size_t length) { return body(rb, p, length); }
-};
-extern struct ringbuffer_pop ringbuffer_pop;
-
-// Name: ringbuffer_size
-// Params: const ringbuffer_t* rb
-// Return: size_t
-struct ringbuffer_size {
- size_t return_value{0};
- std::function<size_t(const ringbuffer_t* rb)> body{
- [this](const ringbuffer_t* /* rb */) { return return_value; }};
- size_t operator()(const ringbuffer_t* rb) { return body(rb); }
-};
-extern struct ringbuffer_size ringbuffer_size;
-
-} // namespace osi_ringbuffer
-} // namespace mock
-} // namespace test
-
-// END mockcify generation
diff --git a/system/test/mock/mock_osi_socket.cc b/system/test/mock/mock_osi_socket.cc
index 7daa32c5e2..e605356954 100644
--- a/system/test/mock/mock_osi_socket.cc
+++ b/system/test/mock/mock_osi_socket.cc
@@ -23,13 +23,11 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_osi_socket.h"
+#include "osi/include/socket_utils/sockets.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_socket {
diff --git a/system/test/mock/mock_osi_thread_scheduler.cc b/system/test/mock/mock_osi_thread_scheduler.cc
deleted file mode 100644
index a248efc327..0000000000
--- a/system/test/mock/mock_osi_thread_scheduler.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright 2021 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.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:2
- *
- * mockcify.pl ver 0.3.0
- */
-// Mock include file to share data between tests and mock
-#include "test/mock/mock_osi_thread_scheduler.h"
-
-#include "test/common/mock_functions.h"
-
-// Mocked internal structures, if any
-
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
-namespace test {
-namespace mock {
-namespace osi_thread_scheduler {
-
-// Function state capture and return values, if needed
-struct thread_scheduler_enable_real_time thread_scheduler_enable_real_time;
-struct thread_scheduler_get_priority_range thread_scheduler_get_priority_range;
-
-} // namespace osi_thread_scheduler
-} // namespace mock
-} // namespace test
-
-// Mocked functions, if any
-bool thread_scheduler_enable_real_time(pid_t linux_tid) {
- inc_func_call_count(__func__);
- return test::mock::osi_thread_scheduler::thread_scheduler_enable_real_time(linux_tid);
-}
-bool thread_scheduler_get_priority_range(int& min, int& max) {
- inc_func_call_count(__func__);
- return test::mock::osi_thread_scheduler::thread_scheduler_get_priority_range(min, max);
-}
-// Mocked functions complete
-// END mockcify generation
diff --git a/system/test/mock/mock_osi_thread_scheduler.h b/system/test/mock/mock_osi_thread_scheduler.h
deleted file mode 100644
index f80f84b069..0000000000
--- a/system/test/mock/mock_osi_thread_scheduler.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright 2021 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.
- */
-
-/*
- * Generated mock file from original source file
- * Functions generated:2
- *
- * mockcify.pl ver 0.3.0
- */
-
-#include <sys/types.h>
-
-#include <functional>
-
-// Original included files, if any
-
-// Mocked compile conditionals, if any
-
-namespace test {
-namespace mock {
-namespace osi_thread_scheduler {
-
-// Shared state between mocked functions and tests
-// Name: osi_enable_real_time_scheduling
-// Params: pid_t linux_tid
-// Return: bool
-struct thread_scheduler_enable_real_time {
- bool return_value{false};
- std::function<bool(pid_t linux_tid)> body{[this](pid_t /* linux_tid */) { return return_value; }};
- bool operator()(pid_t linux_tid) { return body(linux_tid); }
-};
-extern struct thread_scheduler_enable_real_time thread_scheduler_enable_real_time;
-
-// Name: osi_fifo_scheduing_priority_range
-// Params: int& min, int& max
-// Return: bool
-struct thread_scheduler_get_priority_range {
- bool return_value{false};
- std::function<bool(int& min, int& max)> body{
- [this](int& /* min */, int& /* max */) { return return_value; }};
- bool operator()(int& min, int& max) { return body(min, max); }
-};
-extern struct thread_scheduler_get_priority_range thread_scheduler_get_priority_range;
-
-} // namespace osi_thread_scheduler
-} // namespace mock
-} // namespace test
-
-// END mockcify generation
diff --git a/system/test/mock/mock_osi_wakelock.cc b/system/test/mock/mock_osi_wakelock.cc
index b2805a7cba..5a5759a16e 100644
--- a/system/test/mock/mock_osi_wakelock.cc
+++ b/system/test/mock/mock_osi_wakelock.cc
@@ -23,13 +23,11 @@
// Mock include file to share data between tests and mock
#include "test/mock/mock_osi_wakelock.h"
+#include "osi/include/wakelock.h"
#include "test/common/mock_functions.h"
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace osi_wakelock {
diff --git a/system/test/mock/mock_stack_a2dp_sbc.cc b/system/test/mock/mock_stack_a2dp_sbc.cc
index 7423ae79cb..71c0dd24ff 100644
--- a/system/test/mock/mock_stack_a2dp_sbc.cc
+++ b/system/test/mock/mock_stack_a2dp_sbc.cc
@@ -25,15 +25,13 @@
#include <cstdint>
#include <string>
+#include "stack/include/a2dp_sbc.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_a2dp_sbc {
diff --git a/system/test/mock/mock_stack_avrc_apt.cc b/system/test/mock/mock_stack_avrc_apt.cc
index 2380d1756e..6922da47cf 100644
--- a/system/test/mock/mock_stack_avrc_apt.cc
+++ b/system/test/mock/mock_stack_avrc_apt.cc
@@ -24,15 +24,13 @@
#include <cstdint>
+#include "stack/include/avrc_api.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_avrc_apt {
diff --git a/system/test/mock/mock_stack_avrc_utils.cc b/system/test/mock/mock_stack_avrc_utils.cc
index b4eca59731..6953823feb 100644
--- a/system/test/mock/mock_stack_avrc_utils.cc
+++ b/system/test/mock/mock_stack_avrc_utils.cc
@@ -24,15 +24,14 @@
#include <cstdint>
+#include "stack/avrc/avrc_int.h"
+#include "stack/include/avrc_api.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_avrc_utils {
diff --git a/system/test/mock/mock_stack_btm_ble.cc b/system/test/mock/mock_stack_btm_ble.cc
index 620b9e252c..f9dcac4673 100644
--- a/system/test/mock/mock_stack_btm_ble.cc
+++ b/system/test/mock/mock_stack_btm_ble.cc
@@ -25,7 +25,10 @@
#include <cstdint>
#include <optional>
+#include "stack/btm/btm_ble_int.h"
#include "stack/include/btm_api_types.h"
+#include "stack/include/btm_ble_api.h"
+#include "stack/include/btm_ble_sec_api.h"
#include "stack/include/btm_status.h"
#include "test/common/mock_functions.h"
@@ -33,9 +36,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_ble {
@@ -70,10 +70,6 @@ struct btm_ble_ltk_request_reply btm_ble_ltk_request_reply;
struct btm_ble_read_sec_key_size btm_ble_read_sec_key_size;
struct btm_ble_reset_id btm_ble_reset_id;
struct btm_ble_set_encryption btm_ble_set_encryption;
-struct btm_ble_set_keep_rfu_in_auth_req btm_ble_set_keep_rfu_in_auth_req;
-struct btm_ble_set_no_disc_if_pair_fail btm_ble_set_no_disc_if_pair_fail;
-struct btm_ble_set_test_local_sign_cntr_value btm_ble_set_test_local_sign_cntr_value;
-struct btm_ble_set_test_mac_value btm_ble_set_test_mac_value;
struct btm_ble_start_encrypt btm_ble_start_encrypt;
struct btm_ble_start_sec_check btm_ble_start_sec_check;
struct btm_ble_test_command_complete btm_ble_test_command_complete;
@@ -243,22 +239,6 @@ tBTM_STATUS btm_ble_set_encryption(const RawAddress& bd_addr, tBTM_BLE_SEC_ACT s
inc_func_call_count(__func__);
return test::mock::stack_btm_ble::btm_ble_set_encryption(bd_addr, sec_act, link_role);
}
-void btm_ble_set_keep_rfu_in_auth_req(bool keep_rfu) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_ble::btm_ble_set_keep_rfu_in_auth_req(keep_rfu);
-}
-void btm_ble_set_no_disc_if_pair_fail(bool disable_disc) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_ble::btm_ble_set_no_disc_if_pair_fail(disable_disc);
-}
-void btm_ble_set_test_local_sign_cntr_value(bool enable, uint32_t test_local_sign_cntr) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_ble::btm_ble_set_test_local_sign_cntr_value(enable, test_local_sign_cntr);
-}
-void btm_ble_set_test_mac_value(bool enable, uint8_t* p_test_mac_val) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_ble::btm_ble_set_test_mac_value(enable, p_test_mac_val);
-}
tBTM_STATUS btm_ble_start_encrypt(const RawAddress& bda, bool use_stk, Octet16* p_stk) {
inc_func_call_count(__func__);
return test::mock::stack_btm_ble::btm_ble_start_encrypt(bda, use_stk, p_stk);
diff --git a/system/test/mock/mock_stack_btm_ble.h b/system/test/mock/mock_stack_btm_ble.h
index 9c1b14d014..aed50358e2 100644
--- a/system/test/mock/mock_stack_btm_ble.h
+++ b/system/test/mock/mock_stack_btm_ble.h
@@ -414,46 +414,6 @@ struct btm_ble_set_encryption {
};
extern struct btm_ble_set_encryption btm_ble_set_encryption;
-// Name: btm_ble_set_keep_rfu_in_auth_req
-// Params: bool keep_rfu
-// Return: void
-struct btm_ble_set_keep_rfu_in_auth_req {
- std::function<void(bool)> body{[](bool /* keep_rfu */) {}};
- void operator()(bool keep_rfu) { body(keep_rfu); }
-};
-extern struct btm_ble_set_keep_rfu_in_auth_req btm_ble_set_keep_rfu_in_auth_req;
-
-// Name: btm_ble_set_no_disc_if_pair_fail
-// Params: bool disable_disc
-// Return: void
-struct btm_ble_set_no_disc_if_pair_fail {
- std::function<void(bool)> body{[](bool /* disable_disc */) {}};
- void operator()(bool disable_disc) { body(disable_disc); }
-};
-extern struct btm_ble_set_no_disc_if_pair_fail btm_ble_set_no_disc_if_pair_fail;
-
-// Name: btm_ble_set_test_local_sign_cntr_value
-// Params: bool enable, uint32_t test_local_sign_cntr
-// Return: void
-struct btm_ble_set_test_local_sign_cntr_value {
- std::function<void(bool enable, uint32_t test_local_sign_cntr)> body{
- [](bool /* enable */, uint32_t /* test_local_sign_cntr */) {}};
- void operator()(bool enable, uint32_t test_local_sign_cntr) {
- body(enable, test_local_sign_cntr);
- }
-};
-extern struct btm_ble_set_test_local_sign_cntr_value btm_ble_set_test_local_sign_cntr_value;
-
-// Name: btm_ble_set_test_mac_value
-// Params: bool enable, uint8_t* p_test_mac_val
-// Return: void
-struct btm_ble_set_test_mac_value {
- std::function<void(bool enable, uint8_t* p_test_mac_val)> body{
- [](bool /* enable */, uint8_t* /* p_test_mac_val */) {}};
- void operator()(bool enable, uint8_t* p_test_mac_val) { body(enable, p_test_mac_val); }
-};
-extern struct btm_ble_set_test_mac_value btm_ble_set_test_mac_value;
-
// Name: btm_ble_start_encrypt
// Params: const RawAddress& bda, bool use_stk, Octet16* p_stk
// Return: tBTM_STATUS
diff --git a/system/test/mock/mock_stack_btm_ble_addr.cc b/system/test/mock/mock_stack_btm_ble_addr.cc
index 2a52fb57ea..5f7998d1fc 100644
--- a/system/test/mock/mock_stack_btm_ble_addr.cc
+++ b/system/test/mock/mock_stack_btm_ble_addr.cc
@@ -25,6 +25,9 @@
// Original included files, if any
+#include "stack/btm/btm_ble_int.h"
+#include "stack/include/btm_ble_addr.h"
+#include "stack/include/btm_ble_privacy.h"
#include "test/common/mock_functions.h"
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
@@ -32,9 +35,6 @@
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_ble_addr {
diff --git a/system/test/mock/mock_stack_btm_ble_gap.cc b/system/test/mock/mock_stack_btm_ble_gap.cc
index e14ad5116b..1eafc5f416 100644
--- a/system/test/mock/mock_stack_btm_ble_gap.cc
+++ b/system/test/mock/mock_stack_btm_ble_gap.cc
@@ -27,6 +27,7 @@
#include "stack/btm/btm_ble_int.h"
#include "stack/btm/btm_ble_int_types.h"
#include "stack/include/bt_dev_class.h"
+#include "stack/include/btm_ble_api.h"
#include "stack/include/btm_status.h"
#include "stack/include/hci_error_code.h"
#include "stack/include/rnr_interface.h"
@@ -34,9 +35,6 @@
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using StartSyncCb = base::Callback<void(
uint8_t /*status*/, uint16_t /*sync_handle*/, uint8_t /*advertising_sid*/,
uint8_t /*address_type*/, RawAddress /*address*/, uint8_t /*phy*/, uint16_t /*interval*/)>;
@@ -104,10 +102,6 @@ void BTM_BleGetDynamicAudioBuffer(
void BTM_BleGetVendorCapabilities(tBTM_BLE_VSC_CB* /* p_cmn_vsc_cb */) {
inc_func_call_count(__func__);
}
-void BTM_BleSetScanParams(uint32_t /* scan_interval */, uint32_t /* scan_window */,
- tBLE_SCAN_MODE /* scan_mode */, base::Callback<void(uint8_t)> /* cb */) {
- inc_func_call_count(__func__);
-}
void btm_ble_decrement_link_topology_mask(uint8_t /* link_role */) {
inc_func_call_count(__func__);
}
@@ -150,7 +144,8 @@ void btm_ble_write_adv_enable_complete(uint8_t* /* p */, uint16_t /* evt_len */)
}
void btm_send_hci_set_scan_params(uint8_t /* scan_type */, uint16_t /* scan_int_1m */,
uint16_t /* scan_win_1m */, uint16_t /* scan_int_coded */,
- uint16_t /* scan_win_coded */, tBLE_ADDR_TYPE /* addr_type_own */,
+ uint16_t /* scan_win_coded */, uint8_t /* scan_phy */,
+ tBLE_ADDR_TYPE /* addr_type_own */,
uint8_t /* scan_filter_policy */) {
inc_func_call_count(__func__);
}
diff --git a/system/test/mock/mock_stack_btm_ble_privacy.cc b/system/test/mock/mock_stack_btm_ble_privacy.cc
index 7781d9cc75..4c523b12e8 100644
--- a/system/test/mock/mock_stack_btm_ble_privacy.cc
+++ b/system/test/mock/mock_stack_btm_ble_privacy.cc
@@ -25,14 +25,13 @@
// Original included files, if any
+#include "stack/include/ble_hci_link_interface.h"
+#include "stack/include/btm_ble_privacy.h"
#include "test/common/mock_functions.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_ble_privacy {
@@ -42,8 +41,6 @@ struct btm_ble_clear_resolving_list_complete btm_ble_clear_resolving_list_comple
struct btm_ble_add_resolving_list_entry_complete btm_ble_add_resolving_list_entry_complete;
struct btm_ble_remove_resolving_list_entry_complete btm_ble_remove_resolving_list_entry_complete;
struct btm_ble_read_resolving_list_entry_complete btm_ble_read_resolving_list_entry_complete;
-struct btm_ble_remove_resolving_list_entry btm_ble_remove_resolving_list_entry;
-struct btm_ble_clear_resolving_list btm_ble_clear_resolving_list;
struct btm_ble_read_resolving_list_entry btm_ble_read_resolving_list_entry;
struct btm_ble_resolving_list_load_dev btm_ble_resolving_list_load_dev;
struct btm_ble_resolving_list_remove_dev btm_ble_resolving_list_remove_dev;
@@ -70,14 +67,6 @@ void btm_ble_read_resolving_list_entry_complete(const uint8_t* p, uint16_t evt_l
inc_func_call_count(__func__);
test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry_complete(p, evt_len);
}
-tBTM_STATUS btm_ble_remove_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) {
- inc_func_call_count(__func__);
- return test::mock::stack_btm_ble_privacy::btm_ble_remove_resolving_list_entry(p_dev_rec);
-}
-void btm_ble_clear_resolving_list(void) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_ble_privacy::btm_ble_clear_resolving_list();
-}
bool btm_ble_read_resolving_list_entry(tBTM_SEC_DEV_REC* p_dev_rec) {
inc_func_call_count(__func__);
return test::mock::stack_btm_ble_privacy::btm_ble_read_resolving_list_entry(p_dev_rec);
diff --git a/system/test/mock/mock_stack_btm_ble_privacy.h b/system/test/mock/mock_stack_btm_ble_privacy.h
index 357e7adf3d..2cc88fac60 100644
--- a/system/test/mock/mock_stack_btm_ble_privacy.h
+++ b/system/test/mock/mock_stack_btm_ble_privacy.h
@@ -71,23 +71,6 @@ struct btm_ble_read_resolving_list_entry_complete {
void operator()(const uint8_t* p, uint16_t evt_len) { body(p, evt_len); }
};
extern struct btm_ble_read_resolving_list_entry_complete btm_ble_read_resolving_list_entry_complete;
-// Name: btm_ble_remove_resolving_list_entry
-// Params: tBTM_SEC_DEV_REC* p_dev_rec
-// Returns: tBTM_STATUS
-struct btm_ble_remove_resolving_list_entry {
- std::function<tBTM_STATUS(tBTM_SEC_DEV_REC* p_dev_rec)> body{
- [](tBTM_SEC_DEV_REC* /* p_dev_rec */) { return tBTM_STATUS::BTM_SUCCESS; }};
- tBTM_STATUS operator()(tBTM_SEC_DEV_REC* p_dev_rec) { return body(p_dev_rec); }
-};
-extern struct btm_ble_remove_resolving_list_entry btm_ble_remove_resolving_list_entry;
-// Name: btm_ble_clear_resolving_list
-// Params: void
-// Returns: void
-struct btm_ble_clear_resolving_list {
- std::function<void(void)> body{[](void) {}};
- void operator()(void) { body(); }
-};
-extern struct btm_ble_clear_resolving_list btm_ble_clear_resolving_list;
// Name: btm_ble_read_resolving_list_entry
// Params: tBTM_SEC_DEV_REC* p_dev_rec
// Returns: bool
diff --git a/system/test/mock/mock_stack_btm_dev.cc b/system/test/mock/mock_stack_btm_dev.cc
index 60f88b0d6e..779d482219 100644
--- a/system/test/mock/mock_stack_btm_dev.cc
+++ b/system/test/mock/mock_stack_btm_dev.cc
@@ -28,13 +28,12 @@
#include "stack/btm/btm_dev.h"
#include "stack/include/bt_octets.h"
+#include "stack/include/btm_ble_addr.h"
#include "stack/include/btm_client_interface.h"
+#include "stack/include/btm_sec_api.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_dev {
@@ -96,8 +95,6 @@ void btm_consolidate_dev(tBTM_SEC_DEV_REC* /* p_target_rec */) { inc_func_call_c
void btm_dev_consolidate_existing_connections(const RawAddress& /* bd_addr */) {
inc_func_call_count(__func__);
}
-void BTM_SecDump(const std::string& /* label */) { inc_func_call_count(__func__); }
-void BTM_SecDumpDev(const RawAddress& /* bd_addr */) { inc_func_call_count(__func__); }
std::vector<tBTM_SEC_DEV_REC*> btm_get_sec_dev_rec() {
inc_func_call_count(__func__);
return {};
diff --git a/system/test/mock/mock_stack_btm_devctl.cc b/system/test/mock/mock_stack_btm_devctl.cc
index da8d8b2053..82a7f3f275 100644
--- a/system/test/mock/mock_stack_btm_devctl.cc
+++ b/system/test/mock/mock_stack_btm_devctl.cc
@@ -23,15 +23,15 @@
#include <stddef.h>
#include <stdlib.h>
+#include "stack/btm/internal/btm_api.h"
#include "stack/include/bt_dev_class.h"
#include "stack/include/btm_api_types.h"
+#include "stack/include/btm_sec_api.h"
#include "stack/include/btm_status.h"
+#include "stack/include/dev_hci_link_interface.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
tBTM_STATUS BTM_DeleteStoredLinkKey(const RawAddress* /* bd_addr */, tBTM_CMPL_CB* /* p_cb */) {
inc_func_call_count(__func__);
return tBTM_STATUS::BTM_SUCCESS;
diff --git a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc
index d2ed992484..ef5d533dcc 100644
--- a/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc
+++ b/system/test/mock/mock_stack_btm_hfp_lc3_encoder.cc
@@ -26,15 +26,13 @@
#ifndef __clang_analyzer__
+#include "stack/include/hfp_lc3_encoder.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_hfp_lc3_encoder {
diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc
index dea537f621..92ef9ec1ef 100644
--- a/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc
+++ b/system/test/mock/mock_stack_btm_hfp_msbc_decoder.cc
@@ -24,15 +24,13 @@
#include <cstdint>
+#include "stack/include/hfp_msbc_decoder.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_hfp_msbc_decoder {
diff --git a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc
index 3c38e66754..f963bf9691 100644
--- a/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc
+++ b/system/test/mock/mock_stack_btm_hfp_msbc_encoder.cc
@@ -27,15 +27,13 @@
#ifndef __clang_analyzer__
+#include "stack/include/hfp_msbc_encoder.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_hfp_msbc_encoder {
diff --git a/system/test/mock/mock_stack_btm_inq.cc b/system/test/mock/mock_stack_btm_inq.cc
index ed99d05e6f..4c1f49a7e2 100644
--- a/system/test/mock/mock_stack_btm_inq.cc
+++ b/system/test/mock/mock_stack_btm_inq.cc
@@ -24,16 +24,16 @@
#include <cstdint>
+#include "stack/btm/internal/btm_api.h"
+#include "stack/include/btm_inq.h"
#include "stack/include/btm_status.h"
+#include "stack/include/inq_hci_link_interface.h"
#include "test/common/mock_functions.h"
// Original usings
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_inq {
@@ -48,7 +48,6 @@ struct BTM_SetConnectability BTM_SetConnectability;
struct BTM_SetDiscoverability BTM_SetDiscoverability;
struct BTM_SetInquiryMode BTM_SetInquiryMode;
struct BTM_StartInquiry BTM_StartInquiry;
-struct btm_clr_inq_db btm_clr_inq_db;
struct btm_clr_inq_result_flt btm_clr_inq_result_flt;
struct btm_inq_db_find btm_inq_db_find;
struct btm_inq_db_new btm_inq_db_new;
@@ -116,10 +115,6 @@ tBTM_STATUS BTM_StartInquiry(tBTM_INQ_RESULTS_CB* p_results_cb, tBTM_CMPL_CB* p_
inc_func_call_count(__func__);
return test::mock::stack_btm_inq::BTM_StartInquiry(p_results_cb, p_cmpl_cb);
}
-void btm_clr_inq_db(const RawAddress* p_bda) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_inq::btm_clr_inq_db(p_bda);
-}
void btm_clr_inq_result_flt(void) {
inc_func_call_count(__func__);
test::mock::stack_btm_inq::btm_clr_inq_result_flt();
diff --git a/system/test/mock/mock_stack_btm_inq.h b/system/test/mock/mock_stack_btm_inq.h
index 4c0acd08a4..68b9665dff 100644
--- a/system/test/mock/mock_stack_btm_inq.h
+++ b/system/test/mock/mock_stack_btm_inq.h
@@ -143,15 +143,6 @@ struct BTM_StartInquiry {
};
extern struct BTM_StartInquiry BTM_StartInquiry;
-// Name: btm_clr_inq_db
-// Params: const RawAddress* p_bda
-// Return: void
-struct btm_clr_inq_db {
- std::function<void(const RawAddress* p_bda)> body{[](const RawAddress* /* p_bda */) {}};
- void operator()(const RawAddress* p_bda) { body(p_bda); }
-};
-extern struct btm_clr_inq_db btm_clr_inq_db;
-
// Name: btm_clr_inq_result_flt
// Params: void
// Return: void
diff --git a/system/test/mock/mock_stack_btm_interface.cc b/system/test/mock/mock_stack_btm_interface.cc
index 2361ce1307..20a8f7a586 100644
--- a/system/test/mock/mock_stack_btm_interface.cc
+++ b/system/test/mock/mock_stack_btm_interface.cc
@@ -18,6 +18,9 @@
* Generated mock file from original source file
*/
+#include "mock_stack_btm_interface.h"
+
+#include "stack/include/btm_ble_api.h"
#include "stack/include/btm_ble_api_types.h"
#include "stack/include/btm_ble_sec_api_types.h"
#include "stack/include/btm_client_interface.h"
@@ -26,9 +29,6 @@
#include "types/bt_transport.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
// Test accessible feature page
uint8_t hci_feature_bytes_per_page[HCI_FEATURE_BYTES_PER_PAGE] = {};
@@ -140,7 +140,7 @@ struct btm_client_interface_t default_btm_client_interface = {
.BTM_SecIsLeSecurityPending = [](const RawAddress& /* bd_addr */) -> bool {
return false;
},
- .BTM_IsLinkKeyKnown = [](const RawAddress& /* bd_addr */,
+ .BTM_IsBonded = [](const RawAddress& /* bd_addr */,
tBT_TRANSPORT /* transport */) -> bool { return false; },
.BTM_SetSecurityLevel = [](bool /* is_originator */, const char* /*p_name */,
uint8_t /* service_id */, uint16_t /* sec_level */,
diff --git a/system/test/mock/mock_stack_btm_main.cc b/system/test/mock/mock_stack_btm_main.cc
index e188d0d89c..3dce60a6f4 100644
--- a/system/test/mock/mock_stack_btm_main.cc
+++ b/system/test/mock/mock_stack_btm_main.cc
@@ -21,13 +21,12 @@
#include <string>
+#include "stack/include/btm_client_interface.h"
+#include "stack/include/btm_log_history.h"
#include "test/common/mock_functions.h"
#include "types/ble_address_with_type.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
void BTM_LogHistory(const std::string& /* tag */, const RawAddress& /* bd_addr */,
const std::string& /* msg */) {
inc_func_call_count(__func__);
diff --git a/system/test/mock/mock_stack_btm_sco.cc b/system/test/mock/mock_stack_btm_sco.cc
index 0128227349..7012a3cfa3 100644
--- a/system/test/mock/mock_stack_btm_sco.cc
+++ b/system/test/mock/mock_stack_btm_sco.cc
@@ -24,15 +24,14 @@
#include "device/include/esco_parameters.h"
#include "hci/class_of_device.h"
#include "stack/btm/btm_sco.h"
+#include "stack/btm/internal/btm_api.h"
#include "stack/include/btm_api_types.h"
#include "stack/include/btm_status.h"
#include "stack/include/hci_error_code.h"
+#include "stack/include/sco_hci_link_interface.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
const RawAddress* BTM_ReadScoBdAddr(uint16_t /* sco_inx */) {
inc_func_call_count(__func__);
return nullptr;
diff --git a/system/test/mock/mock_stack_btm_sec.cc b/system/test/mock/mock_stack_btm_sec.cc
index 4ca3189b30..ca53fb0040 100644
--- a/system/test/mock/mock_stack_btm_sec.cc
+++ b/system/test/mock/mock_stack_btm_sec.cc
@@ -25,6 +25,8 @@
#include <cstdint>
#include <string>
+#include "stack/btm/btm_sec.h"
+#include "stack/include/btm_ble_sec_api.h"
#include "stack/include/btm_sec_api_types.h"
#include "stack/include/btm_status.h"
#include "test/common/mock_functions.h"
@@ -34,9 +36,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_btm_sec {
@@ -47,7 +46,7 @@ struct BTM_ConfirmReqReply BTM_ConfirmReqReply;
struct BTM_IsAuthenticated BTM_IsAuthenticated;
struct BTM_IsEncrypted BTM_IsEncrypted;
struct BTM_IsLinkKeyAuthed BTM_IsLinkKeyAuthed;
-struct BTM_IsLinkKeyKnown BTM_IsLinkKeyKnown;
+struct BTM_IsBonded BTM_IsBonded;
struct BTM_PINCodeReply BTM_PINCodeReply;
struct BTM_PasskeyReqReply BTM_PasskeyReqReply;
struct BTM_PeerSupportsSecureConnections BTM_PeerSupportsSecureConnections;
@@ -74,7 +73,6 @@ struct btm_rem_oob_req btm_rem_oob_req;
struct btm_sec_abort_access_req btm_sec_abort_access_req;
struct btm_sec_auth_complete btm_sec_auth_complete;
struct btm_sec_bond_by_transport btm_sec_bond_by_transport;
-struct btm_sec_check_pending_reqs btm_sec_check_pending_reqs;
struct btm_sec_clear_ble_keys btm_sec_clear_ble_keys;
struct btm_sec_conn_req btm_sec_conn_req;
struct btm_sec_connected btm_sec_connected;
@@ -113,7 +111,7 @@ bool BTM_CanReadDiscoverableCharacteristics::return_value = false;
bool BTM_IsAuthenticated::return_value = false;
bool BTM_IsEncrypted::return_value = false;
bool BTM_IsLinkKeyAuthed::return_value = false;
-bool BTM_IsLinkKeyKnown::return_value = false;
+bool BTM_IsBonded::return_value = false;
bool BTM_PeerSupportsSecureConnections::return_value = false;
tBTM_STATUS BTM_SecBond::return_value = tBTM_STATUS::BTM_SUCCESS;
tBTM_STATUS BTM_SecBondCancel::return_value = tBTM_STATUS::BTM_SUCCESS;
@@ -124,7 +122,7 @@ bool BTM_SecIsLeSecurityPending::return_value = false;
bool BTM_SecRegister::return_value = false;
tBTM_STATUS BTM_SetEncryption::return_value = tBTM_STATUS::BTM_SUCCESS;
bool BTM_SetSecurityLevel::return_value = false;
-const DEV_CLASS btm_get_dev_class::return_value = kDevClassEmpty;
+DEV_CLASS btm_get_dev_class::return_value = kDevClassEmpty;
tBTM_STATUS btm_sec_bond_by_transport::return_value = tBTM_STATUS::BTM_SUCCESS;
tBTM_STATUS btm_sec_disconnect::return_value = tBTM_STATUS::BTM_SUCCESS;
bool btm_sec_is_a_bonded_dev::return_value = false;
@@ -157,9 +155,9 @@ bool BTM_IsLinkKeyAuthed(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
inc_func_call_count(__func__);
return test::mock::stack_btm_sec::BTM_IsLinkKeyAuthed(bd_addr, transport);
}
-bool BTM_IsLinkKeyKnown(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
+bool BTM_IsBonded(const RawAddress& bd_addr, tBT_TRANSPORT transport) {
inc_func_call_count(__func__);
- return test::mock::stack_btm_sec::BTM_IsLinkKeyKnown(bd_addr, transport);
+ return test::mock::stack_btm_sec::BTM_IsBonded(bd_addr, transport);
}
void BTM_PINCodeReply(const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t* p_pin) {
inc_func_call_count(__func__);
@@ -238,7 +236,7 @@ void btm_create_conn_cancel_complete(uint8_t status, const RawAddress bd_addr) {
inc_func_call_count(__func__);
test::mock::stack_btm_sec::btm_create_conn_cancel_complete(status, bd_addr);
}
-const DEV_CLASS btm_get_dev_class(const RawAddress& bda) {
+DEV_CLASS btm_get_dev_class(const RawAddress& bda) {
inc_func_call_count(__func__);
return test::mock::stack_btm_sec::btm_get_dev_class(bda);
}
@@ -275,10 +273,6 @@ tBTM_STATUS btm_sec_bond_by_transport(const RawAddress& bd_addr, tBLE_ADDR_TYPE
inc_func_call_count(__func__);
return test::mock::stack_btm_sec::btm_sec_bond_by_transport(bd_addr, addr_type, transport);
}
-void btm_sec_check_pending_reqs(void) {
- inc_func_call_count(__func__);
- test::mock::stack_btm_sec::btm_sec_check_pending_reqs();
-}
void btm_sec_clear_ble_keys(tBTM_SEC_DEV_REC* p_dev_rec) {
inc_func_call_count(__func__);
test::mock::stack_btm_sec::btm_sec_clear_ble_keys(p_dev_rec);
@@ -396,9 +390,5 @@ void btm_simple_pair_complete(const RawAddress bd_addr, uint8_t status) {
inc_func_call_count(__func__);
test::mock::stack_btm_sec::btm_simple_pair_complete(bd_addr, status);
}
-bool BTM_BleIsLinkKeyKnown(const RawAddress /* address */) {
- inc_func_call_count(__func__);
- return false;
-}
// Mocked functions complete
// END mockcify generation
diff --git a/system/test/mock/mock_stack_btm_sec.h b/system/test/mock/mock_stack_btm_sec.h
index 688ab5dca1..3ae397be41 100644
--- a/system/test/mock/mock_stack_btm_sec.h
+++ b/system/test/mock/mock_stack_btm_sec.h
@@ -111,10 +111,10 @@ struct BTM_IsLinkKeyAuthed {
};
extern struct BTM_IsLinkKeyAuthed BTM_IsLinkKeyAuthed;
-// Name: BTM_IsLinkKeyKnown
+// Name: BTM_IsBonded
// Params: const RawAddress& bd_addr, tBT_TRANSPORT transport
// Return: bool
-struct BTM_IsLinkKeyKnown {
+struct BTM_IsBonded {
static bool return_value;
std::function<bool(const RawAddress& bd_addr, tBT_TRANSPORT transport)> body{
[](const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */) {
@@ -124,7 +124,7 @@ struct BTM_IsLinkKeyKnown {
return body(bd_addr, transport);
}
};
-extern struct BTM_IsLinkKeyKnown BTM_IsLinkKeyKnown;
+extern struct BTM_IsBonded BTM_IsBonded;
// Name: BTM_PINCodeReply
// Params: const RawAddress& bd_addr, tBTM_STATUS res, uint8_t pin_len, uint8_t*
@@ -345,10 +345,10 @@ extern struct btm_create_conn_cancel_complete btm_create_conn_cancel_complete;
// Params: const RawAddress& bda
// Return: DEV_CLASS
struct btm_get_dev_class {
- static const DEV_CLASS return_value;
- std::function<const DEV_CLASS(const RawAddress& bda)> body{
+ static DEV_CLASS return_value;
+ std::function<DEV_CLASS(const RawAddress& bda)> body{
[](const RawAddress& /* bda */) { return return_value; }};
- const DEV_CLASS operator()(const RawAddress& bda) { return body(bda); }
+ DEV_CLASS operator()(const RawAddress& bda) { return body(bda); }
};
extern struct btm_get_dev_class btm_get_dev_class;
@@ -439,15 +439,6 @@ struct btm_sec_bond_by_transport {
};
extern struct btm_sec_bond_by_transport btm_sec_bond_by_transport;
-// Name: btm_sec_check_pending_reqs
-// Params: void
-// Return: void
-struct btm_sec_check_pending_reqs {
- std::function<void(void)> body{[](void) {}};
- void operator()(void) { body(); }
-};
-extern struct btm_sec_check_pending_reqs btm_sec_check_pending_reqs;
-
// Name: btm_sec_clear_ble_keys
// Params: tBTM_SEC_DEV_REC* p_dev_rec
// Return: void
diff --git a/system/test/mock/mock_stack_btu_hcif.cc b/system/test/mock/mock_stack_btu_hcif.cc
index 0a4da4bc03..1d27c8a0b7 100644
--- a/system/test/mock/mock_stack_btu_hcif.cc
+++ b/system/test/mock/mock_stack_btu_hcif.cc
@@ -34,9 +34,8 @@ using hci_cmd_cb = base::OnceCallback<void(uint8_t* /* return_parameters */,
void btu_hcif_send_cmd(uint8_t /* controller_id */, const BT_HDR* /* p_buf */) {
inc_func_call_count(__func__);
}
-void btu_hcif_send_cmd_with_cb(const base::Location& /* posted_from */, uint16_t /* opcode */,
- uint8_t* /* params */, uint8_t /* params_len */,
- hci_cmd_cb /* cb */) {
+void btu_hcif_send_cmd_with_cb(uint16_t /* opcode */, uint8_t* /* params */,
+ uint8_t /* params_len */, hci_cmd_cb /* cb */) {
inc_func_call_count(__func__);
}
void btu_hci_msg_process(BT_HDR* /* p_msg */) { inc_func_call_count(__func__); }
diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.cc b/system/test/mock/mock_stack_hcic_hciblecmds.cc
index b44bbff0a4..0a130b2024 100644
--- a/system/test/mock/mock_stack_hcic_hciblecmds.cc
+++ b/system/test/mock/mock_stack_hcic_hciblecmds.cc
@@ -28,9 +28,6 @@
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_hcic_hciblecmds {
@@ -69,7 +66,6 @@ struct btsnd_hcic_ble_set_periodic_advertising_receive_enable
btsnd_hcic_ble_set_periodic_advertising_receive_enable;
struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params
btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params;
-struct btsnd_hcic_ble_set_privacy_mode btsnd_hcic_ble_set_privacy_mode;
struct btsnd_hcic_ble_set_rand_priv_addr_timeout btsnd_hcic_ble_set_rand_priv_addr_timeout;
struct btsnd_hcic_ble_set_scan_enable btsnd_hcic_ble_set_scan_enable;
struct btsnd_hcic_ble_set_scan_params btsnd_hcic_ble_set_scan_params;
@@ -227,12 +223,6 @@ void btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params(
test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params(
conn_handle, mode, skip, sync_timeout, cte_type, std::move(cb));
}
-void btsnd_hcic_ble_set_privacy_mode(uint8_t addr_type_peer, const RawAddress& bda_peer,
- uint8_t privacy_type) {
- inc_func_call_count(__func__);
- test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_privacy_mode(addr_type_peer, bda_peer,
- privacy_type);
-}
void btsnd_hcic_ble_set_rand_priv_addr_timeout(uint16_t rpa_timeout) {
inc_func_call_count(__func__);
test::mock::stack_hcic_hciblecmds::btsnd_hcic_ble_set_rand_priv_addr_timeout(rpa_timeout);
diff --git a/system/test/mock/mock_stack_hcic_hciblecmds.h b/system/test/mock/mock_stack_hcic_hciblecmds.h
index c9855165f1..cbecbc4aee 100644
--- a/system/test/mock/mock_stack_hcic_hciblecmds.h
+++ b/system/test/mock/mock_stack_hcic_hciblecmds.h
@@ -371,19 +371,6 @@ struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params {
extern struct btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params
btsnd_hcic_ble_set_periodic_advertising_sync_transfer_params;
-// Name: btsnd_hcic_ble_set_privacy_mode
-// Params: uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t
-// privacy_type Return: void
-struct btsnd_hcic_ble_set_privacy_mode {
- std::function<void(uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t privacy_type)>
- body{[](uint8_t /* addr_type_peer */, const RawAddress& /* bda_peer */,
- uint8_t /* privacy_type */) {}};
- void operator()(uint8_t addr_type_peer, const RawAddress& bda_peer, uint8_t privacy_type) {
- body(addr_type_peer, bda_peer, privacy_type);
- }
-};
-extern struct btsnd_hcic_ble_set_privacy_mode btsnd_hcic_ble_set_privacy_mode;
-
// Name: btsnd_hcic_ble_set_rand_priv_addr_timeout
// Params: uint16_t rpa_timeout
// Return: void
diff --git a/system/test/mock/mock_stack_l2cap_api.cc b/system/test/mock/mock_stack_l2cap_api.cc
index de117f06a9..2d81fdeca3 100644
--- a/system/test/mock/mock_stack_l2cap_api.cc
+++ b/system/test/mock/mock_stack_l2cap_api.cc
@@ -24,14 +24,13 @@
// Original included files, if any
+#include "stack/include/l2cap_module.h"
+#include "stack/l2cap/internal/l2c_api.h"
#include "test/common/mock_functions.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_l2cap_api {
diff --git a/system/test/mock/mock_stack_l2cap_ble.cc b/system/test/mock/mock_stack_l2cap_ble.cc
index 6224446eb0..0ddc91c917 100644
--- a/system/test/mock/mock_stack_l2cap_ble.cc
+++ b/system/test/mock/mock_stack_l2cap_ble.cc
@@ -25,15 +25,14 @@
// Original included files, if any
+#include "stack/include/l2cap_controller_interface.h"
+#include "stack/include/l2cap_hci_link_interface.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_l2cap_ble {
diff --git a/system/test/mock/mock_stack_l2cap_main.cc b/system/test/mock/mock_stack_l2cap_main.cc
index 606551fb98..8f6dcae4b3 100644
--- a/system/test/mock/mock_stack_l2cap_main.cc
+++ b/system/test/mock/mock_stack_l2cap_main.cc
@@ -20,12 +20,11 @@
*/
#include "stack/include/bt_hdr.h"
+#include "stack/include/l2cap_acl_interface.h"
+#include "stack/include/l2cap_module.h"
#include "stack/l2cap/l2c_int.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
tL2CAP_DW_RESULT l2c_data_write(uint16_t /* cid */, BT_HDR* /* p_data */, uint16_t /* flags */) {
inc_func_call_count(__func__);
return tL2CAP_DW_RESULT::FAILED;
diff --git a/system/test/mock/mock_stack_l2cap_utils.cc b/system/test/mock/mock_stack_l2cap_utils.cc
index f485c111e4..cca521601e 100644
--- a/system/test/mock/mock_stack_l2cap_utils.cc
+++ b/system/test/mock/mock_stack_l2cap_utils.cc
@@ -22,13 +22,13 @@
#include <cstdint>
#include "stack/include/bt_hdr.h"
+#include "stack/include/l2cap_controller_interface.h"
+#include "stack/include/l2cap_hci_link_interface.h"
+#include "stack/include/l2cap_security_interface.h"
#include "stack/l2cap/l2c_int.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
bool l2c_is_cmd_rejected(uint8_t /* cmd_code */, uint8_t /* signal_id */, tL2C_LCB* /* p_lcb */) {
inc_func_call_count(__func__);
return false;
@@ -37,10 +37,6 @@ bool l2cu_create_conn_le(tL2C_LCB* /* p_lcb */) {
inc_func_call_count(__func__);
return false;
}
-bool l2cu_create_conn_le(tL2C_LCB* /* p_lcb */, uint8_t /* initiating_phys */) {
- inc_func_call_count(__func__);
- return false;
-}
bool l2cu_initialize_fixed_ccb(tL2C_LCB* /* p_lcb */, uint16_t /* fixed_cid */) {
inc_func_call_count(__func__);
return false;
@@ -201,7 +197,7 @@ void l2cu_send_peer_config_rsp(tL2C_CCB* /* p_ccb */, tL2CAP_CFG_INFO* /* p_cfg
inc_func_call_count(__func__);
}
void l2cu_send_peer_connect_req(tL2C_CCB* /* p_ccb */) { inc_func_call_count(__func__); }
-void l2cu_send_peer_connect_rsp(tL2C_CCB* /* p_ccb */, uint16_t /* result */,
+void l2cu_send_peer_connect_rsp(tL2C_CCB* /* p_ccb */, tL2CAP_CONN /* result */,
uint16_t /* status */) {
inc_func_call_count(__func__);
}
@@ -230,7 +226,7 @@ void l2cu_send_peer_info_rsp(tL2C_LCB* /* p_lcb */, uint8_t /* remote_id */,
void l2cu_set_acl_hci_header(BT_HDR* /* p_buf */, tL2C_CCB* /* p_ccb */) {
inc_func_call_count(__func__);
}
-void l2cu_set_lcb_handle(struct t_l2c_linkcb& /* p_lcb */, uint16_t /* handle */) {
+void l2cu_set_lcb_handle(tL2C_LCB& /* p_lcb */, uint16_t /* handle */) {
inc_func_call_count(__func__);
}
void l2cu_set_non_flushable_pbf(bool /* is_supported */) { 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 751fcc3794..ff2cee4472 100644
--- a/system/test/mock/mock_stack_metrics_logging.cc
+++ b/system/test/mock/mock_stack_metrics_logging.cc
@@ -29,15 +29,13 @@
#include <frameworks/proto_logging/stats/enums/bluetooth/enums.pb.h>
#include <frameworks/proto_logging/stats/enums/bluetooth/hci/enums.pb.h>
+#include "stack/include/stack_metrics_logging.h"
#include "test/common/mock_functions.h"
#include "types/raw_address.h"
// Mocked compile conditionals, if any
// Mocked internal structures, if any
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace test {
namespace mock {
namespace stack_metrics_logging {
@@ -56,13 +54,6 @@ 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
@@ -105,16 +96,6 @@ void log_sdp_attribute(const RawAddress& address, uint16_t protocol_uuid, uint16
attribute_size, attribute_value);
}
void log_manufacturer_info(const RawAddress& address,
- 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& software_version) {
- inc_func_call_count(__func__);
- test::mock::stack_metrics_logging::log_manufacturer_info(address, source_type, source_name,
- manufacturer, model, hardware_version,
- software_version);
-}
-void log_manufacturer_info(const RawAddress& address,
android::bluetooth::AddressTypeEnum address_type,
android::bluetooth::DeviceInfoSrcEnum source_type,
const std::string& source_name, const std::string& manufacturer,
@@ -167,39 +148,4 @@ void log_le_connection_completion(bluetooth::hci::Address address, bluetooth::hc
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 d807c1f761..40212e60ea 100644
--- a/system/test/mock/mock_stack_metrics_logging.h
+++ b/system/test/mock/mock_stack_metrics_logging.h
@@ -247,58 +247,6 @@ struct log_le_connection_completion {
};
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_security_client_interface.cc b/system/test/mock/mock_stack_security_client_interface.cc
index 5ccb5e31df..3930c1a281 100644
--- a/system/test/mock/mock_stack_security_client_interface.cc
+++ b/system/test/mock/mock_stack_security_client_interface.cc
@@ -19,9 +19,6 @@
#include "stack/include/security_client_callbacks.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
namespace {
// Initialize the working btm client interface to the default
@@ -42,6 +39,6 @@ const SecurityClientInterface& get_security_client_interface() {
return *mock_security_client_interface;
}
-void set_security_client_interface(SecurityClientInterface* interface) {
- mock_security_client_interface = interface;
+void set_security_client_interface(SecurityClientInterface& interface) {
+ mock_security_client_interface = &interface;
}
diff --git a/system/test/mock/mock_stack_security_client_interface.h b/system/test/mock/mock_stack_security_client_interface.h
index 224d880905..1487326ac5 100644
--- a/system/test/mock/mock_stack_security_client_interface.h
+++ b/system/test/mock/mock_stack_security_client_interface.h
@@ -44,7 +44,7 @@ struct MockSecurityClientInterface : public SecurityClientInterface {
MOCK_METHOD((bool), BTM_IsEncrypted,
(const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */));
MOCK_METHOD((bool), BTM_SecIsLeSecurityPending, (const RawAddress& /* bd_addr */));
- MOCK_METHOD((bool), BTM_IsLinkKeyKnown,
+ MOCK_METHOD((bool), BTM_IsDeviceBonded,
(const RawAddress& /* bd_addr */, tBT_TRANSPORT /* transport */));
MOCK_METHOD((bool), BTM_SetSecurityLevel,
(bool /* is_originator */, const char* /* p_name */, uint8_t /* service_id */,
diff --git a/system/test/mock/mock_udrv_ulinux_uipc.cc b/system/test/mock/mock_udrv_ulinux_uipc.cc
index daa7cc7f7c..6ecd0bdd1f 100644
--- a/system/test/mock/mock_udrv_ulinux_uipc.cc
+++ b/system/test/mock/mock_udrv_ulinux_uipc.cc
@@ -24,9 +24,6 @@
#include "test/common/mock_functions.h"
#include "udrv/include/uipc.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
std::unique_ptr<tUIPC_STATE> mock_uipc_init_ret;
uint32_t mock_uipc_read_ret;
bool mock_uipc_send_ret;
@@ -41,10 +38,6 @@ bool UIPC_Send(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, uint16_t /* msg
inc_func_call_count(__func__);
return mock_uipc_send_ret;
}
-int uipc_start_main_server_thread(tUIPC_STATE& /* uipc */) {
- inc_func_call_count(__func__);
- return 0;
-}
std::unique_ptr<tUIPC_STATE> UIPC_Init() {
inc_func_call_count(__func__);
return std::move(mock_uipc_init_ret);
@@ -64,8 +57,3 @@ bool UIPC_Ioctl(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */, uint32_t /* re
return false;
}
void UIPC_Close(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */) { inc_func_call_count(__func__); }
-void uipc_close_locked(tUIPC_STATE& /* uipc */, tUIPC_CH_ID /* ch_id */) {
- inc_func_call_count(__func__);
-}
-void uipc_main_cleanup(tUIPC_STATE& /* uipc */) { inc_func_call_count(__func__); }
-void uipc_stop_main_server_thread(tUIPC_STATE& /* uipc */) { inc_func_call_count(__func__); }
diff --git a/system/test/stub/osi.cc b/system/test/stub/osi.cc
index c087497528..cffeb4c3bf 100644
--- a/system/test/stub/osi.cc
+++ b/system/test/stub/osi.cc
@@ -34,17 +34,18 @@
#include "osi/include/future.h"
#include "osi/include/hash_map_utils.h"
#include "osi/include/list.h"
+#include "osi/include/mutex.h"
+#include "osi/include/properties.h"
#include "osi/include/reactor.h"
-#include "osi/include/ringbuffer.h"
#include "osi/include/socket.h"
+#include "osi/include/socket_utils/socket_local.h"
+#include "osi/include/socket_utils/sockets.h"
#include "osi/include/thread.h"
#include "osi/include/wakelock.h"
#include "osi/src/compat.cc" // For strlcpy
#include "test/common/fake_osi.h"
#include "test/common/mock_functions.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
#pragma GCC diagnostic ignored "-Wunused-parameter"
OsiObject::OsiObject(void* ptr) : ptr_(ptr) {}
@@ -511,10 +512,6 @@ list_t* list_new(list_free_cb callback) {
inc_func_call_count(__func__);
return nullptr;
}
-list_t* list_new_internal(list_free_cb callback, const allocator_t* zeroed_allocator) {
- inc_func_call_count(__func__);
- return nullptr;
-}
size_t list_length(const list_t* list) {
inc_func_call_count(__func__);
return 0;
@@ -552,32 +549,6 @@ int osi_socket_make_sockaddr_un(const char* name, int namespaceId, struct sockad
return 0;
}
-size_t ringbuffer_available(const ringbuffer_t* rb) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t ringbuffer_delete(ringbuffer_t* rb, size_t length) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t ringbuffer_insert(ringbuffer_t* rb, const uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t ringbuffer_peek(const ringbuffer_t* rb, off_t offset, uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t ringbuffer_pop(ringbuffer_t* rb, uint8_t* p, size_t length) {
- inc_func_call_count(__func__);
- return 0;
-}
-size_t ringbuffer_size(const ringbuffer_t* rb) {
- inc_func_call_count(__func__);
- return 0;
-}
-void ringbuffer_free(ringbuffer_t* rb) { inc_func_call_count(__func__); }
-
bool osi_property_get_bool(const char* key, bool default_value) {
inc_func_call_count(__func__);
if (fake_osi_bool_props_map.count(key)) {
diff --git a/system/test/suite/Android.bp b/system/test/suite/Android.bp
index b916f691d5..e8762d6737 100644
--- a/system/test/suite/Android.bp
+++ b/system/test/suite/Android.bp
@@ -72,18 +72,15 @@ cc_defaults {
"libbt-audio-asrc",
"libbt-audio-hal-interface",
"libbt-bta",
- "libbt-bta-core",
"libbt-common",
"libbt-hci",
"libbt-sbc-decoder",
"libbt-sbc-encoder",
"libbt-stack",
- "libbt-stack-core",
"libbtcore",
"libbtdevice",
"libbte",
"libbtif",
- "libbtif-core",
"libcom.android.sysprop.bluetooth.wrapped",
"libexpresslog",
"libflatbuffers-cpp",
diff --git a/system/udrv/ulinux/uipc.cc b/system/udrv/ulinux/uipc.cc
index d0d7de0fbb..c3444d4b57 100644
--- a/system/udrv/ulinux/uipc.cc
+++ b/system/udrv/ulinux/uipc.cc
@@ -47,9 +47,6 @@
#include "osi/include/osi.h"
#include "osi/include/socket_utils/sockets.h"
-// TODO(b/369381361) Enfore -Wmissing-prototypes
-#pragma GCC diagnostic ignored "-Wmissing-prototypes"
-
using namespace bluetooth;
/*****************************************************************************
@@ -223,7 +220,7 @@ static int uipc_main_init(tUIPC_STATE& uipc) {
return 0;
}
-void uipc_main_cleanup(tUIPC_STATE& uipc) {
+static void uipc_main_cleanup(tUIPC_STATE& uipc) {
int i;
log::debug("uipc_main_cleanup");
@@ -433,7 +430,7 @@ static int uipc_close_ch_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
return 0;
}
-void uipc_close_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
+static void uipc_close_locked(tUIPC_STATE& uipc, tUIPC_CH_ID ch_id) {
if (uipc.ch[ch_id].srvfd == UIPC_DISCONNECTED) {
log::debug("CHANNEL {} ALREADY CLOSED", ch_id);
return;
@@ -499,7 +496,7 @@ static void* uipc_read_task(void* arg) {
return nullptr;
}
-int uipc_start_main_server_thread(tUIPC_STATE& uipc) {
+static int uipc_start_main_server_thread(tUIPC_STATE& uipc) {
uipc.running = 1;
if (pthread_create(&uipc.tid, (const pthread_attr_t*)NULL, uipc_read_task, &uipc) != 0) {
@@ -511,7 +508,7 @@ int uipc_start_main_server_thread(tUIPC_STATE& uipc) {
}
/* blocking call */
-void uipc_stop_main_server_thread(tUIPC_STATE& uipc) {
+static void uipc_stop_main_server_thread(tUIPC_STATE& uipc) {
/* request shutdown of read thread */
{
std::lock_guard<std::recursive_mutex> lock(uipc.mutex);
diff --git a/tools/rootcanal/Android.bp b/tools/rootcanal/Android.bp
index e7ccec6657..501a3efeb2 100644
--- a/tools/rootcanal/Android.bp
+++ b/tools/rootcanal/Android.bp
@@ -314,11 +314,6 @@ python_test_host {
test_options: {
unit_test: true,
},
- version: {
- py3: {
- embedded_launcher: true,
- },
- },
}
// test-vendor unit tests for host